Ranvier.Pure.Concurrency

Reading settings

Look

Mode

Definitions

Proofs

Imports

Arguments

References

References open

Saved in this browser.

ModulesGuarantees

Modules

Audit0Extract12

Base

Prelude9Syntax43

Reference

Semantics63Properties202

Pure

ObserverSet29SourceList104State16Edges12Marking117Engine103Check204Runs259Scheduler241Ownership49WholeGraph562Refinement465Witnesses244Optimised271Ledger6Collections302Concurrency141Extensions123Deltas68FastPaths435Combinators106MemoTable147MemoTableWitnesses62MemoTableFastPaths113

Heap

ObserverSet46SourceList89Ghost160Marking22Run286Scheduler7Ownership29Adequacy3Collections38Concurrency41Extensions17Deltas10MemoTable28

Conformance

Expected64Check119
On this page

On this page

Graph concurrency, thread affinity, and inbox contracts (pure tier)1. Thread-affinity gate and Serialised reentrant holder lockthread_affinityconcurrency_stateis_on_graph_threadgraph_entergraph_releaseguarded_enter_iff_ownerserialised_acquire_mutual_exclusionserialised_reentrant_preserves_holder2. No-lost-drain handover between PostQueued, PumpFromDispatcher, and Releasepost_queuedpump_from_dispatcher_contendeddrain_guaranteedserialised_release_reposts_nonempty_inbox3. Fault-isolated FIFO inbox drain (Graph.Drain)inbox_item_outcomedrain_statedrain_inbox_loopgraph_drain_inboxdrain_inbox_loop_specinbox_drain_fifo_fault_isolated4. PendingDispatch three-state atomic claim (DispatchAsync)pd_statepd_try_claimpd_try_closepending_dispatch_claim_exclusive5. Hot/cold fast-path decompositions for Memo.Value and Signal.Valuefreshness_bytestatus_byteis_clean_and_ready_bitsclean_and_ready_bits_ifftrack_preserves_nodesread_memo_fastmemo_read_fast_split_eqsignal_journal_recordsignal_set_enteredsignal_set_after_acquiresignal_set_fast_splitwrite_signal_unjournaled_eqsignal_set_fast_split_refinescmp_outcomenullable_comparercomparer_sentineleval_nullable_comparerencode_comparer_sentineleval_comparer_sentineldefault_comparer_null_sentinel_eqcompute_fast_write_tokencheck_fast_write_tokensignal_set_token_fastfast_write_token_iffrequest_flush_from_entered_eqequality_policyresolve_policy_comparergraph_uses_js_identitygraph_encoded_comparer_fablegraph_encoded_comparer_cache_eq6. Wave 4 fast-path contracts: optional encoded comparers, source read splits, direct graph-thread post, concrete binding refresh, and versioned edit stateeval_optional_comparerencode_optional_comparerref_same_seedsame_seed_encodedoptional_comparer_sentinel_eqis_unready_bitssource_read_valsource_try_valpush_read_refpush_read_fastpull_value_refpull_value_fastpull_try_refpull_try_fastclean_ready_source_read_split_eqpost_outcomegraph_postdirect_post_on_threadcontinue_with_statedirect_post_on_graph_thread_eqis_stale_nodeensure_current_memoensure_current_guardedbinding_check_virtualbinding_check_concretememo_read_untrackedbinding_read_fastbinding_concrete_memo_refresh_and_read_eqedit_stateunedited_stateedit_state_of_optedit_state_activeedit_state_eqref_edit_opt_eqread_edit_optread_edit_stateeditable_versioned_state_refines_voptionTimed.Wake volatile reset and no-lost-wakeup (B14)timed_wake_stateinit_timed_wake_statetimed_wake_opstep_timed_waketw_no_lost_wakeup_invrun_timed_wake_tracebad_wake_opstep_bad_wakerun_bad_wake_tracereversed_wake_bad_tracetimed_wake_volatile_reset_no_lost_wakeupCoalesced drain posts and no lost draindrain_post_stateinit_drain_post_statedrain_post_opstep_drain_postdp_no_lost_draindp_invrun_drain_post_tracestep_drain_post_invrun_drain_post_trace_invlate_reset_opstep_late_resetrun_late_reset_tracelate_reset_bad_traceraise_keeps_flag_opstep_raise_keeps_flagrun_raise_keeps_flag_tracecoalesced_drain_post_no_lost_drain7. Zero-allocation coalescing SignalPort and cross-graph bridge contractssignal_port_stateinit_signal_port_statesp_invsignal_port_opsp_post_offsp_post_inlinesp_drainsp_disposestep_signal_portrun_signal_port_tracesp_naive_inline_poststep_signal_port_invrun_signal_port_trace_invburst_off_posts_coalescesignal_port_inv_and_coalescesignal_port_inline_supersedes_pendingbridge_memo_readingbridge_memo_stepsignal_port_disposed_drops_and_bridge_cutoffbridge_ce_stateinit_bridge_ce_statebridge_ce_stepbridge_ce_drainbridge_ce_projected_cutoff_and_unready_guard
This definition

Ranvier.Pure.Concurrency

Graph concurrency, thread affinity, and inbox contracts (pure tier)

This module proves the exact minimum specifications for Ranvier's thread-affinity gates (ThreadAffinity.Guarded, ThreadAffinity.Unchecked, ThreadAffinity.Serialised), the reentrant Serialised holder protocol (Acquire / Release / Entered), the cross-thread inbox handover (PostQueued, Release, Pump, Drain), the coalesced drain post (drainPosted), and PendingDispatch three-state atomic claim (TryClaim / Cancel / Abandon) in Core.fs (lines 1747–1805, 2427–3307).

5
From stdpp Require Import prelude gmap.
From Stdlib Require Import ZArith.
From Ranvier.Base Require Import Prelude Syntax.
From Ranvier.Pure Require Import SourceList State Engine Scheduler.
Open Scope nat_scope.

1. Thread-affinity gate and Serialised reentrant holder lock

Inductive thread_affinity :=
  | AffGuarded
  | AffUnchecked
  | AffSerialised.
References

Concurrency control state of a Graph (Core.fs lines 2427–2478, 2546).

Record concurrency_state := {
  cs_affinity : thread_affinity;
  cs_owner_thread : nat;
  cs_context : nat;
  cs_holder : nat;          (* 0 when free, positive thread id me > 0 when held *)
  cs_inbox : list nat;      (* queued work item ids in FIFO arrival order *)
  cs_pump_posted : bool     (* whether a dispatcher drain wake is pending *)
}.
References

Uses

Graph.IsOnGraphThread (Core.fs lines 2954–2962).

Definition is_on_graph_thread (me : nat) (cs : concurrency_state) : bool :=
  match cs_affinity cs with
  | AffSerialised => bool_decide (cs_holder cs = me)
  | _ => bool_decide (me = cs_owner_thread cs)
  end.
References

Result of Graph.Enter (Core.fs lines 2736–2793):

  • None: raises InvalidOperationException (off-thread under Guarded, wrong context or concurrent holder under Serialised) before any graph state is touched;
  • Some (cs', must_release): succeeds, returning the updated concurrency state and whether the caller acquired a free Serialised graph and must pair the entry with Release.
Definition graph_enter (me ctx : nat) (cs : concurrency_state) : option (concurrency_state * bool) :=
  match cs_affinity cs with
  | AffGuarded =>
      if decide (me = cs_owner_thread cs) then Some (cs, false)
      else None
  | AffUnchecked =>
      Some (cs, false)
  | AffSerialised =>
      if decide (cs_holder cs = me) then Some (cs, false)
      else if decide (ctx = cs_context cs /\ cs_holder cs = 0) then
        Some ({| cs_affinity := cs_affinity cs;
                 cs_owner_thread := cs_owner_thread cs;
                 cs_context := cs_context cs;
                 cs_holder := me;
                 cs_inbox := cs_inbox cs;
                 cs_pump_posted := cs_pump_posted cs |}, true)
      else None
  end.
References

Graph.Release (Core.fs lines 2754–2763): clears holder to 0 and, if cs_inbox is non-empty, posts a dispatcher drain (cs_pump_posted := true).

Definition graph_release (cs : concurrency_state) : concurrency_state :=
  {| cs_affinity := cs_affinity cs;
     cs_owner_thread := cs_owner_thread cs;
     cs_context := cs_context cs;
     cs_holder := 0;
     cs_inbox := cs_inbox cs;
     cs_pump_posted := if decide (cs_inbox cs = []) then cs_pump_posted cs else true |}.
References
✓ No axioms

Under ThreadAffinity.Guarded, graph_enter succeeds if and only if the calling thread is cs_owner_thread, leaving the state unchanged on failure.

Matches 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.

Arguments

me : nat
the calling thread id.
ctx : nat
the calling thread's SynchronizationContext id.
the concurrency state with cs_affinity cs = AffGuarded.
Theorem guarded_enter_iff_owner (me ctx : nat) (cs : concurrency_state) :
  cs_affinity cs = AffGuarded ->
  (graph_enter me ctx cs = Some (cs, false) <-> me = cs_owner_thread cs) /\
  (me <> cs_owner_thread cs <-> graph_enter me ctx cs = None).

Arguments

me : nat
the calling thread id.
ctx : nat
the calling thread's SynchronizationContext id.
the concurrency state with cs_affinity cs = AffGuarded.
Qed
Proof.
  intros Haff. unfold graph_enter. rewrite Haff.
  destruct (decide (me = cs_owner_thread cs)) as [Heq|Hne].
  - split; split; intros; [done|done|contradiction|discriminate].
  - split; split; intros; [discriminate|contradiction|done|done].
Qed.
References
✓ No axioms

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.

Matches Graph.Acquire and Graph.Enter (Core.fs lines 2736–2749, 2792, 3274–3306):

  • If cs_holder cs = me, a nested entry succeeds with must_release = false and keeps cs_holder = me.
  • If cs_holder cs = 0 and ctx = cs_context cs, the outermost entry sets cs_holder = me and returns must_release = true.
  • If cs_holder cs holds another thread (cs_holder cs <> 0 /\ cs_holder cs <> me) or ctx <> cs_context cs, entry fails (None).

Arguments

me : nat
the calling thread id (me > 0).
ctx : nat
the calling thread's SynchronizationContext id.
the concurrency state with cs_affinity cs = AffSerialised.
Theorem serialised_acquire_mutual_exclusion (me ctx : nat) (cs : concurrency_state) :
  cs_affinity cs = AffSerialised ->
  me > 0 ->
  (cs_holder cs = me ->
     graph_enter me ctx cs = Some (cs, false)) /\
  (cs_holder cs = 0 -> ctx = cs_context cs ->
     exists cs',
       graph_enter me ctx cs = Some (cs', true) /\
       cs_holder cs' = me /\
       is_on_graph_thread me cs' = true) /\
  ((cs_holder cs <> me /\ (cs_holder cs <> 0 \/ ctx <> cs_context cs)) ->
     graph_enter me ctx cs = None).

Arguments

me : nat
the calling thread id (me > 0).
ctx : nat
the calling thread's SynchronizationContext id.
the concurrency state with cs_affinity cs = AffSerialised.
Qed
Proof.
  intros Haff Hme. unfold graph_enter. rewrite Haff. split_and!.
  - intros Hhold. rewrite decide_True by done. reflexivity.
  - intros Hfree Hctx.
    rewrite decide_False by lia.
    rewrite decide_True by done.
    eexists. split_and!; [done|done|].
    unfold is_on_graph_thread; simpl.
    by apply bool_decide_eq_true_2.
  - intros [Hne Hbad].
    rewrite decide_False by done.
    rewrite decide_False; [done|].
    intros [Hctx Hfree]. destruct Hbad; contradiction.
Qed.
References

Uses

7 more
  • Some
  • false
  • nat
  • true
  • bool_decide_eq_true_2
  • decide_False
  • decide_True
✓ No axioms

A nested (reentrant) entry on the holding thread leaves must_release = false, and only the outermost Entered scope releases cs_holder back to 0.

Certifies 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.

Arguments

me : nat
the holding thread id (me > 0).
ctx : nat
the construction context id.
the free Serialised state before the outer entry.
Theorem serialised_reentrant_preserves_holder (me ctx : nat) (cs : concurrency_state) :
  cs_affinity cs = AffSerialised ->
  cs_holder cs = 0 ->
  ctx = cs_context cs ->
  me > 0 ->
  exists cs_outer,
    graph_enter me ctx cs = Some (cs_outer, true) /\
    graph_enter me ctx cs_outer = Some (cs_outer, false) /\
    cs_holder cs_outer = me /\
    cs_holder (graph_release cs_outer) = 0.

Arguments

me : nat
the holding thread id (me > 0).
ctx : nat
the construction context id.
the free Serialised state before the outer entry.
Qed
Proof.
  intros Haff Hfree Hctx Hme.
  unfold graph_enter. rewrite Haff.
  rewrite decide_False by lia.
  rewrite decide_True by done.
  eexists. split_and!; [done| |done|done].
  simpl. rewrite decide_True by done. reflexivity.
Qed.
References

2. No-lost-drain handover between PostQueued, PumpFromDispatcher, and Release

Graph.PostQueued (Core.fs lines 2992–3008): enqueues w in cs_inbox and posts a dispatcher drain (cs_pump_posted := true).

Definition post_queued (w : nat) (cs : concurrency_state) : concurrency_state :=
  {| cs_affinity := cs_affinity cs;
     cs_owner_thread := cs_owner_thread cs;
     cs_context := cs_context cs;
     cs_holder := cs_holder cs;
     cs_inbox := cs_inbox cs ++ [w];
     cs_pump_posted := true |}.
References

Graph.PumpFromDispatcher under Serialised (Core.fs lines 3215–3235):

  • if cs_holder = 0, acquires holder := me, drains cs_inbox, and releases;
  • if cs_holder <> 0 (another thread holds the graph), the CAS CompareExchange(&holder, me, 0) fails and consumes the dispatcher wake (cs_pump_posted := false), leaving the inbox for the holding thread's Release() to re-post.
Definition pump_from_dispatcher_contended (cs : concurrency_state) : concurrency_state :=
  {| cs_affinity := cs_affinity cs;
     cs_owner_thread := cs_owner_thread cs;
     cs_context := cs_context cs;
     cs_holder := cs_holder cs;
     cs_inbox := cs_inbox cs;
     cs_pump_posted := false |}.
References

Drain availability invariant: whenever cs_inbox is non-empty, either a dispatcher wake is currently posted (cs_pump_posted = true) or a thread currently holds the Serialised graph (cs_holder > 0, whose graph_release will post a wake upon exit).

Definition drain_guaranteed (cs : concurrency_state) : Prop :=
  cs_inbox cs <> [] -> cs_pump_posted cs = true \/ cs_holder cs > 0.
References
✓ No axioms

The PostQueued / PumpFromDispatcher / Release protocol preserves drain_guaranteed and re-posts a drain on exit whenever a contended pump was skipped.

Proves 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):

  1. post_queued establishes drain_guaranteed.
  2. If PumpFromDispatcher runs while another thread holds the graph (cs_holder cs > 0), skipping the pump (pump_from_dispatcher_contended) preserves drain_guaranteed because cs_holder > 0.
  3. When the holding thread subsequently calls graph_release, cs_pump_posted is guaranteed to be true whenever cs_inbox is non-empty, so no queued work item is ever stranded.

Arguments

w : nat
a work item id enqueued via PostQueued.
the concurrency state.
Theorem serialised_release_reposts_nonempty_inbox (w : nat) (cs : concurrency_state) :
  drain_guaranteed (post_queued w cs) /\
  (cs_holder cs > 0 ->
     drain_guaranteed (pump_from_dispatcher_contended (post_queued w cs)) /\
     cs_pump_posted (graph_release (pump_from_dispatcher_contended (post_queued w cs))) = true /\
     cs_inbox (graph_release (pump_from_dispatcher_contended (post_queued w cs))) = cs_inbox cs ++ [w]).

Arguments

w : nat
a work item id enqueued via PostQueued.
the concurrency state.
Qed
Proof.
  split.
  - intros _. left. reflexivity.
  - intros Hheld.
    assert (Hne : cs_inbox cs ++ [w] <> []).
    { intros Hnil. apply app_eq_nil in Hnil as [_ Hnil]. discriminate. }
    split_and!.
    + intros _. right. simpl. lia.
    + unfold graph_release, pump_from_dispatcher_contended, post_queued; simpl.
      rewrite decide_False by exact Hne. reflexivity.
    + reflexivity.
Qed.
References

3. Fault-isolated FIFO inbox drain (Graph.Drain)

Outcome of executing a single inbox work item (unit -> unit in Graph.Drain, Core.fs lines 3191–3208): either returns normally (producing state update eff) or throws exception err (which Drain catches and passes to root.RecordError err so remaining inbox items still run).

Inductive inbox_item_outcome :=
  | InboxOk (eff : nat)
  | InboxThrow (err : Z).
References

Uses

  • nat
  • Z
Record drain_state := {
  ds_inbox : list inbox_item_outcome;
  ds_applied : list nat;
  ds_root_errors : list Z;
  ds_flush_requested : bool
}.
References

Uses

Fixpoint drain_inbox_loop (items : list inbox_item_outcome) (applied : list nat) (errs : list Z)
    : list nat * list Z * nat :=
  match items with
  | [] => (applied, errs, 0)
  | InboxOk eff :: rest =>
      let '(app', errs', ran) := drain_inbox_loop rest (applied ++ [eff]) errs in
      (app', errs', S ran)
  | InboxThrow err :: rest =>
      let '(app', errs', ran) := drain_inbox_loop rest applied (errs ++ [err]) in
      (app', errs', S ran)
  end.
References

Graph.Drain (Core.fs lines 3173–3213): drains every item in ds_inbox in FIFO arrival order, records any thrown exception in ds_root_errors, requests a flush iff ran > 0, and returns ran.

Definition graph_drain_inbox (ds : drain_state) : drain_state * nat :=
  let '(app', errs', ran) := drain_inbox_loop (ds_inbox ds) (ds_applied ds) (ds_root_errors ds) in
  ({| ds_inbox := [];
      ds_applied := app';
      ds_root_errors := errs';
      ds_flush_requested := if decide (0 < ran) then true else ds_flush_requested ds |},
   ran).
References
Lemma drain_inbox_loop_spec items applied errs :
  drain_inbox_loop items applied errs =
  (applied ++ omap (fun it => match it with InboxOk e => Some e | InboxThrow _ => None end) items,
   errs ++ omap (fun it => match it with InboxOk _ => None | InboxThrow ex => Some ex end) items,
   length items).
Qed
Proof.
  revert applied errs.
  induction items as [|[eff|err] rest IH]; intros applied errs; simpl.
  - rewrite !app_nil_r. reflexivity.
  - rewrite IH. rewrite <- app_assoc. reflexivity.
  - rewrite IH. rewrite <- app_assoc. reflexivity.
Qed.
References

Uses

1 more
  • omap
✓ No axioms

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.

Matches 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 empties ds_inbox.
  • Appends every InboxOk eff in arrival order to ds_applied.
  • Appends every InboxThrow err in arrival order to ds_root_errors.
  • Sets ds_flush_requested = true whenever ds_inbox ds <> [].

Arguments

the inbox drain state before Pump / Drain.
Theorem inbox_drain_fifo_fault_isolated (ds : drain_state) :
  let '(ds', ran) := graph_drain_inbox ds in
  ran = length (ds_inbox ds) /\
  ds_inbox ds' = [] /\
  ds_applied ds' =
    ds_applied ds ++ omap (fun it => match it with InboxOk e => Some e | InboxThrow _ => None end) (ds_inbox ds) /\
  ds_root_errors ds' =
    ds_root_errors ds ++ omap (fun it => match it with InboxOk _ => None | InboxThrow ex => Some ex end) (ds_inbox ds) /\
  (ds_inbox ds <> [] -> ds_flush_requested ds' = true).

Arguments

the inbox drain state before Pump / Drain.
Qed
Proof.
  unfold graph_drain_inbox.
  rewrite drain_inbox_loop_spec. simpl.
  split_and!; [done|done|done|done|].
  intros Hne. destruct (ds_inbox ds) as [|x xs]; [contradiction|done].
Qed.
References

4. PendingDispatch three-state atomic claim (DispatchAsync)

State of a PendingDispatch<'T> item (Core.fs lines 1747–1775, 3070–3140):

  • 0 (PdWaiting): waiting in the inbox;
  • 1 (PdClaimed): claimed by the inbox drain (TryClaim succeeded);
  • 2 (PdClosed): cancelled via CancellationToken or abandoned by Graph.Dispose.
Definition pd_state := nat.
References

Uses

  • nat
Definition pd_try_claim (st : pd_state) : pd_state * bool :=
  if decide (st = 0) then (1, true) else (st, false).
References

Uses

Definition pd_try_close (st : pd_state) : pd_state * bool :=
  if decide (st = 0) then (2, true) else (st, false).
References

Uses

✓ No axioms

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).

Proves the PendingDispatch<'T> contract (Core.fs lines 1747–1775):

  • Starting from st = 0, the first transition (pd_try_claim or pd_try_close) returns true and moves st to 1 or 2.
  • Once st is 1 (claimed by the drain) or 2 (cancelled or abandoned on disposal), both pd_try_claim and pd_try_close return (st, false), so a cancelled/abandoned item is skipped by the drain and a claimed item cannot be cancelled or faulted by disposal.

Arguments

st
the PendingDispatch state.
Theorem pending_dispatch_claim_exclusive :
  pd_try_claim 0 = (1, true) /\
  pd_try_close 0 = (2, true) /\
  (forall st, st <> 0 -> pd_try_claim st = (st, false) /\ pd_try_close st = (st, false)) /\
  snd (pd_try_close (fst (pd_try_claim 0))) = false /\
  snd (pd_try_claim (fst (pd_try_close 0))) = false /\
  snd (pd_try_close (fst (pd_try_close 0))) = false.

Arguments

st
the PendingDispatch state.
Qed
Proof.
  unfold pd_try_claim, pd_try_close.
  split_and!.
  - reflexivity.
  - reflexivity.
  - intros st Hne. split; rewrite decide_False by done; reflexivity.
  - reflexivity.
  - reflexivity.
  - reflexivity.
Qed.
References

Uses

5. Hot/cold fast-path decompositions for Memo.Value and Signal.Value

Byte encoding of Freshness (Core.fs lines 29–44).

Definition freshness_byte (fr : freshness) : Z :=
  match fr with Clean => 0%Z | Check => 1%Z | Dirty => 2%Z end.
References

Bit-flag encoding of Status (Types.fs lines 11–19): None = 0, Pending = 1, Error = 2, Uninitialized = 4, plus optional Stale = 8 (stale_flag = true).

Definition status_byte (st : status) (stale_flag : bool) : Z :=
  (match st with
   | StNone => 0%Z
   | StPending => 1%Z
   | StError => 2%Z
   | StUninitialized => 4%Z
   end + if stale_flag then 8%Z else 0%Z)%Z.
References

StatusBits.isCleanAndReady (Core.fs lines 173–174): checks ((byte freshness) ||| (byte status &&& 3uy)) = 0uy.

Definition is_clean_and_ready_bits (fr : freshness) (st : status) (stale_flag : bool) : bool :=
  bool_decide (Z.lor (freshness_byte fr) (Z.land (status_byte st stale_flag) 3%Z) = 0%Z).
References

Uses

✓ No axioms

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.

Matches 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).

Arguments

the node's Freshness.
st : status
the node's readiness/error/uninitialized Status.
stale_flag : bool
whether the orthogonal Status.Stale (8uy) bit is set.
Theorem clean_and_ready_bits_iff (fr : freshness) (st : status) (stale_flag : bool) :
  is_clean_and_ready_bits fr st stale_flag = true <->
  (fr = Clean /\ st <> StPending /\ st <> StError).

Arguments

the node's Freshness.
st : status
the node's readiness/error/uninitialized Status.
stale_flag : bool
whether the orthogonal Status.Stale (8uy) bit is set.
Qed
Proof.
  unfold is_clean_and_ready_bits, freshness_byte, status_byte.
  destruct fr, st, stale_flag.
  all: split; [intro H; vm_compute in H; try discriminate; repeat split; discriminate |].
  all: intros [Hfr [Hp He]]; try discriminate Hfr;
    try (exfalso; exact (Hp eq_refl));
    try (exfalso; exact (He eq_refl));
    vm_compute; reflexivity.
Qed.
References
Lemma track_preserves_nodes (n : node_id) (s s' : state) :
  track n s = Some (s', tt) -> g_nodes s' = g_nodes s.
Qed
Proof.
  unfold track.
  destruct (live_current s) as [c|]; [|intros [= <-]; reflexivity].
  destruct (sources_add c n (g_edges s)) as [w|]; [|discriminate].
  intros [= <-].
  unfold ghost_read.
  destruct (g_nodes (with_edges w s) !! n); destruct s; reflexivity.
Qed.
References

Fast/slow decomposition of Memo.Value (Core.fs lines 5526–5557): inspects is_clean_and_ready_bits first, tracks and returns the cached value on hit, and otherwise delegates to read_node.

Definition read_memo_fast (fuel : nat) (n : node_id) : M outcome :=
  match fuel with
  | 0 => stuck
  | S f =>
    let* d := get_node n in
    match n_kind d with
    | KMemo =>
      if is_clean_and_ready_bits (n_freshness d) (n_status d) false then
        let* _ := track n in
        m_return (Ok (n_value d))
      else read_node (S f) n
    | _ => read_node (S f) n
    end
  end.
References
✓ No axioms

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.

Matches the #else .NET split between Memo.Value (GetFast) and Memo.ReadSlow (Core.fs lines 5526–5557).

Arguments

f : nat
inner fuel budget for read_node (S f).
the target node id.
s : state
the graph state before reading.
Theorem memo_read_fast_split_eq (f : nat) (n : node_id) (s : state) :
  read_memo_fast (S f) n s = read_node (S f) n s /\
  read (S (S f)) n true s = read_memo_fast (S f) n s.

Arguments

f : nat
inner fuel budget for read_node (S f).
the target node id.
s : state
the graph state before reading.
Qed
Proof.
  unfold read_memo_fast, m_bind, get_node. cbn [read].
  destruct (g_nodes s !! n) as [d|] eqn:Hnode.
  - destruct (n_kind d) eqn:Hk.
    + split; reflexivity.
    + destruct (is_clean_and_ready_bits (n_freshness d) (n_status d) false) eqn:Hfast.
      * apply clean_and_ready_bits_iff in Hfast as (Hfr & Hnp & Hne).
        assert (Hnsl : stale_live d = false) by (unfold stale_live; rewrite Hfr; reflexivity).
        cbn [read_node]. unfold m_bind, m_return, get_node. simpl. rewrite Hnode, Hk, Hnsl.
        destruct (track n s) as [[s' []]|] eqn:Htr; simpl.
        -- rewrite (track_preserves_nodes n s s' Htr), Hnode.
           destruct (n_status d); [split; reflexivity | split; reflexivity | exfalso; exact (Hne eq_refl) | split; reflexivity].
        -- split; reflexivity.
      * split; reflexivity.
    + split; reflexivity.
  - cbn [read_node]. unfold m_bind, get_node. simpl. rewrite Hnode. split; reflexivity.
Qed.
References
Definition signal_journal_record (v : val) (j : option (list Z)) : option (list Z) :=
  match j with
  | None => None
  | Some log => Some (log ++ [v])
  end.
References

Uses

  • val
  • None
  • Some
  • list
  • option
  • Z

Reference Entered-composed Signal.Value setter (#if FABLE_COMPILER, Core.fs lines 4414–4444).

Definition signal_set_entered
    (me ctx fuel : nat) (n : node_id) (v : val)
    (cs : concurrency_state) (j : option (list Z)) (s : state)
    : option (concurrency_state * option (list Z) * state) :=
  match graph_enter me ctx cs with
  | None => None
  | Some (cs1, must_rel) =>
      let j1 := signal_journal_record v j in
      let cs2 := if must_rel then graph_release cs1 else cs1 in
      match write_signal fuel n v s with
      | None => None
      | Some (s', tt) => Some (cs2, j1, s')
      end
  end.
References

Slow cold path for Signal.Value set after Graph.Enter returns true (Signal.SetAfterAcquire, Core.fs lines 4529–4547).

Definition signal_set_after_acquire
    (fuel : nat) (n : node_id) (v : val)
    (cs : concurrency_state) (j : option (list Z)) (s : state)
    : option (concurrency_state * option (list Z) * state) :=
  let cs_out := graph_release cs in
  match j with
  | None =>
      match g_nodes s !! n with
      | Some d =>
          match n_kind d with
          | KSignal =>
              if decide (n_value d = v) then Some (cs_out, None, s)
              else
                match write_signal fuel n v s with
                | Some (s', tt) => Some (cs_out, None, s')
                | None => None
                end
          | _ => None
          end
      | None => None
      end
  | Some log =>
      let j1 := Some (log ++ [v]) in
      match write_signal fuel n v s with
      | Some (s', tt) => Some (cs_out, j1, s')
      | None => None
      end
  end.
References

Split .NET fast/cold decomposition of Signal.Value set (Core.fs lines 4446–4547).

Definition signal_set_fast_split
    (me ctx fuel : nat) (n : node_id) (v : val)
    (cs : concurrency_state) (j : option (list Z)) (s : state)
    : option (concurrency_state * option (list Z) * state) :=
  match graph_enter me ctx cs with
  | None => None
  | Some (cs1, false) =>
      match j with
      | None =>
          match g_nodes s !! n with
          | Some d =>
              match n_kind d with
              | KSignal =>
                  if decide (n_value d = v) then Some (cs1, None, s)
                  else
                    match write_signal fuel n v s with
                    | Some (s', tt) => Some (cs1, None, s')
                    | None => None
                    end
              | _ => None
              end
          | None => None
          end
      | Some log =>
          let j1 := Some (log ++ [v]) in
          match write_signal fuel n v s with
          | Some (s', tt) => Some (cs1, j1, s')
          | None => None
          end
      end
  | Some (cs1, true) =>
      signal_set_after_acquire fuel n v cs1 j s
  end.
References
Local Lemma write_signal_unjournaled_eq
    (f : nat) (n : node_id) (v : val) (cs_out : concurrency_state) (s : state) :
  (match write_signal (S f) n v s with
   | Some (s', tt) => Some (cs_out, None, s')
   | None => None
   end : option (concurrency_state * option (list Z) * state)) =
  match g_nodes s !! n with
  | Some d =>
      match n_kind d with
      | KSignal =>
          if decide (n_value d = v) then Some (cs_out, None, s)
          else
            match write_signal (S f) n v s with
            | Some (s', tt) => Some (cs_out, None, s')
            | None => None
            end
      | _ => None
      end
  | None => None
  end.
Qed
Proof.
  destruct (g_nodes s !! n) as [d|] eqn:Hnode.
  - destruct (n_kind d) eqn:Hk.
    + destruct (decide (n_value d = v)) as [Heq|Hne].
      * cbn [write_signal]. unfold m_bind, get_node, m_return. simpl.
        rewrite Hnode, Hk, decide_True; [reflexivity | exact Heq].
      * reflexivity.
    + cbn [write_signal]. unfold m_bind, get_node, stuck. simpl.
      rewrite Hnode, Hk. reflexivity.
    + cbn [write_signal]. unfold m_bind, get_node, stuck. simpl.
      rewrite Hnode, Hk. reflexivity.
  - cbn [write_signal]. unfold m_bind, get_node, stuck. simpl.
    rewrite Hnode. reflexivity.
Qed.
References
✓ No axioms

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.

Matches 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.

Arguments

me : nat
the calling thread id.
ctx : nat
the calling thread's SynchronizationContext id.
f : nat
inner fuel budget for write_signal (S f).
the signal node id.
v : val
the value being written.
the concurrency state before the write.
j : option (list Z)
None when unjournaled, or Some log for an attached journal log.
s : state
the graph state before the write.
Theorem signal_set_fast_split_refines
    (me ctx f : nat) (n : node_id) (v : val) (cs : concurrency_state) (j : option (list Z)) (s : state) :
  signal_set_fast_split me ctx (S f) n v cs j s = signal_set_entered me ctx (S f) n v cs j s /\
  (cs_affinity cs = AffGuarded -> me <> cs_owner_thread cs ->
   signal_set_fast_split me ctx f n v cs j s = None).

Arguments

me : nat
the calling thread id.
ctx : nat
the calling thread's SynchronizationContext id.
f : nat
inner fuel budget for write_signal (S f).
the signal node id.
v : val
the value being written.
the concurrency state before the write.
j : option (list Z)
None when unjournaled, or Some log for an attached journal log.
s : state
the graph state before the write.
Qed
Proof.
  split.
  - unfold signal_set_fast_split, signal_set_after_acquire, signal_set_entered, signal_journal_record.
    destruct (graph_enter me ctx cs) as [[cs1 []]|]; [| |reflexivity].
    + destruct j as [log|]; [reflexivity | symmetry; apply write_signal_unjournaled_eq].
    + destruct j as [log|]; [reflexivity | symmetry; apply write_signal_unjournaled_eq].
  - intros Haff Hne.
    unfold signal_set_fast_split.
    destruct (guarded_enter_iff_owner me ctx cs Haff) as [_ Hiff].
    rewrite (proj1 Hiff Hne). reflexivity.
Qed.
References

Outcome of invoking an IEqualityComparer<'T>.Equals implementation (Core.fs lines 4304–4337): returns CmpBool b, raises NullReferenceException (CmpNullRef), or throws a user exception (CmpThrow err).

Inductive cmp_outcome :=
  | CmpBool (b : bool)
  | CmpNullRef
  | CmpThrow (err : Z).
References

Uses

  • bool
  • Z

Classification of the IEqualityComparer<'T> returned by IEqualityPolicy.Comparer<'T>() (Core.fs lines 4315–4326).

Inductive nullable_comparer :=
  | CmpNullInput
  | CmpValDefault
  | CmpRefIdentity
  | CmpCustomInput (f : Z -> Z -> cmp_outcome).
References

Encoded equal field stored on Signal and Memo by ComparerSentinel.encode (Core.fs lines 4315–4326): SentDefaultNull represents null (signalling intrinsic EqualityComparer<'T>.Default.Equals when is_val_type = true, or obj.ReferenceEquals when is_val_type = false), SentNullComparer represents NullComparer<'T>.Instance, and SentCustom f stores any non-intrinsic comparer (such as EqualityComparer<string>.Default or custom policies).

Inductive comparer_sentinel :=
  | SentDefaultNull
  | SentNullComparer
  | SentCustom (f : Z -> Z -> cmp_outcome).
References
Definition eval_nullable_comparer
    (val_eq ref_eq : Z -> Z -> bool) (c : nullable_comparer) (a b : Z) : cmp_outcome :=
  match c with
  | CmpNullInput => CmpNullRef
  | CmpValDefault => CmpBool (val_eq a b)
  | CmpRefIdentity => CmpBool (ref_eq a b)
  | CmpCustomInput f => f a b
  end.
References
Definition encode_comparer_sentinel
    (is_val_type : bool) (val_eq ref_eq : Z -> Z -> bool) (c : nullable_comparer) : comparer_sentinel :=
  match c with
  | CmpNullInput => SentNullComparer
  | CmpValDefault =>
      if is_val_type then SentDefaultNull
      else SentCustom (fun a b => CmpBool (val_eq a b))
  | CmpRefIdentity =>
      if is_val_type then SentCustom (fun a b => CmpBool (ref_eq a b))
      else SentDefaultNull
  | CmpCustomInput f => SentCustom f
  end.
References
Definition eval_comparer_sentinel
    (is_val_type : bool) (val_eq ref_eq : Z -> Z -> bool) (s : comparer_sentinel) (a b : Z) : cmp_outcome :=
  match s with
  | SentDefaultNull => CmpBool (if is_val_type then val_eq a b else ref_eq a b)
  | SentNullComparer => CmpNullRef
  | SentCustom f => f a b
  end.
References
✓ No axioms

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.

Matches 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>.Default maps to SentDefaultNull (null), dispatching directly to val_eq a b without interface dispatch;
  • for reference types (is_val_type = false), ReferenceComparer<'T> maps to SentDefaultNull (null), dispatching directly to ref_eq a b (obj.ReferenceEquals) without interface calls or generic dictionary lookups;
  • a faulty policy returning null maps to SentNullComparer (NullComparer<'T>.Instance), still raising NullReferenceException (CmpNullRef) on comparison;
  • any other comparer (EqualityComparer<string>.Default, StructuralPolicy reference comparers, or custom/throwing comparers) is preserved unchanged as SentCustom.

Arguments

is_val_type : bool
true when typeof<'T>.IsValueType, false otherwise.
val_eq : Z -> Z -> bool
the intrinsic EqualityComparer<'T>.Default.Equals relation.
ref_eq : Z -> Z -> bool
the intrinsic obj.ReferenceEquals relation.
the input comparer returned by IEqualityPolicy.Comparer<'T>().
a : Z
the previous value.
b : Z
the candidate value.
Theorem default_comparer_null_sentinel_eq
    (is_val_type : bool) (val_eq ref_eq : Z -> Z -> bool) (c : nullable_comparer) (a b : Z) :
  eval_comparer_sentinel is_val_type val_eq ref_eq
    (encode_comparer_sentinel is_val_type val_eq ref_eq c) a b =
    eval_nullable_comparer val_eq ref_eq c a b /\
  (encode_comparer_sentinel is_val_type val_eq ref_eq c = SentDefaultNull <->
    (if is_val_type then c = CmpValDefault else c = CmpRefIdentity)) /\
  (c = CmpNullInput ->
    eval_comparer_sentinel is_val_type val_eq ref_eq
      (encode_comparer_sentinel is_val_type val_eq ref_eq c) a b = CmpNullRef).

Arguments

is_val_type : bool
true when typeof<'T>.IsValueType, false otherwise.
val_eq : Z -> Z -> bool
the intrinsic EqualityComparer<'T>.Default.Equals relation.
ref_eq : Z -> Z -> bool
the intrinsic obj.ReferenceEquals relation.
the input comparer returned by IEqualityPolicy.Comparer<'T>().
a : Z
the previous value.
b : Z
the candidate value.
Qed
Proof.
  destruct is_val_type, c as [| | |f]; simpl;
    (split_and!; [reflexivity | split; intro H; try reflexivity; discriminate H | intro H; try reflexivity; discriminate H]).
Qed.
References

Graph.fastWriteToken (Core.fs lines 2476–2479): -1 when Serialised or journaled, ownerToken (>= 1, assigned by OwnerThreadToken.Ensure) when Guarded and unjournaled, and 0 when Unchecked and unjournaled.

Definition compute_fast_write_token (aff : thread_affinity) (has_journal : bool) (owner_tok : Z) : Z :=
  match aff with
  | AffSerialised => (-1)%Z
  | AffGuarded => if has_journal then (-1)%Z else owner_tok
  | AffUnchecked => if has_journal then (-1)%Z else 0%Z
  end.
References

Inline fast-path gate in Signal.SetFast and Signal.WriteExcept (Core.fs lines 4458–4463, 4574–4579): tok >= 0L && (tok = 0L || tok = OwnerThreadToken.Current), avoiding any TLS read when tok = -1L (Serialised or journaled), where caller_tok = 0 on an uninitialized thread and caller_tok >= 1 on any thread initialized by OwnerThreadToken.Ensure.

Definition check_fast_write_token (tok caller_tok : Z) : bool :=
  bool_decide (0 <= tok)%Z && (bool_decide (tok = 0%Z) || bool_decide (tok = caller_tok)).
References

Uses

  • bool
  • Z
  • bool_decide

Full .NET Signal.Value setter (Signal.SetFast + Signal.SetSlow, Core.fs lines 4454–4547): tests check_fast_write_token first for unjournaled Unchecked / owner-thread Guarded writes, and delegates Serialised, journaled, and off-thread Guarded writes to signal_set_fast_split.

Definition signal_set_token_fast
    (owner_tok caller_tok : Z) (me ctx fuel : nat) (n : node_id) (v : val)
    (cs : concurrency_state) (j : option (list Z)) (s : state)
    : option (concurrency_state * option (list Z) * state) :=
  let has_j := match j with Some _ => true | None => false end in
  let tok := compute_fast_write_token (cs_affinity cs) has_j owner_tok in
  if check_fast_write_token tok caller_tok then
    match g_nodes s !! n with
    | Some d =>
        match n_kind d with
        | KSignal =>
            if decide (n_value d = v) then Some (cs, None, s)
            else
              match write_signal fuel n v s with
              | Some (s', tt) => Some (cs, None, s')
              | None => None
              end
        | _ => None
        end
    | None => None
    end
  else
    signal_set_fast_split me ctx fuel n v cs j s.
References
✓ No axioms

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.

Matches 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 >= 0 is checked first, tok = -1 (Serialised or journaled) short-circuits to false without reading OwnerThreadToken.Current, routing all Serialised (including reentrant) and journaled writes to SetSlow.
  • Under Guarded without a journal (tok = owner_tok >= 1), tok = 0 is false and tok = caller_tok holds iff the caller is the owner thread (in particular, an uninitialized thread with caller_tok = 0 is rejected).
  • Across all affinities, threads, and journal states, signal_set_token_fast equals signal_set_entered.

Arguments

owner_tok : Z
the positive token (>= 1) assigned to cs_owner_thread cs by OwnerThreadToken.Ensure.
caller_tok : Z
OwnerThreadToken.Current on the calling thread (0 if uninitialized, >= 1 if initialized).
me : nat
the calling thread id.
ctx : nat
the calling thread's SynchronizationContext id.
f : nat
inner fuel budget for write_signal (S f).
the signal node id.
v : val
the written value.
the concurrency state before the write.
j : option (list Z)
None when unjournaled, or Some log when journaled.
s : state
the graph state before the write.
Theorem fast_write_token_iff
    (owner_tok caller_tok : Z) (me ctx f : nat) (n : node_id) (v : val)
    (cs : concurrency_state) (j : option (list Z)) (s : state) :
  (1 <= owner_tok)%Z ->
  (0 <= caller_tok)%Z ->
  (caller_tok = owner_tok <-> me = cs_owner_thread cs) ->
  let has_j := match j with Some _ => true | None => false end in
  let tok := compute_fast_write_token (cs_affinity cs) has_j owner_tok in
  (check_fast_write_token tok caller_tok = true <->
    (j = None /\
     (cs_affinity cs = AffUnchecked \/
      (cs_affinity cs = AffGuarded /\ me = cs_owner_thread cs)))) /\
  (cs_affinity cs = AffGuarded -> caller_tok = 0%Z ->
    check_fast_write_token tok caller_tok = false) /\
  signal_set_token_fast owner_tok caller_tok me ctx (S f) n v cs j s =
    signal_set_entered me ctx (S f) n v cs j s.

Arguments

owner_tok : Z
the positive token (>= 1) assigned to cs_owner_thread cs by OwnerThreadToken.Ensure.
caller_tok : Z
OwnerThreadToken.Current on the calling thread (0 if uninitialized, >= 1 if initialized).
me : nat
the calling thread id.
ctx : nat
the calling thread's SynchronizationContext id.
f : nat
inner fuel budget for write_signal (S f).
the signal node id.
v : val
the written value.
the concurrency state before the write.
j : option (list Z)
None when unjournaled, or Some log when journaled.
s : state
the graph state before the write.
Qed
Proof.
  intros Hown Hcaller Htok_eq. simpl.
  assert (Hgate :
    check_fast_write_token
      (compute_fast_write_token (cs_affinity cs) (match j with Some _ => true | None => false end) owner_tok)
      caller_tok = true <->
    (j = None /\
     (cs_affinity cs = AffUnchecked \/
      (cs_affinity cs = AffGuarded /\ me = cs_owner_thread cs)))).
  { unfold check_fast_write_token, compute_fast_write_token.
    destruct (cs_affinity cs) eqn:Haff, j as [log|].
    - rewrite (bool_decide_eq_false_2 (0 <= -1)%Z) by lia. simpl.
      split; [discriminate | intros [Hj _]; discriminate Hj].
    - rewrite (bool_decide_eq_true_2 (0 <= owner_tok)%Z) by lia.
      rewrite (bool_decide_eq_false_2 (owner_tok = 0%Z)) by lia. simpl.
      split.
      + intro Hb. apply bool_decide_eq_true_1 in Hb. symmetry in Hb.
        apply Htok_eq in Hb. split; [reflexivity | right; split; [reflexivity | exact Hb]].
      + intros [_ [Hbad | [_ Hme]]]; [discriminate Hbad |].
        apply bool_decide_eq_true_2. symmetry. by apply Htok_eq.
    - rewrite (bool_decide_eq_false_2 (0 <= -1)%Z) by lia. simpl.
      split; [discriminate | intros [Hj _]; discriminate Hj].
    - rewrite (bool_decide_eq_true_2 (0 <= 0)%Z) by lia.
      rewrite (bool_decide_eq_true_2 (0%Z = 0%Z)) by reflexivity. simpl.
      split; [intros _; split; [reflexivity | by left] | intros _; reflexivity].
    - rewrite (bool_decide_eq_false_2 (0 <= -1)%Z) by lia. simpl.
      split; [discriminate | intros [Hj _]; discriminate Hj].
    - rewrite (bool_decide_eq_false_2 (0 <= -1)%Z) by lia. simpl.
      split; [discriminate | intros [_ [Hbad | [Hbad _]]]; discriminate Hbad]. }
  split_and!.
  - exact Hgate.
  - intros Haff Hc0.
    unfold check_fast_write_token, compute_fast_write_token.
    rewrite Haff, Hc0.
    destruct j as [log|].
    + rewrite (bool_decide_eq_false_2 (0 <= -1)%Z) by lia. reflexivity.
    + rewrite (bool_decide_eq_true_2 (0 <= owner_tok)%Z) by lia.
      rewrite !bool_decide_eq_false_2 by lia. reflexivity.
  - unfold signal_set_token_fast.
    destruct (check_fast_write_token _ caller_tok) eqn:Hchk.
    + destruct (proj1 Hgate eq_refl) as [-> Hcase].
      unfold signal_set_entered, graph_enter, signal_journal_record.
      destruct Hcase as [Haff | [Haff Hme]].
      * rewrite Haff. symmetry. apply write_signal_unjournaled_eq.
      * rewrite Haff, decide_True by exact Hme. symmetry. apply write_signal_unjournaled_eq.
    + apply (proj1 (signal_set_fast_split_refines me ctx f n v cs j s)).
Qed.
References
✓ No axioms

Calling RequestFlushFromEntered after graph_enter has already succeeded skips a redundant Enter/Release round-trip identically to RequestFlush.

Matches 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.

Arguments

me : nat
the calling thread id (me > 0 under Serialised).
ctx : nat
the calling thread's SynchronizationContext id.
the concurrency state before the outer entry.
cs_entered : concurrency_state
the entered concurrency state.
must_rel : bool
whether the outer entry must pair with Release.
Theorem request_flush_from_entered_eq
    (me ctx : nat) (cs cs_entered : concurrency_state) (must_rel : bool) :
  (cs_affinity cs = AffSerialised -> me > 0) ->
  graph_enter me ctx cs = Some (cs_entered, must_rel) ->
  graph_enter me ctx cs_entered = Some (cs_entered, false).

Arguments

me : nat
the calling thread id (me > 0 under Serialised).
ctx : nat
the calling thread's SynchronizationContext id.
the concurrency state before the outer entry.
cs_entered : concurrency_state
the entered concurrency state.
must_rel : bool
whether the outer entry must pair with Release.
Qed
Proof.
  intros Hme Hent. unfold graph_enter in *.
  destruct (cs_affinity cs) eqn:Haff.
  - destruct (decide (me = cs_owner_thread cs)) as [Heq|Hne]; [|discriminate].
    simplify_eq. simpl. by rewrite Haff, decide_True by congruence.
  - simplify_eq. simpl. by rewrite Haff.
  - destruct (decide (cs_holder cs = me)) as [Hh|Hh].
    + simplify_eq. simpl. by rewrite Haff, decide_True by congruence.
    + destruct (decide (ctx = cs_context cs /\ cs_holder cs = 0)); [|discriminate].
      simplify_eq. simpl. by rewrite ?Haff, decide_True by reflexivity.
Qed.
References

Classification of GraphOptions.Equality (Types.fs lines 331–346, Core.fs Graph.EncodedComparer): either JsIdentityPolicy (PolJsIdentity, where Fable's Comparer<'T>() always returns ReferenceComparer<'T> with is_val_type = false) or a custom/structural policy (PolCustom resolve).

Inductive equality_policy :=
  | PolJsIdentity
  | PolCustom (resolve : nullable_comparer).
References
Definition resolve_policy_comparer (p : equality_policy) : nullable_comparer :=
  match p with
  | PolJsIdentity => CmpRefIdentity
  | PolCustom c => c
  end.
References
Definition graph_uses_js_identity (p : equality_policy) : bool :=
  match p with
  | PolJsIdentity => true
  | PolCustom _ => false
  end.
References
Definition graph_encoded_comparer_fable
    (uses_js_id : bool) (val_eq ref_eq : Z -> Z -> bool) (p : equality_policy) : comparer_sentinel :=
  if uses_js_id then SentDefaultNull
  else encode_comparer_sentinel false val_eq ref_eq (resolve_policy_comparer p).
References
✓ No axioms

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.

Matches 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.

Arguments

val_eq : Z -> Z -> bool
value equality relation.
ref_eq : Z -> Z -> bool
JS === / reference equality relation.
the graph's immutable IEqualityPolicy.
a : Z
the previous value.
b : Z
the candidate value.
Theorem graph_encoded_comparer_cache_eq
    (val_eq ref_eq : Z -> Z -> bool) (p : equality_policy) (a b : Z) :
  graph_encoded_comparer_fable (graph_uses_js_identity p) val_eq ref_eq p =
    encode_comparer_sentinel false val_eq ref_eq (resolve_policy_comparer p) /\
  eval_comparer_sentinel false val_eq ref_eq
    (graph_encoded_comparer_fable (graph_uses_js_identity p) val_eq ref_eq p) a b =
    eval_nullable_comparer val_eq ref_eq (resolve_policy_comparer p) a b.

Arguments

val_eq : Z -> Z -> bool
value equality relation.
ref_eq : Z -> Z -> bool
JS === / reference equality relation.
the graph's immutable IEqualityPolicy.
a : Z
the previous value.
b : Z
the candidate value.
Qed
Proof.
  destruct p as [|c]; simpl.
  - split; reflexivity.
  - split; [reflexivity | apply (proj1 (default_comparer_null_sentinel_eq false val_eq ref_eq c a b))].
Qed.
References

6. Wave 4 fast-path contracts: optional encoded comparers, source read splits, direct graph-thread post, concrete binding refresh, and versioned edit state

Definition eval_optional_comparer
    (val_eq ref_eq : Z -> Z -> bool) (p : equality_policy) (oc : option nullable_comparer) (a b : Z) : cmp_outcome :=
  match oc with
  | Some c => eval_nullable_comparer val_eq ref_eq c a b
  | None => eval_nullable_comparer val_eq ref_eq (resolve_policy_comparer p) a b
  end.
References
Definition encode_optional_comparer
    (is_val_type : bool) (val_eq ref_eq : Z -> Z -> bool) (p : equality_policy) (oc : option nullable_comparer)
    : comparer_sentinel :=
  match oc with
  | Some c => encode_comparer_sentinel is_val_type val_eq ref_eq c
  | None =>
      if negb is_val_type && graph_uses_js_identity p then SentDefaultNull
      else encode_comparer_sentinel is_val_type val_eq ref_eq (resolve_policy_comparer p)
  end.
References
Definition ref_same_seed
    (is_val_type : bool) (val_eq ref_eq : Z -> Z -> bool) (c : nullable_comparer) (a b : Z) : cmp_outcome :=
  if negb is_val_type && ref_eq a b then CmpBool true
  else eval_nullable_comparer val_eq ref_eq c a b.
References
Definition same_seed_encoded
    (is_val_type : bool) (val_eq ref_eq : Z -> Z -> bool) (s : comparer_sentinel) (a b : Z) : cmp_outcome :=
  if is_val_type then eval_comparer_sentinel true val_eq ref_eq s a b
  else if ref_eq a b then CmpBool true
  else match s with
       | SentDefaultNull => CmpBool false
       | _ => eval_comparer_sentinel false val_eq ref_eq s a b
       end.
References
✓ No axioms

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.

Matches Timed (Timed.fs), StreamMemo (Streams.fs), and Identity.sameSeed (Api.fs):

Arguments

is_val_type : bool
true when typeof<'T>.IsValueType, false otherwise.
val_eq : Z -> Z -> bool
the intrinsic EqualityComparer<'T>.Default.Equals relation.
ref_eq : Z -> Z -> bool
the intrinsic obj.ReferenceEquals relation.
the graph's IEqualityPolicy.
oc : option nullable_comparer
TimedOptions.Comparer (Some c or None).
the resolved nullable comparer passed to sameSeed.
a : Z
the previous value.
b : Z
the candidate value.
Theorem optional_comparer_sentinel_eq
    (is_val_type : bool) (val_eq ref_eq : Z -> Z -> bool)
    (p : equality_policy) (oc : option nullable_comparer) (c : nullable_comparer) (a b : Z) :
  eval_comparer_sentinel is_val_type val_eq ref_eq
    (encode_optional_comparer is_val_type val_eq ref_eq p oc) a b =
    eval_optional_comparer val_eq ref_eq p oc a b /\
  same_seed_encoded is_val_type val_eq ref_eq
    (encode_comparer_sentinel is_val_type val_eq ref_eq c) a b =
    ref_same_seed is_val_type val_eq ref_eq c a b.

Arguments

is_val_type : bool
true when typeof<'T>.IsValueType, false otherwise.
val_eq : Z -> Z -> bool
the intrinsic EqualityComparer<'T>.Default.Equals relation.
ref_eq : Z -> Z -> bool
the intrinsic obj.ReferenceEquals relation.
the graph's IEqualityPolicy.
oc : option nullable_comparer
TimedOptions.Comparer (Some c or None).
the resolved nullable comparer passed to sameSeed.
a : Z
the previous value.
b : Z
the candidate value.
Qed
Proof.
  split.
  - destruct oc as [c0|].
    + simpl. apply (proj1 (default_comparer_null_sentinel_eq is_val_type val_eq ref_eq c0 a b)).
    + unfold encode_optional_comparer, eval_optional_comparer.
      destruct is_val_type, p as [|c0]; simpl; try reflexivity;
        apply (proj1 (default_comparer_null_sentinel_eq _ val_eq ref_eq c0 a b)).
  - unfold same_seed_encoded, ref_same_seed.
    destruct is_val_type.
    + simpl. apply (proj1 (default_comparer_null_sentinel_eq true val_eq ref_eq c a b)).
    + simpl. destruct (ref_eq a b) eqn:Href; [reflexivity|].
      destruct c; simpl; try reflexivity. rewrite Href. reflexivity.
Qed.
References
Definition is_unready_bits (st : status) : bool :=
  bool_decide (Z.land (status_byte st false) 3%Z <> 0%Z).
References

Uses

Inductive source_read_val :=
  | SRValue (v : Z)
  | SRPending
  | SRError (err : Z).
References

Uses

  • Z
Inductive source_try_val :=
  | STReady (v : Z)
  | STPending
  | STFailed (err : Z).
References

Uses

  • Z
Definition push_read_ref (st : status) (v err : Z) : source_read_val :=
  match st with
  | StPending => SRPending
  | StError => SRError err
  | _ => SRValue v
  end.
References
Definition push_read_fast (st : status) (v err : Z) : source_read_val :=
  if is_unready_bits st then
    match st with
    | StPending => SRPending
    | _ => SRError err
    end
  else SRValue v.
References
Definition pull_value_ref
    (slow : freshness -> bool -> status -> Z -> Z -> nat * source_read_val)
    (fr : freshness) (disp : bool) (st : status) (v err : Z) : nat * source_read_val :=
  if negb (bool_decide (fr = Clean)) && negb disp then slow fr disp st v err
  else (1, push_read_ref st v err).
References

Uses

2 more
  • Z
  • bool_decide
Definition pull_value_fast
    (slow : freshness -> bool -> status -> Z -> Z -> nat * source_read_val)
    (fr : freshness) (disp : bool) (st : status) (v err : Z) : nat * source_read_val :=
  if is_clean_and_ready_bits fr st false then (1, SRValue v)
  else pull_value_ref slow fr disp st v err.
References
Definition pull_try_ref
    (slow : freshness -> bool -> status -> Z -> Z -> nat * source_try_val)
    (fr : freshness) (disp : bool) (st : status) (v err : Z) : nat * source_try_val :=
  if negb (bool_decide (fr = Clean)) && negb disp then slow fr disp st v err
  else (1, match st with StPending => STPending | StError => STFailed err | _ => STReady v end).
References
Definition pull_try_fast
    (slow : freshness -> bool -> status -> Z -> Z -> nat * source_try_val)
    (fr : freshness) (disp : bool) (st : status) (v err : Z) : nat * source_try_val :=
  if is_clean_and_ready_bits fr st false then (1, STReady v)
  else pull_try_ref slow fr disp st v err.
References
✓ No axioms

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.

Matches AsyncSource.Value, AsyncMemo.Value/TryValue, Boundary.Value/TryValue (Core.fs), StreamMemo.Value/TryValue (Streams.fs), and Timed.Value (Timed.fs):

Arguments

slow_val : freshness -> bool -> status -> Z -> Z -> nat * source_read_val
the slow-path transition for Value when stale and undisposed.
slow_try : freshness -> bool -> status -> Z -> Z -> nat * source_try_val
the slow-path transition for TryValue when stale and undisposed.
the node's Freshness.
disp : bool
whether the node is disposed.
st : status
the node's Status.
v : Z
the cached ready value.
err : Z
the stored error identity.
Theorem clean_ready_source_read_split_eq
    (slow_val : freshness -> bool -> status -> Z -> Z -> nat * source_read_val)
    (slow_try : freshness -> bool -> status -> Z -> Z -> nat * source_try_val)
    (fr : freshness) (disp : bool) (st : status) (v err : Z) :
  push_read_fast st v err = push_read_ref st v err /\
  pull_value_fast slow_val fr disp st v err = pull_value_ref slow_val fr disp st v err /\
  pull_try_fast slow_try fr disp st v err = pull_try_ref slow_try fr disp st v err.

Arguments

slow_val : freshness -> bool -> status -> Z -> Z -> nat * source_read_val
the slow-path transition for Value when stale and undisposed.
slow_try : freshness -> bool -> status -> Z -> Z -> nat * source_try_val
the slow-path transition for TryValue when stale and undisposed.
the node's Freshness.
disp : bool
whether the node is disposed.
st : status
the node's Status.
v : Z
the cached ready value.
err : Z
the stored error identity.
Qed
Proof.
  unfold push_read_fast, push_read_ref, is_unready_bits,
         pull_value_fast, pull_value_ref, pull_try_fast, pull_try_ref,
         is_clean_and_ready_bits, freshness_byte, status_byte.
  destruct fr, disp, st; vm_compute; repeat split; reflexivity.
Qed.
References
Inductive post_outcome :=
  | PostInline
  | PostEnqueued (cs' : concurrency_state).
References
Definition graph_post (me : nat) (w : nat) (cs : concurrency_state) : post_outcome :=
  if is_on_graph_thread me cs then PostInline else PostEnqueued (post_queued w cs).
References
Definition direct_post_on_thread (me : nat) (w : nat) (cs : concurrency_state) : post_outcome :=
  if is_on_graph_thread me cs then PostInline else PostEnqueued (post_queued w cs).
References
Definition continue_with_state (cb : Z -> Z) (settled_v : Z) : Z :=
  let invoke := (fun s (v : Z) => (fun x => cb x) v) in
  invoke tt settled_v.
References

Uses

  • tt
  • Z
✓ No axioms

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.

Arguments

me : nat
the calling thread id.
w : nat
the posted work item id.
the graph concurrency state.
cb : Z -> Z
the continuation function.
settled_v : Z
the settled task outcome value.
Theorem direct_post_on_graph_thread_eq
    (me : nat) (w : nat) (cs : concurrency_state) (cb : Z -> Z) (settled_v : Z) :
  direct_post_on_thread me w cs = graph_post me w cs /\
  continue_with_state cb settled_v = cb settled_v.

Arguments

me : nat
the calling thread id.
w : nat
the posted work item id.
the graph concurrency state.
cb : Z -> Z
the continuation function.
settled_v : Z
the settled task outcome value.
Qed
Proof.
  unfold direct_post_on_thread, graph_post, continue_with_state.
  split; reflexivity.
Qed.
References
Definition is_stale_node (fr : freshness) (disp : bool) : bool :=
  negb (bool_decide (fr = Clean)) && negb disp.
References

Uses

Definition ensure_current_memo (refresh : freshness -> status -> freshness * status * Z) (fr : freshness) (disp : bool) (st : status) : freshness * status * Z :=
  if negb (bool_decide (fr = Clean)) && negb disp then refresh fr st else (fr, st, 0%Z).
References

Uses

Definition ensure_current_guarded (refresh : freshness -> status -> freshness * status * Z) (fr : freshness) (disp : bool) (st : status) : freshness * status * Z :=
  if is_stale_node fr disp then ensure_current_memo refresh fr disp st else (fr, st, 0%Z).
References
Definition binding_check_virtual (b_fr : freshness) (is_stale is_active : bool) : freshness :=
  match b_fr with
  | Check => if is_stale && is_active then Dirty else b_fr
  | _ => b_fr
  end.
References
Definition binding_check_concrete (has_memo : bool) (b_fr m_fr : freshness) (m_disp m_active : bool) : freshness :=
  if has_memo then
    match b_fr with
    | Check => if is_stale_node m_fr m_disp && m_active then Dirty else b_fr
    | _ => b_fr
    end
  else b_fr.
References
Definition memo_read_untracked (fr : freshness) (disp : bool) (st : status) (v err : Z)
    (pull : freshness -> bool -> status -> Z -> Z -> source_try_val) : source_try_val :=
  if negb (bool_decide (fr = Clean)) && negb disp then pull fr disp st v err
  else match st with
       | StPending => STPending
       | StError => STFailed err
       | _ => STReady v
       end.
References
Definition binding_read_fast (fr : freshness) (disp : bool) (st : status) (v err : Z)
    (pull : freshness -> bool -> status -> Z -> Z -> source_try_val) : source_try_val :=
  if is_clean_and_ready_bits fr st false then STReady v
  else memo_read_untracked fr disp st v err pull.
References
✓ No axioms

Replacing 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.

Matches Memo.EnsureCurrent / IsStaleNode / IsActiveNode (Core.fs), Binding.Execute / Binding.Run (Bindings.fs), and Editable.Value setter (Api.fs):

  • is_stale_node m_fr m_disp equals m_fr <> Clean && negb m_disp.
  • Guarding EnsureCurrent with is_stale_node (Editable.set_Value) equals calling EnsureCurrent directly.
  • Concrete Binding.Execute check resolution distinguishes OfSignal (IsStale = false, no loop) from OfMemo identically to ISource.IsStale && ISource.IsActive.
  • binding_read_fast (elif memo.IsCleanAndReady then memo.Peek) equals memo.ReadUntracked () for every (fr, disp, st, v, err).

Arguments

refresh : freshness -> status -> freshness * status * Z
the memo refresh action when stale.
pull : freshness -> bool -> status -> Z -> Z -> source_try_val
the untracked pull transition when stale.
has_memo : bool
true for OfMemo, false for OfSignal.
b_fr : freshness
the binding's freshness.
m_fr : freshness
the source memo's freshness.
m_disp : bool
whether the source memo is disposed.
m_active : bool
whether the source memo is active.
st : status
the source memo's Status.
v : Z
the source memo's cached value.
err : Z
the source memo's error identity.
Theorem binding_concrete_memo_refresh_and_read_eq
    (refresh : freshness -> status -> freshness * status * Z)
    (pull : freshness -> bool -> status -> Z -> Z -> source_try_val)
    (has_memo : bool) (b_fr m_fr : freshness) (m_disp m_active : bool) (st : status) (v err : Z) :
  ensure_current_guarded refresh m_fr m_disp st = ensure_current_memo refresh m_fr m_disp st /\
  binding_check_concrete has_memo b_fr m_fr m_disp m_active =
    binding_check_virtual b_fr (if has_memo then is_stale_node m_fr m_disp else false) (if has_memo then m_active else false) /\
  binding_read_fast m_fr m_disp st v err pull = memo_read_untracked m_fr m_disp st v err pull.

Arguments

refresh : freshness -> status -> freshness * status * Z
the memo refresh action when stale.
pull : freshness -> bool -> status -> Z -> Z -> source_try_val
the untracked pull transition when stale.
has_memo : bool
true for OfMemo, false for OfSignal.
b_fr : freshness
the binding's freshness.
m_fr : freshness
the source memo's freshness.
m_disp : bool
whether the source memo is disposed.
m_active : bool
whether the source memo is active.
st : status
the source memo's Status.
v : Z
the source memo's cached value.
err : Z
the source memo's error identity.
Qed
Proof.
  unfold ensure_current_guarded, ensure_current_memo, is_stale_node,
         binding_check_concrete, binding_check_virtual,
         binding_read_fast, memo_read_untracked,
         is_clean_and_ready_bits, freshness_byte, status_byte.
  destruct has_memo, b_fr, m_fr, m_disp, m_active, st; vm_compute; repeat split; reflexivity.
Qed.
References
Record edit_state := { es_ver : Z; es_val : Z }.
References

Uses

  • Z
Definition unedited_state (default_v : Z) : edit_state := {| es_ver := (-1)%Z; es_val := default_v |}.
References
Definition edit_state_of_opt (default_v : Z) (o : option (nat * Z)) : edit_state :=
  match o with
  | None => unedited_state default_v
  | Some (ver, v) => {| es_ver := Z.of_nat ver; es_val := v |}
  end.
References

Uses

2 more
  • Z
  • Z.of_nat
Definition edit_state_active (es : edit_state) : bool :=
  bool_decide (0 <= es_ver es)%Z.
References

Uses

Definition edit_state_eq (val_eq : Z -> Z -> bool) (a b : edit_state) : bool :=
  bool_decide (es_ver a = es_ver b) && (bool_decide (es_ver a < 0)%Z || val_eq (es_val a) (es_val b)).
References

Uses

Definition ref_edit_opt_eq (val_eq : Z -> Z -> bool) (a b : option (nat * Z)) : bool :=
  match a, b with
  | None, None => true
  | Some (va, xa), Some (vb, xb) => bool_decide (va = vb) && val_eq xa xb
  | _, _ => false
  end.
References

Uses

  • None
  • Some
  • bool
  • false
  • nat
  • option
  • true
  • Z
1 more
  • bool_decide
Definition read_edit_opt (in_force : nat -> bool) (seed_v : Z) (o : option (nat * Z)) : bool * Z :=
  match o with
  | Some (ver, x) => if in_force ver then (true, x) else (false, seed_v)
  | None => (false, seed_v)
  end.
References

Uses

  • None
  • Some
  • bool
  • false
  • nat
  • option
  • true
  • Z
Definition read_edit_state (in_force : nat -> bool) (seed_v : Z) (es : edit_state) : bool * Z :=
  if edit_state_active es then
    let ver := Z.to_nat (es_ver es) in
    if in_force ver then (true, es_val es) else (false, seed_v)
  else (false, seed_v).
References

Uses

2 more
  • Z
  • Z.to_nat
✓ No axioms

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.

Matches EditState<'T>, EditComparer<'T>, and Editable<'T> (Api.fs):

  • edit_state_of_opt maps None to es_ver = -1 and Some (ver, v) to es_ver = Z.of_nat ver >= 0.
  • edit_state_eq val_eq matches ref_edit_opt_eq val_eq for any cutoff comparator val_eq, regardless of the arbitrary default payload stored in unedited_state.
  • read_edit_state (IsEdited, Value) matches read_edit_opt for any in_force predicate (covering both Editable and Draft).

Arguments

val_eq : Z -> Z -> bool
the encoded cutoff equality predicate on 'T.
in_force : nat -> bool
whether a given seed version still holds the edit.
d1 : Z
default payload of the first unedited sentinel.
d2 : Z
default payload of the second unedited sentinel.
seed_v : Z
the seed's fallback value when unedited or superseded.
a : option (nat * Z)
first reference edit option.
b : option (nat * Z)
second reference edit option.
Theorem editable_versioned_state_refines_voption
    (val_eq : Z -> Z -> bool) (in_force : nat -> bool) (d1 d2 seed_v : Z) (a b : option (nat * Z)) :
  edit_state_eq val_eq (edit_state_of_opt d1 a) (edit_state_of_opt d2 b) = ref_edit_opt_eq val_eq a b /\
  read_edit_state in_force seed_v (edit_state_of_opt d1 a) = read_edit_opt in_force seed_v a.

Arguments

val_eq : Z -> Z -> bool
the encoded cutoff equality predicate on 'T.
in_force : nat -> bool
whether a given seed version still holds the edit.
d1 : Z
default payload of the first unedited sentinel.
d2 : Z
default payload of the second unedited sentinel.
seed_v : Z
the seed's fallback value when unedited or superseded.
a : option (nat * Z)
first reference edit option.
b : option (nat * Z)
second reference edit option.
Qed
Proof.
  unfold edit_state_eq, ref_edit_opt_eq, read_edit_state, read_edit_opt,
         edit_state_of_opt, unedited_state, edit_state_active.
  split.
  - destruct a as [[va xa]|], b as [[vb xb]|]; simpl.
    + destruct (decide (va = vb)) as [->|Hne].
      * rewrite (bool_decide_eq_true_2 (Z.of_nat vb = Z.of_nat vb)) by reflexivity.
        rewrite (bool_decide_eq_true_2 (vb = vb)) by reflexivity.
        rewrite (bool_decide_eq_false_2 (Z.of_nat vb < 0)%Z) by lia.
        reflexivity.
      * rewrite (bool_decide_eq_false_2 (Z.of_nat va = Z.of_nat vb)) by lia.
        rewrite (bool_decide_eq_false_2 (va = vb)) by exact Hne.
        reflexivity.
    + rewrite (bool_decide_eq_false_2 (Z.of_nat va = (-1)%Z)) by lia. reflexivity.
    + rewrite (bool_decide_eq_false_2 ((-1)%Z = Z.of_nat vb)) by lia. reflexivity.
    + vm_compute. reflexivity.
  - destruct a as [[va xa]|]; simpl.
    + rewrite (bool_decide_eq_true_2 (0 <= Z.of_nat va)%Z) by lia.
      rewrite Nat2Z.id. reflexivity.
    + vm_compute. reflexivity.
Qed.
References

Uses

8 more
  • nat
  • option
  • Z
  • Z.of_nat
  • Nat2Z.id
  • decide
  • bool_decide_eq_false_2
  • bool_decide_eq_true_2

Timed.Wake volatile reset and no-lost-wakeup (B14)

State of the `Timed` wake handshake between an off-thread timer callback and the graph thread.

Record timed_wake_state := {
  tw_pending_fire : bool;
  tw_wake_posted : nat;
  tw_wake_in_flight : bool;
  tw_effect_queued : bool
}.
References

Uses

  • bool
  • nat

Initial `Timed` wake state before any timer callback fires.

Definition init_timed_wake_state : timed_wake_state :=
  {| tw_pending_fire := false; tw_wake_posted := 0; tw_wake_in_flight := false; tw_effect_queued := false |}.
References

Atomic transitions for `Timed.OnTimerFired`, `Timed.Wake` (`Volatile.Write` then `Enqueue`), and `Timed.Execute`.

Inductive timed_wake_op :=
  | TwTimerFire
  | TwWakeClear
  | TwWakeEnqueue
  | TwConsume.
References

Executes one atomic transition preserving the ordering `wakePosted := 0` before `Enqueue`.

References

Global invariant asserting no pending timer trigger can exist without a posted wake, an in-flight wake handler, or a queued execution.

Definition tw_no_lost_wakeup_inv (st : timed_wake_state) : Prop :=
  (tw_pending_fire st = true ->
   tw_wake_posted st = 1 \/ tw_wake_in_flight st = true \/ tw_effect_queued st = true) /\
  (tw_wake_posted st = 0 \/ tw_wake_posted st = 1) /\
  (tw_wake_posted st = 1 -> tw_wake_in_flight st = true).
References

Trace evaluator over a list of atomic `timed_wake_op` events.

Fixpoint run_timed_wake_trace (st : timed_wake_state) (tr : list timed_wake_op) : timed_wake_state :=
  match tr with
  | [] => st
  | op :: rest => run_timed_wake_trace (step_timed_wake op st) rest
  end.
References

Atomic transitions for a buggy wrong-order `Wake` (`Enqueue` before clearing `wakePosted`).

Inductive bad_wake_op :=
  | BadTimerFire
  | BadWakeEnqueue
  | BadWakeClear
  | BadConsume.
References

Executes one transition of the reversed-order (`Enqueue` before `Clear`) `Wake` model.

References

Trace evaluator for the buggy wrong-order `Wake` model.

Fixpoint run_bad_wake_trace (st : timed_wake_state) (tr : list bad_wake_op) : timed_wake_state :=
  match tr with
  | [] => st
  | op :: rest => run_bad_wake_trace (step_bad_wake op st) rest
  end.
References

Concrete wrong-order interleaving (`TimerFire` -> `Enqueue` -> `Consume` -> `TimerFire` -> delayed `Clear`) that loses a wakeup.

Definition reversed_wake_bad_trace : list bad_wake_op :=
  [BadTimerFire; BadWakeEnqueue; BadConsume; BadTimerFire; BadWakeClear].
References
✓ No axioms

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).

Models 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).

Arguments

starting handshake state satisfying tw_no_lost_wakeup_inv.
tr : list timed_wake_op
arbitrary trace of atomic timer fires, Wake clear/enqueue steps, and effect executions.
Theorem timed_wake_volatile_reset_no_lost_wakeup
    (st0 : timed_wake_state) (tr : list timed_wake_op) :
  tw_no_lost_wakeup_inv st0 ->
  let st := run_timed_wake_trace st0 tr in
  (tw_pending_fire st = true ->
   tw_wake_posted st = 1 \/ tw_wake_in_flight st = true \/ tw_effect_queued st = true) /\
  (tw_pending_fire (run_timed_wake_trace init_timed_wake_state tr) = true ->
   tw_wake_posted (run_timed_wake_trace init_timed_wake_state tr) = 1 \/
   tw_wake_in_flight (run_timed_wake_trace init_timed_wake_state tr) = true \/
   tw_effect_queued (run_timed_wake_trace init_timed_wake_state tr) = true) /\
  (let st_race := run_timed_wake_trace st [TwTimerFire; TwWakeClear; TwTimerFire; TwWakeEnqueue] in
   tw_pending_fire st_race = true /\
   tw_wake_posted st_race = 1 /\
   tw_wake_in_flight st_race = true /\
   tw_effect_queued st_race = true) /\
  (let st_bad := run_bad_wake_trace init_timed_wake_state reversed_wake_bad_trace in
   tw_pending_fire st_bad = true /\
   tw_wake_posted st_bad = 0 /\
   tw_wake_in_flight st_bad = false /\
   tw_effect_queued st_bad = false).

Arguments

starting handshake state satisfying tw_no_lost_wakeup_inv.
tr : list timed_wake_op
arbitrary trace of atomic timer fires, Wake clear/enqueue steps, and effect executions.
Qed
Proof.
  intros Hinv0.
  assert (Hstep : forall op s, tw_no_lost_wakeup_inv s -> tw_no_lost_wakeup_inv (step_timed_wake op s)).
  { intros op s [Hp [Hw Hinf]].
    destruct op; simpl.
    - destruct (tw_wake_posted s =? 0)%nat eqn:Ewp; simpl.
      + split; [intros _; left; reflexivity|].
        split; [right; reflexivity|intros _; reflexivity].
      + destruct Hw as [Hw0|Hw1]; [rewrite Hw0 in Ewp; discriminate|].
        split; [intros _; left; exact Hw1|].
        split; [right; exact Hw1|exact Hinf].
    - destruct (tw_wake_in_flight s) eqn:Eif; simpl.
      + split; [intros _; right; left; reflexivity|].
        split; [left; reflexivity|intros Hc; discriminate].
      + unfold tw_no_lost_wakeup_inv. rewrite Eif. split; [exact Hp|split; assumption].
    - destruct (tw_wake_in_flight s) eqn:Eif; simpl.
      + split; [intros _; right; right; reflexivity|].
        split; [exact Hw|intros Hw1; simpl in Hw1; rewrite Hw1; reflexivity].
      + unfold tw_no_lost_wakeup_inv. rewrite Eif. split; [exact Hp|split; assumption].
    - destruct (tw_effect_queued s) eqn:Heq; simpl.
      + split; [intros Hc; discriminate|split; assumption].
      + unfold tw_no_lost_wakeup_inv. rewrite Heq. split; [exact Hp|split; assumption]. }
  assert (Hrun : forall tr' s, tw_no_lost_wakeup_inv s -> tw_no_lost_wakeup_inv (run_timed_wake_trace s tr')).
  { intros tr'. induction tr' as [|op rest IH]; intros s Hs; simpl; [exact Hs|].
    apply IH. apply Hstep. exact Hs. }
  assert (Hinit : tw_no_lost_wakeup_inv init_timed_wake_state).
  { split; simpl; [intros H; discriminate|split; [left; reflexivity|intros H; discriminate]]. }
  pose proof (Hrun tr st0 Hinv0) as Hinv_st.
  pose proof (Hrun tr init_timed_wake_state Hinit) as Hinv_init.
  split; [intros Hp; exact (proj1 Hinv_st Hp)|].
  split; [intros Hp; exact (proj1 Hinv_init Hp)|].
  split; [|repeat split; reflexivity].
  destruct Hinv_st as [_ [[Hw0|Hw1] Hinf]].
  - simpl. rewrite Hw0. repeat split; reflexivity.
  - pose proof (Hinf Hw1) as Hif. simpl. rewrite Hw1, Hif. repeat split; reflexivity.
Qed.
References

Coalesced drain posts and no lost drain

State of the coalesced drain post on a graph that is not Serialised (Graph.PostQueued, PostDrainOnce, Drain and PumpFromDispatcher, Core.fs): the inbox, the drainPosted flag, and the drains posted to the dispatcher.

Record drain_post_state := {
  dp_queued : nat;      (* items in the inbox *)
  dp_unposted : nat;    (* items enqueued whose `PostDrainOnce` has yet to run *)
  dp_posted : nat;      (* `drainPosted`: 0 or 1 *)
  dp_scheduled : nat;   (* drains posted to the dispatcher that have yet to start *)
  dp_draining : bool;   (* a drain has cleared `drainPosted` and takes from the inbox *)
  dp_pump_owed : bool   (* a posted drain raised before draining; the inbox waits for the owning thread's `Pump` *)
}.
References

Uses

  • bool
  • nat

The state of a new graph.

Definition init_drain_post_state : drain_post_state :=
  {| dp_queued := 0; dp_unposted := 0; dp_posted := 0; dp_scheduled := 0;
     dp_draining := false; dp_pump_owed := false |}.
References

Atomic steps of the protocol.

Inductive drain_post_op :=
  | DpEnqueue        (* `PostQueued`: `inbox.Enqueue` *)
  | DpPost           (* `PostDrainOnce`: `CompareExchange (&drainPosted, 1, 0)`, then `dispatcher.Post` on success *)
  | DpDispatchStart  (* a posted drain starts: `Drain`'s `Interlocked.Exchange (&drainPosted, 0)` *)
  | DpPumpStart      (* the owning thread's `Pump` starts a drain the same way, without a posted drain *)
  | DpDispatchRaise  (* a posted drain raises before draining: `PumpFromDispatcher`'s `Volatile.Write (&drainPosted, 0)` *)
  | DpTake           (* `inbox.TryTake` returns an item *)
  | DpDrainEnd.
References

`inbox.TryTake` returns none, and the drain ends

One atomic step. A step whose precondition fails leaves the state unchanged.

Definition step_drain_post (op : drain_post_op) (st : drain_post_state) : drain_post_state :=
  match op with
  | DpEnqueue =>
    {| dp_queued := S (dp_queued st); dp_unposted := S (dp_unposted st); dp_posted := dp_posted st;
       dp_scheduled := dp_scheduled st; dp_draining := dp_draining st; dp_pump_owed := dp_pump_owed st |}
  | DpPost =>
    match dp_unposted st with
    | 0 => st
    | S u =>
      match dp_posted st with
      | 0 =>
        {| dp_queued := dp_queued st; dp_unposted := u; dp_posted := 1;
           dp_scheduled := S (dp_scheduled st); dp_draining := dp_draining st; dp_pump_owed := dp_pump_owed st |}
      | S _ =>
        {| dp_queued := dp_queued st; dp_unposted := u; dp_posted := dp_posted st;
           dp_scheduled := dp_scheduled st; dp_draining := dp_draining st; dp_pump_owed := dp_pump_owed st |}
      end
    end
  | DpDispatchStart =>
    match dp_scheduled st with
    | 0 => st
    | S s =>
      {| dp_queued := dp_queued st; dp_unposted := dp_unposted st; dp_posted := 0;
         dp_scheduled := s; dp_draining := true; dp_pump_owed := dp_pump_owed st |}
    end
  | DpPumpStart =>
    {| dp_queued := dp_queued st; dp_unposted := dp_unposted st; dp_posted := 0;
       dp_scheduled := dp_scheduled st; dp_draining := true; dp_pump_owed := false |}
  | DpDispatchRaise =>
    match dp_scheduled st with
    | 0 => st
    | S s =>
      {| dp_queued := dp_queued st; dp_unposted := dp_unposted st; dp_posted := 0;
         dp_scheduled := s; dp_draining := dp_draining st; dp_pump_owed := true |}
    end
  | DpTake =>
    match dp_draining st, dp_queued st with
    | true, S q =>
      {| dp_queued := q; dp_unposted := dp_unposted st; dp_posted := dp_posted st;
         dp_scheduled := dp_scheduled st; dp_draining := true; dp_pump_owed := dp_pump_owed st |}
    | _, _ => st
    end
  | DpDrainEnd =>
    match dp_draining st, dp_queued st with
    | true, 0 =>
      {| dp_queued := 0; dp_unposted := dp_unposted st; dp_posted := dp_posted st;
         dp_scheduled := dp_scheduled st; dp_draining := false; dp_pump_owed := dp_pump_owed st |}
    | _, _ => st
    end
  end.
References

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 `Pump` after a raising drain.

Definition dp_no_lost_drain (st : drain_post_state) : Prop :=
  dp_queued st > 0 ->
  dp_draining st = true \/ dp_scheduled st > 0 \/ dp_unposted st > 0 \/ dp_pump_owed st = true.
References

The protocol invariant: no lost drain, and a set `drainPosted` always has a posted drain yet to start.

Definition dp_inv (st : drain_post_state) : Prop :=
  dp_no_lost_drain st /\
  (dp_posted st = 0 \/ dp_posted st = 1) /\
  (dp_posted st = 1 -> dp_scheduled st > 0).
References

Trace evaluator over a list of atomic steps.

Fixpoint run_drain_post_trace (st : drain_post_state) (tr : list drain_post_op) : drain_post_state :=
  match tr with
  | [] => st
  | op :: rest => run_drain_post_trace (step_drain_post op st) rest
  end.
References
✓ No axioms

Each atomic step preserves `dp_inv`.

Lemma step_drain_post_inv (op : drain_post_op) (st : drain_post_state) :
  dp_inv st -> dp_inv (step_drain_post op st).
Qed
Proof.
  destruct st as [q u p s d o].
  unfold dp_inv, dp_no_lost_drain; simpl.
  intros [Hlost [Hp01 Hps]].
  destruct op; simpl.
  - split; [intros _; right; right; left; lia|].
    split; assumption.
  - destruct u as [|u']; simpl.
    + split; [exact Hlost|split; assumption].
    + destruct p as [|p']; simpl.
      * split; [intros _; right; left; lia|].
        split; [right; reflexivity|intros _; lia].
      * assert (Hs : s > 0) by (apply Hps; lia).
        split; [intros _; right; left; exact Hs|].
        split; [exact Hp01|intros _; exact Hs].
  - destruct s as [|s']; simpl.
    + split; [exact Hlost|split; assumption].
    + split; [intros _; left; reflexivity|].
      split; [left; reflexivity|intros H; discriminate].
  - split; [intros _; left; reflexivity|].
    split; [left; reflexivity|intros H; discriminate].
  - destruct s as [|s']; simpl.
    + split; [exact Hlost|split; assumption].
    + split; [intros _; right; right; right; reflexivity|].
      split; [left; reflexivity|intros H; discriminate].
  - destruct d, q as [|q']; simpl.
    + split; [exact Hlost|split; assumption].
    + split; [intros _; left; reflexivity|split; assumption].
    + split; [exact Hlost|split; assumption].
    + split; [exact Hlost|split; assumption].
  - destruct d, q as [|q']; simpl.
    + split; [intros H; lia|split; assumption].
    + split; [exact Hlost|split; assumption].
    + split; [exact Hlost|split; assumption].
    + split; [exact Hlost|split; assumption].
Qed.
References
✓ No axioms

Every trace preserves `dp_inv`.

Lemma run_drain_post_trace_inv (tr : list drain_post_op) (st : drain_post_state) :
  dp_inv st -> dp_inv (run_drain_post_trace st tr).
Qed
Proof.
  revert st. induction tr as [|op rest IH]; intros st Hst; simpl; [exact Hst|].
  apply IH. apply step_drain_post_inv. exact Hst.
Qed.
References

Atomic steps of a drain that clears `drainPosted` after it ends rather than before its first take.

Inductive late_reset_op :=
  | LrEnqueue
  | LrPost
  | LrStart
  | LrTake
  | LrDrainEnd
  | LrLateReset.
References

One step of the late-reset drain: `LrStart` leaves `drainPosted` set, and `LrLateReset` clears it afterwards.

Definition step_late_reset (op : late_reset_op) (st : drain_post_state) : drain_post_state :=
  match op with
  | LrEnqueue => step_drain_post DpEnqueue st
  | LrPost => step_drain_post DpPost st
  | LrStart =>
    match dp_scheduled st with
    | 0 => st
    | S s =>
      {| dp_queued := dp_queued st; dp_unposted := dp_unposted st; dp_posted := dp_posted st;
         dp_scheduled := s; dp_draining := true; dp_pump_owed := dp_pump_owed st |}
    end
  | LrTake => step_drain_post DpTake st
  | LrDrainEnd => step_drain_post DpDrainEnd st
  | LrLateReset =>
    {| dp_queued := dp_queued st; dp_unposted := dp_unposted st; dp_posted := 0;
       dp_scheduled := dp_scheduled st; dp_draining := dp_draining st; dp_pump_owed := dp_pump_owed st |}
  end.
References

Trace evaluator for the late-reset drain.

Fixpoint run_late_reset_trace (st : drain_post_state) (tr : list late_reset_op) : drain_post_state :=
  match tr with
  | [] => st
  | op :: rest => run_late_reset_trace (step_late_reset op st) rest
  end.
References

A second item enqueued after the drain's last take, and posted before the late reset, loses its drain.

Definition late_reset_bad_trace : list late_reset_op :=
  [LrEnqueue; LrPost; LrStart; LrTake; LrDrainEnd; LrEnqueue; LrPost; LrLateReset].
References

Atomic steps of a dispatcher-run pump that raises and leaves `drainPosted` set.

Inductive raise_keeps_flag_op :=
  | RkEnqueue
  | RkPost
  | RkRaise.
References

One step of the flag-keeping raise: `RkRaise` consumes the posted drain and leaves `drainPosted` at its value.

Definition step_raise_keeps_flag (op : raise_keeps_flag_op) (st : drain_post_state) : drain_post_state :=
  match op with
  | RkEnqueue => step_drain_post DpEnqueue st
  | RkPost => step_drain_post DpPost st
  | RkRaise =>
    match dp_scheduled st with
    | 0 => st
    | S s =>
      {| dp_queued := dp_queued st; dp_unposted := dp_unposted st; dp_posted := dp_posted st;
         dp_scheduled := s; dp_draining := dp_draining st; dp_pump_owed := true |}
    end
  end.
References

Trace evaluator for the flag-keeping raise.

Fixpoint run_raise_keeps_flag_trace (st : drain_post_state) (tr : list raise_keeps_flag_op) : drain_post_state :=
  match tr with
  | [] => st
  | op :: rest => run_raise_keeps_flag_trace (step_raise_keeps_flag op st) rest
  end.
References
✓ No axioms

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.

Models 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:

  1. 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 Pump after a raising drain (dp_no_lost_drain);
  2. a set drainPosted always has a posted drain yet to start, so a post that finds it set has a drain to join;
  3. 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.

Arguments

a starting state satisfying dp_inv.
tr : list drain_post_op
an arbitrary trace of atomic steps.
Theorem coalesced_drain_post_no_lost_drain (st0 : drain_post_state) (tr : list drain_post_op) :
  dp_inv st0 ->
  dp_inv (run_drain_post_trace st0 tr) /\
  dp_inv (run_drain_post_trace init_drain_post_state tr) /\
  (let st_raise :=
     run_drain_post_trace init_drain_post_state [DpEnqueue; DpPost; DpDispatchRaise; DpEnqueue; DpPost] in
   dp_queued st_raise = 2 /\ dp_scheduled st_raise = 1 /\ dp_posted st_raise = 1) /\
  (let st_late := run_late_reset_trace init_drain_post_state late_reset_bad_trace in
   dp_queued st_late = 1 /\ dp_draining st_late = false /\ dp_scheduled st_late = 0 /\
   dp_unposted st_late = 0 /\ dp_pump_owed st_late = false) /\
  (let st_keep :=
     run_raise_keeps_flag_trace init_drain_post_state [RkEnqueue; RkPost; RkRaise; RkEnqueue; RkPost] in
   dp_queued st_keep = 2 /\ dp_scheduled st_keep = 0 /\ dp_posted st_keep = 1).

Arguments

a starting state satisfying dp_inv.
tr : list drain_post_op
an arbitrary trace of atomic steps.
Qed
Proof.
  intros Hinv0.
  assert (Hinit : dp_inv init_drain_post_state).
  { unfold dp_inv, dp_no_lost_drain; simpl.
    split; [intros H; lia|split; [left; reflexivity|intros H; discriminate]]. }
  split; [apply run_drain_post_trace_inv; exact Hinv0|].
  split; [apply run_drain_post_trace_inv; exact Hinit|].
  split; [simpl; repeat split; reflexivity|].
  split; [simpl; repeat split; reflexivity|].
  simpl; repeat split; reflexivity.
Qed.
References

7. Zero-allocation coalescing SignalPort and cross-graph bridge contracts

State of a SignalPort<'T> and its target Signal<'T> (src/Ranvier/Core.fs, src/Ranvier/Bindings.fs):

Record signal_port_state := {
  sp_disposed : bool;
  sp_in_inbox : bool;
  sp_has_pending : bool;
  sp_pending_val : Z;
  sp_pending_attr : option nat;
  sp_signal_val : Z;
  sp_inbox_queued : nat;
  sp_drain_posted : bool
}.
References

Uses

  • bool
  • nat
  • option
  • Z
Definition init_signal_port_state (v0 : Z) : signal_port_state :=
  {| sp_disposed := false;
     sp_in_inbox := false;
     sp_has_pending := false;
     sp_pending_val := 0%Z;
     sp_pending_attr := None;
     sp_signal_val := v0;
     sp_inbox_queued := 0;
     sp_drain_posted := false |}.
References

Coalescing port representation & liveness invariant:

  1. A pending off-thread value implies sp_in_inbox = true.
  2. sp_in_inbox = true implies exactly 1 inbox slot is queued (sp_inbox_queued = 1) and sp_drain_posted = true (no lost wakeup, O(1) bounded queue occupancy).
  3. sp_in_inbox = false implies sp_inbox_queued = 0, sp_has_pending = false, sp_pending_val = 0%Z, and sp_pending_attr = None (zero retained payload or journal attribution when idle).
Definition sp_inv (st : signal_port_state) : Prop :=
  (sp_has_pending st = true -> sp_in_inbox st = true) /\
  (sp_in_inbox st = true -> sp_inbox_queued st = 1 /\ sp_drain_posted st = true) /\
  (sp_in_inbox st = false ->
     sp_inbox_queued st = 0 /\
     sp_has_pending st = false /\
     sp_pending_val st = 0%Z /\
     sp_pending_attr st = None).
References
Inductive signal_port_op :=
  | SpOffThreadPost (v : Z) (attr : option nat)
  | SpInlinePost (v : Z)
  | SpDrain
  | SpDispose.
References

Uses

  • nat
  • option
  • Z

Off-thread SignalPort.Post(v) under Monitor.Enter port: drops silently when sp_disposed = true; otherwise overwrites sp_pending_val and sp_pending_attr, sets sp_has_pending := true, and enqueues the pre-allocated drain callback iff sp_in_inbox = false.

Definition sp_post_off (v : Z) (attr : option nat) (st : signal_port_state) : signal_port_state :=
  if sp_disposed st then st
  else if sp_in_inbox st then
    {| sp_disposed := false;
       sp_in_inbox := true;
       sp_has_pending := true;
       sp_pending_val := v;
       sp_pending_attr := attr;
       sp_signal_val := sp_signal_val st;
       sp_inbox_queued := sp_inbox_queued st;
       sp_drain_posted := sp_drain_posted st |}
  else
    {| sp_disposed := false;
       sp_in_inbox := true;
       sp_has_pending := true;
       sp_pending_val := v;
       sp_pending_attr := attr;
       sp_signal_val := sp_signal_val st;
       sp_inbox_queued := S (sp_inbox_queued st);
       sp_drain_posted := true |}.
References

Owning-thread SignalPort.Post(v) (IsOnGraphThread = true): drops silently when sp_disposed = true; when sp_has_pending = false (fast path), writes sp_signal_val := v directly; when sp_has_pending = true, clears sp_has_pending, sp_pending_val, and sp_pending_attr under Monitor.Enter port (keeping sp_in_inbox balanced with the already-enqueued drain item) and writes v inline.

Definition sp_post_inline (v : Z) (st : signal_port_state) : signal_port_state :=
  if sp_disposed st then st
  else if sp_has_pending st then
    {| sp_disposed := false;
       sp_in_inbox := sp_in_inbox st;
       sp_has_pending := false;
       sp_pending_val := 0%Z;
       sp_pending_attr := None;
       sp_signal_val := v;
       sp_inbox_queued := sp_inbox_queued st;
       sp_drain_posted := sp_drain_posted st |}
  else
    {| sp_disposed := false;
       sp_in_inbox := sp_in_inbox st;
       sp_has_pending := false;
       sp_pending_val := sp_pending_val st;
       sp_pending_attr := sp_pending_attr st;
       sp_signal_val := v;
       sp_inbox_queued := sp_inbox_queued st;
       sp_drain_posted := sp_drain_posted st |}.
References

Pre-allocated drain () callback invoked by Graph.Drain / Pump ().

Definition sp_drain (st : signal_port_state) : signal_port_state :=
  if sp_in_inbox st then
    let next_val :=
      if negb (sp_disposed st) && sp_has_pending st then sp_pending_val st
      else sp_signal_val st in
    {| sp_disposed := sp_disposed st;
       sp_in_inbox := false;
       sp_has_pending := false;
       sp_pending_val := 0%Z;
       sp_pending_attr := None;
       sp_signal_val := next_val;
       sp_inbox_queued := Nat.pred (sp_inbox_queued st);
       sp_drain_posted := false |}
  else st.
References
References
Definition step_signal_port (op : signal_port_op) (st : signal_port_state) : signal_port_state :=
  match op with
  | SpOffThreadPost v attr => sp_post_off v attr st
  | SpInlinePost v => sp_post_inline v st
  | SpDrain => sp_drain st
  | SpDispose => sp_dispose st
  end.
References
Fixpoint run_signal_port_trace (st : signal_port_state) (tr : list signal_port_op) : signal_port_state :=
  match tr with
  | [] => st
  | op :: rest => run_signal_port_trace (step_signal_port op st) rest
  end.
References

Naive owning-thread `Post` that writes `sp_signal_val := v` without clearing `sp_has_pending` (falsified below).

Definition sp_naive_inline_post (v : Z) (st : signal_port_state) : signal_port_state :=
  if sp_disposed st then st
  else
    {| sp_disposed := false;
       sp_in_inbox := sp_in_inbox st;
       sp_has_pending := sp_has_pending st;
       sp_pending_val := sp_pending_val st;
       sp_pending_attr := sp_pending_attr st;
       sp_signal_val := v;
       sp_inbox_queued := sp_inbox_queued st;
       sp_drain_posted := sp_drain_posted st |}.
References
Lemma step_signal_port_inv (op : signal_port_op) (st : signal_port_state) :
  sp_inv st -> sp_inv (step_signal_port op st).
Qed
Proof.
  intros Hinv.
  pose proof Hinv as (Hpend_in & Hin_q & Hout_q).
  destruct op as [v attr | v | |]; simpl.
  - unfold sp_post_off.
    destruct (sp_disposed st); [exact Hinv|].
    destruct (sp_in_inbox st) eqn:Hin; simpl.
    + destruct (Hin_q eq_refl) as [Hq Hdp].
      unfold sp_inv; simpl.
      split_and!; [intros _; reflexivity | intros _; split; assumption | intros H; discriminate H].
    + destruct (Hout_q eq_refl) as (Hq & _ & _ & _).
      unfold sp_inv; simpl. rewrite Hq.
      split_and!; [intros _; reflexivity | intros _; split; reflexivity | intros H; discriminate H].
  - unfold sp_post_inline.
    destruct (sp_disposed st); [exact Hinv|].
    destruct (sp_has_pending st) eqn:Hp; simpl.
    + pose proof (Hpend_in eq_refl) as Hin.
      destruct (Hin_q Hin) as [Hq Hdp].
      unfold sp_inv; simpl. rewrite Hin.
      split_and!; [intros H; discriminate H | intros _; split; assumption | intros H; discriminate H].
    + destruct (sp_in_inbox st) eqn:Hin; simpl.
      * destruct (Hin_q eq_refl) as [Hq Hdp].
        unfold sp_inv; simpl.
        split_and!; [intros H; discriminate H | intros _; split; assumption | intros H; discriminate H].
      * destruct (Hout_q eq_refl) as (Hq & _ & Hpv & Hpa).
        unfold sp_inv; simpl.
        split_and!; [intros H; discriminate H | intros H; discriminate H | intros _; repeat split; assumption].
  - unfold sp_drain.
    destruct (sp_in_inbox st) eqn:Hin; [|exact Hinv].
    destruct (Hin_q eq_refl) as [Hq _].
    unfold sp_inv; simpl. rewrite Hq.
    split_and!; [intros H; discriminate H | intros H; discriminate H | intros _; repeat split; reflexivity].
  - unfold sp_dispose, sp_inv in *; simpl. exact Hinv.
Qed.
References
Lemma run_signal_port_trace_inv (tr : list signal_port_op) (st : signal_port_state) :
  sp_inv st -> sp_inv (run_signal_port_trace st tr).
Qed
Proof.
  revert st.
  induction tr as [|op rest IH]; intros st Hinv; simpl; [exact Hinv|].
  apply IH. apply step_signal_port_inv. exact Hinv.
Qed.
References
Local Lemma burst_off_posts_coalesce
    (v1 : Z) (a1 : option nat) (more : list (Z * option nat)) (st : signal_port_state) :
  sp_disposed st = false ->
  sp_inv st ->
  let burst := map (fun p => SpOffThreadPost (fst p) (snd p)) ((v1, a1) :: more) in
  let st_burst := run_signal_port_trace st burst in
  let last_pair := List.last ((v1, a1) :: more) (v1, a1) in
  sp_disposed st_burst = false /\
  sp_in_inbox st_burst = true /\
  sp_has_pending st_burst = true /\
  sp_inbox_queued st_burst = 1 /\
  sp_drain_posted st_burst = true /\
  sp_pending_val st_burst = fst last_pair /\
  sp_pending_attr st_burst = snd last_pair.
Qed
Proof.
  intros Hlive Hinv.
  assert (Hstep1 :
    let st1 := sp_post_off v1 a1 st in
    sp_disposed st1 = false /\
    sp_in_inbox st1 = true /\
    sp_has_pending st1 = true /\
    sp_inbox_queued st1 = 1 /\
    sp_drain_posted st1 = true /\
    sp_pending_val st1 = v1 /\
    sp_pending_attr st1 = a1).
  { destruct Hinv as (_ & Hin_q & Hout_q).
    unfold sp_post_off. rewrite Hlive.
    destruct (sp_in_inbox st) eqn:Hin; simpl.
    - destruct (Hin_q eq_refl) as [Hq Hdp]. repeat split; assumption + reflexivity.
    - destruct (Hout_q eq_refl) as (Hq & _). rewrite Hq. repeat split; reflexivity. }
  simpl.
  set (st1 := sp_post_off v1 a1 st) in *.
  clearbody st1. clear Hlive Hinv st.
  revert v1 a1 st1 Hstep1.
  induction more as [|[v2 a2] rest IH]; intros v1 a1 st1 Hst1; simpl in *.
  - exact Hst1.
  - destruct Hst1 as (Hlive1 & Hin1 & _ & Hq1 & Hdp1 & _ & _).
    set (st2 := sp_post_off v2 a2 st1).
    assert (Hst2 :
      sp_disposed st2 = false /\
      sp_in_inbox st2 = true /\
      sp_has_pending st2 = true /\
      sp_inbox_queued st2 = 1 /\
      sp_drain_posted st2 = true /\
      sp_pending_val st2 = v2 /\
      sp_pending_attr st2 = a2).
    { unfold st2, sp_post_off. rewrite Hlive1, Hin1, Hq1, Hdp1. simpl. repeat split; reflexivity. }
    pose proof (IH v2 a2 st2 Hst2) as Hrec.
    destruct rest as [|p rest'].
    + exact Hrec.
    + assert (Hlast : forall (x : Z * option nat) xs d1 d2, List.last (x :: xs) d1 = List.last (x :: xs) d2).
      { intros x xs. revert x. induction xs as [|y ys IHys]; intros x d1 d2; simpl; [reflexivity | apply IHys]. }
      rewrite (Hlast p rest' (v1, a1) (v2, a2)).
      exact Hrec.
Qed.
References
✓ No axioms

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.

Arguments

v0 : Z
initial value of the target Signal<'T>.
any state satisfying sp_inv.
tr : list signal_port_op
an arbitrary interleaving of off-thread posts, inline posts, drains, and disposal.
v1 : Z
first value of an off-thread burst.
a1 : option nat
first journal attribution of the burst.
more : list (Z * option nat)
remaining (value, attribution) pairs of the burst before SpDrain.
Theorem signal_port_inv_and_coalesce
    (v0 : Z) (st0 : signal_port_state) (tr : list signal_port_op)
    (v1 : Z) (a1 : option nat) (more : list (Z * option nat)) :
  sp_inv st0 ->
  sp_inv (init_signal_port_state v0) /\
  sp_inv (run_signal_port_trace st0 tr) /\
  sp_inv (run_signal_port_trace (init_signal_port_state v0) tr) /\
  (sp_inbox_queued (run_signal_port_trace st0 tr) <= 1) /\
  (sp_disposed st0 = false ->
    let burst := map (fun p => SpOffThreadPost (fst p) (snd p)) ((v1, a1) :: more) in
    let st_drained := run_signal_port_trace st0 (burst ++ [SpDrain]) in
    let last_pair := List.last ((v1, a1) :: more) (v1, a1) in
    sp_signal_val st_drained = fst last_pair /\
    sp_in_inbox st_drained = false /\
    sp_has_pending st_drained = false /\
    sp_inbox_queued st_drained = 0 /\
    sp_pending_attr st_drained = None).

Arguments

v0 : Z
initial value of the target Signal<'T>.
any state satisfying sp_inv.
tr : list signal_port_op
an arbitrary interleaving of off-thread posts, inline posts, drains, and disposal.
v1 : Z
first value of an off-thread burst.
a1 : option nat
first journal attribution of the burst.
more : list (Z * option nat)
remaining (value, attribution) pairs of the burst before SpDrain.
Qed
Proof.
  intros Hinv0.
  assert (Hinit : sp_inv (init_signal_port_state v0)).
  { unfold sp_inv, init_signal_port_state; simpl.
    split_and!; [intros H; discriminate H | intros H; discriminate H | intros _; repeat split; reflexivity]. }
  pose proof (run_signal_port_trace_inv tr st0 Hinv0) as Htr0.
  pose proof (run_signal_port_trace_inv tr (init_signal_port_state v0) Hinit) as Htr_init.
  assert (Hq_bound : sp_inbox_queued (run_signal_port_trace st0 tr) <= 1).
  { destruct Htr0 as (_ & Hin_q & Hout_q).
    destruct (sp_in_inbox (run_signal_port_trace st0 tr)) eqn:Hin.
    - destruct (Hin_q eq_refl) as [Hq _]. lia.
    - destruct (Hout_q eq_refl) as [Hq _]. lia. }
  split_and!; [exact Hinit | exact Htr0 | exact Htr_init | exact Hq_bound |].
  intros Hlive. cbv zeta.
  pose proof (burst_off_posts_coalesce v1 a1 more st0 Hlive Hinv0) as Hburst.
  cbv zeta in Hburst.
  set (burst := map (fun p => SpOffThreadPost (fst p) (snd p)) ((v1, a1) :: more)) in *.
  clearbody burst.
  assert (Hcat : forall s a b, run_signal_port_trace s (a ++ b) = run_signal_port_trace (run_signal_port_trace s a) b).
  { intros s a b. revert s. induction a as [|x xs IHa]; intros s; simpl; [reflexivity | apply IHa]. }
  rewrite Hcat. simpl.
  destruct Hburst as (Hb_live & Hb_in & Hb_pend & Hb_q & _ & Hb_val & _).
  unfold sp_drain. rewrite Hb_in, Hb_live, Hb_pend, Hb_val, Hb_q. simpl.
  repeat split; reflexivity.
Qed.
References
✓ No axioms

An 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.

Arguments

any live state satisfying sp_inv.
v_stale : Z
earlier off-thread value waiting in the port.
attr : option nat
optional journal attribution on v_stale.
v_fresh : Z
newer value posted inline on the owning thread before Pump ().
v_newer : Z
optional later off-thread value posted after v_fresh and before Pump ().
attr2 : option nat
optional journal attribution on v_newer.
Theorem signal_port_inline_supersedes_pending
    (st0 : signal_port_state) (v_stale v_fresh v_newer : Z) (attr attr2 : option nat) :
  sp_inv st0 ->
  sp_disposed st0 = false ->
  (let st1 := run_signal_port_trace st0 [SpOffThreadPost v_stale attr; SpInlinePost v_fresh; SpDrain] in
   sp_signal_val st1 = v_fresh /\
   sp_in_inbox st1 = false /\
   sp_has_pending st1 = false /\
   sp_inbox_queued st1 = 0) /\
  (let st2 :=
     run_signal_port_trace st0
       [SpOffThreadPost v_stale attr; SpInlinePost v_fresh; SpOffThreadPost v_newer attr2; SpDrain] in
   sp_signal_val st2 = v_newer /\
   sp_in_inbox st2 = false /\
   sp_has_pending st2 = false /\
   sp_inbox_queued st2 = 0) /\
  (let st_naive :=
     sp_drain (sp_naive_inline_post 20%Z (sp_post_off 10%Z None (init_signal_port_state 0%Z))) in
   sp_signal_val st_naive = 10%Z /\ sp_signal_val st_naive <> 20%Z).

Arguments

any live state satisfying sp_inv.
v_stale : Z
earlier off-thread value waiting in the port.
attr : option nat
optional journal attribution on v_stale.
v_fresh : Z
newer value posted inline on the owning thread before Pump ().
v_newer : Z
optional later off-thread value posted after v_fresh and before Pump ().
attr2 : option nat
optional journal attribution on v_newer.
Qed
Proof.
  intros Hinv Hlive.
  destruct Hinv as (_ & Hin_q & Hout_q).
  assert (Hq1 :
    sp_inbox_queued (sp_post_off v_stale attr st0) = 1 /\
    sp_in_inbox (sp_post_off v_stale attr st0) = true /\
    sp_has_pending (sp_post_off v_stale attr st0) = true /\
    sp_disposed (sp_post_off v_stale attr st0) = false).
  { unfold sp_post_off. rewrite Hlive.
    destruct (sp_in_inbox st0) eqn:Hin; simpl.
    - destruct (Hin_q eq_refl) as [Hq _]. repeat split; assumption + reflexivity.
    - destruct (Hout_q eq_refl) as [Hq _]. rewrite Hq. repeat split; reflexivity. }
  destruct Hq1 as (Hq1 & Hin1 & Hp1 & Hd1).
  split_and!.
  - simpl. unfold sp_post_inline. rewrite Hd1, Hp1, Hin1, Hq1.
    unfold sp_drain; simpl. repeat split; reflexivity.
  - simpl. unfold sp_post_inline. rewrite Hd1, Hp1, Hin1, Hq1.
    unfold sp_post_off; simpl.
    unfold sp_drain; simpl. repeat split; reflexivity.
  - vm_compute. split; [reflexivity | lia].
Qed.
References

Cross-graph `bindMemoTo` source reading (`Bindings.fs` lines 85–97): only `Ready` values post to the target port.

Inductive bridge_memo_reading :=
  | BridgeReady (v : Z)
  | BridgePending
  | BridgeFailed (err : Z).
References

Uses

  • Z
Definition bridge_memo_step
    (last_sent : option Z) (r : bridge_memo_reading) (port : signal_port_state)
    : option Z * signal_port_state :=
  match r with
  | BridgePending => (last_sent, port)
  | BridgeFailed _ => (last_sent, port)
  | BridgeReady v =>
      match last_sent with
      | Some prev =>
          if decide (prev = v) then (last_sent, port)
          else (Some v, sp_post_off v None port)
      | None => (Some v, sp_post_off v None port)
      end
  end.
References
✓ No axioms

Disposing 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.

Arguments

any state satisfying sp_inv.
v : Z
candidate posted value.
attr : option nat
optional journal attribution.
v0 : Z
initial value of a fresh target SignalPort.
Theorem signal_port_disposed_drops_and_bridge_cutoff
    (st0 : signal_port_state) (v : Z) (attr : option nat) (v0 : Z) :
  sp_inv st0 ->
  (let st_d := sp_dispose st0 in
   sp_signal_val (sp_post_off v attr st_d) = sp_signal_val st0 /\
   sp_inbox_queued (sp_post_off v attr st_d) = sp_inbox_queued st0 /\
   sp_signal_val (sp_post_inline v st_d) = sp_signal_val st0 /\
   sp_signal_val (sp_drain st_d) = sp_signal_val st0 /\
   sp_in_inbox (sp_drain st_d) = false) /\
  (let p0 := init_signal_port_state v0 in
   let '(s1, p1) := bridge_memo_step None BridgePending p0 in
   let '(s2, p2) := bridge_memo_step s1 (BridgeFailed 99%Z) p1 in
   let '(s3, p3) := bridge_memo_step s2 (BridgeReady 42%Z) p2 in
   let p3_drained := sp_drain p3 in
   let '(s4, p4) := bridge_memo_step s3 (BridgeReady 42%Z) p3_drained in
   s1 = None /\ p1 = p0 /\
   s2 = None /\ p2 = p0 /\
   s3 = Some 42%Z /\ sp_signal_val p3_drained = 42%Z /\
   s4 = Some 42%Z /\ sp_in_inbox p4 = false /\ sp_inbox_queued p4 = 0).

Arguments

any state satisfying sp_inv.
v : Z
candidate posted value.
attr : option nat
optional journal attribution.
v0 : Z
initial value of a fresh target SignalPort.
Qed
Proof.
  intros Hinv.
  split.
  - unfold sp_dispose, sp_post_off, sp_post_inline, sp_drain; simpl.
    destruct (sp_in_inbox st0); simpl; repeat split; reflexivity.
  - simpl. repeat split; reflexivity.
Qed.
References

Two-level cutoff state of `Ranvier.CE.BridgeBuilder<'T>` (`bridge target { ... }` in `Builders.fs`).

Record bridge_ce_state := mk_bridge_ce {
  bce_last_key : option Z;
  bce_last_out : option Z;
  bce_map_runs : nat;
  bce_port : signal_port_state;
}.
References

Uses

Definition init_bridge_ce_state (v0 : Z) : bridge_ce_state :=
  {| bce_last_key := None;
     bce_last_out := None;
     bce_map_runs := 0;
     bce_port := init_signal_port_state v0 |}.
References
Definition bridge_ce_step
    (eq_key eq_out : Z -> Z -> bool) (proj : Z -> Z)
    (r : bridge_memo_reading) (st : bridge_ce_state) : bridge_ce_state :=
  match r with
  | BridgePending => st
  | BridgeFailed _ => st
  | BridgeReady k =>
      let same_key :=
        match bce_last_key st with
        | Some prev_k => eq_key prev_k k
        | None => false
        end in
      if same_key then st
      else
        let out := proj k in
        let same_out :=
          match bce_last_out st with
          | Some prev_out => eq_out prev_out out
          | None => false
          end in
        if same_out then
          {| bce_last_key := Some k;
             bce_last_out := bce_last_out st;
             bce_map_runs := S (bce_map_runs st);
             bce_port := bce_port st |}
        else
          {| bce_last_key := Some k;
             bce_last_out := Some out;
             bce_map_runs := S (bce_map_runs st);
             bce_port := sp_post_off out None (bce_port st) |}
  end.
References
Definition bridge_ce_drain (st : bridge_ce_state) : bridge_ce_state :=
  {| bce_last_key := bce_last_key st;
     bce_last_out := bce_last_out st;
     bce_map_runs := bce_map_runs st;
     bce_port := sp_drain (bce_port st) |}.
References
✓ No axioms

BridgeBuilder<'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.

Arguments

eq_key : Z -> Z -> bool
Phase-1 input key cutoff (withComparer or graph equality policy).
eq_out : Z -> Z -> bool
Phase-2 output cutoff (comparer header or graph equality policy).
proj : Z -> Z
closed Phase-2 return projection ('K -> 'T).
Phase-1 source reading (BridgeReady, BridgePending, or BridgeFailed).
v0 : Z
initial value of a fresh target SignalPort.
Theorem bridge_ce_projected_cutoff_and_unready_guard
    (eq_key eq_out : Z -> Z -> bool) (proj : Z -> Z)
    (r : bridge_memo_reading) (st : bridge_ce_state) (v0 : Z) :
  sp_inv (bce_port st) ->
  sp_inv (bce_port (bridge_ce_step eq_key eq_out proj r st)) /\
  (r = BridgePending -> bridge_ce_step eq_key eq_out proj r st = st) /\
  (forall err, r = BridgeFailed err -> bridge_ce_step eq_key eq_out proj r st = st) /\
  (let b0 := init_bridge_ce_state v0 in
   let step := bridge_ce_step Z.eqb Z.eqb (fun k => Z.rem k 2) in
   let b1 := step BridgePending b0 in
   let b2 := step (BridgeFailed 7%Z) b1 in
   let b3 := bridge_ce_drain (step (BridgeReady 2%Z) b2) in
   let b4 := step (BridgeReady 2%Z) b3 in
   let b5 := step (BridgeReady 4%Z) b4 in
   let b6 := bridge_ce_drain (step (BridgeReady 5%Z) b5) in
   bce_map_runs b2 = 0 /\ sp_in_inbox (bce_port b2) = false /\
   bce_map_runs b3 = 1 /\ sp_signal_val (bce_port b3) = 0%Z /\
   bce_map_runs b4 = 1 /\ sp_in_inbox (bce_port b4) = false /\
   bce_map_runs b5 = 2 /\ sp_in_inbox (bce_port b5) = false /\ sp_inbox_queued (bce_port b5) = 0 /\
   bce_map_runs b6 = 3 /\ sp_signal_val (bce_port b6) = 1%Z).

Arguments

eq_key : Z -> Z -> bool
Phase-1 input key cutoff (withComparer or graph equality policy).
eq_out : Z -> Z -> bool
Phase-2 output cutoff (comparer header or graph equality policy).
proj : Z -> Z
closed Phase-2 return projection ('K -> 'T).
Phase-1 source reading (BridgeReady, BridgePending, or BridgeFailed).
v0 : Z
initial value of a fresh target SignalPort.
Qed
Proof.
  intros Hinv.
  split_and!.
  - destruct r as [k | | err]; simpl; [|exact Hinv | exact Hinv].
    destruct (match bce_last_key st with Some prev_k => eq_key prev_k k | None => false end);
      [exact Hinv|].
    destruct (match bce_last_out st with Some prev_out => eq_out prev_out (proj k) | None => false end);
      simpl; [exact Hinv|].
    exact (step_signal_port_inv (SpOffThreadPost (proj k) None) (bce_port st) Hinv).
  - intros ->. reflexivity.
  - intros err ->. reflexivity.
  - vm_compute. repeat split; reflexivity.
Qed.
References