Guarantees
Falsified
Ranvier.Pure.Witnesses
Counterexample [
Counterexample [stale_source_reader](#stale_source_reader) is now resolved: both the source and the reader finish Clean at 3.
no_lost_wakeups_statement now holds on the engine (no_lost_wakeups).
engine_inv_preserved_statement now holds on the engine (engine_inv_preserved).
Counterexample [nested_host](#nested_host) is now resolved: the mark received during the run survives to nested_end, with n_unannounced set.
Counterexample [nested_host](#nested_host) is now resolved: the memo's source list at nested_end matches the reads of the run.
Falsified on the present engine: a read of a disposed memo answers what it stored, not what its body computes.
This is a counterexample, not a guarantee. It proves glitch_free_read_statement false, on disposed_stale_source_read: the memo is disposed at 0 over a signal at 1, and its body answers 1. Core.fs 4372-4376 documents this answer.
Both former counterexamples [self_marking_cleanup](#self_marking_cleanup) and [never_lost](#never_lost) now satisfy converged_all.
The unconditional exact refinement is false: a batch restoring a signal reruns its effect.
exact_refinement_statement fails on restored, from batch_restored_value_reruns, scenario S07. The engine's trace has a run the reference's trace does not, under every valid order and fuel. Closed in BUGS.md (Core.fs 4639-4640). F#: the trace of scenario S07.
The unconditional weak refinement is false: a memo disposed unread answers its default, and the reference answers its value.
weak_refinement_statement fails on unread_memo, from disposed_unread_memo_value, whose trace the F# scenario of the same name gives: the effect logs 0, where the reference logs 5. Closed in BUGS.md (Core.fs 4372-4373). write_then_dispose_memo_current_value and redundant_run_reads_untracked are two more falsifiers.
The queue at a flush's start does not give the flush's order: an effect marked during its own run runs after a later entry.
engine_order_exact_statement defines the order by engine_order, the queue at the flush's start, and it fails on requeue_order, a program meeting refinable: that queue is [5; 4], and the flush runs 5, 4, 5. F#: scenario requeue_runs_after_later_entry. The theorem refutes this definition of the order. history_order is a different one, and this theorem does not reach it.
The engine has no answer on a well-formed program where the reference settles: no fuel ends restored_source.
The effect reads a source, writes it and restores it. Each run marks the effect and enqueues it, so the drain takes one more entry for each entry it takes. The reference compares reads, finds them equal, and settles after one run under every order. effect_restored_source_loop in BUGS.md, whose F# scenario runs the same body until a budget ends it.
Ranvier.Pure.Optimised
A Dirty mark leaves a clean memo holding an announcement unsaturated.
mark_dirty_saturates, a lemma of the plan for the record's soundness, is false.
Ranvier.Pure.MemoTableWitnesses
W1: Dropping compute determinism (rule_frame) falsifies eviction transparency: on [ActGet 0; ActEvictPayload 0; ActGet 0], the evicted table returns [ROk 1; ROk 2] while the unbounded family returns [ROk 1; ROk 1].
W2: Dropping cutoff_sound (stamp_of := fun _ => 0%Z, colliding on 0%Z <> 1%Z) falsifies memotable_no_lost_wakeups (T12) and T9a: after [ActFlush; ActEvictPayload 0; ActWrite 0 1; ActFlush], the downstream effect stays settled at Some 0%Z while signal 0 holds 1%Z (a lost wakeup).
W3: Omitting the sl_pins = 0 guard in mt_retire_key allows a nested sweep during compute k (while observer_count = 0 before Track) to dispose n, causing sources_add caller n to create a live edge pointing to a disposed MemoNode (n_disposed d = true /\ edge s_trk n caller).
W4: Detaching a dormant slot's upstream ds_deps (ObserverCount = 0) while keeping ds_fresh = Clean and DPResident 10 without global source epochs causes dag_write 0 99 to miss invalidating key 0, returning stale ROk 10 instead of ROk 99.
W5: Retaining Some (stamp_of v0) instead of resetting to SlotNonValue when transitioning into StError (Ok v0 -> Evict -> Error -> Ok v0) produces mv_rec = false, suppressing observer notification when the slot recovers from StError back to Ok v0.
W6: Creating a slot via ordinary CMemo under the caller's frame (hosted 2) instead of detached mt_owner (mt_create_slot, T1) fails with Fail pure_scope_failure (-2) whenever the caller is a ScopeMode.Pure memo.
W7: Whereas preserving n_unannounced = true across mt_refill_clean (T7) forwards Check to observer 2 (mark_check 3 1 (w7_check_state true) marks 2 Check), clobbering n_unannounced := false leaves observer 2 Clean (~ unannounced_clobbered_by_refill_statement).
Ranvier.Pure.MemoTableFastPaths
W8: Updating tableKey in place without restoring the saved (hasTableKey, tableKey) pair in finally causes a nested memoTable evaluation (k_inner = 2) to clobber the outer slot's memoTable.key (k_outer = 1).
Checks
Ranvier.Reference.Properties
An engine with no traces passes refines for every observation.
✓ No axiomsCheck, not a guarantee.
refines constrains only the answers an engine gives, so this is a caution about the definition. An engine proof also owes engine_answers, which rejects this engine: see none_engine_not_answers.
Dropping a redundant run can change what a reader sees, when its cleanup fails.
✓ No axiomsCheck, not a guarantee.
This is a counterexample on one program, resetting_failing_cleanup, under the reversed order: effect 8's second run counts as redundant and discharges a failing cleanup, and the trace without that run has a different observe_settled. The failure is the one the removal loses.
refines rejects an engine that answers only the full history.
✓ No axiomsCheck, not a guarantee.
An engine matching the reference's settled view on a two-batch history fails at the empty prefix, where it gives no answer. This tests the definition of refines.
refines rejects traces that match at each prefix but don't extend each other.
✓ No axiomsCheck, not a guarantee.
An engine answering each prefix of two_writes with only its last run has the reference's settled view at each prefix, and fails the requirement that a prefix's trace is a prefix of the whole trace. This tests the definition of refines.
refines rejects an engine that emits nothing.
✓ No axiomsCheck, not a guarantee.
A valid order runs every effect in the initial round, so an empty trace misses a run's value under observe_settled. This tests the definition of refines.
engine_answers rejects an engine with no traces.
✓ No axiomsCheck, not a guarantee.
The counterpart of none_engine_refines. This tests the definition of engine_answers.
Ranvier.Pure.Edges
A removal without blanking the removed slot breaks coherence.
✓ No axiomsCheck, not a guarantee.
From a coherent world, removing the slot's observer entry and leaving the slot's handle in place gives a world that is not coherent. This marks a step the engine has to pair with another.
A move to a different handle without a removal breaks coherence.
✓ No axiomsCheck, not a guarantee.
From a coherent world, giving a slot a different handle and leaving the observer set in place gives a world that is not coherent. This marks a step the engine has to pair with another.
Ranvier.Pure.Witnesses
Removing the skip of NotifyDirtyExcept breaks notice_skips_current.
✓ No axiomsCheck, not a guarantee.
Source 1 is observed by effect 2, the current computation, which is Clean. The notice leaves the effect short of Dirty. The same notice with the skip removed, which is notify_dirty, leaves it Dirty.
Removing MarkReaderCheck breaks wake_told, and wake_ok cannot see it.
✓ No axiomsCheck, not a guarantee.
With f_reader_mark cleared, the program's final state has an effect clean and idle over a live stale memo it read, with gh_over empty, so wake_told fails. no_wake_lost_unless_resolved has it holding with the flag on. The memo holds its announcement, so wake_ok holds on the broken state too: wake_told is the statement that detects this mutant.
Never setting n_unannounced without MarkReaderCheck breaks wake_ok.
✓ No axiomsCheck, not a guarantee.
With both f_unannounced and f_reader_mark cleared, a run ending stale sets no flag and the reader stays Clean over a live stale memo with no flag, so wake_ok fails on stale_late_reader. With f_unannounced on (no_reader_mark) or current_flags, wake_ok holds.
Regression witness for #290: without MarkReaderCheck, a reader of a stale memo goes untold.
✓ No axiomsCheck, not a guarantee.
prog_S04 ends in a state where wake_told fails with f_reader_mark cleared and holds on the present engine. wake_ok holds on both: the stale memo holds its flag. With the mark the effect logs -1, 0, 2, 3 and the signal ends at 3. Without it the log stops at -1, 0 and the signal ends at 1. The flag on with the mark off is a model configuration: 2e8f9690 predates the flag. This witness has no effect_ran_for_last_write clause: a memo that writes its own source denotes nothing.
The premises of convergence hold on a live effect over live memos, and the theorem answers the latest value.
✓ No axiomsCheck, not a guarantee.
live_diamond reaches every premise of convergence and well_behaved_nothing_passed. The effect read the memo at 10, the value its body answers over the signal at 3, and its last run logged 10.
Batches and computed read targets, in memos and effects, reach every premise of convergence.
✓ No axiomsCheck, not a guarantee.
widened_forms has a batch and a computed target in a memo, and the same in an effect. After the write the memo reads signal 2, and the effect's last run logs what the memo and the node named by signal 1 denote.
An untracked read on a branch that never runs fails its premise, and the conclusion holds.
✓ No axiomsCheck, not a guarantee.
memos_no_untracked is checked over the whole body. On dead_untracked it is false, den_all answers Ok 5, and converged_all holds on the present engine.
EPrev on a branch that never runs fails its premise, and the conclusion holds.
✓ No axiomsCheck, not a guarantee.
memos_no_prev is checked over the whole body. On dead_prev it is false, den_all answers Ok 5, and converged_all holds on the present engine.
A node created on a branch that never runs fails its premise, and the conclusion holds.
✓ No axiomsCheck, not a guarantee.
memos_no_creation is checked over the whole body. On dead_creation it is false, den_all answers Ok 5, and converged_all holds on the present engine.
A throwing comparer that is never called fails its premise, and the conclusion holds.
✓ No axiomsCheck, not a guarantee.
memos_no_throwing_comparer is checked on the comparer, whether or not it fires. On uncalled_comparer it is false, den_all answers Ok 0, and converged_all holds on the present engine.
An effect's untracked read reaches every premise of convergence, and its log stays behind.
✓ No axiomsCheck, not a guarantee.
After untracked_read the effect has logged 5 and signal 2 holds 6. convergence holds: the log is a run of the body with the untracked read answered by some value, and no more is promised of it. A write of the tracked signal brings the log up to date.
The premises of the refinement are reachable.
✓ No axiomsCheck, not a guarantee.
refinable_program is well formed and refinable, under a history with a write, a host read and a disposal of its effect, and the engine's trace on it matches the reference at the full history.
runs_agree and queue_steady are met on a program whose order is not creation order.
✓ No axiomsCheck, not a guarantee.
On drain_order, the flush after the write runs 5 then 4. The history-wide order meets runs_agree, so exact_refinement_history applies and the engine's trace is the reference's under it. The identity order does not meet runs_agree. The batch's flush also meets queue_steady, with start queue [5; 4].
The premises of engine_of_answers_on are reachable.
✓ No axiomsCheck, not a guarantee.
drain_order meets bodies_total, its history meets inputs_total, and the reference answers on that history.
runs_agree fails on a redundant run, at the order read from the engine, and queue_steady fails on a reachable program.
✓ No axiomsCheck, not a guarantee.
order_by keeps the copies of a value together, so [5; 4; 5] as a round's list gives 5, 4 to the reference. That does not meet the premise: the engine's runs at the whole history hold one more 5 than the reference's. Taking the queue at the flush's start, flush_queue holds [6; 5; 6], so queue_steady fails too.
bodies_total fails on a stuck arm no run takes, and the engine and the reference both answer.
✓ No axiomsCheck, not a guarantee.
bodies_total reads a body over all answers to its reads. On dead_stuck_arm it is false, and the two traces are equal, so that premise is conservative on this program.
reads_higher is refinable under a rank other than the ids, and not under the ids.
✓ No axiomsCheck, not a guarantee.
The memo with the lower id reads the memo with the higher id, so memos_below fails with the ids as the rank. Under swap_rank it holds, and reads_higher meets refinable with its two-batch history, so the theorems over refinable cover it.
Guarantees
Ranvier.Reference.Properties
The reference gives one trace for a program, a history and an effect order.
✓ No axiomsTwo orders that agree at every round on every list, with any two fuels that both reach a result, give the same trace.
With the same disposed memos, a memo's value depends only on the signals its evaluation reached.
✓ No axiomsA memo's value over one set of signals is also its value over any other set that agrees on the signals in memo_deps of the first evaluation, with the same disposed memos' answers.
Premise: the program is well formed.
The run holding a log, when it writes no signal, computes from one snapshot.
✓ No axiomsA trace is the concatenation of its records' events, and a given EvLog lies in some record for its node. When that record writes no signal, its reads and events are reproduced by replaying it with every read answered from one snapshot of the signals and the disposed memos' values. The guarantee is silent on a record that writes, and on every other record. A cleanup's environment, and so a value it logs, can date from the run that registered it. This describes the reference, not the engine.
Equal full traces have equal settled views.
✓ No axiomsobserve_full distinguishes at least as much as observe_settled.
An engine refining the full trace refines the settled view.
✓ No axiomsA history's trace extends the trace of each batch prefix.
✓ No axiomsUnder one order and fuel, if the history has a trace, each batch prefix has a trace that is a prefix of it.
The reference refines itself on the full trace.
✓ No axiomsHolds under each valid order and any fuel, at every batch prefix of a well-formed program. refines only constrains histories the reference answers at that fuel.
The reference answers whenever it settles.
✓ No axiomsUnder a valid order, some fuel gives a trace for a well-formed program and history, provided the reference settles under every valid order.
Ranvier.Pure.ObserverSet
Adding an observer appends it to the end of the set.
✓ No axiomsThe returned handle is the old observer count, and that position now holds the observer with its slot. The visible order is the old order followed by the new observer, and observer_latest holds the new handle. Holds for every set.
A small set always knows whether it holds an observer.
✓ No axiomsWith at most scan_limit observers, TryAdd answers TAdded or TUnlinked, and TUnlinked exactly when the observer is already in the set.
A handle that holds another observer fails the removal.
✓ No axiomsWhen the handle's position is out of range or holds a different observer, RemoveAt returns None, the model's InvalidOperationException.
Removal fills the hole with the last observer and reports the move.
✓ No axiomsRemoving from a middle position moves the last observer there. The result names that observer, its slot and its new handle, and observer_latest follows it if it pointed at the moved observer. Removing the last observer shortens the set and reports no move. The handle has to be the observer's actual position.
A notification walk visits every observer held exactly once throughout.
✓ No axiomsThe set can change between visits. An observer in exactly one position at the start, and after every mutation of the walk, appears among the visits at least once. The walk starts from the full observer count.
An observer held twice can be missed, as walk_covers_duplicate_observer shows. A moved observer can be visited twice, as walk_visits_moved_twice shows.
A walk visits only observers present at the time of the visit.
✓ No axiomsThe kth observer visited belongs to the set as it stands after the mutations of the k earlier visits. Holds from any starting cursor. An observer added during the walk can be visited: see walk_visits_added_observer.
Ranvier.Pure.SourceList
A read matching the slot at the cursor only advances the cursor.
✓ No axiomsWhen the slot at the cursor holds the source being read, Add succeeds, the cursor moves up one, and every observer set, this computation's slots and every other computation's source list stay as they were.
Reading the source just matched again changes nothing.
✓ No axiomsWhen the slot at the cursor holds a different source and the slot just before the cursor holds this one, Add returns the world unchanged.
A read matching neither slot drops the rest of the list and appends the source.
✓ No axiomsWhen the read matches neither the slot at the cursor nor the one before it, the new list is the slots before the cursor followed by the source, with the cursor at its end. The two ends of every edge still agree, and the computation appears only in the observers of sources in its new list.
Premise: the two ends of every edge agree beforehand (edge_match).
A computation holds at most one edge per source, in that source's first slot.
✓ No axiomsIn every world built from empty by the source-list operations, two slots of a computation that hold edges to one source are the same slot, and a slot holds an edge exactly when no earlier slot names its source.
Removing a computation's edge moves only another computation's edge.
✓ No axiomsThe observer that a removal moves into the hole is a different computation from the one being removed.
Premises: the two ends of every edge agree (edge_match), every computation holds at most one edge per source (slots_unique), and the removal uses the handle stored in the computation's slot.
Every world between the removals of a trim stays consistent.
✓ No axiomsAfter any number of removals, the two ends of every edge agree, each computation holds at most one edge per source, each observer set holds an observer at most once, and the next removal moves only another computation's edge.
Premises: the first two properties hold when the trim starts.
An observer in a set occupies exactly one position.
✓ No axiomsHolds in every reachable world and in every world between the removals of a trim that starts from one.
A clear stays correct when a removal moves the computation's own later edge.
✓ No axiomsTake the source list A, B, A with an edge in each slot, the later A edge last in A's observers. The first removal moves that edge, the later slot then holds the moved handle, and Clear still succeeds, leaving an empty list and the computation in no observer set.
Premises: this exact list and the two ends of every edge agreeing. Reachable worlds exclude this list (sources_no_duplicate_edge), so this covers a world built by hand: see aba_reachable_trim.
A read that TryAdd can't answer for still leaves one edge.
✓ No axiomsWhen a read misses its slot, the source has more than scan_limit observers and observer_latest holds another observer, TryAdd answers TUnknown. Add still succeeds, the world stays well formed, and the computation holds exactly one position in the source's observers, whether or not the source already had a slot.
Premise: the world is well formed beforehand. The observer count and observer_latest are measured after the trim of the slots from the cursor onward.
Unrolling cur = 0 in SourceList.Add refines sources_add with identical edge-world transitions.
✓ No axiomsMatches SourceList.Add (Core.fs): when cursor = 0, the repeat-read guard 0 < cursor is statically
false and cursor + 1 is 1, so checking slot 0 directly and skipping the repeat branch yields the exact
same edge-world update as sources_add.
Ranvier.Pure.Edges
Starting a run keeps the two ends of every edge in agreement.
✓ No axiomsBeginRun on a coherent world gives a coherent world.
A tracked read succeeds and keeps the two ends of every edge in agreement.
✓ No axiomsAdd on a coherent world returns a world, and that world is coherent.
Ending a run succeeds and keeps the two ends of every edge in agreement.
✓ No axiomsEndRun on a coherent world returns a world, and that world is coherent.
Clearing a source list succeeds and keeps the two ends of every edge in agreement.
✓ No axiomsClear on a coherent world returns a world, and that world is coherent.
Removing a slot's edge keeps coherence, and the moved observer takes the removed handle.
✓ No axiomsThe result is the removal, the blanked slot and, when the removal moved another observer, that observer's MovedIn. The moved observer's slot holds the source with the removed handle.
Premises: a coherent world, and a slot holding the source with this handle.
In a coherent world, either side of an edge implies the other.
✓ No axiomsc observes src exactly when c is in src's observers, and exactly when a slot of c holds src with a handle.
In a well-formed world, a computation observes exactly the sources in its slots.
✓ No axiomsA world is well formed when the two ends of every edge agree and a slot holds an edge exactly when no earlier slot of the computation names its source. Every source in a slot has an edge, whichever slot holds the handle.
Ranvier.Pure.Marking
Marking a node finishes on any graph, cycles included.
✓ No axiomsWith fuel above mark_measure, mark_check and mark_dirty return a state.
Marking a node's observers finishes on any graph, cycles included.
✓ No axiomsWith fuel above mark_measure, notify_check, notify_dirty and notify_dirty_except return a state.
Marks only raise freshness.
✓ No axiomsAfter any of the five marking operations, each existing node still exists, and its freshness has stayed or risen in the order Clean, Check, Dirty.
A Check mark leaves a Dirty node Dirty.
✓ No axiomsCovers mark_check only. mark_monotone gives the same for every marking operation.
Marks leave the edges alone.
✓ No axiomsEach of the five marking operations leaves both ends of every edge unchanged.
A marking walk visits the observers present at its start, last position first.
✓ No axiomsEach notify operation folds its mark over that one list, and the walk is a walk with empty mutations at every visit. A walk with a mutation behaves differently: see walk_visits_added_observer.
A marking walk leaves each observer stale.
✓ No axiomsEach observer of the source that takes marks ends Check or Dirty. notify_dirty_except skips the running computation unless it has already read the source in its current run, so the guarantee covers observers other than that one and running observers that have already read the source. An observer takes marks when it is a memo, or an effect outside its disposal and its cleanups.
A clean memo goes stale and passes the mark to its observers.
✓ No axiomsAfter mark_check or mark_dirty of a Clean memo, the memo is stale, and so is each of its observers that takes marks. An effect in its cleanups stays clean: see in_cleanup_observer_stays_clean.
A stale memo holding an announcement passes the mark on and spends the announcement.
✓ No axiomsAfter mark_check or mark_dirty, the memo is still stale with n_unannounced cleared, and each of its observers that takes marks is stale.
Premises: the f_unannounced flag is on, and the memo is stale with n_unannounced set.
Marks keep each effect's queue entries in step with its queued flag.
✓ No axiomsEach marking operation preserves queue_once: at most one pending entry for the node, and none while its flag is unset. An effect marked along several paths has at most one pending entry.
Premise: queue_once holds beforehand.
A marked effect ends queued.
✓ No axiomsAfter mark_check or mark_dirty, the effect's n_queued is set and queue_once still holds. An effect that was not queued has a pending entry, provided the queue head lies within the queue.
Premises: the effect is outside its disposal and its cleanups, and queue_once holds beforehand.
A disposed effect ignores marks.
✓ No axiomsmark_check and mark_dirty return the state unchanged, given any positive fuel.
An effect running its cleanups ignores marks.
✓ No axiomsmark_check and mark_dirty return the state unchanged, given any positive fuel.
A Dirty mark makes its target Dirty.
✓ No axiomsA memo, or an effect outside its disposal and its cleanups, ends Dirty. That includes an effect already queued on Check.
A dirty walk leaves each observer Dirty.
✓ No axiomsEach observer of the source that takes marks ends Dirty. notify_dirty_except skips the running computation, so the guarantee covers observers other than that one.
A Check mark makes no node Dirty.
✓ No axiomsmark_check and notify_check leave each node short of Dirty still short of it.
A Dirty mark on a memo makes no other node Dirty.
✓ No axiomsmark_dirty of a memo leaves every other node that was short of Dirty still short of it.
Marking a clean memo leaves its announcement flag as it was.
✓ No axiomsmark_check sets the memo to Check and mark_dirty sets it to Dirty, each with n_unannounced unchanged, and then each walks the observers with mark_check. Given any positive fuel.
Hoisting slot 0 out of the while i > 0 notification loop preserves notify_with across all dynamic observer-set mutations.
✓ No axiomsMatches ObserverSet.NotifyDirty, NotifyDirtyExcept, NotifyDirtyOther, and NotifyCheck (Core.fs):
walking overflow observers down to index 1 (while i > 0) and handling slot 0 (first) afterward
executes the identical sequence of observer marks and handles dynamic removal of slot 0 identically.
Ranvier.Pure.Check
Every engine function keeps the check invariant, at every fuel.
✓ No axiomsWhen a function returns, the check invariant still holds, g_running and g_current are back to their starting values, each node keeps its kind, and each memo's run count and disposal only go forward (frame). After run_memo or recompute of a memo, the memo is disposed, or RecomputeScoped has never cleared its Dirty, or the memo has run since RecomputeScoped last did.
Premises: the invariant holds at the start. Functions over a memo or an effect require a node of that kind, and run_effect_body requires that effect's run to be in progress.
A new graph satisfies the check invariant.
✓ No axiomsThe check invariant holds under any flags.
A whole program keeps the check invariant.
✓ No axiomsIf the check invariant holds at the start and run_top returns, the invariant holds in the final state. A program that gets stuck or runs out of fuel returns nothing, and is outside this guarantee.
update_if_necessary keeps the check invariant.
✓ No axiomsIf the check invariant holds at the start and update_if_necessary returns, the invariant holds afterwards.
A memo short of Dirty with settled reads has read what each source now stores.
✓ No axiomsEach source in the memo's slots has a recorded read, and each recorded read equals the source's stored value, status and failure, which can themselves be stale.
Premises: the check invariant holds, and reads_settled: the memo has no unnoticed difference in its reads, and neither it nor any of its sources is running.
A memo resolved Clean with settled reads has read what each source now stores.
✓ No axiomsEach source in the memo's slots has a recorded read, and each recorded read equals the source's stored value, status and failure, which can themselves be stale: self_marking_through_memo_unmoved has the source Dirty and the reader Clean.
Premises: the check invariant holds, the memo starts in Check, update_if_necessary returns with the memo Clean, and reads_settled holds at the end. reads_settled says the memo has no unnoticed difference in its reads, and neither it nor any of its sources is running. The guarantee comes from the invariant and that premise, not from the walk. The unqualified claim is false: see resolve_clean_no_move_statement.
The check walk stops as soon as the node leaves Check.
✓ No axiomsWith the node Clean or Dirty, the walk returns the state unchanged at this slot, given any positive fuel.
The check walk updates one source, then moves to the next slot.
✓ No axiomsWith the node in Check and a source in this slot, the walk runs update_if_necessary on that source and continues from the next slot, given any positive fuel.
A check walk that ends with the node still in Check leaves no live stale source in its slots.
✓ No axiomsWith fl_walk_recheck enabled, resolve_walk re-walks from slot 0 whenever a slot still holds a live stale source at the end of the pass, and only returns in Check when no slot does.
Resolving a memo to Clean clears its announcement flag.
✓ No axiomsHolds on every path of update_if_necessary: the walk ending in Check, a run after it, or disposal during RecomputeScoped.
Premises: the check invariant holds, and the memo starts in Check and ends Clean.
A check walk that ends in Check makes the node Clean with no run after the walk.
✓ No axiomsFor a node that starts in Check outside g_checking and g_running, refresh succeeds with the node as the walk left it, except Clean with n_unannounced false. Its run count is the one the walk left, which says nothing of runs during the walk.
Updating a signal does nothing.
✓ No axiomsupdate_if_necessary on a signal returns the state unchanged, given any positive fuel.
Reading a disposed memo keeps every node as it was and answers what it stored.
✓ No axiomsThe read returns a failure when the memo's status is StError, otherwise the stored value. The failure is n_failure, or 0 when n_failure is None. This covers nodes only: a tracked read can still add an edge.
Tagging an observer-set handle (0 <= h < 2^28) with EdgeHandle.SignalBit (2^29) produces a non-negative 31-bit Smi tagged handle distinct from untagged handles and EdgeHandle.Unlinked, and unified RemoveAt masking recovers both the raw index (&&& IndexMask, 2^28 - 1) and SignalBit.
✓ No axiomsMatches EdgeHandle.SignalBit, EdgeHandle.IndexMask, EdgeHandle.isSignal, Signal.AddObserver,
Signal.TryAddObserver, and ObserverSet.RemoveAt (Core.fs:402,410): setting bit 29 (0x20000000)
distinguishes signal handles (>= 2^29) from memo/untagged handles (< 2^29) and sentinels (< 0),
while &&& IndexMask (0x0FFFFFFF) extracts h for 0 <= h < 2^28 and &&& SignalBit preserves
SignalBit on swap-removed signal edges and 0 on untagged edges.
Skipping SignalBit-tagged sources in ResolveCheck (RefreshSourceAt) and HasStaleSource preserves exact engine behavior because updating a signal is a no-op and a signal is never stale or live-stale.
✓ No axiomsMatches SourceList.RefreshSourceAt and SourceList.HasStaleSource (Core.fs): since
Signal.UpdateIfNecessary returns immediately without reading or writing state and Signal.IsStale
is always false, skipping any slot whose handle carries EdgeHandle.SignalBit produces the identical
state transition as calling UpdateIfNecessary and IsStale on that slot.
Ranvier.Pure.Runs
The settled invariant holds at every return of every engine function, at every fuel.
✓ No axiomsengine_settled is the invariant run-level proofs carry: the check invariant, the stack discipline, source-list bookkeeping, equal-length owner cleanup lists, an effect in its cleanups being on the stack, and the record of what each computation has been told.
Premises: the invariant holds at the start, and the function's own premise, as listed in preserved_by. A function that gets stuck or runs out of fuel returns nothing and is outside this guarantee. This is the form that holds on the present engine: engine_inv_preserved_statement adds wake_ok, and that form is false.
A new graph with the current flags satisfies the settled invariant.
✓ No axiomsEvery live stale source has its observers covered, apart from observers a walk resolved over a stale source.
✓ No axiomsFor any edge from a live, stale source to an observer, after a whole program: the observer is stale or queued, or on the running stack, or the source holds its announcement flag, or the observer is in gh_passed. gh_passed holds exactly the computations whose check walk ended and went Clean while a slot held a live, stale source with no announcement, since their latest run start. Membership is per computation, not per source: once an observer has passed over one source, the exception covers every source of that observer until its next run starts, a different lost wake-up on another source included.
This says nothing of whether an observer read a source's latest value. A skipped notice leaves the source Clean, so it has no stale edge to cover, and effect_resolves_over_moved_source loses a re-run that way with this statement holding.
Premise: engine_settled holds at the start. A program that gets stuck or runs out of fuel returns nothing, and is outside this guarantee.
walk_passed_source_marked reaches gh_passed, and no_lost_wakeups_statement without the exception is false.
A reader of a live stale source has been told, unless a walk of its went Clean over a stale source.
✓ No axiomsFor any edge from a live, stale source to an observer, after a whole program: the observer is stale or queued, or on the running stack, or in gh_over, which holds the computations whose check walk ended and went Clean while a slot held a live, stale source, since their latest run start. The source's announcement flag is not a disjunct here, so a reader that read a memo left stale and took no MarkReaderCheck breaks this statement: reader_mark_off_fires.
Premise: engine_settled holds at the start.
No lost wake-ups, when no walk has passed over a stale source.
✓ No axiomsAfter a whole program whose final gh_passed is empty, every observer of a live, stale source is stale, queued or running, or the source holds its announcement flag. No theorem yet says which programs keep gh_passed empty.
Premises: engine_settled holds at the start and nothing_passed holds at the end. The premise rules out one route to a lost wake-up by name, so this is a statement about every other route to an uncovered edge. It does not say a stale node's next run will happen.
Headline statement: every program keeps every observer of a live stale source covered.
✓ No axiomsAfter any whole program starting from engine_inv, every observer with an edge from a live, stale source is itself stale, queued or running, or the source holds its announcement flag.
Every engine function keeps the invariant with wake_ok.
✓ No axiomsengine_inv holds across run_top, update_if_necessary, mark_check, mark_dirty, notify_check, notify_dirty, and every step of a run.
A new graph with the current flags satisfies the invariant with wake_ok.
✓ No axiomsA later mark of a stale or clean live memo leaves every observer stale, queued or running.
✓ No axiomsFrom wake_ok, when mark_check or mark_dirty of a live memo returns, each computation with an edge from the memo is stale or queued, or on the running stack. An effect in its cleanups, or disposed mid-body, ignores the mark, and is on the running stack: engine_settled carries that.
Premises: the invariant with wake_ok holds, and the memo is live. wake_ok says nothing of a disposed source, whose reader can be uncovered: see disposed_stale_source_read.
A memo stale when its body returns is stale when its run returns, holding its announcement.
✓ No axiomsThis covers only the tail of a run, from the body's return to the run's. If the memo is stale at that point, it is still stale when run_memo returns, with n_unannounced set, so its next mark tells its observers again. A mark received earlier in the body can be cleared before the body returns: see marks_survive_run_statement.
Premises: the settled invariant holds at the start, the node is a memo, and run_memo returns.
A run whose value, status and failure hold still marks no observer.
✓ No axiomsEach node's freshness and the effect queue are as they were when the body returned. Marks raised during the body, by writes in it or by other nodes' runs, are outside this statement, which covers what the end of the run adds. A memo with CmpNever or CmpThrows tells its observers whatever the value: that is what those comparers ask for.
Premises: the node is a memo with the CmpEq comparer, its stored view at the return of run_memo equals the view before the run, and run_memo returns.
A moved run marks every observer Dirty, apart from the computation that was current.
✓ No axiomsWhen run_memo returns with the memo's stored view changed, or a comparer other than CmpEq, each observer that takes marks ends Dirty. The exception is the computation current at the run's start: NotifyDirtyExcept skips it. On a memo that loses a read: check_resolves_over_moved_source. On an effect, the same skip loses a re-run: effect_resolves_over_moved_source.
Premises: run_memo returns, and the observer is not the computation current at the start. An observer takes marks when it is a memo, or an effect outside its disposal and its cleanups.
The notice of a moved run leaves the computation it skips short of Dirty.
✓ No axiomsnotify_dirty_except of a source, with a computation to skip that has not yet read the source in its current run, leaves that computation short of Dirty if it was short of it. A memo among the other observers can still tell it Check. skip_removed_fires shows this fails when the skip is removed.
A moved run's end leaves the computation current at its start short of Dirty when it has not read the memo.
✓ No axiomsIf the computation current when run_memo started has not read n in its current run and is short of Dirty when the run's body returns, it is short of Dirty when the run returns. This is the skip of NotifyDirtyExcept, the half moved_marks_except_running leaves out. A computation that is the memo itself is outside this statement.
Premises: the current computation is another node that has not read n in its current run, and run_memo returns.
After a run, a live computation's source list is its tracked reads since its latest run start.
✓ No axiomsThe source list holds those reads in order, with a read of the source just read adding nothing, as sources_add stores them. A nested run of the same memo starts over: reads of the outer run ahead of it have no slot, as nested_self_run_ends_clean_and_wrong shows. So "the run" here is the latest to start, which is the reason this is not run_end_edges_are_reads_statement.
Premises: the settled invariant holds at the start, the computation is not on the running stack, run_memo or run_effect returns, and it is not disposed at the end.
After a run with no nested self-run, a live computation's source list is the reads of that run.
✓ No axiomsThe source list holds the run's tracked reads in order, with a read of the source just read adding nothing, as sources_add stores them. gh_nested holds a computation when a run of it started inside its own, so the premise says that did not happen.
Premises: the settled invariant holds at the start, the computation is not on the running stack, run_memo or run_effect returns, it is not disposed at the end, and it is not in gh_nested at the end.
Entering and leaving a HostedFrame around body followed by EndRun/Clear equals hosted n body composed with EndRun/Clear.
✓ No axiomsMatches the .NET EnterHosted/LeaveHosted decomposition in Memo.Run, Effect.RunBody,
EffectOn.Run, and Boundary.Run (Core.fs): replacing the closure-taking RunHosted wrapper
with EnterHosted before the body and LeaveHosted in the outer finally ahead of sources.EndRun/Clear
yields identical engine states and outcomes without allocating a delegate or second exception handler.
Ranvier.Pure.Scheduler
Every engine function keeps the scheduler's invariant, at every fuel.
✓ No axiomsWhen a function returns, the scheduler's invariant still holds with the same in-progress effect, except that execute_effect of n starts with n in progress and ends with none. The current computation, the untracked flag, the batch and pull depths and the flushing flag are back at their starting values. A flush newly owed was owed from batch depth 0. Nodes keep their kinds, a disposed node stays disposed, a disposed effect's run count and EvRun count stay put, the trace only extends, owners keep their hosts, and the cleanup events and held cleanups of a host rise by at most its registrations. run_cleanup and teardown are allowed one more per cleanup they were handed, which the detached list held before.
Premises: the invariant holds at the start, and the function's own premise, as listed in sched_ok. A function that gets stuck or runs out of fuel returns nothing, and is outside this guarantee.
A new graph satisfies the scheduler's invariant.
✓ No axiomsThe invariant holds of init under any flags, with no effect in progress.
A whole program keeps the scheduler's invariant.
✓ No axiomsIf the invariant holds at the start, with no effect in progress, and run_top returns, it holds in the final state.
An effect has at most one live queue entry, and its queued flag says whether it has one.
✓ No axiomsAfter a program, every node has at most one entry in the live part of g_queue, and its queued flag is set exactly when it has one. So queue_once holds of every node. During resolve_walk of an effect n in Execute, the same holds with one exception: n's flag is set with no entry, since it has been dequeued. execute_effect ends with that exception gone.
Premise: the scheduler's invariant holds at the start, and for the second and third parts its in-progress effect is n. That invariant includes this conclusion, so the theorem is a preservation statement; queued_at_most_once_new_graph discharges the premise for a program on a new graph.
On a new graph, an effect has at most one live queue entry, and its queued flag says whether it has one.
✓ No axiomsAfter a program run from init under any flags, every node has at most one entry in the live part of g_queue, and its queued flag is set exactly when it has one.
A flush entered during a flush changes nothing.
✓ No axiomsGiven any positive fuel, run_flush with g_flushing set returns the state it was given.
A program at top level leaves no flush owed.
✓ No axiomsIf run_top starts with no batch, no stale read and no current computation, and returns, then g_flush_owed is false at the end, whether or not an effect is queued.
Premise: the scheduler's invariant holds at the start, with no effect in progress. This says nothing of effects still queued: read_move_leaves_effect_queued and failed_batch_leaves_queue each end with an effect queued and no flush owed.
A flush that returns leaves an empty queue and every live effect Clean and unqueued.
✓ No axiomsWhen run_flush starts outside a flush and returns, g_queue is empty and its head is 0, and each effect that is not disposed is Clean with queued unset. This needs no premise on whether a body failed.
Clean is a mark: the effect has none left to act on. It does not say the effect read up-to-date values, and this conclusion holds on three Confirmed lost wake-ups: self_marking_wake_lost (self_marking_cleanup_left_behind), walk_passed_source_marked and effect_resolves_over_moved_source. It does not say a marked effect ran either: flush_reruns_dirty holds the rerun. A disposed effect can stay stale. A flush that gets stuck or runs out of fuel returns nothing, and is outside this guarantee.
Premise: the scheduler's invariant holds at the start, with no effect in progress.
A live effect that is Dirty at its dequeue, or raised to Dirty by its walk, runs again, unless it is disposed first.
✓ No axiomsDirty at the dequeue. When execute_effect of a live, Dirty effect returns, its EvRun count has risen by at least one, or the effect is disposed.
Check at the dequeue. When its resolve_walk leaves it Dirty, and execute_effect returns, its EvRun count has risen by at least one from the walk's end, or the effect is disposed.
The disposal is a cleanup of its discharge or of a run in its walk: run_effect tests for it ahead of the body. This is the rerun guarantee beside flush_returns_clean, which holds of an engine that clears marks and never runs. A walk that leaves the effect in Check is outside it: effect_resolves_over_moved_source resolves Clean with no run over a source that moved.
Premises: the scheduler's invariant holds with n in progress, n is an effect, and a flush is running.
A failing effect body returns, with its failure in the effect's status.
✓ No axiomsWhen an effect's body ends in Fail y, run_effect_body returns, the effect's status is StError and its failure is y, and the only event after the body's is EvFail n y. The queue and its head are as the body left them. This answers Effect.RunBody's handler (Core.fs 4866). drain_continues is what happens next.
Premises: the body's result is Fail y, from the state run_effect_body starts it in, and the effect exists at the body's end. The edges there are coherent, a premise this theorem takes and does not derive: engine_settled holds it at a function's return, and no theorem states it at a body's end.
The flush goes on after an effect.
✓ No axiomsWhen the entry at the head of the queue is n, drain consumes it, and once execute_effect of n returns, the rest of drain is the same call on the state it returned. This holds of every result execute_effect returns, whatever the effect's body did: body_failure_contained gives the return for a failing body.
A failing cleanup returns, with its failure recorded on the owner's sink.
✓ No axiomsWhen a cleanup's body ends in Fail y, run_cleanup returns, the failure is appended to the errors of the owner's sink, or of the owner when it has none, and the only event after the body's is EvFail of the host. This answers Owner.DisposeScope's handler (Core.fs 1171-1184). teardown_continues is what happens next.
Premises: the scheduler's invariant holds, the owner exists, and the body's result is Fail y, from the state run_cleanup starts it in.
A teardown goes on after each step.
✓ No axiomsOnce a cleanup or a child's release returns, the rest of teardown is the same call on the state it returned, with that step gone. Together with cleanup_failure_contained, a failing cleanup leaves the steps behind it to run. A child's release has no outcome of its own: its failure is a cleanup of the child's scope, which the same theorem covers. The scenario flush_child_release runs that on the F#.
A failing late cleanup returns, with its failure recorded.
✓ No axiomsA cleanup registered on a disposed scope runs under detached. When its body ends in Fail y, the detached call returns with the failure appended to the errors of the owner's sink, or of the owner when it has none. This answers Owner.RunLate (Core.fs 1025-1033). exec then goes on with the command after CCleanup, by late_registration_immediate.
Premises: as for cleanup_failure_contained, from the state detached starts the cleanup in.
A failing memo run returns, with a failure in the memo's status.
✓ No axiomsWhen a memo's run fails with y, run_memo returns and the memo's status is StError. Its failure is y. The one exception is a memo that already held StError and y: Core.fs 4266-4274 then consults the comparer, and a comparer that throws z replaces the failure with z, as Core.fs 4275-4279 does. A reader takes the failure from the status. This answers Memo.Run's handlers (Core.fs 4247-4261).
The run fails with y in two ways, both in the premise on r: the body's result is Fail y, or the body breached a pure memo's scope, which sets n_violated and makes y the fixed pure_scope_failure whatever the body returned (Core.fs 4248-4250). memo_scope_violation_returns and memo_comparer_replaces_failure run those two paths.
Premises: r is the body's result, from the state run_memo starts it in, and the memo exists at the body's end. The edges there are coherent, and the fuel exceeds mark_measure there, so the notice has a result. This theorem takes both and does not derive them.
A throwing comparer returns, with its failure in the memo's status.
✓ No axiomsWhen a memo's comparer is consulted and throws z, run_memo returns, the memo's status is StError, its failure is z, and its value is the one from before the run. A reader takes the failure from the status. This answers Memo.Run's handler of the comparison (Core.fs 4275-4279).
Premises: the body's result is Ok v, from the state run_memo starts it in. The memo exists at the body's end with no scope violation, and with the status and failure it had before the run, since otherwise the comparer is not consulted. The edges there are coherent, and the fuel exceeds mark_measure there. This theorem takes both and does not derive them.
A flush that returns ends with g_flushing false and an empty live queue.
✓ No axiomsWhen run_flush starts outside a flush and returns, g_flushing is false, pending is empty and the head is 0. This statement has a returned flush as its premise, so it alone would hold of an engine turning a Fail into no result. These theorems close that. Each containment theorem takes a sub-body's result, a Fail or for the comparer an Ok, and concludes that the enclosing function returns, with the failure recorded where the F# records it. teardown_continues takes a step's return and goes on from it.
| Core.fs | Site | Theorem |
|---|---|---|
| 1025-1033 | Owner.RunLate |
late_cleanup_contained |
| 1171-1184 | Owner.DisposeScope |
cleanup_failure_contained, teardown_continues |
| 4247-4261 | Memo.Run, a body or a scope violation |
memo_failure_contained |
| 4275-4279 | Memo.Run, a comparer |
comparer_throw_contained |
| 4866 | Effect.RunBody |
body_failure_contained |
drain_continues takes the drain on from there, and flush_survives_body and the four examples after it run each failure with an effect behind it.
returns excludes the fatal path: self_read_check_overflow is a read with no result in the model, and a stack overflow that ends the process in the F#. This covers Effect. Other IScheduled items, such as a pass, are outside the model. Effect.Execute contains each of the command language's failures, so the comment at Core.fs 3140-3142, on an effect that throws, does not apply to Effect here.
Ranvier.Pure.Ownership
A scope tears down its children and cleanups in reverse acquisition order.
✓ No axiomsdispose_scope detaches the owner's lists and then runs one merged list of steps. Each child and each cleanup held at that moment appears in it exactly once, and their acquisition counts strictly fall. So a later acquisition is torn down first, and a cleanup runs before the release of any child acquired ahead of it. This covers the lists detached at the start: a registration made during the teardown joins the emptied scope.
Premise: the owner's lists are in acquisition order, acq_ok. owners_in_order holds that of every owner after a program. The fuel in the first clause is one step less than dispose_scope is given, and a step that runs out of fuel leaves the whole call with no result.
After any program, every owner's children and cleanups are in acquisition order.
✓ No axiomsPremise: the program starts from a new graph.
Each cleanup entry runs once, and a host's cleanup events never exceed its registrations.
✓ No axiomsThe count is structural, per list entry, because a registration carries no id. These hold together:
- The bound. After a program,
EvCleanup hevents plus the cleanups still held by owners of hosthare at most the cleanups registered with owners of hosth, late ones included.g_registeredis ghost state written atCCleanup. This is a sum per host, so it alone would hold of a teardown running one cleanup twice and dropping the next. - The list. The cleanups of
schedule ls cs, in order, are exactlycs. The bodies ofowner_cleanupsareo_cleanupsreversed, for an owner inacq_ok. - The teardown.
teardownisrun_itemsover that schedule, andrun_itemsrunsrun_cleanuponce for each cleanup step and goes on with the rest.dispose_scopehands it the owner's detached entries, andowner_detachedleaves all the lists empty, so a later teardown holds none of them. - The late path. On a disposed current owner,
CCleanuprunsrun_cleanuponce underdetached, with no write to the owners.
Premises of the bound: the scheduler's invariant and the bound hold at the start. cleanup_once_new_graph discharges both for a program on a new graph. An entry's body can itself register or dispose, and those are further registrations and further steps.
On a new graph, each cleanup entry runs once, and a host's cleanup events never exceed its registrations.
✓ No axiomsThe count is structural, per list entry, because a registration carries no id. The second part is cleanup_entries, as cleanup_once describes it.
A disposed computation holds no source edges once its run has ended.
✓ No axiomsAfter a program, a disposed node that is not on the running stack has no slots, no edge from any source, and appears in no source's observers. A computation disposed mid-body links edges until its run ends: disposed_running_observer_stays_clean.
Premise: engine_settled holds at the start. That invariant's b_disposed states the slots clause, so this is a preservation statement. disposed_no_edges_new_graph discharges the premise for a program on a new graph.
On a new graph, a disposed computation holds no source edges once its run has ended.
✓ No axiomsA disposed effect never runs again.
✓ No axiomsFrom a state where the effect is disposed, a whole program, a flush or a drain that returns leaves it disposed, with n_runs unchanged and no new EvRun n in the trace. The drain clause covers a disposal mid-flush: from the loop head after the effect that disposed it, its own entry is dequeued with no run, as queued_effect_disposed_skipped has it. The execute_effect clauses are that dequeue, which changes only queued, as Core.fs 4785 does. A body in progress at its disposal keeps running to its end: this is about later runs.
Premises: the scheduler's invariant holds at the start, with no effect in progress, or for execute_effect with this effect in progress. A drain starts during a flush.
A disposed memo answers from what it stored, without running.
✓ No axiomsA read of a disposed memo that returns leaves every node, the trace and the queue as they were, so no body ran and nothing was scheduled. It answers Fail of the stored failure when the status is StError (0 when n_failure is None), and otherwise Ok of the stored value. Core.fs 4372-4376 documents that a disposed memo "still answers reads, with the last value it computed".
That stored value need not be a computed one, and need not be up to date. A memo disposed before its first run answers the default: disposed_unread_answers_default. The reference tier answers from the signals at the disposal, and BUGS.md holds that difference as disposed_unread_memo_value and write_then_dispose_memo_current_value, Awaiting ruling. A tracked read can still add an edge from the disposed memo: disposed_stale_source_read.
A cleanup registered on a disposed scope runs at once.
✓ No axiomsOn a disposed current owner, CCleanup b k counts the registration, runs the cleanup under detached, requests a flush, and only then continues with k, with no write to the owner's cleanup list. When the whole command returns, the trace starts with the starting trace followed by EvCleanup of the owner's host.
Premises: the current owner is disposed, and for the second clause the scheduler's invariant holds and the fuel leaves the cleanup at least one step.
A node attached to a disposed scope is disposed at once.
✓ No axiomsattach on a disposed owner releases the node first. When it returns the node is disposed, and it holds a link with no generation. So an effect created on a disposed scope is disposed before the mark of its creation, and disposed_effect_never_runs applies from there: late_registrations_run_at_once has such a child.
Premises: the owner is disposed, the node exists, and the scheduler's invariant holds.
Detaching a stale link changes nothing.
✓ No axiomsunlink of a link whose generation is not the owner's current one returns the state it was given. A teardown bumps the generation before its first step, so a child disposed during that teardown takes this path.
This pins the model's check and no reachable behaviour. On reachable states owner_without matches on child and acquisition, and a later generation holds no such link, so the check is redundant there. The F#'s check guards Prev and Next of a detached list (Core.fs 1053-1072), which the model does not have.
Premise: the owner exists.
Ranvier.Pure.WholeGraph
A well-behaved program keeps gh_passed empty.
✓ No axiomsAfter a whole program from a new graph, gh_passed is empty: each computation that resolved Clean did so over sources that were clean, disposed or holding their flag. wake_ok follows: well_behaved_no_lost_wakeups.
Premises: the program's end state has every memo outside the self-dirtying case, and every effect only reads. A CmpNever comparer falsifies the conclusion: cmp_never_passes_source. So does clearing f_unannounced: witness_302. An effect that writes or registers a cleanup is unproved either way.
A well-behaved program leaves no lost wake-up.
✓ No axiomsEvery observer of a live stale source is stale or queued, or on the running stack, or the source holds its announcement flag.
Premises: as well_behaved_nothing_passed.
A read answers from the current signals, in a well-behaved program.
✓ No axiomsAfter a whole program from a new graph, a read of a node outside the self-dirtying case answers what the node denotes over the current signals: a signal its value, a live memo its body, with each read in that body answered the same way, and a disposed memo what it stored, as Core.fs 4372-4376 documents.
Premises: the program's end state has every memo outside the self-dirtying case and every effect only reading, and the read returns.
The statement speaks at a program's end. A read in an open batch or a body is unstated. A read here can settle a flush, and the answer holds across it.
The form over the node alone, with its other nodes free, is false in a state with a queue: read_settles_writer. It is false at quiescence too: read_quiescent_falsified. The form with no exception for a disposed memo is false: glitch_free_read_falsified.
Convergence: at quiescence, every effect ran, and its last run read and logged what its sources now denote.
✓ No axiomsAfter a whole program from a new graph that leaves no live queue entry and nothing running, each live effect is Clean and has an EvRun in the trace. Each source of a tracked read in its last run has a recorded read, each answering what the source denotes over the current signals. Its last run's EvLogs are the logs of a run of its body with each tracked read answered by the denotation and each untracked read by some value, or, when its target is a memo, by some failure. An untracked read is entitled to no more: its source can move with no run, and the state records no answer, so a log of the read's value can hold any value. By reading, with the mutant run unfinished: a log after an untracked read of a memo can be absent, through the failure case. With no untracked read in the body, the body gives one result over its recorded reads and over the denotation, with the logs of its last run, and the trace ends that run with those logs, followed by an EvFail when the result is a failure.
Premises: the program's end state has every memo outside the self-dirtying case, and every effect only reads. Batches and computed read targets, in memos and in effects, and an effect's untracked reads are inside the premises: widened_forms_reached, untracked_read_reached.
Exclusions from an effect's body:
- A write rests on a counterexample:
effect_resolves_over_moved_sourcefalsifies the conclusion (effects_only_read_needed). This premise is provisional, pending the owner's ruling on that entry. - A cleanup, a disposal, and an effect or other node created in the body rest on the proof's reach. They are unproved by choice of scope: no proof was attempted, no counterexample is known, and the owner has been told.
quiescent excludes the queue failed_batch_leaves_queue leaves. convergence_reached reaches every premise on a live effect over live memos. The form over all programs is the Open convergence_all_statement.
Ranvier.Pure.Refinement
A read or a walk step on any readable node ends, and raises no measure.
✓ No axiomsEvery memo body in Sh meets body_ends, with its reads below its own id. From a state of gd under a flush or a batch, read_node and update_if_necessary end at enough fuel, in gd. The rank of the id bounds the memo calls, the body bounds each run and the slot count bounds each walk.
mu, the sum of the stale memos' weights and the live queue entries, does not rise. A run takes wt n off, and its marks add at most cost n, half of it. A read of a memo left stale by its own run marks the reader, within the other half.
The drain ends: each entry it takes lowers mu.
✓ No axiomsFrom a state of gd with the flush open and no current computation, drain ends at enough fuel. execute_effect raises no mu, and taking an entry takes one off the live queue.
The engine answers on a refinable program where the reference settles, when every body meets body_ends.
✓ No axiomsFor a well-formed, refinable program with bodies_total, if the reference gives a trace of the history under some order, some fuel gives the engine's trace.
The measure of the drain is mu: the weights of the stale memos and the live queue entries. A run of a memo pays for its own marks and for a read's mark of its reader, and each entry the drain takes lowers mu: drain_ends and reads_end. The reference's success gives each input's target: inputs_total_of_runs.
bodies_total reads a body over all answers to its reads, so it fails on a path no run takes, and no counterexample backs it on such a program: bodies_conservative. Deriving it from the reference's success is open: answers_where_reference_settles in BUGS.md.
refinable alone is not enough: refinable_alone_no_answer. There the reference has no answer at the fuel and order computed, so that theorem does not refute the form with the reference's success. engine_of_answers_falsified refutes the statement with neither refinable nor bodies_total, which is engine_answers itself: its effect reads and then writes, so it fails both.
Weak refinement: on a refinable program, the engine's settled view is the reference's, at every batch prefix.
✓ No axiomsFor each fuel, each trace engine_of gives on a refinable program extends to each batch prefix of the history, and the prefix's trace has the observe_settled of the reference's trace at that prefix.
Premises, beyond well_formed_program, each named by refinable:
memos_below, under the rankRk: every read of a memo's body, on every path a stuck path included, reaches a node of lower rank. The theorem holds for every rank, so a memo reading a higher id is covered:reads_higher_refinable.well_formed_programasks for some rank over the paths that return, andmemos_belowasks for one over every path.effects_read_only: an effect's body holds no write, cleanup or untracked read. Effect cleanups and child effects are excluded by the owner's choice, with no proof attempted. Effect writes are excluded pending the ruling oneffect_resolves_over_moved_source. An untracked read rests on a counterexample:redundant_run_reads_untracked.no_memo_disposal: the history disposes no memo. This rests on the two counterexamplesdisposed_unread_memo_valueandwrite_then_dispose_memo_current_value, both of which reproduce on the F#, Closed inBUGS.md(Core.fs 4372-4373). It also excludes a memo disposed where its stored value is current, such ashost_read_then_dispose_memo.
erase gives every memo Pure and CmpEq. A default-policy memo returning a new reference value each run, or nan, is CmpNever in the model: this theorem does not cover it, and cmp_never_passes_source under Confirmed in BUGS.md shows it losing updates.
The unconditional statement is the Open weak_refinement_statement. engine_answers is a separate obligation: see engine_of_answers_statement.
Exact refinement, where the engine and the reference run the same effects in the same order.
✓ No axiomsOn a refinable program, with an order under which every batch prefix has the same sequence of EvRuns in the engine's trace and in the reference's, the two traces are equal at every prefix.
With equal EvRun sequences, logs, failures, disposals and host reads agree event for event. The premise runs_agree excludes a redundant run (batch_restored_value_reruns, S07, and diamond_marks_running_effect, S15), a missed run and a reordering. No theorem derives runs_agree from the absence of redundant runs: see runs_agree_bridge in BUGS.md. The unconditional statement is the Open exact_refinement_statement.
A refinable program meets the premises of convergence at every batch.
✓ No axiomsThis is the link between well_formed_program and well_behaved_program, effects_only_read and quiescent. Each gap between them, and what closes it:
- Rank.
memos_acyclicgives some rank over the paths that return.pure_attakes its rank from the classRank, and the theorem holds for every rank, so a memo may read a higher id.erasekeeps ids, shifted by one so that node 0 exists, andmemos_belowranks the shifted ids. - Stuck paths.
memo_reads_belowsays nothing of a path with no result, andbody_purecovers every path.memos_belowasks for every path, so a memo reading a node of equal or higher rank on a stuck path is outside the theorems, conservatively. By reading, such a read has no effect on either side's answer. EVar 4096.expr_no_prevaccepts it andexpr_plainrejects it.renamecloses this gap with no premise:rvmoves a body's variables offprev_var, so a renamed body's expressions are plain (plain_rename) and the engine's binding of the previous value is out of reach of every body.CmpEq.erasechooses it for every memo. A default-policy memo returning a new reference value each run, ornan, isCmpNeverin the model, so neither this theorem nor the refinements cover such a memo.cmp_never_passes_sourceshows that memo losing updates.- Memo logs.
well_behaved_memoallowsCLog, and the reference discards a memo's logs.engine_ofprojects them out of the trace, which is what the reference's semantics asks for, so the refinements say nothing about how often a memo's body runs. - Effects.
well_behaved_effectallows writes, cleanups and untracked reads.effects_read_onlyrejects them, as the docs ofweak_refinement_exceptsay.
The EvRuns of a flush follow the entries its drain takes.
✓ No axiomsFor a refinable program, take the state of the engine at a batch's flush, and let runs be the flush's EvRuns and Q the entries the drain takes, in the reference's ids. Then:
runsis a sublist ofQ: an entry whose effect is clean or disposed is skipped.Qextends the live queue at the flush's start, in order:live_queue_ofis the head ofQ.- Under
queue_steady,runsis ordered byengine_order.
The last conjunct is conditional on its premise: queue_steady is a statement about the computed drain, not a class of programs. What this theorem delivers for every refinable program is "runs follow the drain". The last conjunct with no premise is the Open engine_order_exact_statement, and engine_order_exact_falsified refutes it for the queue at a flush's start. That says nothing of history_order, the order that fits a whole history.
history_order is an effect order, so it can instantiate exact_refinement_except.
✓ No axiomsEach round's list is a permutation, whatever the engine ran.
Exact refinement under the engine's own order.
✓ No axiomsexact_refinement_except at history_order. The order conclusion holds by construction, since history_order is read from the engine's runs. The content is at the level of values: under runs_agree, logs, failures, disposals and host reads agree event for event. runs_agree has content: runs_agree_has_content has it fail at history_order on a program with a redundant run, and history_order_reached meets it on a program where the order of creation does not.
A write's walk over effect observers queues them from the last observer position to the first.
✓ No axiomsEach observer of src is an effect that is live, unqueued and outside a cleanup, each once. notify_dirty then appends their ids to the queue in the reverse of observer_items.
This covers a source's direct observers. A memo among them forwards through mark_check, depth first, under a freshness test that reads the state: BUGS.md under queue_order_through_memos names what is open.
A swap-removal moves the last observer from first in the walk's queue to the removed observer's place.
✓ No axiomsThe source's observers are pre, c, mid, m. Before the removal, the walk appends m, mid reversed, c, pre reversed. observers_remove_at_swap removes c and moves m into its position, and over the resulting observer set the walk appends mid reversed, m, pre reversed.
Ranvier.Pure.Witnesses
Regression witness for #302: with the check-walk and self-marking fixes, prog_S03 converges with or without f_unannounced.
✓ No axiomswake_ok, wake_told, and converged_all hold on [self_marking_cleanup](#self_marking_cleanup) and [self_marking_through_memo](#self_marking_through_memo).
✓ No axiomseffect_resolves_over_moved_source is now resolved: on [effect_over_moved](#effect_over_moved), the effect reruns and reads what its source denotes.
✓ No axiomsWith the check-walk fix, cmp_never_source restarts its walk on memo 5 and ends with nothing_passed and wake_ok holding.
✓ No axiomsWith the check-walk fix, [never_lost](#never_lost) wakes the effect on both writes to signal 2, logging 7 and then 8.
✓ No axiomsrefinable alone does not give an answer: an effect reading an id the program does not use has none at any fuel.
✓ No axiomsreads_unused is well formed and refinable, and no fuel gives an engine trace. The reference has no answer at fuel 5 under order_identity (computed, the last conjunct), so the theorem refutes the form with no premise on the reference, and it does not refute engine_of_answers_on without bodies_total.
Ranvier.Pure.Optimised
Under SkipOff the optimised engine is the present engine.
✓ No axiomsThe trace of trace_of_mode in mode SkipOff is the trace of trace_of, at every fuel and flags.
Under SkipOff the optimised reference engine is the present one.
✓ No axiomsA Dirty mark of a saturated node changes nothing.
✓ No axiomsMarks keep every saturated node saturated.
✓ No axiomsA Dirty mark leaves its node saturated, unless the node is a clean memo holding a due announcement.
✓ No axiomsThe exception is the memo of RecomputeScoped (Core.fs 4191) and the reason the record checks
all_saturated.
A stamped signal's walk changes nothing.
✓ No axiomsUnder stamp_ok, the notify_dirty of a signal with a current stamp returns its starting state.
An unchecked record after a walk to a clean memo holding an announcement is unsound.
✓ No axiomsFrom window_state, under SkipUnchecked, the walk of a write records the signal's stamp and leaves
its observer, memo 2, unsaturated: stamp_ok fails. The next write skips, where the present engine's
walk spends memo 2's announcement, so the two engines' states differ.
The checked record withholds the stamp from the window.
✓ No axiomsFrom window_state under SkipAll, the write's walk leaves memo 2 unsaturated, so it records no stamp,
and the next write walks.
The unchecked record breaks the simulation on a reachable program.
✓ No axiomsUnder SkipUnchecked, prog_window ends with the present engine's trace and a state that differs from
the present engine's beyond the fields of the skip: memo 2 keeps the announcement its present-engine copy
spends. SkipAll ends in sim: prog_window_checked.
A node write that keeps node_sat keeps every node saturated.
✓ No axiomsUnder SkipAll a write at an advance point advances the epoch.
✓ No axiomsA checked record keeps stamp_ok.
✓ No axiomsAfter a walk from a state meeting stamp_ok, under SkipAll, the record leaves stamp_ok and the
bound on the stamps holding.
The optimised engine simulates the present engine.
✓ No axiomsFrom sim-related states with bounded stamps, exec and oexec at every fuel both return None, or
return equal outcomes in sim-related states with bounded stamps. rsims_all states the same of every
other function of the engine, with the mode of the present engine's state left free.
Under SkipAll the engine keeps stamp_ok.
✓ No axiomsFrom a state meeting stamp_ok with bounded stamps, an oexec run at any fuel ends in one.
The optimised engine's trace is the present engine's.
✓ No axiomsAt every fuel and flags, trace_of_mode in mode SkipAll is trace_of. The queue's content and order
agree at every step, so this fixes the effect order too.
The optimised reference engine is the present one.
✓ No axiomsThe optimised engine refines the reference on refinable programs, under observe_settled.
✓ No axiomsExact refinement carries over to the optimised engine under runs_agree.
✓ No axiomsThe optimised engine answers wherever the present engine does.
✓ No axiomsA flush's order on the optimised engine is the present engine's.
✓ No axiomsThe conclusion of engine_order_exact_except holds of the optimised engine's runs, at a present-engine
state s1 equal to the optimised one apart from the fields of the skip.
Regression witness for #302 on the optimised engine.
✓ No axiomswitness_302 holds of the optimised engine's end states: without the announcement flag, the effect is
left behind.
Under SkipAll, prog_window ends in sim with the present engine.
✓ No axiomsThe checked record withholds the stamp inside RecomputeScoped, so the second write walks and spends the
announcement, as the present engine does.
Cleanups on the optimised engine: the present engine's events, and at most one per registration.
✓ No axiomsThe EvCleanup events of the optimised trace are the present engine's. After a run of the optimised
engine on a new graph, each host's EvCleanup events number at most its registrations, and each
teardown runs each detached cleanup once (cleanup_entries).
Ranvier.Pure.Collections
Direct observer attachment preserves world_well_formed and gives the observer a single entry in the source's observer set.
✓ No axiomsCovers Binding, FoldRow, ValueRow, ForwardingEdge (where source_slots is empty before linking)
and FoldReads.AddSource (where a HashSet ensures s ∉ fst <$> source_slots (sources_of w self)).
A direct observer link with its cursor at the end of its slots is an exact sources_add step and stays in world_reachable.
✓ No axiomsFormalises the boundary simulation in CORRESPONDENCE.md: each direct AddObserver call on a node whose
cursor sits at the end of its deduplicated slots equals sources_add, so arbitrary interleavings of
SourceList computations and direct collection observers remain within world_reachable and world_point.
Detaching all edges of a direct observer preserves world_well_formed and removes the observer from every source.
✓ No axiomsCovers Binding.Dispose, FoldRow.Dispose, ValueRow.Detach, ForwardingEdge.Clear, and FoldReads.Clear.
Removing a single slot of a direct observer preserves edge_match, slots_unique, and observers_once.
✓ No axiomsWhen RemoveObserverAt swap-removes the last observer in the source's ObserverSet into the vacated index and
invokes MovedIn, both ends of every remaining edge stay matched and no observer appears twice.
Every attached direct observer is visited by ObserverSet's backward walk despite concurrent swap-removals.
✓ No axiomsIn any world_point (including arbitrary interleavings of SourceList computations and direct_link /
direct_unlink observers), every attached observer c of s occupies a unique slot in observers_of w s
(held_once) and is therefore visited by walk (NotifyDirty, NotifyDirtyExcept, NotifyCheck) whenever
each intermediate mutation point comes from a world_point in which c remains attached.
Unlinking an active child link from a live parent owner removes the child and preserves strict acquisition order (acq_ok).
✓ No axiomsWhen a projection key or keyed-collection row is retired while its parent scope is still live
(l_generation l = Some (o_generation y)), unlink removes l from o_children, preserves acq_ok,
and keeps all remaining sibling children in their exact acquisition order.
Retiring an already-disposed per-key child scope is a no-op on owners and trace.
✓ No axiomsOnce a removed key's scope has been retired during a projection pass (entry.Scope.Dispose()), any later
retire call on that scope id leaves g_owners and g_trace unchanged.
SchedulePass and Schedule preserve the two-queue single-entry invariant tq_inv.
✓ No axiomsEach projection pass or lookup refresh is pending at most once in tq_passes, and each normal effect is
pending at most once in tq_queue.
No normal effect is selected while any projection or lookup pass is pending (pass_runs_before_effect).
✓ No axiomsThis is the minimum scheduling specification required by collections: whenever pending_passes st is
non-empty, the next scheduled action is ActPass p (the head of pending_passes st) and never ActEffect e.
run_passes_loop returns only when the pass queue is completely empty and reset to head 0.
✓ No axiomsEven when executing a pass schedules downstream passes (for example, a projection over another projection's
Keys), RunPasses loops until pending_passes is empty before yielding control back to the effect queue.
Core.fs's QueueDrain (queueHead - 1 preemption) refines the direct two-queue priority step.
✓ No axiomsCertifies the optimisation space in Core.fs: mutating queue[queueHead - 1] <- passDrain during effect
execution (leaving pending_effects after S h untouched) and popping passDrain on the next iteration
produces the exact same state and execution trace as a direct two-queue loop that checks passHead < passCount
before dequeueing the next effect.
write_signal_except marks every observer other than r dirty while skipping r when n is not in r's read prefix.
✓ No axiomsMatches the minimum specification for anyPending.WriteExcept(v, running) and
inFlightVersion.WriteExcept(v, running) in Projections.fs: all other readers of the summary signal are
woken (ends_dirty), while the currently pulling computation running is not self-marked if it has not yet
recorded n in read_prefix.
notify_removed marks every live observer of a retiring row memo Dirty.
✓ No axiomsWhen Projections.fs retires a removed key's row, calling notify_removed before dispose_node ensures
every live observer m of row n ends Dirty (and is queued if m is an effect), even though dispose_node
subsequently marks n disposed so n itself never recomputes again.
Every distinct companion passed to Memo.Adopt is disposed in order and exactly once when the memo is disposed.
✓ No axiomsWhether a memo adopts one companion (as in Projection.foldGroupBy / Projection.map), replaces its
companion across multiple Adopt calls, or adopts a companion after the memo is already disposed, every
distinct companion is disposed once and ad_current ends None.
When invertible = false (Projection.fold), any non-empty key-order change (had_keys = true, order_changed = true) triggers Recompute so the state equals fold_cached_keys folder zero vals next_keys even when zero keys were added, removed, or edited (Combinators.fs lines 1030–1060).
✓ No axiomsConversely, when invertible = true (Projection.foldGroup), a pure reorder with full = false preserves state without invoking Recompute.
In Projection.ApplyDiff, size entries + length adds = size seen holds if and only if zero live keys were removed (dom entries ∖ seen = ∅).
✓ No axiomsDuring Enumerate, every visited key is added to seen without duplicates, and adds collects every
visited key absent from entries (entries !! k = None). Because dom entries partitions into
(dom entries ∩ seen) ⊎ (dom entries ∖ seen) while seen partitions into
(dom entries ∩ seen) ⊎ list_to_set adds, we obtain the exact removal-count identity
size entries + length adds = size seen + size (dom entries ∖ seen). Thus ApplyDiff (Projections.fs
lines 987–993) can skip iterating entries altogether whenever entries.Count + Pass.AddedCount = seen.Count,
including when failed rows are hidden via HideLast (which leaves entries, seen, and adds intact).
A key-direct derived row (RowsByKey) occupies one inline source slot for its upstream row and still wakes Dirty when the upstream row retires.
✓ No axiomsCertifies the RowsByKey optimisation in Projections.fs and Combinators.fs: derived view rows (MapView,
SliceView, FilterView, DistinctView, SortView, GroupView, perKey) read upstream by a fixed key
'K rather than through an intermediate per-row Signal<'K>. Linking directly to up_row keeps the row memo
at a single source slot (length = 1) when up_row is its sole source, and retiring up_row via
notify_removed marks row_m Dirty without any item-signal write.
ChooseView's per-key boolean gate cuts off every Some u1 -> Some u2 edit (moved = false) while classifying Ready, Pending, and Failed chooser outcomes identically to a two-projection Option.isSome FilterView.
✓ No axiomsCertifies the ChooseView single-projection fusion in Combinators.fs:
- After settling
GR_Ready (Some u1), a subsequentGR_Ready (Some u2)transition producesmoved = falseon the boolean gate memo, resolvingChooseView'sCheckwalk toCleanwith zero view passes whilechoices.GetyieldsSome u2. - Across every
Ready,Pending(both unsettled and previously settled), andFailedtransition,classify_choice_gatematchesFilterView'spredicate = trueclassification overOption.isSome.
Lazily allocating HeldOut's signal cell and staging list refines an eager Signal<'K[]> initialized to Array.empty, preserving read values, observer status, and wake notifications while allocating nothing on empty passes.
✓ No axiomsCertifies the HeldOut<'K> lazy cell and pass-buffer optimisation in Combinators.fs:
- Initially
(eho = ([], [], false), lho = (None, None, false))satisfiesheld_out_relwith zero allocated signal or buffer. - Reading
Keys/CellallocatesSome []on demand, marks it observed, returns the exact same slice as the eager cell, and preservesheld_out_rel. - Publishing any combination of staged keys and inherited
PendingExtrakeys preservesheld_out_rel, leaveslho_cell = Nonewhenever no key has ever been held out or read, and wakes observers iff the eager cell wakes observers.
Pooling unionBuf and revisitBuf across Lookup.Invalidate error-recovery passes (with a fresh-buffer fallback on reentrant entry) revisits the exact duplicate-free union failed ∪ affected and restores the empty-buffer invariant.
✓ No axiomsCertifies the Lookup.Invalidate pooled buffer optimisation in Projections.fs:
- Whenever
failed ≠ ∅andlookup_pool_inv psholds, both the non-reentrant pooled branch (lps_busy = false) and the reentrant fallback branch (lps_busy = true) produce a duplicate-free revisit list whose elements are preciselyfailed ∪ list_to_set affected— identical to allocating a freshKeySetandResizeArrayper call. - Clearing
unionBuf,revisitBuf, andinvalidatinginfinallypreserveslookup_pool_invfor subsequent transitions.
Reinserting a single rank-changed key at its binary-search partition point produces the exact output array of a full lexicographic (rank, upstreamIndex) sort.
✓ No axiomsCertifies the SortView.updateOrder single-key fast path in Combinators.fs:
- When placed keys are unchanged and only
changedIdxchanged rank, removingchangedIdxfromoldPosleaves then - 1unchanged indicesbefore ++ afterstrictly ordered underR(i, j) := compareRanks ranks[i] ranks[j] < 0 ∨ (compareRanks = 0 ∧ i < j). - Binary search partitions
before ++ afterintopre ++ sufwhere every index inpreprecedeschangedIdxunderRandchangedIdxprecedes every index insufunderR. - Shifting
orderin-place topre ++ changedIdx :: sufyields a strictlyR-sorted permutation of allnindices, which by strict-order permutation uniqueness equals (=) the array produced by any full sort (Array.sortInPlaceWith).
An unchanged Check pass resolves clean without advancing view runs.
✓ No axiomsWhen every per-row InclusionSlot predicate or chooser re-evaluates to its
previously cached boolean inclusion flag, ensure_current_step resolves
CVCheck directly back to CVClean while leaving ivs_runs and
ivs_values unchanged.
Point flipping a boolean slot updates every prefix count by exact +/-1.
✓ No axiomsFlipping entry idx from b_old to b_new alters prefix_count bits k
only when idx < k, adding 1 if b_new is true and subtracting 1 if
b_old is true.
Splicing a batch of inclusion flips refines full filter_scan.
✓ No axiomsStarting from filter_scan rows, applying each flip (idx, b_new) via
prefix-count splice insertion or removal produces the exact key list computed
by scanning the updated row table apply_row_updates rows flips.
Hidden Excluded / Failed / Included transitions cancel or coalesce exactly.
✓ No axiomsOver two sequential slot transitions s0 -> s1 -> s2, merging per-step
membership changes keeps ISExcluded <-> ISFailed silent, cancels
ISExcluded -> ISIncluded -> ISFailed back to None, and coalesces
ISIncluded -> ISFailed -> ISIncluded to Some IKCChanged.
The subtraction guard accepts exactly the in-range Fenwick parents, each representable as a signed 32-bit index.
✓ No axiomsLeftward reinsertion preserves inverse-order array coherence (inv_order).
✓ No axiomsMirrors SortView.reinsertPlacedSlot's newPos < oldPos loop: shifting
order[old_pos - 1 .. new_pos] right by one slot while updating orderPos
and placing p_idx at new_pos preserves the bijection order <-> orderPos
and installs order' !! new_pos = Some p_idx.
Incremental single-slot insertion and key removal refine full upstream-tie-broken sorting.
✓ No axiomsUnder distinct upstream indices (NoDup (snd <$> ...)), sorted_insert on
the already-sorted list equals full_insertion_sort of (x :: xs), and
sorted_remove_key k equals full_insertion_sort over the filtered list
with key k removed.
Incremental 2-bucket updates and Members[0] winner selection in DistinctView refine distinct_scan.
✓ No axiomsUpdating row u0 from optional settled value mg_old to mg_new removes u0
from bucket mg_old (if Some), inserts (u0, k0) by ascending upstream index
into bucket mg_new (if Some), leaves every other bucket untouched, and
preserves the exact Members[0] winner sequence computed by sequential
distinct_scan over the updated rows.
Incremental Grouping move isolates untouched inner views and refines member and outer FirstIdx scans.
✓ No axiomsMoving row u0 from optional group mg_old to mg_new removes u0 from group
mg_old (if Some), inserts (u0, k0) by ascending upstream index into group
mg_new (if Some), leaves every other group's member cell completely untouched,
yields exact group_scan_members for every group (so untouched inner GroupView
readers stay asleep), and sorting active non-empty groups by FirstIdx
(Members[0].UpIdx) equals group_scan_order over the updated rows.
Bottom-up tournament build finds an optimal rank at the earliest Keys-order slot.
✓ No axiomsFor any tree height h, base slot index base, and optional slot ranks leaves:
tour_winner (build_tour h base leaves)equals the left-to-rightextreme_scanover[base, base + 2^h), and- if it returns
Some (i_win, r_win), theni_winis a settled slot in[base, base + 2^h)with rankr_win,(r_win <= r)%Zfor every settled slot in[base, base + 2^h), and strictly(r_win < r)%Zfor every settled slot strictly beforei_win.
Incremental SiftUp with early stop agrees bit-for-bit with a full tournament rebuild.
✓ No axiomsUpdating slot target in [base, base + 2^h) from leaves to leaves' (v_new at
target, leaves everywhere else) and running sift_id_step along the ancestor path of
target yields build_id_tree h base leaves', preserves exact equality whenever the
early-stop condition fires (cont = false implies nextW = oldW and nextW <> Some target),
and shifts left-justified leaves under capacity doubling (build_id_tree_double_cap) with
zero comparisons.
Winner-tree selection with sticky_select refines sequential sticky_extreme_scan.
✓ No axiomsFor any tree height h with valid slot bounds (None or < 2^h) for the previous sticky
holder sticky_prev: resolving sticky_select against tour_winner (build_tour h 0 leaves)
yields the exact same key and rank (including sticky tie preservation when the previous holder
remains tied for best rank) as a full Keys-order scan sticky_extreme_scan.
A lazily allocated partitioned map (prims, option objs) starting at (∅, None) and allocating objs only on the first non-primitive insert refines a total gmap K V across Find, Set, Remove, and Count (Platform.fs).
✓ No axiomsIn a NoDup key array prevKeys where slot idx holds pk, single-index Trim replacement preserves prevKeys with removed = [] when k = pk, preserves NoDup (<[idx := k]> prevKeys) if and only if (k <> pk -> k ∉ prevKeys), and drops precisely trim_single_removed pk k (Projections.fs).
✓ No axiomsIn a NoDup key array prevKeys where distinct slots i0 < i1 hold pk0 and pk1, updating those slots to (k0, k1) preserves NoDup iff k1 <> k0 and neither k0 nor k1 collides with an outside key, while emitting duplicate-free removals matching set difference (Projections.fs).
✓ No axiomsIndexProjection's dense positional pass transforms dense_entries 0 prev directly into dense_entries 0 cur while skipping unchanged overlap slots (prev !! i = cur !! i), skipping Keys publication iff length cur = length prev, and preserving unchanged reference-equal row values (Projections.fs).
✓ No axiomsSkipping Lookup.Refresh when syncedRun = state.Runs && state.IsCleanAndReady is identical to running Refresh, Refresh preserves ls_sync_inv on non-negative runs, and pooling affectedBuf under collectingAffected isolates reentrant notifications and restores the empty buffer (Projections.fs).
✓ No axiomsReading a cached RowEntry directly whenever ce_live e = true, and falling back to entries !! key on None or retirement (ce_live e = false), agrees with entries !! key under the live-entry invariant (Projections.fs ReadEntry, Combinators.fs EntryCache).
✓ No axiomsWhen upstream changes only [chg_start .. chg_prev_end] into [chg_start .. chg_end] (pref ++ mid_old ++ suf to pref ++ mid_new ++ suf), a fixed-length SliceView window strictly before chg_start or strictly after the edited range with constant shift relative to chg_end/chg_prev_end yields the identical slice in $O(1)$ (Combinators.fs SliceView.Enumerate).
✓ No axiomsTrimming equal shared prefix pref and suffix suf before diffing prev = pref ++ mid_prev ++ suf against next = pref ++ mid_next ++ suf (under NoDup prev) visits only mid_next for additions and detects removals only within mid_prev via membership in mid_next (Combinators.fs SliceView.Enumerate, GroupView.Enumerate).
✓ No axiomsCaching the Keys-ordered sequence of FoldRow references (orderedRows) whenever key membership or order is unchanged makes non-invertible Projection.fold recomputation over orderedRows identical to keys.Length hash lookups across arbitrary in-place row value updates (Combinators.fs ProjectionFold).
✓ No axiomsRestoring EnsureLive () immediately after keyOf value in CollectionProjection.AddOrUpdateBy prevents inserting zombie items after reentrant disposal during the selector, while agreeing identically with unguarded upserts whenever the collection remains live (Collections.fs AddOrUpdateBy).
✓ No axiomsModels the bug fix from codex-astra-plan.md §2:
col_add_or_update_by_guardedpreservescol_liveness_invwheneverselectordoes, rejecting (None) any run in whichselectordisposed the collection (cp_stopped st1 = true) without modifyingcp_items,cp_order,cp_changes, orcp_revision.- By contrast,
col_add_or_update_by_unguardedpermitsselectorto dispose the collection and then inserts(k, v)into the clearedcp_items, breakingcol_liveness_inv. - Whenever
selectorleaves the collection live (cp_stopped st1 = false), including under reentrant edits to the collection duringselector, both guarded and unguarded paths return the exact sameSome (col_add_or_update_core k v st1).
Reading a live CollectionProjection row's Signal directly and applying cached ProjectionFold adapters preserves exact equivalence with the two-level RowsOf row-memo read across steady updates, batch-restored cutoffs, generation replacement (remove + re-add), and external FoldReads or comparer failures (Collections.fs, Combinators.fs).
✓ No axiomsModels the Stage B direct collection-row contribution path from codex-astra-plan.md §3:
- When
item_sig_by_gen !! rc_gen cell = Some cell,read_direct_row cellequalsread_indirect_row item_sig_by_gen (rc_gen cell). - Under the same generation match,
fold_direct_stepproduces the identical row state(fra_gen, fra_has_value, fra_value, fra_err)and fold accumulator state(fas_state, fas_valued, fas_failed, fas_full, fas_moved)asfold_indirect_step— both whenrc_gen cell = fra_gen r(in-place update) and whenrc_gen cell <> fra_gen r(remove + re-add triggering detach and re-attach). - Writing an unchanged or batch-restored value (
eq_v (fra_value r) (rc_signal_val cell) = Some truewithrc_status = StNone,fra_has_value = true,fra_err = None,rc_gen = fra_gen) leaves bothrandfsuntouched (fas_movedunchanged, no reducer call). - For an invertible, live, unfailed changed row (
rc_status = StNone,fra_has_value = true,fra_err = None,eq_v (fra_value r) (rc_signal_val cell) = Some false), the replacement adapter computessub_fn (fas_state fs) ext (fra_value r) ≫= fun s' => add_fn s' ext (rc_signal_val cell)under the externalFoldReadscontextext, settingfas_full := trueif either fails.
An untracked read (ProjectionFold.Read Peek) on a clean, ready (StNone, stale_live = false) memo returns Ok (n_value d) in identical state s with zero edge mutations, trace emissions, or refresh allocations.
✓ No axiomsModels the Clean /\ StNone Peek fast path in ProjectionFold.Read (Combinators.fs): because read (S (S f)) m false s runs read_node (S f) m inside untracked, g_current is None during track m (so live_current = None and no dependency edge is added), stale_live d = false bypasses refresh_or_pull, and n_status d = StNone directly returns Ok (n_value d) while restoring s verbatim.
When SortView's linear order scan confirms every adjacent pair (rank, up_idx) is ordered under rank_up_le (LocallySorted / Sorted), full_insertion_sort is the identity.
✓ No axiomsModels the certified strict-order fast path for sorted reactive collections: if incoming (rank, up_idx) pairs already satisfy pairwise rank_up_le (whether witnessed by the computable scan is_rank_up_sorted, adjacent LocallySorted rank_up_le, or standard Sorted rank_up_le), full_insertion_sort xs leaves xs unchanged, justifying skipping insertion-sort allocations altogether.
When incoming ranked items are strictly descending by rank (LocallySorted (fun x y => (x.1.2 > y.1.2)%Z) xs), full_insertion_sort xs produces rev xs in linear pass without general sorting (Combinators.fs:3365).
✓ No axiomsExcluded tail rows preserve the dirty splice and its changed window.
✓ No axiomsRanvier.Pure.Concurrency
Under ThreadAffinity.Guarded, graph_enter succeeds if and only if the calling thread is cs_owner_thread, leaving the state unchanged on failure.
✓ No axiomsMatches Graph.Enter and Graph.AssertOnGraphThread (Core.fs lines 2786–2790, 3248–3253):
any off-thread call raises InvalidOperationException before mutating the graph, based on thread
identity alone regardless of SynchronizationContext.
Under ThreadAffinity.Serialised, graph_enter grants exclusive ownership to a free caller on the construction context (must_release = true), allows reentrant entry by the current holder (must_release = false), and rejects any concurrent thread or wrong context.
✓ No axiomsMatches Graph.Acquire and Graph.Enter (Core.fs lines 2736–2749, 2792, 3274–3306):
- If
cs_holder cs = me, a nested entry succeeds withmust_release = falseand keepscs_holder = me. - If
cs_holder cs = 0andctx = cs_context cs, the outermost entry setscs_holder = meand returnsmust_release = true. - If
cs_holder csholds another thread (cs_holder cs <> 0 /\ cs_holder cs <> me) orctx <> cs_context cs, entry fails (None).
A nested (reentrant) entry on the holding thread leaves must_release = false, and only the outermost Entered scope releases cs_holder back to 0.
✓ No axiomsCertifies that Entered (if this.Enter operation then try body () finally this.Release () else body ())
never releases holder prematurely during a nested call on the same thread.
The PostQueued / PumpFromDispatcher / Release protocol preserves drain_guaranteed and re-posts a drain on exit whenever a contended pump was skipped.
✓ No axiomsProves the handover comment at Core.fs lines 2756 and 3229 (a full fence ensures the inbox check
observes every enqueue whose drain found the graph held by the exiting thread):
post_queuedestablishesdrain_guaranteed.- If
PumpFromDispatcherruns while another thread holds the graph (cs_holder cs > 0), skipping the pump (pump_from_dispatcher_contended) preservesdrain_guaranteedbecausecs_holder > 0. - When the holding thread subsequently calls
graph_release,cs_pump_postedis guaranteed to betruewhenevercs_inboxis non-empty, so no queued work item is ever stranded.
graph_drain_inbox drains every item in FIFO arrival order, isolates throwing items into ds_root_errors without stranding later items, and requests a flush whenever at least one item ran.
✓ No axiomsMatches Graph.Drain (Core.fs lines 3198–3205, where one bad continuation must not strand the rest of the
inbox, for the same reason one bad effect must not strand the flush queue):
- Returns
ran = length (ds_inbox ds)and emptiesds_inbox. - Appends every
InboxOk effin arrival order tods_applied. - Appends every
InboxThrow errin arrival order tods_root_errors. - Sets
ds_flush_requested = truewheneverds_inbox ds <> [].
Exactly one of pd_try_claim (drain execution), pd_try_close (cancellation), or pd_try_close (graph disposal) succeeds from PdWaiting (0), and all subsequent attempts are no-ops (false).
✓ No axiomsProves the PendingDispatch<'T> contract (Core.fs lines 1747–1775):
- Starting from
st = 0, the first transition (pd_try_claimorpd_try_close) returnstrueand movesstto1or2. - Once
stis1(claimed by the drain) or2(cancelled or abandoned on disposal), bothpd_try_claimandpd_try_closereturn(st, false), so a cancelled/abandoned item is skipped by the drain and a claimed item cannot be cancelled or faulted by disposal.
is_clean_and_ready_bits holds if and only if freshness is Clean and status has neither Pending nor Error set, independent of Uninitialized and Stale bits.
✓ No axiomsMatches StatusBits.isCleanAndReady (Core.fs lines 173–174): masking status with 3uy ignores both
Status.Uninitialized (4uy) and Status.Stale (8uy) while rejecting Status.Pending (1uy) and Status.Error (2uy).
Splitting Memo.Value into an inline is_clean_and_ready_bits fast path and a slow fallback preserves read_node and tracked read identically across all states.
✓ No axiomsMatches the #else .NET split between Memo.Value (GetFast) and Memo.ReadSlow (Core.fs lines 5526–5557).
Splitting Signal.Value set into inline Enter / unjournaled cutoff check and SetChanged / SetJournaled / SetAfterAcquire cold helpers refines the Entered setter identically and still enforces Guarded affinity before cutoff.
✓ No axiomsMatches Signal.Value (set), SetSlow, SetChanged, SetJournaled, and SetAfterAcquire (Core.fs lines 4450–4547):
journaled equal writes still append to the journal, and off-thread equal writes under ThreadAffinity.Guarded
still fail (None) before any cutoff check is reached.
Encoding EqualityComparer<'T>.Default on value types and ReferenceComparer<'T> on reference types as null, and null as NullComparer<'T>.Instance, preserves exact comparison and exception outcomes across value, reference, custom, throwing, and faulty-null comparers.
✓ No axiomsMatches NullComparer<'T> and ComparerSentinel.encode / ComparerSentinel.equals (Core.fs lines 4304–4337) and
Signal.SetFast / Signal.SetCustom (Core.fs lines 4454–4493):
- for value types (
is_val_type = true),EqualityComparer<'T>.Defaultmaps toSentDefaultNull(null), dispatching directly toval_eq a bwithout interface dispatch; - for reference types (
is_val_type = false),ReferenceComparer<'T>maps toSentDefaultNull(null), dispatching directly toref_eq a b(obj.ReferenceEquals) without interface calls or generic dictionary lookups; - a faulty policy returning
nullmaps toSentNullComparer(NullComparer<'T>.Instance), still raisingNullReferenceException(CmpNullRef) on comparison; - any other comparer (
EqualityComparer<string>.Default,StructuralPolicyreference comparers, or custom/throwing comparers) is preserved unchanged asSentCustom.
check_fast_write_token passes inline if and only if the graph is unjournaled and either Unchecked or Guarded on its owner thread (short-circuiting tok = -1 before reading OwnerThreadToken.Current and rejecting uninitialized 0 threads under Guarded), and signal_set_token_fast refines signal_set_entered identically.
✓ No axiomsMatches OwnerThreadToken (Core.fs lines 1792–1807), Graph.fastWriteToken (Core.fs lines 2476–2479), and
Signal.SetFast / Signal.SetSlow (Core.fs lines 4454–4506):
- Since
tok >= 0is checked first,tok = -1(Serialisedor journaled) short-circuits tofalsewithout readingOwnerThreadToken.Current, routing allSerialised(including reentrant) and journaled writes toSetSlow. - Under
Guardedwithout a journal (tok = owner_tok >= 1),tok = 0is false andtok = caller_tokholds iff the caller is the owner thread (in particular, an uninitialized thread withcaller_tok = 0is rejected). - Across all affinities, threads, and journal states,
signal_set_token_fastequalssignal_set_entered.
Calling RequestFlushFromEntered after graph_enter has already succeeded skips a redundant Enter/Release round-trip identically to RequestFlush.
✓ No axiomsMatches Graph.RequestFlushFromEntered called from Signal writes, Graph.RunBatchCore, and
Graph.Drain (Core.fs): once graph_enter me ctx cs = Some (cs_entered, must_rel), re-entering
the same thread immediately returns Some (cs_entered, false) with no state change or release duty,
so calling RunFlush directly on cs_entered preserves concurrency and flush behavior across all
ThreadAffinity modes.
Caching usesJsIdentity once per Graph and short-circuiting Graph.EncodedComparer to null (SentDefaultNull) produces the exact same sentinel and comparison outcomes as resolving options.Equality.Comparer<'T>() and encoding per node.
✓ No axiomsMatches Graph.usesJsIdentity and Graph.EncodedComparer<'T>() (Core.fs), plus RowsOf / RowsByKey pre-encoded
row comparer reuse (Projections.fs): under JsIdentityPolicy on Fable (is_val_type = false, JS ===),
Comparer<'T>() always resolves to ReferenceComparer<'T> (CmpRefIdentity), whose encoded sentinel is SentDefaultNull.
Encoding TimedOptions.Comparer (Some c vs None via Graph.EncodedComparer) and short-circuiting reference-type seed checks in Identity.sameSeed preserve exact comparison and exception outcomes across value, reference, custom, throwing, and faulty-null comparers.
✓ No axiomsMatches Timed (Timed.fs), StreamMemo (Streams.fs), and Identity.sameSeed (Api.fs):
encode_optional_compareragrees witheval_optional_comparerfor all policies (PolJsIdentityandPolCustom) and override options (Some candNone).same_seed_encodedchecksref_eq a bonce on reference types (is_val_type = false), skips redundant second checks onSentDefaultNull, and preserves custom/throwing/null outcomes identically toref_same_seed.
Splitting pullable (StreamMemo, AsyncMemo, Boundary) and push (AsyncSource, Timed) Value/TryValue reads on is_clean_and_ready_bits and is_unready_bits preserves exact read outcomes and dependency tracking across all freshness, disposal, and status states.
✓ No axiomsMatches AsyncSource.Value, AsyncMemo.Value/TryValue, Boundary.Value/TryValue (Core.fs), StreamMemo.Value/TryValue (Streams.fs), and Timed.Value (Timed.fs):
push_read_fast(is_unready_bitsfast branch + out-of-lineRaiseUnready) equalspush_read_ref.pull_value_fastandpull_try_fast(is_clean_and_ready_bitsfast path +ReadSlow/ReadTrySlow) equalpull_value_refandpull_try_reffor any slow pull semantics.
Checking is_on_graph_thread before posting (AsyncMemo.publish/publishQueued, StreamMemo.Launch/ReportFoldFailure) and passing the continuation as ContinueWith state (Platform.whenSettled/whenDone/apply/after) behave identically to Graph.Post and per-call closures across all ThreadAffinity modes.
✓ No axiomsReplacing virtual ISource dispatch on Binding (OfSignal vs OfMemo) and Editable.set_Value with concrete IsStaleNode/IsActiveNode/EnsureCurrent calls and a clean-ready Memo.Peek shortcut produces identical refresh and read outcomes across all states.
✓ No axiomsMatches Memo.EnsureCurrent / IsStaleNode / IsActiveNode (Core.fs), Binding.Execute / Binding.Run (Bindings.fs), and Editable.Value setter (Api.fs):
is_stale_node m_fr m_dispequalsm_fr <> Clean && negb m_disp.- Guarding
EnsureCurrentwithis_stale_node(Editable.set_Value) equals callingEnsureCurrentdirectly. - Concrete
Binding.Executecheck resolution distinguishesOfSignal(IsStale = false, no loop) fromOfMemoidentically toISource.IsStale && ISource.IsActive. binding_read_fast(elif memo.IsCleanAndReady then memo.Peek) equalsmemo.ReadUntracked ()for every(fr, disp, st, v, err).
Encoding struct (int * 'T) voption edits as EditState(version, value) with Unedited.Version = -1 and EditComparer's negative-version short-circuit refines the option-tuple edit representation across cutoff equality, Reset, IsEdited, and Value selection.
✓ No axiomsMatches EditState<'T>, EditComparer<'T>, and Editable<'T> (Api.fs):
edit_state_of_optmapsNonetoes_ver = -1andSome (ver, v)toes_ver = Z.of_nat ver >= 0.edit_state_eq val_eqmatchesref_edit_opt_eq val_eqfor any cutoff comparatorval_eq, regardless of the arbitrary default payload stored inunedited_state.read_edit_state(IsEdited,Value) matchesread_edit_optfor anyin_forcepredicate (covering bothEditableandDraft).
Clearing wakePosted := 0 (Volatile.Write) strictly before Enqueue (effect_queued := true) in Timed.Wake makes lost wakeups unreachable across all fine-grained atomic interleavings with off-thread Interlocked.Exchange(&wakePosted, 1).
✓ No axiomsModels Timed.OnTimerFired (TwTimerFire, setting pending_fire := true and posting a wake iff wake_posted = 0), graph-thread Timed.Wake split into two atomic steps (TwWakeClear clearing wake_posted := 0 while tw_wake_in_flight stays true, followed by TwWakeEnqueue setting effect_queued := true and keeping tw_wake_in_flight := (wake_posted =? 1)), and Timed.Execute (TwConsume). Across any interleaving tr from any invariant-preserving state st0 (and from init_timed_wake_state), tw_pending_fire st = true implies tw_wake_posted st = 1 \/ tw_wake_in_flight st = true \/ tw_effect_queued st = true, and a concurrent fire arriving between TwWakeClear and TwWakeEnqueue preserves both tw_wake_posted = 1, tw_wake_in_flight = true, and tw_effect_queued = true. By contrast, running run_bad_wake_trace with Enqueue before Clear reaches a lost wakeup (tw_pending_fire = true /\ tw_wake_posted = 0 /\ tw_wake_in_flight = false /\ tw_effect_queued = false).
Clearing drainPosted before a drain's first take, and when a dispatcher-run pump raises, posts a drain for every queued item across all fine-grained interleavings of off-thread enqueues and posts.
✓ No axiomsModels PostQueued as two atomic steps (DpEnqueue, then DpPost: CompareExchange (&drainPosted, 1, 0) and, on
success, dispatcher.Post), a posted or owner-started drain (DpDispatchStart, DpPumpStart: Drain's
Interlocked.Exchange (&drainPosted, 0) before the first TryTake), the drain's takes (DpTake, DpDrainEnd), and a
dispatcher-run pump that raises before draining (DpDispatchRaise: PumpFromDispatcher's Volatile.Write).
Across any trace from a state satisfying dp_inv, and from a new graph:
- every queued item is taken by a running drain, has a posted drain ahead of it, has its own post yet to run, or
waits for the owning thread's
Pumpafter a raising drain (dp_no_lost_drain); - a set
drainPostedalways has a posted drain yet to start, so a post that finds it set has a drain to join; - after a raising drain, the next item's post posts a new drain.
By contrast, a drain that clears drainPosted after it ends (run_late_reset_trace) strands an item enqueued after
its last take, and a raising pump that leaves drainPosted set (run_raise_keeps_flag_trace) leaves the next item
with no posted drain.
SignalPort preserves sp_inv (at most 1 queued inbox item, no lost wakeups, and zero retained payload/attribution when idle) across all traces, and coalesces any multi-write off-thread burst to its final value and attribution upon SpDrain.
✓ No axiomsAn owning-thread SpInlinePost supersedes any un-drained SpOffThreadPost (so the later SpDrain never clobbers v_fresh with v_stale), allows subsequent off-thread posts before SpDrain to re-arm the single queued slot cleanly, and falsifies a naive non-superseding inline Post.
✓ No axiomsDisposing the target graph turns SpOffThreadPost, SpInlinePost, and SpDrain into value-preserving no-ops without adding inbox work, and bridge_memo_step suppresses Pending, Failed, and equal Ready readings while forwarding unequal Ready values into SignalPort.
✓ No axiomsBridgeBuilder<'T> (bridge target { ... }) preserves sp_inv, suppresses Phase-1 Pending and Failed reads without running the Phase-2 projection or posting, cuts off eq_key-equal Phase-1 keys before running proj, cuts off eq_out-equal Phase-2 outputs on the source graph before waking the target SignalPort, and forwards unequal settled outputs cleanly.
✓ No axiomsRanvier.Pure.Extensions
Gating a CmpNever signal write behind bool_decide (n_value d <> v) preserves exact equality cutoff when n_value d = v and wakes all observers (ends_dirty) when n_value d <> v.
✓ No axiomsProves the PublicationComparer optimization contract (Types.fs lines 133–136, Entry.fs lines 10–16,
55–65, 231–249): precomputing changed outside graph.Batch over a CmpNever signal avoids comparing a
second time inside Signal.Set while preserving both halves of the signal cutoff contract:
- When
n_value d = v,guarded_pub_writeis a no-op (Some (s, tt)), waking zero observers. - When
n_value d <> v, publishingvupdatesnand marks every observermdirty (ends_dirty s1 m).
qe_publish mutates the entry only for the active generation of a live entry; superseded or post-disposal completions are no-ops.
✓ No axiomsProves the generation-fencing contract (Entry.fs lines 48–106, 151–158, 275–281):
- Any completion whose
flight_gen <> qe_gen qeor that arrives afterqe_disposeleavesqeuntouched. - In particular, starting a refresh (
qe_start) or disposing the entry (qe_dispose) advancesqe_genfromgtoS g, so any late reply from generationgis ignored.
Refreshing a loaded QueryEntry (qe_data = Some v) or failing a refresh retains qe_data = Some v and never faults the initial-load gate.
✓ No axiomsProves the stale-while-revalidate contract (Entry.fs lines 81–100, 111–115, 167–185):
- When
qe_data qe = Some v,qe_startpreservesqe_data = Some vwhile settingqe_status = FsFetchingandqe_stale = true. - When
qe_data qe = Some vand the active flight fails (outcome = inr err),qe_publishpreservesqe_data = Some v, recordsqe_error = Some errandqe_stale = true, and keepsqe_gate_faulted = false(only an initial load failure withqe_data = Nonefaults the gate).
QueryLease.Dispose is idempotent, decrements the family reference count at most once, and evicts the shared QueryEntry iff the last active lease releases.
✓ No axiomsProves the QueryLease ownership contract (Queries.fs lines 66–79, 125–133):
- Disposing a lease twice equals disposing it once (
query_lease_dispose (query_lease_dispose st) = query_lease_dispose st). - When
ql_lease_disposed st = falseandql_ref_count st = S kwithql_entry_alive st = true,query_lease_disposesetsql_ref_counttokand keepsql_entry_alive = trueiffk > 0(evicting and disposing the entry exactly whenk = 0, i.e.,ql_ref_count st = 1).
QueryDraft edits compose in order on loaded data, leave unloaded entries empty, reject reentrant client calls during staging, and leave the cache untouched if Prepare() fails.
✓ No axiomsProves the QueryStaging and Commit contracts (Types.fs lines 52–80, Queries.fs lines 163–207, 234–273):
- Applying
[DraftUpdate f; DraftUpdate g]to a loaded draft (Some v) yieldsSome (g (f v))withqd_stale = falseandqd_updated = true. - Applying any sequence of
DraftUpdateandDraftInvalidateedits to an unloaded draft (None) preservesqd_data = Noneandqd_stale = true(unloaded entries are invalidated, never fabricated). - While
staging = true,client_reentrancy_allowedisfalse. - If
prepare_all = None,commit_stagingreturns the originalcacheunmodified.
Once the constructing scope is torn down (mvu_disposed = true), mvu_apply drops every message and mvu_run_cmds skips all remaining commands.
✓ No axiomsProves the scope-bound lifetime contract of Ranvier.Elmish (Mvu.fs lines 17–20, 38–46, 63–65):
- When
mvu_disposed st = true,mvu_apply step msg st = standmvu_run_cmds cmds st = st. - If a command
ctears down the owning scope (mvu_disposed (c st) = true),mvu_run_cmds (c :: rest) strunscand immediately halts without executing any command inrest.
mvu_apply writes the updated model before running commands (root.Value <- model; this.Run commands), so every command observes the post-update model in list order.
✓ No axiomsProves the command-ordering contract of Ranvier.Elmish (Mvu.fs lines 43–45, 62–65, 131–132):
when mvu_disposed st = false and step msg (mvu_model st) returns (next_model, [obs_cmd c1; obs_cmd c2]),
mvu_apply updates mvu_model to next_model first and executes obs_cmd c1 then obs_cmd c2 against
next_model.
Mvu.Arrive bypassing RunUntracked when graph.IsTracking () = false and Mvu.RunCommands skipping JournalWork when graph.Options.Journal.IsNone agree identically with the full untracked and journaled paths.
✓ No axiomsProves the Mvu.fs hot-path bypasses:
- For any tracking environment
eand callbackapply,arrive_fast e apply = arrive_run_untracked e apply, and whenae_tracking e = falseit returns(apply false, e)directly without touching host scope state. - For any
has_journalflag, command listcmds, andMvustatest,run_cmds_optagrees withrun_cmds_journaled_specwhile emittingWorkNonewhenhas_journal = false.
Lazy initial-load gate allocation (EnsureGate) simulates eager AsyncSource allocation across every trace of entry operations and leaves le_gate = None whenever .Value is never read while empty.
✓ No axiomsProves the lazy gate optimization in QueryEntry<'T> (Entry.fs):
- Across any sequence of
OpStart,OpOk,OpErr, andOpReadValue,run_lazypreservesentry_gate_reland produces the exact same sequence of read results asrun_eager. - On any trace whose
OpReadValuecalls occur only after data has loaded (reads_while_empty ops false = false),le_gatestaysNone(zeroAsyncSourceallocations).
Unboxed (hasData, data) and per-entry inline draftStaged staging (with DraftSet fusion and pre-batch / rollback reset) refine map-allocated QueryDraft over 'T option for arbitrary edit sequences.
✓ No axiomsProves the Entry.fs / Queries.fs inline staging optimization:
- For any initial
(has_data, cur)and arbitrary sequenceesofExtUpdate,ExtSet, andExtInvalidateedits,decode_draft (apply_inline_drafts es (init_inline_draft has_data cur))equalsapply_draft_edits (map to_model_edit es) (init_draft (if has_data then Some cur else None)). - Under any edit sequence
es,inline_preparecomputes the exact samechangedbit asmodel_prepare. - Both successful
Publish(publish = true) and rollbackResetDraft(publish = false) clearid_stagedtofalse, while rollback leaves(has_data, cur)unmodified.
QueryKey default-comparer equality/hashing handles nullable and unit (None) keys consistently, and checking QuerySession.Guard once at QueryLease matches double-checked QueryLease + QueryEntry guards.
✓ No axiomsProves the Queries.fs QueryKey devirtualization and QuerySession single-guard elimination:
- Whenever
eqZis reflexive (eqZ x x = true) and hash-compatible (eqZ x y = true -> hashZ x = hashZ y),qk_default_eq eqZis reflexive on alloption Z(includingNoneforunit/null) and preservesqk_default_hash hashZwithout invoking a null dereference onNone. - For all thread, disposal, and staging flags,
single_checked_opagrees withdouble_checked_op.
QueryEntry.AwaitImmediate allocates zero waiters when FetchStatus = FsIdle with identical outcome, QueryAwaiter.TryClaim is idempotent, and OwnerLink-backed QueryLease.Dispose detaches cleanly and decrements refcount at most once.
✓ No axiomsProves the Entry.fs / Queries.fs waiter and lease-link optimizations:
- When
status = FsIdle,await_fast_optmatchesawait_waiter_specand requires zero waiter allocation (fst = false). - Disposing a
linked_lease_stateis idempotent (linked_lease_dispose (linked_lease_dispose st) = linked_lease_dispose st), setsll_owner_attached = falseandll_waiter_detached = true, and decrements the entry's reference count once (query_lease_dispose_idempotent_refcount).
BoundValue / BoundSignal struct reads and unchanged-BoundState reuse match fresh allocations under default equality, and BoundSignal.set_Value direct on-thread dispatch matches Graph.Dispatch.
✓ No axiomsProves the Memo.TryReadStruct, BoundValue/BoundSignal unchanged-state reuse, and BoundSignal.set_Value optimizations (Core.fs, Bindings.fs):
decode_struct_readingfaithfully decodesTryReadStruct(Status * 'T * exn)tuples intoBRReady,BRPending, andBRFailed.- Whenever
eqZrespects strict equality whencustom_cmp = false(forall a b, eqZ a b = true -> a = b),bound_refresh_reuse false eqZ old r = bound_refresh_alloc eqZ old racross all prior statesoldand readingsr, and forcustom_cmp = trueboth also agree unconditionally (bound_refresh_reuse true eqZ old r = bound_refresh_alloc eqZ old r). direct_signal_dispatch on_thread inbox v = queued_signal_dispatch on_thread inbox v.
Synchronous ReactiveCommand execution without CancellationTokenSource preserves exact running-count, error, and task-outcome semantics, and skipping RunUntracked without handlers emits identical events.
✓ No axiomsProves the ReactiveCommand and ReactiveBindings.notify optimizations (Bindings.fs):
rc_sync_direct failure stproduces the exact same post-executionrc_state(including restoringrc_runningtorc_running st, updatingrc_errortofailure, and leavingrc_flightsunchanged) andrc_task_outcomeasrc_sync_with_cts failure st.rc_onthread_task need_task outmatches immediate completed task return whenneed_task = falseand exact faulted/canceled propagation whenneed_task = true.notify_deliveredskipsRunUntracked(fst = false) wheneverhas_handlers = falseand produces the exact same delivered notificationssndasnotify_eager.
Reactive.AnyPending while loop short-circuits cleanly, Exposure.publish backwards scan preserves registration order with zero empty-diff changes, InputState.isModifierKey matches the 15 DOM modifier names, and empty-observer DOM fast-paths match full iteration.
✓ No axiomsProves the loop, publishing, and observer-guard optimizations in Reactive.fs, Exposure.fs, and Ranvier.Dom:
any_pending_loop is_pending xsreturns(existsb is_pending xs, vis)wherevisis a prefix ofxsthat visitsxsstrictly in order up to the first pending node (all prior nodes non-pending, stopping immediately attrue).exposure_rev_diff pairsmatchesexposure_filter_diff pairsand is[]iff every entry text equals its previous text (Forall (fun '(_, a, b) => a = b) pairs).is_modifier_key_match k = existsb (String.eqb k) modifier_key_namesfor every stringk.dispatch_dom_observers obs = obsfor every observer snapshotobs.
Skipping any surrogate-free prefix in loneSurrogate, validating single char scalars in-place, and skipping plain BMP runs inside Prescan.check strings preserve exact scanner results.
✓ No axiomsProves the UTF-16 scalar validation and JSON string pre-scan optimizations (Helpers.fs, Prescan.fs):
- For any surrogate-free prefix
pref(Forall (fun c => is_any_surr c = false) pref) and any suffixsuf,lone_surr_from (pref ++ suf) idx = lone_surr_from suf (idx + length pref)(andNonewhensuf = []). - For a single UTF-16 code unit
c(encodeChar),lone_surr_from [c] 0 = (if is_any_surr c then Some 0 else None). - Whenever
pending = 0inside a JSON string, skipping a contiguous runplainof unescaped non-quote characters below0xD800(55296%Z) leavesprescan_plain_loop true 0 (plain ++ suf) = prescan_plain_loop true 0 suf.
inPropertyOrder without array-index keys is the identity, Dictionary.Count increase characterizes first-time member insertion, and fitsDecimal in-place mantissa scanning matches string-allocating normalization and ordinal comparison.
✓ No axiomsProves the Helpers.fs and Codecs.fs zero-allocation algorithms:
- Whenever
is_idxisfalseon all elements ofxs,filter is_idx xs ++ filter (negb ∘ is_idx) xs = xs. - For any finite dictionary
m : gmap nat Z, inserting(k, v)strictly increasessizeiffm !! k = None. - On any digit/dot list
xs,scan_mantissa max_digits xscomputes(length (mantissa_digits xs), cmp)such thatscan_fits_mantissa max_digits xs = ref_fits_mantissa max_digits (mantissa_digits xs)with zero intermediate list or string allocations.
Scanning successive vector masks and a scalar tail returns the first special UTF-16 lane.
✓ No axiomsThe block identity holds for any partition, including 32-, 16- and 8-lane blocks and skipped hardware tiers.
A unit selector preserves the result and tracked reads across model updates.
✓ No axiomsThe selector returns both its value and the sources it read for that model.
Ranvier.Pure.Deltas
Recording KcAdded on an absent key k followed by KcRemoved on k cancels out and restores kc (Deltas.fs lines 43–55).
✓ No axiomsRecording KcRemoved followed by KcAdded on the same key coalesces to Some KcReplaced (Deltas.fs lines 57–60).
✓ No axiomsMembership changes (KcAdded, KcRemoved, KcReplaced) take precedence over KcChanged, while KcChanged on an absent or KcChanged key records Some KcChanged (Deltas.fs lines 61–63).
✓ No axiomsReplacing index idx of prefix (where prefix !! idx = Some (k, c)) with last_pair and dropping the tail element refines delete k (list_to_map (prefix ++ [last_pair])) and preserves NoDup.
✓ No axiomsCertifies the Deltas.fs lines 47–55 optimization: KeyChanges<'K> avoids O(N) shifting on
Added-then-Removed cancellation by overwriting slot idx with the final entry last_pair and
truncating the ResizeArray, which permutes enumeration order while preserving the exact gmap of changes.
pr_record keeps size (pr_changes pr) <= Nat.max 64 live_count, and when a new change exceeds that cap it clears pr_changes to ∅ and flags pr_reset = true so the next pr_read reports a reset.
✓ No axiomsProves the bounded-memory contract of ProjectionReader (Deltas.fs lines 150–152, 187–194, 213–219).
pr_read delivers (current_keys, pr_cursor pr), clears pr_reset and pr_changes, and advances pr_cursor to current_keys; an immediate second read with no intervening changes reports pd_is_empty = true.
✓ No axiomsProves the cursor-advancement and idle-read contracts of ProjectionReader.Read (Deltas.fs lines 200–236).
ProjectionFold.Sync refines upstream.Entries in $O(\Delta)$ on normal deltas (for any NoDup enumeration order of pd_changes) and via Diff when pd_is_reset = true (Combinators.fs lines 1004–1085).
✓ No axiomsOn a pure upstream reorder (pd_is_reset d = false, pairs = [], had_keys = true, pd_order_changed d = true), foldGroup (invertible = true) leaves (rows, full) untouched, whereas fold (invertible = false) sets full = true so Recompute folds in the new key order (Combinators.fs lines 1072–1085).
✓ No axiomsAfter any sequence of tail-append ColAdd and arbitrary-position ColRemove operations on a NoDup key list init, if the coalesced KeyChanges map is ∅, the resulting key list equals init (Collections.fs lines 38–60).
✓ No axiomsShifting every edit index in a valid middle-slice script es by length P rewrites P ++ M ++ Sfx into P ++ M' ++ Sfx (Positional.fs).
✓ No axiomsEmitting InsertAt (length P + k, x) for each inserted element x at offset k transforms P ++ Sfx directly into P ++ Ins ++ Sfx (Positional.fs).
✓ No axiomsEmitting back-to-front RemoveAt edits from length P + length Rem - 1 down to length P transforms P ++ Rem ++ Sfx directly into P ++ Sfx (Positional.fs).
✓ No axiomsUnder the distinct-key invariant on both input arrays, trimmed middle slices M1 and M2 contain no keys from P or Sfx, so all matching survivors remain strictly inside the middle window (Positional.fs).
✓ No axiomsA single Move(length P, length P + length mid) transforms P ++ (x :: mid) ++ Sfx directly into P ++ (mid ++ [x]) ++ Sfx (Positional.fs).
✓ No axiomsA single Move(length P + length mid, length P) transforms P ++ (mid ++ [x]) ++ Sfx directly into P ++ (x :: mid) ++ Sfx (Positional.fs).
✓ No axiomsTwo Move edits swap the first and last elements of a :: mid ++ [b] inside P ++ (a :: mid ++ [b]) ++ Sfx (Positional.fs).
✓ No axiomsOn any non-reset ProjectionDelta, patching view only over delta.Changes entries with KcChanged or KcReplaced yields the exact same sequence as scanning all 0 .. length visible - 1 visible elements (Projections.fs).
✓ No axiomsA one-based small slot retrieves exactly the change stored in the abstract map.
✓ No axiomsScanning the first two keys agrees with their promoted one-based slots.
✓ No axiomsCancelling the first unpromoted key moves the last key to slot one.
✓ No axiomsThe compacted array prefix contains the zero-based survivor ranks in read order.
✓ No axiomsRanvier.Pure.FastPaths
Whenever g_flushing is true under sched_inv (and hence after any run_top from init), g_flush_owed is false.
✓ No axiomsrun_flush clears g_flush_owed to false before setting g_flushing := true, and request_flush, run_memo, and discharge only set g_flush_owed := true when g_flushing = false. Consequently sc_owed in sched_inv rules out any owed flush while a flush is running.
Including g_flushing in deferring (deferring_b1) preserves exact program outcomes, states, and traces, and makes pull identical to refresh when g_flushing = true, g_pull_depth = 0, and g_current = None.
✓ No axiomsEvery engine primitive except refresh_or_pull is identical between Engine and Engine_B1, and whenever g_flushing = true, any pull leaves g_flushing = true, restores g_pull_depth, and skips settle_flush. Consequently whole-program execution from any non-flushing state (including init fl) and single-node pulls during a flush reach identical final states (hence identical g_trace).
Every disposed computation reachable from a new graph holds empty source_slots at all points (including on the running stack), and off-stack disposed nodes have no edges in either map.
✓ No axiomsStrengthens [Ownership.disposed_no_edges] to hold even during an in-flight computation (dispose_node clears sources via sources_clear and #318 live_current blocks track on a disposed current node), guaranteeing that reading any slot k during track witnesses n_disposed d = false.
When source_cursor = 0 and slot 0 matches src, track refines to n_disposed = false and setting source_cursor := 1.
✓ No axiomsRefines Graph.Track + SourceList.Add under b2_inv (and for any state reachable from init or satisfying engine_inv + on-stack cleared disposed slots): the presence of slot 0 rules out disposal without an explicit branch, #318 makes live_current s = Some c, and sources_add c src hits slot 0 and sets source_cursor := 1.
When source_cursor = 1 and slot 1 matches src, track refines to n_disposed = false and setting source_cursor := 2.
✓ No axiomsRefines Graph.Track + SourceList.Add under b2_inv: reading slot 1 establishes n_disposed d = false (disposed_empty_sources), so live_current s = Some c and sources_add c src bumps source_cursor from 1 to 2.
When slot k at the cursor matches src, track refines to n_disposed = false and setting source_cursor := k + 1, for every k.
✓ No axiomsRefines the Graph.TrackNodeRest hit at slots 2 and up (cur < count and rest[cur - 2].Source == source) under b2_inv: a slot at the cursor rules out disposal (disposed_empty_sources), so the hit needs no IsDisposed test, and sources_add c src advances source_cursor from k to k + 1. track_slot0_fast_eq and track_slot1_fast_eq are its cases k = 0 and k = 1.
Marking a Clean leaf memo dirty updates n_freshness := Dirty directly while preserving n_unannounced and g_edges.
✓ No axiomsRefines the leaf-clean fast path in NodeOps.MarkDirty: because observer_items of m is empty, notify_with (mark_check f) terminates immediately without touching g_edges or n_unannounced.
notify_dirty_except on a source with sole observer [m] (KMemo, Check, n_unannounced = false) promotes m directly to Dirty.
✓ No axiomsRefines NotifyMoved / NotifyMovedTop fast path (r = None): since m is already Check and unflagged for deferred announcement, mark_dirty updates n_freshness m := Dirty in one write without propagating mark_check downstream.
The iterative single-memo spine walk iter_mark_check_chain is extensionally equal to mark_check on all inputs and states.
✓ No axiomsRefines NotifyCheckSpine: tail-recursing down single KMemo observer edges and falling back to notify_check on empty, non-memo, or multi-observer edges produces the exact same option state as recursive mark_check (and in particular along any clean single-memo chain).
The explicit-stack iterative Check-chain refresh iter_chain_refresh produces the exact same states as recursive refresh.
✓ No axiomsRefines RefreshChain: descending down single-memo Check edges while pushing g_checking and checkStack frames and unwinding in LIFO order with the repeat check, resolve_walk ... 1, and recompute agrees extensionally with refresh on every state.
On an idle graph, fused S -> E execution without intermediate enqueue/dequeue produces the exact same final state and trace as write_signal.
✓ No axiomsRefines the idle S -> E branch of NotifySingleFromIdleSignal: setting g_flushing := true, clearing eff to Clean / n_queued := false, running run_effect eff, and draining any reentrant effects gives the identical state s' (g_trace, g_nodes, g_queue) as write_signal.
On an idle graph, fused S -> M -> E execution with E marked Check/queued and g_flushing = true yields the exact same final state and trace as write_signal.
✓ No axiomsRefines the idle S -> M -> E branch of NotifySingleFromIdleSignal together with Section B1 (flushing in Deferring): refreshing M inline via b1_refresh under g_flushing = true and then checking/running E and draining reentrant effects produces the identical final state and trace as write_signal.
When previous and next memo states are both ready (StNone, failure = None), outcome_moved simplifies directly to value comparison without status or failure checks.
✓ No axiomsRefines RunTopCore / Memo.Recompute steady-state cutoff on ready-published memos: the status/failure difference guard is identically false, reducing outcome_moved to ready_value_moved (and for CmpEq, to bool_decide (next_val <> prev_val)).
Bit-tagging edge handles with SignalBit = 2^29 and MemoBit = 2^28 leaves all idx < 2^28 lossless, stays within 31-bit Smi bounds (< 2^30), preserves mutual exclusion of signal/memo tags, and makes index-only swap updates preserve tag bits.
✓ No axiomsTagging an observer slot index < 2^29 with NodeSlotBit = 2^29 encodes both the is_node bit and slot losslessly within 30 bits (< 2^30, matching EdgeHandle.NodeSlotBit = 0x20000000 and SlotMask = 0x1FFFFFFF in Core.fs:417,421).
✓ No axiomsTag-preserving ObserverList swap-remove refines untagged sources_remove_slot, preserves edge_match on untag_world, and preserves the swapped peer's is_node and source-handle tag bits.
✓ No axiomsPacking Kind (2b), Freshness (2b), Status (4b), Active (2b), and all 10 boolean node flags (Disposed, Unannounced, Queued, InCleanup, Publishes, Violated, Published, SafeEq, HasActed, Acting) into a 31-bit Smi word (< 2^31) is a lossless exact bijection on well-formed unpacked flag records.
✓ No axiomsSingle-word mask-and-compare guards on packed 31-bit Node.Flags are logically equivalent to the unpacked multi-field conjunctions for idle effects (0x740F, Core.fs:340), clean leaf memos (0x40F), and ready published safe-eq memos (0x307F0 / 0x30000, Core.fs:324,328).
✓ No axiomsFor a ready-published memo n with zero observers (observer_items = []) and a non-throwing comparer (cmp <> CmpThrows _), skipping equality evaluation (moved := false, omitting notify_dirty_except) yields the exact same engine state s' as ready_value_moved plus conditional notify_dirty_except whenever no un-owed queued flush transition triggers.
✓ No axiomsWhen writing v to an idle-graph signal with a single observer effect eff using a non-throwing custom comparer cmp_eq evaluating unequal (cmp_eq (n_value d_src) v = false), fused S -> E execution equals write_signal_cmp (and matches write_signal when cmp_eq is reflexive).
✓ No axiomsWhen a newly attached Clean, unqueued, non-disposed effect eff is triggered for its first run on an idle graph with empty pending queue, mark_dirty followed by request_flush is observationally and state-identical to opening the flush window directly, running eff, draining any newly enqueued work, and closing flushing (EffectNode.Start / EffectOn.Start, Core.fs:8478,13125).
✓ No axiomsAcross every well-bracketed ambient_op trace, the lazy-epoch AmbientCell state machine (Clock incremented only on AActivate, in-place epoch update at HostDepth = 0 with EpochDepth = 0 sentinel, sparse push at HostDepth > 0 iff HostEpoch <> Clock, pop iff HostDepth = EpochDepth) resolves the exact same active ambient graph as the eager per-frame reference model.
✓ No axiomsWhen memo m has a sole observer e (KEffect, Check, already n_queued = true, not disposed or in cleanup) and r <> Some e, notify_dirty_except equals directly setting e's freshness to Dirty (TryPromoteTop).
✓ No axiomsOn a single-memo chain link where child c is the sole observer of parent m (KMemo, Check, n_unannounced = false), branching directly on moved : bool returned from m's recomputation matches notify_dirty_except followed by checking c's Freshness = Dirty.
✓ No axiomsUnder sched_inv, whenever b1_deferring s = true (g_pull_depth s > 0 \/ g_batch_depth s > 0 \/ g_flushing s = true), skipping EnterPull/ExitPullDeferSettle (b1_refresh) refines b1_pull with identical final engine state s' and result (d or tt) for matching fuel.
✓ No axiomsReusing the captured now timestamp for a strictly positive delay ms > 0 guarantees both deadline = now + ms lies strictly in the future ((now <? now + ms)%Z = true /\ ~ (now >= now + ms)%Z) and the immediate elapsed-time test now - startedAt (now - now = 0) is strictly below ms ((now - now <? ms)%Z = true /\ ~ (now - now >= ms)%Z), so a freshly armed Timed node cannot immediately fire on the same tick.
✓ No axiomsVersion-only equality on (ver, payload) stamp pairs is an equivalence relation (Equivalence), decidable, reflected by Z.eqb on version numbers, and non-throwing (CmpEq on ver matches ready_value_moved with zero error transition).
✓ No axiomsA completed source scan leaves the edge world unchanged.
✓ No axiomsMemoOn Phase 1 skips finalization when every slot matched in place.
Ranvier.Pure.Combinators
Two-phase memo_on_step surfaces Phase 1 CPending/CFailed while preserving (mo_has_key, mo_last_key, mo_phase2_out, mo_scope_gen), restores mo_phase2_out with zero Phase 2 runs on eq_K-equal settled keys (even after arbitrary unready excursions), and increments mo_scope_gen and mo_compute_runs only on initial or eq_K-unequal settled keys.
✓ No axiomsMatches createMemoOn, createMemoOnWithComparer, createMemoWithOn, and createOwningMemoOnWithComparer (Core.fs, Api.fs):
Phase 1 unready readings never clobber the Phase 2 key or discharge its owned scope, equal settled keys restore the cached Phase 2 reading (CReady or Phase 2 CFailed), and unequal settled keys discharge the prior scope generation and invoke compute once.
Across all six FlightPolicy constructors, async_on_step preserves Phase 2 state on eq_K-equal settled keys and Phase 1 CPending/CFailed overlays, sets ao_queued = 2 strictly on unequal settled keys while ao_queued <> 0 under FinishCurrent/Drop/DropWhilePending (resetting ao_has_key = false on owed faulted drops and holding ao_owed_trailing = true on owed FinishCurrent RVal completions), surfaces background completions across all six active policies once Phase 1 recovers, and drains Queue in FIFO start order.
✓ No axiomsCertifies the two-phase AsyncMemo *On engine (createAsyncOn, createAsyncWithOn, createAsyncOnWithPolicy, createOwningAsyncOnWithPolicy, AsyncMemo.bind*, and AsyncSource.bind):
- Equal settled keys clear
ao_phase1_overlayandao_owed_trailingwhile preservingao_flight_gen,ao_queued,ao_scope_gen,ao_last_key, andao_phase2_slot. - Phase 1
CPending/CFailedreadings uniformly setao_phase1_overlayacross all six policies without mutatingao_has_key,ao_last_key,ao_flight_gen,ao_queued,ao_fifo,ao_phase2_slot, orao_owed_trailing. - Unequal settled
CReady k'during an active deferring flight (ao_queued <> 0underFinishCurrent/Drop/DropWhilePending) setsao_queued = 2while retainingao_last_keyandao_flight_gen. - Under
active_overlay_flight st(active in-flight state across all six policies, covering bothCPendingandCFailedPhase 1 overlays), background settlement updatesao_phase2_slotbehind the overlay and surfaces immediately with zero new launches once Phase 1 settles back to aneq_K-equal key. - When an
owed(ao_queued = 2) flight faults underFinishCurrentorDropWhilePending,async_on_settleresetsao_has_key = falsesoasync_on_stepon anyCReady k(evenk = ao_last_key) launches a fresh flight (ao_queued = 1,ao_flight_gen = S gen); when anowedFinishCurrentflight completes withRVal u,ao_phase2_slotstoresCReady uwhileao_owed_trailing = trueholdsao_visible = CPending ao_self_iduntilasync_on_steponeq_K-equalCReady kclearsao_owed_trailingand surfacesCReady uwith zero new launches. - Under
Queue, out-of-order completionsg2theng1(g1 <> g2) holdao_phase2_slotuntilg1arrives and applyout1thenout2in start order.
Fused eval_fused_chain produces the exact same (St * comb_reading B), origin, and multi-step trace as sequential unfused eval_unfused_chain over arbitrary boolean stage cutoffs eq_i without Leibniz equality, early-exiting on intermediate stage cutoffs and attributing stage throws to the throwing stage's node_id.
✓ No axiomsCertifies MapFusion (FusedSignalMap1--4, FusedSourceMap1--4, FusedChainMap in Core.fs) across Signal.map, Memo.map, AsyncMemo.map, AsyncSource.map, and StreamMemo.map (Core.fs, Streams.fs, Api.fs):
- From any synchronized state
chain_sync uc fc, single-stepeval_fused_chainandeval_unfused_chainreturn identical(St, comb_reading B)and preservechain_syncacrossCPending, upstreamCFailed, stage throws, intermediate cutoffs, and fullCReadypropagation. - Over any input trace
inputsstarting frominit_fused_chain specandinit_unfused_chain spec,run_fused_chainandrun_unfused_chainyield identical finalSt(allocation/identity state) and output reading sequences. - On an intermediate cutoff (
eq_m old_m v_mid = true) or stage throw (RThrow ex),eval_fused_chainstops at that stage without invoking downstreamreststeps, preservingcached_tailor attributingCFailed ex idto stageid.
Static eval_map2 and eval_zip match sequential let! x = r1 in let! y = r2 in f x y across all 3 * 3 comb_reading pairs, preserving St, failure origin, and static [id1; id2] upstream edges.
✓ No axiomsCertifies map2 and zip across Signal, Memo, AsyncMemo, AsyncSource, StreamMemo, and RanvierExtensions.Zip:
the fast both-ready check combined with slow left-to-right unready resolution yields the exact same (St * comb_reading C) and origin as monadic comb_bind evaluation across all nine constructor combinations, skips f (St unchanged) whenever either input is unready, and retains both static upstream edges [id1; id2] without dynamic re-tracking churn.
Split split_bind_step invokes binder iff outer settles to an initial or eq_K-unequal key, discharges the prior outer scope iff sb_has_key = true and outer settles to an eq_K-unequal key, and performs zero binder calls or scope discharges across inner U transitions and transient outer CPending/CFailed excursions recovering to an eq_K-equal key.
✓ No axiomsCertifies Signal.bind, Memo.bind (SplitBindState in Core.fs, Api.fs), and RanvierExtensions.SelectMany (Ranvier.CSharp/Extensions.fs):
sb_binder_runsincrements if and only ifr_outer = CReady kwithsb_has_key = falseoreq_K sb_last_key k = false; otherwisesb_binder_runsis unchanged.sb_dischargesincrements if and only ifr_outer = CReady kwithsb_has_key = trueandeq_K sb_last_key k = false; otherwisesb_dischargesis unchanged.- Across any sequence of inner
Utransitionsinners ++ [inner_last]while outer settles to aneq_K-equal keyk,split_bind_inner_ticksupdatessb_visibletoinner_last inner_idwith zerobinderruns and zero scope discharges. - Across any sequence
usof transient outerCPending/CFailedreadings followed byCReady kwitheq_K sb_last_key k = true,split_bind_outer_stepspreservessb_bound,sb_last_key,sb_binder_runs, andsb_discharges, resumingresolve_bound_innerdirectly.
with_eval_depth and with_suspended_run return ce_depth to its entry value on every RVal/RThrow outcome, MemoBuilder.BindReturn at depth 0 constructs one static node (MemoStatic) and leaves read and f unevaluated, and at depth S d it evaluates inline (MemoInline) with a tracked Phase 1 read, an untracked f, and zero node allocations of its own.
✓ No axiomsCertifies the reentrant evalDepth dispatch of Ranvier.CE (InternalCeState, MemoStep<'Phase, 'Prev, 'U>, and MemoRunner.EvalBound / CeRuntime.ProbeBound):
with_eval_depth(CeRuntime.CreateDynamicMemo) runsbodyat depthS dandwith_suspended_run(CeRuntime.SuspendNested/InternalCeState.SuspendForNestedRun) runs it at depth0; both end at the entry depthdwith the body's outcomeres, tracking flag, and node count, forRVal vandRThrow exalike viaInternalCeState.ExitEval.- After a dynamic evaluation entered at depth
0ends with any outcome, including a Phase 1NotReadyExceptionor an exception thrown insidematch!, the next top-levelMemoBuilder.BindReturndispatches statically. - At depth
0,ce_bind_return_evalreturnsOfFactory n(MemoStatic) for the fresh noden = ce_nodes_created stand increments the node count by one. The result is independent ofreadandf. - At depth
S d,readruns withce_tracking = true. An unready Phase 1 reading ends the step with its exactCPending srcorCFailed ex origand the entry state, leavingfunevaluated. A ready reading runsfat depthS dwithce_tracking = false(EnterUntrackedPure/RunUntrackedPureArg) and the entry node count; the step then restores the entry tracking flag and takes its depth and node count from the result state off. - A synchronous
CPending srcraised by the untrackedfsurfaces asCFailed (wrap_ex src) self_id. CeRuntime.SuspendNestedaroundMemoRunner.EvalBound(with_suspended_runaroundce_bind_return_eval) constructs one node viaCeRuntime.ProbeBoundand returns to the entry depth, at the top level and for a nestedmemo { ... }inside anowningPhase 2 callback alike.
Right-nested MergeSources over $n \ge 2$ sources reads as the sequential let! chain, with left-to-right CPending/CFailed precedence and exact origin, and its nested struct-tuple key cuts off iff every component predicate holds.
✓ No axiomsCertifies let! ... and! ... over $n \ge 2$ sources in Ranvier.CE (MergeSources returning MergedSignals, MergedMemos, or MergedReactive, nested to the right), generalizing the two-source precedence of B19:
eval_merged_chain sc = eval_seq_chain sc: the merged reading is the nested tuple of all $n$ ready values, or else the exactCPending srcorCFailed ex originof the leftmost unready source.eq_chain eqs k1 k2 = trueiff every entry ofeq_checks eqs k1 k2istrue.- On a
Memo.CreateOnnode (memo_on_step,B16) undereq_chain eqswith no settled key, a run that settlessctoCReady k1followed by a run that settlessc'toCReady k2keepsmo_compute_runsunchanged on the second run iffeq_chain eqs k1 k2 = true.
AsyncMemo settled-value cutoff suppresses Wake iff was_ready = true and cmp prev_v v = RVal true, wakes observers after any intervening Pending/Error state (was_ready = false), and contains throwing comparers as CFailed ex self_id; whereas a was_ready-blind cutoff loses wakeups after Ready -> Pending -> Ready.
✓ No axiomsReadOnlySignal<'T> preserves underlying Signal reads and Signal.map composition, while TryGet / tryAt on open-domain Lookup and MemoTable inspects only live slots (None / CReady None when absent without allocating a slot) and forwards Ready / Pending / Failed on live slots.
✓ No axiomsPublishing a nonempty stream snapshot uses the accumulator paired with its folded count.
✓ No axiomsThe count and captured state are observed under the same stream lock.
Ranvier.Pure.MemoTable
T1: Calling mt_create_slot on an absent/retired key from inside a ScopeMode.Pure memo or untrack block attaches the new KMemo node to mt_owner without setting n_violated on the caller or polluting g_edges.
✓ No axiomsT2: Every MemoTable slot body executes with ScopeMode.Pure (n_kind = KMemo, n_mode = Pure, n_scope = None); attempting to create a CMemo, CEffect, or CCleanup inside hosted (sl_node sl) fails with pure_scope_failure and leaves all owners (g_owners) untouched.
✓ No axiomsT3: Repeated Get(k) lookups for an existing slot reuse the exact same sl_node with zero node allocations, and tracking sl_node from any live caller preserves world_reachable, slots_unique, and held_once.
✓ No axiomsT4: Retiring an unobserved (observer_count = 0), unpinned (sl_pins = 0), idle slot unlinks its child link from mt_owner, clears all upstream SourceList edges, preserves memotable_inv (world_reachable and acq_ok), and deletes k from mt_slots.
✓ No axiomsT5: Passive mt_dispose (Ruling R3) is idempotent, detaches mt_owner without modifying g_queue, g_flush_owed, or g_flushing, leaves zero upstream edges on all former slot nodes, preserves memotable_inv, and causes subsequent reads to fail with disposed_table_failure.
✓ No axiomsT7: When k is Clean with n_status = StNone and SlotEvicted ms (including when n_unannounced = true from #302), deterministic mt_refill_clean restores SlotResident, preserves n_freshness = Clean, n_unannounced, n_runs, g_queue, and g_flush_owed, and emits zero observer marks.
✓ No axiomsT8: eval_slot_recompute_outcome cuts off across eviction (moved = false) iff CutoffStamp produces an equal stamp on a previously ready (StNone) slot; CutoffComparer on an evicted slot and any transition out of StError / StPending (SlotNonValue) conservatively announce moved = true.
✓ No axiomsT6: Master memotable_inv preservation across mt_new, mt_create_slot, mt_evict_payload, mt_retire_key, mt_pin_slot, and mt_dispose.
✓ No axiomsT11: When an evicted slot (SlotEvicted ms) is in Check and all of its upstream sources are settled/clean (stale_live = false), Engine.refresh transitions the slot from Check to Clean while keeping n_runs unchanged and leaving sl_payload = SlotEvicted ms (0 compute k invocations).
✓ No axiomsT9a: Exact Forward Simulation (CutoffStamp, Ruling R2).
✓ No axiomsUnder cutoff_sound (PolyStamp stamp_of), for EVERY demonic schedule tr_ev of ActEvictPayload and ActRetireKey interleaved with user writes, reads, and flushes, MemoTable (evict_enabled = true) produces obs_eq read answers AND the exact same dg_effects map (identical ef_runs, ef_settled, ef_fresh, ef_keys, and ef_sigs) as the unbounded memo family (evict_enabled = false) on strip_evictions tr_ev.
T9b: Settled Forward Simulation (CutoffComparer, Ruling R2).
✓ No axiomsUnder cutoff_sound (PolyComparer eq_V), for EVERY demonic schedule tr_ev of ActEvictPayload and ActRetireKey, MemoTable (evict_enabled = true) produces obs_eq read answers for all ActGet queries across the entire trace, and at every quiescent flush (tr_ev ++ [ActFlush]) settles every live Effect (eid ∈ all_effects) to the exact same ef_settled output as the unbounded memo family (evict_enabled = false) on strip_evictions tr_ev ++ [ActFlush].
T10: Converse Termination / Completeness (unbounded_family_refines_memotable).
✓ No axiomsWhenever the unbounded 'K -> Memo<'V> program settles in fuel_unb steps on tr_unb (dag_run_fueled fuel_unb cm false tr_unb = Some (st_unb, outs_unb)), then for every finite demonic eviction schedule tr_ev projecting to tr_unb (strip_evictions tr_ev = tr_unb), MemoTable terminates at length tr_ev with obs_eq read answers and identical signal state.
T12: Quiescent Denotational Agreement / No Lost Wakeups (memotable_no_lost_wakeups).
✓ No axiomsAfter any sequence of signal writes, Get reads, intermediate flushes, payload evictions, and key retirements ending in ActFlush (under either PolyStamp or PolyComparer satisfying cutoff_sound cm), every live Effect (eid ∈ all_effects) is Clean and its settled output equals the pure denotation eff_eval eid (dg_sigs st_ev) (fun k => (rule_eval (dg_sigs st_ev) k).1), and every subsequent ActGet k returns an outcome obs_eq to (rule_eval (dg_sigs st_ev) k).1.
Ranvier.Pure.MemoTableWitnesses
T13: Active-frame pinning (sl_pins > 0) guarantees Get(k) preserves SlotResident v ms and node residency across any sequence of nested payload evictions and key retirements (even when max_weight = 0 attempts to evict/retire k itself), and cleanly restores the entry pin count upon exit.
✓ No axiomsT14: Pre-Track fan-out coherence.
✓ No axiomsWhen caller reads k for the first time (observer_count s (sl_node sl) = 0), pinning k before running compute k ensures that even if compute k creates sibling keys and executes arbitrary retirement sweeps ops (trying to retire every ObserverCount = 0 slot, including k), sl_node sl remains live and un-retired so the subsequent sources_add caller (sl_node sl) (Graph.Track) links caller -> sl_node sl coherently with world_reachable and memotable_inv preserved.
T15: Direct (k -> k) and mutual (k1 -> k2 -> k1) cycles terminate with unchanged pins (0 leaked pins) and produce identical outcomes (Fail fid under CycleThrow fid, or on_cycle_fn under CycleRecover) regardless of whether intermediate slots were SlotEvicted ms or absent/retired (None).
✓ No axiomsT16: When compute k fails with err (either StError or StPending), apply_slot_nonvalue_transition clears sl_payload to SlotNonValue (weight = 0, prior stamp cleared), unwinds sl_pins to 0, preserves slot_wf, and guarantees eval_slot_recompute_outcome announces moved = true upon recovery to Ok v (even if v matches a pre-error stamped value).
✓ No axiomsT17: Exceptions thrown by stamp_of (CutoffStamp) or CmpThrows ex (CutoffComparer) are contained cleanly: eval_slot_recompute_outcome transitions the slot to (moved, SlotNonValue, StError, Some ex) where moved is true whenever transitioning from StNone or a different error, and SlotNonValue clears any prior stamp.
✓ No axiomsT18: Weight evaluation throw containment and non-negative clamping.
✓ No axiomsIf weigh v = Fail ex, admit_weighed_outcome aborts before modifying total_weight; if weigh v = Ok w, clamp_weight w = Z.to_nat (Z.max 0 w) clamps negative weights to 0 ((w <= 0)%Z -> clamp_weight w = 0) and equals Z.to_nat w for (0 <= w)%Z, ensuring total_weight never underflows.
Ranvier.Pure.MemoTableFastPaths
T20: Packing (tag, has_stamp, in_lru, in_dormant, refilling, pins) with 0 <= tag <= 2 and pins < 2^24 fits in a non-negative 30-bit Smi-safe integer (0 <= flags < 2^30), round-trips losslessly through unpack_slot_flags, tests residency via (flags mod 4 =? 1), and increments/decrements pins via + 64 / - 64.
✓ No axiomsT19: Whenever mt_get_fast_hit succeeds ((node.Flags &&& 0x33C) = 0, ~refilling, and SlotResident v ms), mt_get_full_existing produces the exact same (state, memotable_state, lru, Ok v) without running refresh_or_pull, mt_refill_clean, or allocating; and whenever the slot is active in g_running, g_checking, or sl_refilling, mt_get_fast_hit returns None so cycles always take the slow path.
✓ No axiomsUnit-weight resident entries exceed the budget exactly when their count does.
✓ No axiomsThe weighted LRU invariant accounts for each resident payload once.
T21: Weighted LRU maintains wlru_inv (wlru_total = Σ weights and NoDup), enforces wlru_total <= wlru_max_weight whenever slots are unpinned, and emits eviction lists evs whose corresponding [ActEvictPayload kv | kv <- evs] steps preserve dag_inv and project to [] under strip_evictions (refining Pure/MemoTable.v's demonic eviction oracle).
✓ No axiomsT22 (Ruling R5): When a freshly computed value is oversized (wlru_max_weight wl < w, including wlru_max_weight wl = 0 and 0 < w) on a within-budget cache (wlru_total wl <= wlru_max_weight wl and k ∉ fst <$> wlru_entries wl), wlru_admit_r5 leaves the entire warm LRU (wlru_entries wl and wlru_total wl) 100% intact and emits [k] ([ActEvictPayload k]); whereas wlru_admit_naive_no_bypass flushes every unpinned warm entry to []!
✓ No axiomsT23: When a Clean slot self holds settled upstream slots world_sources w !! self = Some {| source_slots := slots; source_cursor := length slots |}, replaying its deterministic read sequence fst <$> slots from sources_begin_run self w hits the in-place cursor branch at every step, mutates **zero** ObserverSets (world_observers w_mid = world_observers w), and sources_end_run self w_mid restores the exact EdgeWorld w (Some w).
✓ No axiomsT29: Pointwise MemoTable.at, MemoTable.tryAt, and tryRead descriptors preserve graph identity, tracked Get/TryGet readings, left-to-right and! unready precedence, and dynamic outer-key switching across all reactive CEs.
✓ No axiomsT30: memoTable CE evaluation preserves outer memoTable.key and depth across arbitrary reentrant Get calls (including throwing or pending inner slots), runs reactive binds with tce_tracking = true and terminal return computations with tce_tracking = false (wrapping closed-tail NotReadyException), and rejects out-of-scope memoTable.key reads.
✓ No axiomsCarrying a wrapped low word on admission and borrowing on eviction preserve the exact resident weight.
✓ No axiomsComparing the two resident weight words to the budget gives the same eviction decision as the unbounded total.
✓ No axiomsRanvier.Heap.ObserverSet
A walk visits every observer held exactly once throughout.
✓ No axiomsThe heap form of walk_covers. When each visit keeps c in
exactly one position at every point it passes through, and c starts in exactly one position, the walk calls
the visitor on c, so V c is among the results.
Ranvier.Heap.Marking
mark_check_code transitions the heap graph along mark_check.
✓ No axiomsnotify_check_code transitions the heap graph along notify_check.
✓ No axiomsmark_dirty_code transitions the heap graph along mark_dirty.
✓ No axiomsnotify_dirty_code transitions the heap graph along notify_dirty.
✓ No axiomsnotify_dirty_except_code transitions the heap graph along notify_dirty_except.
✓ No axiomsRanvier.Heap.Run
exec_code refines exec over is_graph for every environment and command.
✓ No axiomsread_code refines read over is_graph, tracked or untracked.
✓ No axiomsrun_memo_code refines run_memo (Memo.Run) over is_graph.
✓ No axiomsexecute_effect_code refines execute_effect (Effect.Execute) over is_graph.
✓ No axiomswrite_signal_code refines write_signal (Signal.Value setter) over is_graph.
✓ No axiomsrun_top_code allocates a fresh graph at init current_flags and runs compile_cmd c to outcome_val r.
✓ No axiomsRanvier.Heap.Scheduler
request_flush_code refines request_flush (Graph.RequestFlush) over is_graph.
✓ No axiomssettle_flush_code refines settle_flush (Graph.SettleFlush) over is_graph.
✓ No axiomsrun_flush_code refines run_flush (Graph.RunFlush) over is_graph.
✓ No axiomsdrain_code refines drain (the queue drain loop of Graph.RunFlush) over is_graph.
✓ No axiomsA heap flush started outside a flush returns with g_flushing false, an empty live queue, and head 0.
✓ No axiomsCombines run_flush_spec with drain_no_escape from Pure/Scheduler.v.
A top-level heap run preserves the scheduler invariant sched_inv None.
✓ No axiomsIn the resulting graph state s', each node has at most one pending queue entry, its n_queued flag
agrees with membership in pending s', every live stale effect is queued, and all owners satisfy acq_ok.
Ranvier.Heap.Ownership
owner_links_new_code allocates an empty doubly-linked owner header with initial generation 0 or 1.
✓ No axiomsowner_links_append_code appends a new OwnerLink at the tail in constant time and increments acquisitions.
✓ No axiomsowner_links_detach_code detaches the doubly-linked list in constant time and advances generation.
✓ No axiomsowner_links_walk_prev_code walks Prev pointers from the detached tail and returns links_val (snd <$> rentries).
✓ No axiomsWhen applied to rentries = rev entries after owner_links_detach_code, it yields links_val (rev (snd <$> entries)),
matching rev (o_children x) in dispose_scope.
owner_links_unlink_code is a no-op when called on a link from a detached or unlinked generation.
✓ No axiomsdispose_node_code refines dispose_node (Memo.Dispose and Effect.Dispose) over is_graph.
✓ No axiomsdischarge_code refines discharge (Graph.Discharge) over is_graph.
✓ No axiomsretire_code refines retire (Graph.Retire and Owner.Dispose) over is_graph.
✓ No axiomsdispose_scope_code refines dispose_scope (Owner.DisposeScope) over is_graph.
✓ No axiomsteardown_code refines teardown (the reverse-acquisition merge loop of Owner.DisposeScope) over is_graph.
✓ No axiomsrun_cleanup_code refines run_cleanup over is_graph.
✓ No axiomsrelease_code refines release (IOwned.Release) over is_graph.
✓ No axiomsattach_code refines attach (Owner.AttachLinked) over is_graph.
✓ No axiomsAfter any top-level heap program, every owner's children and cleanups are in acquisition order, each host's cleanup events are bounded by its registrations, and every non-running disposed node holds no source edges.
✓ No axiomsCombines run_top_spec with owners_in_order, cleanup_once_new_graph, and disposed_no_edges_new_graph
from Pure/Ownership.v.
Ranvier.Heap.Adequacy
A terminating HeapLang run of a compiled command produces the outcome of the pure interpreter.
✓ No axiomsCloses run_top_spec over ranvierΣ via heap_adequacy, with no Iris resources in the statement.
Every terminating HeapLang run of a compiled command produces the pure outcome and leaves wake_ok holding.
✓ No axiomsCombines heap_refines_pure with no_lost_wakeups and engine_inv_init from Pure/Runs.v: in the
final state s', every observer with an edge from a live, stale source is itself stale, queued or
running, or the source holds its announcement flag.
Ranvier.Heap.Collections
Direct-observer edge registration (sources_add_code) transitions is_world tbl w to is_world tbl (direct_link self s w) and preserves world_well_formed.
✓ No axiomsWhen a direct observer (Binding, FoldReads, FoldRow, ValueRow, or ForwardingEdge) with
source_cursor = length source_slots attaches to a distinct upstream source s, sources_add_code
updates the heap edge world to direct_link self s w while preserving world_well_formed.
Direct-observer detachment (sources_clear_code) transitions is_world tbl w to is_world tbl w' and preserves world_well_formed.
✓ No axiomsWhen a direct observer (Binding, FoldReads, FoldRow, or ValueRow) is disposed, sources_clear_code
removes every upstream edge, preserves world_well_formed, and leaves source_slots (sources_of w' self) = [].
forwarding_edge_moved_in_code updates the stored handle in is_forwarding_edge when ObserverSet swap-removes another entry into newHandle.
✓ No axiomsforwarding_edge_mark_dirty_code and forwarding_edge_mark_check_code delegate MarkDirty and MarkCheck directly to the target node in is_graph.
✓ No axiomsowner_links_unlink_code detaches an active tail OwnerLink (l_generation l = Some gen) in O(1) time.
✓ No axiomsCovers both the single-child case (entries = [(lk, l)]) and the multi-child tail case
(entries = E0 ++ [(lk_prev, l_prev); (lk, l)]), updating ol's head/tail pointers and clearing lk's
prev, next, and generation fields.
owner_links_unlink_code splices an active interior OwnerLink (l_generation l = Some gen) out of a doubly-linked chain in O(1) time.
✓ No axiomsWhen a projection key or reparented child scope is unlinked from the middle of a live parent's OwnerLink
list (prev = Some lk_prev, next = Some lk_next), owner_links_unlink_code redirects lk_prev.next to
Some lk_next and lk_next.prev to Some lk_prev, and clears lk's prev, next, and generation
fields without traversing the rest of the chain.
schedule_pass_tq_code transitions is_two_queue along schedule_pass_tq and preserves tq_inv.
✓ No axiomsschedule_effect_tq_code transitions is_two_queue along schedule_effect_tq and preserves tq_inv.
✓ No axiomsnotify_dirty_except_code establishes the collection WriteExcept postcondition (ends_dirty s1 m) on the heap graph.
✓ No axiomsCombines notify_dirty_except_spec with write_signal_except_wakes_others: after updating signal n's
value and ghost publication, running notify_dirty_except_code transitions is_graph to s1 where every
observer m (with r <> Some m or n ∈ read_prefix (g_edges s) m) satisfies ends_dirty s1 m.
notify_dirty_code establishes the Memo.NotifyRemoved postcondition (ends_dirty s1 m) on the heap graph before a removed key's row memo is disposed.
✓ No axiomsadopt_step_code transitions is_adopt ad st to is_adopt ad (memo_adopt_step c st).
✓ No axiomsadopt_dispose_code transitions is_adopt ad st to is_adopt ad (memo_dispose_adopted st) and establishes adopt_companion_disposed_once when st = adopt_many cs empty_adopt_state.
✓ No axioms1-based HeapLang Fenwick prefix sum matches pure fenwick_sum_pure.
✓ No axiomsWalking down i via two's-complement step i - (i &&& -i) over the
fractional heap array arr ↦∗{dq} tree returns fenwick_sum_pure tree i
without mutating the Fenwick tree.
1-based HeapLang Fenwick point update matches pure fenwick_add_pure.
✓ No axiomsClimbing i via i + (i &&& -i) up to n adds delta at every covered
Fenwick bucket in arr and leaves arr holding fenwick_add_pure tree n i delta.
HeapLang inv_order_shift_code refines reinsert_left_pure and preserves inv_order.
✓ No axiomsExecutes SortView's leftward reinsertion right-shift loop across heap arrays
order_arr and pos_arr, then writes p_idx and new_pos, leaving both
heap arrays equal to reinsert_left_pure with inv_order restored.
Ranvier.Heap.Concurrency
guarded_enter_code checks me = cs_owner_thread without mutating is_concurrency_state, returning SOME #false on the owner thread and NONE off-thread.
✓ No axiomsserialised_enter_code implements reentrant Serialised acquisition via CAS on holder (cs_loc +ₗ 3) and context verification (cs_loc +ₗ 2).
✓ No axiomsCovers all three outcomes of graph_enter under AffSerialised:
- Reentrant entry (
cs_holder cs = me): returnsSOME #falseand preservescs. - Outermost entry (
cs_holder cs = 0andctx = cs_context cs):CAStransitionsholderfrom0tomeand returnsSOME #true. - Contended or wrong-context entry: returns
NONEand leavescsuntouched.
serialised_release_code clears holder to 0 and sets pumpPosted = true whenever cs_inbox is non-empty (graph_release).
✓ No axiomspost_queued_code appends work item w to the FIFO inbox and leaves pumpPosted = true: by a store under Serialised, and otherwise by a CAS from false that posts a drain only when none is pending (post_queued).
✓ No axiomspd_try_claim_code atomically transitions a PendingDispatch cell from 0 (Waiting) to 1 (Claimed) via CAS (pd_try_claim).
✓ No axiomspd_try_close_code atomically transitions a PendingDispatch cell from 0 (Waiting) to 2 (Closed) via CAS (pd_try_close).
✓ No axiomsread_memo_fast_code inspects freshness and status &&& 3 inline to track and return clean cached memo values directly while matching read_code across all states.
✓ No axiomssignal_set_fast_split_code enters affinity first (aff_enter_code), short-circuits unjournaled equal writes without write_signal_code or serialised_release_code when must_rel = false, and releases acquired Serialised locks cleanly.
✓ No axiomsencode_comparer_code followed by eval_comparer_sentinel_code encodes value-type EqualityComparer<'T>.Default and reference-type ReferenceComparer<'T> as NONE (null) evaluated via primitive =, raises CmpNullRef via null_comparer_code when the input comparer was NONE, and invokes other comparers unchanged.
✓ No axiomssignal_set_token_fast_code loads fastWriteToken (tok_loc) and compares against 0 or caller_tok to bypass aff_enter_code on unjournaled Unchecked and owner-thread Guarded writes while refining signal_set_entered identically across all affinities and threads.
✓ No axiomssignal_port_post_off_code coalesces off-thread posts in port_loc, enqueuing drain_id via post_queued_code iff sp_in_inbox = false, and drops posts silently when sp_disposed = true.
✓ No axiomssignal_port_post_inline_code clears any pending off-thread value (hasPending := false, pendingVal := 0) before applying write_signal_code inline on the owning thread, and drops silently when sp_disposed = true.
✓ No axiomssignal_port_drain_code resets inInbox, hasPending, and pendingVal to idle, applies write_signal_code with sp_pending_val iff sp_in_inbox = true, sp_disposed = false, and sp_has_pending = true, and skips superseded or disposed drains cleanly.
✓ No axiomsRanvier.Heap.Extensions
query_start_code transitions is_query_entry along qe_start, advancing qe_gen and retaining qe_data.
✓ No axiomsquery_publish_ok_code and query_publish_err_code transition is_query_entry along qe_publish, fencing out stale generations and retaining cached data on refresh error.
✓ No axiomsquery_lease_dispose_code transitions is_query_lease along query_lease_dispose, decrementing ql_ref_count once and evicting the entry iff the count reaches 0.
✓ No axiomsquery_commit_staging_code brackets Prepare with staging = true -> false and updates the cache iff prepared = Some v (commit_staging).
✓ No axiomsmvu_apply_code drops dispatches when disposed = true, and when disposed = false writes next_model to mvu_loc before running the command so the command reads Some next_model.
✓ No axiomsRanvier.Heap.Deltas
key_change_merge_code updates slot ↦ opt_kc_val prev to slot ↦ opt_kc_val (kc_merge_opt prev c) for every combination of prev and c.
✓ No axiomsprojection_reader_record_code preserves the reset state when reset = true, flags a reset and clears changes_count to 0 when cap < new_size, and otherwise records new_size.
✓ No axiomsprojection_reader_read_code returns (reset, (reported_count, cursor)), clears changes_count to 0 and reset to false, and advances cursor to current.
✓ No axiomsRanvier.Heap.MemoTable
T24: Intrusive O(1) doubly-linked weighted-LRU pointer specifications (lru_ring_ops_spec)
✓ No axiomscovering:
lru_push_front_codeonto both empty (es = []) and non-empty (es = (h0, d0) :: rest) rings,lru_pop_back_codefrom empty ([]), singleton ([(tl, d)]), and 2-node ([(hd, dh); (tl, dt)]) rings,lru_unlink_codesplicing out a singleton ([(sl, d)]) or an interior node ([(lp, dp); (sl, d); (ln, dn)]).
T25: Separation-logic specifications for slot_get_code (slot_get_and_refill_spec)
✓ No axiomscovering:
- Post-dispose guard (
disposed = truereturnsInjLV #disposed_table_failure), - Cycle detection (
is_active = truereturnsInjLV #cycle_detected_failureorInjRV #cycle_val, Ruling R1), - Resident hot hit (
SlotResident v msreturnsInjRV #vand preserves pin count via+64/-64), - Oversized bypass (
max_w < item_wreturnsInjRV #v, transitions slot directly toSlotEvicted mswithvalue_cell = NONEV, and leaves warmis_lru_ringcompletely untouched, Ruling R5), - Within-budget miss/refill (
item_w <= max_wstoresSOMEV #v, pushesslto MRU head ofis_lru_ring, and restores pin count).
T26: Payload eviction (slot_clear_payload_code) and dormant slot retirement (slot_evict_and_retire_spec)
✓ No axiomscomposing:
- GC-root payload clearing (
value_cell <- NONE), keepingSOMEV #stwhenkeep_stamp = true(CutoffStamp,T9a) and droppingstamp_cell <- NONEwhenkeep_stamp = false(CutoffComparer,T9b), - Upstream
EdgeWorlddetachment viasources_clear_code(world_direct_unlink_specinHeap/Collections.v), - Active mid-list
OwnerLinkunlinking frommt_ownerviaowner_links_unlink_code(owner_links_active_mid_unlink_specinHeap/Collections.v).
T27: Passive, idempotent MemoTable.Dispose() specification (memotable_dispose_spec, Ruling R3):
✓ No axioms- When already disposed (
disposed = true),memotable_dispose_header_codeis a pure no-op; - When live (
disposed = false),memotable_dispose_header_codesetsdisposed <- #true, detaches all childOwnerLinks frommt_owner(ol) inO(1)viaowner_links_detach_code(incrementingol's generation so stale unlinks become no-ops), resetshdr's head, tail, andtotal_weightto0, and leaves scheduler queues untouched.
T28: Closed HeapLang adequacy for MemoTable (heap_memotable_adequacy):
✓ No axiomsClosed Prop statement (zero iProp Σ) proved via heap_adequacy over ranvierΣ:
heap_memotable_progisadequate NotStuckfrominit_heap(memory-safe, never gets stuck), and- Every operational execution terminating in
(v_out, σ')yields the exact pure tuple(InjRV #v1, InjRV #v1, InjRV #v2, #(Z.of_nat w1), InjLV #disposed_table_failure, #0)withw1 <= max_w.