Ranvier.Pure.Extensions
Ranvier.Query and Ranvier.Elmish boundary contracts
Ranvier.Query (Types.fs, Entry.fs, Queries.fs, Mutations.fs) and Ranvier.Elmish (Mvu.fs)
build higher-level state management on top of the core reactive graph. To keep their implementation open
to internal optimization while guaranteeing their documented consumer contracts, this module proves the
exact minimum specifications required at their boundaries:
PublicationComparer(CmpNever) with explicit equality gating (Types.fs,Entry.fs):publication_comparer_guarded_refines_cutoff: gating a write to aCmpNeversignal behind an explicitold <> vcheck leaves the graph state and observers untouched whenold = vand wakes every observer (ends_dirty) whenold <> v, avoiding duplicate comparison insideBatch.
QueryEntrygeneration-fenced publication and stale-while-revalidate (Entry.fs):query_publish_fenced:qe_publishmutates the entry if and only if the entry is not disposed and the completing flight's generation matches the current generation (flight_gen = qe_gen); stale or post-disposal flights are ignored.query_refresh_retains_data: starting a refresh (qe_start) or receiving a refresh failure (qe_publishwithInr err) when cached dataSome vis present retainsqe_data = Some v, recordsqe_error = Some errandqe_stale = true, and never faults the initial-load gate.
- Reference-counted
QueryLeaselifecycle (Queries.fs):query_lease_dispose_idempotent_refcount: disposing aQueryLeaseis idempotent (lease_disposedguards the release callback), decrements the family's reference count at most once, and evicts/disposes the sharedQueryEntryif and only if the last active lease releases (count = 1).
- Two-phase atomic
QueryStagingcommit and reentrancy guard (Types.fs,Queries.fs):query_commit_atomic_staging:QueryDraftedits compose in order on loaded entries while leaving unloaded entries empty and stale;staging = trueblocks reentrant client calls duringPrepare(); and if validation fails duringPrepare(), zero cache entries are mutated.
Ranvier.Elmish(Mvu.fs) scope-gated dispatch and command ordering:mvu_disposed_drops_dispatch: once the owning scope's cleanup setsmvu_disposed = true,mvu_applydrops incoming messages without mutating the model, andmvu_run_cmdshalts immediately without running remaining commands in the tail.mvu_apply_writes_before_commands:mvu_applywrites the updated model before running commands, so every synchronous command observes the new model state.
6
From stdpp Require Import prelude gmap strings.
From Stdlib Require Import ZArith.
From Stdlib Require String.
From Ranvier.Base Require Import Prelude Syntax.
From Ranvier.Pure Require Import ObserverSet SourceList State Marking Engine.
Open Scope nat_scope.1. PublicationComparer (CmpNever) with explicit equality gating
Models the Entry.fs lines 55–65 / 231–249 publication pattern: the signal n is constructed with
PublicationComparer (CmpNever), and the caller evaluates changed before the batch, writing n
only when changed = true.
Definition guarded_pub_write (changed : bool) (fuel : nat) (n : node_id) (v : Z) (s : state)
Definition guarded_pub_write (changed : bool) (fuel : nat) (n : node_id) (v : Z) (s : state)
: option (state * unit) :=
if changed then write_signal fuel n v s else Some (s, tt).References
Gating a CmpNever signal write behind bool_decide (n_value d <> v) preserves exact equality cutoff when n_value d = v and wakes all observers (ends_dirty) when n_value d <> v.
Proves the PublicationComparer optimization contract (Types.fs lines 133–136, Entry.fs lines 10–16,
55–65, 231–249): precomputing changed outside graph.Batch over a CmpNever signal avoids comparing a
second time inside Signal.Set while preserving both halves of the signal cutoff contract:
- When
n_value d = v,guarded_pub_writeis a no-op (Some (s, tt)), waking zero observers. - When
n_value d <> v, publishingvupdatesnand marks every observermdirty (ends_dirty s1 m).
Arguments
Theorem publication_comparer_guarded_refines_cutoff
Theorem publication_comparer_guarded_refines_cutoff
(fuel : nat) (n : node_id) (v : Z) (d : node) (s : state) :
g_nodes s !! n = Some d ->
n_kind d = KSignal ->
n_comparer d = CmpNever ->
(n_value d = v ->
guarded_pub_write (bool_decide (n_value d <> v)) fuel n v s = Some (s, tt)) /\
(n_value d <> v ->
forall s1 m,
m ∈ observer_view (observers_of (g_edges s) n) ->
takes_marks s m ->
(g_current s <> Some m \/ n ∈ read_prefix (g_edges s) m) ->
notify_dirty_except fuel n (g_current s) (ghost_publish n (set_node n (node_with_value v d) s)) = Some s1 ->
ends_dirty s1 m).
Arguments
Qed
Proof.
intros Hd Hk Hcmp. split.
- intros Heq. unfold guarded_pub_write.
rewrite bool_decide_eq_false_2; [done|].
intros Hne. exact (Hne Heq).
- intros Hne s1 m Hin Ht Hcond Hnot.
set (s_pub := ghost_publish n (set_node n (node_with_value v d) s)) in *.
assert (Hedges : g_edges s_pub = g_edges s) by (subst s_pub; unfold ghost_publish; simpl; rewrite lookup_insert_eq; done).
assert (Ht_pub : takes_marks s_pub m).
{ destruct Ht as (dm & Hdm & Hkm).
assert (Hmn : m <> n).
{ intros ->. rewrite Hd in Hdm. injection Hdm as <-.
destruct Hkm as [Hkm|[Hkm _]]; congruence. }
exists dm. subst s_pub. unfold ghost_publish. simpl.
rewrite lookup_insert_eq. simpl. rewrite lookup_insert_ne by done. done. }
eapply (notify_dirty_ends_dirty fuel n (g_current s) s_pub s1 m).
+ by rewrite Hedges.
+ exact Ht_pub.
+ right. rewrite Hedges. done.
Qed.References
Uses
22 more
- n_value
- n_comparer
- state
- g_edges
- g_nodes
- g_current
- set_node
- notify_dirty_except
- takes_marks
- ends_dirty
- notify_dirty_ends_dirty
- node_with_value
- ghost_publish
- guarded_pub_write
- Some
- nat
- tt
- Z
- bool_decide
- bool_decide_eq_false_2
- lookup_insert_eq
- lookup_insert_ne
Used by
2. QueryEntry generation-fenced publication and stale-while-revalidate
Inductive fetch_status :=
Inductive fetch_status :=
| FsIdle
| FsFetching.Global Instance fetch_status_eq_dec : EqDecision fetch_status.
Defined
Proof. solve_decision. Defined.References
Uses
- fetch_status
- EqDecision
Pure state of a QueryEntry<'T> (Entry.fs lines 9–21):
qe_data: accepted cached record (Nonebefore initial load settles,Some vafterwards).qe_status:FsIdleorFsFetching.qe_error: failure from the latest attempt, orNone.qe_stale: whetherEnsureshould start a fresh request.qe_gen: monotonic flight generation counter (generationinEntry.fs).qe_disposed: whetherDisposehas retired the entry.qe_gate_faulted: whether the initial-load suspension gate (AsyncSource) was faulted.
Record query_entry_state := {
Record query_entry_state := {
qe_data : option Z;
qe_status : fetch_status;
qe_error : option nat;
qe_stale : bool;
qe_gen : nat;
qe_disposed : bool;
qe_gate_faulted : bool;
}.Entry.start (Entry.fs lines 145–159): increments qe_gen, cancels any superseded flight,
replaces gate only when qe_data = None, and transitions metadata to (FsFetching, None, true)
while retaining qe_data.
Definition qe_start (qe : query_entry_state) : query_entry_state :=
Definition qe_start (qe : query_entry_state) : query_entry_state :=
if qe_disposed qe then qe
else
{| qe_data := qe_data qe;
qe_status := FsFetching;
qe_error := None;
qe_stale := true;
qe_gen := S (qe_gen qe);
qe_disposed := false;
qe_gate_faulted := false |}.References
Uses
5 more
- qe_gate_faulted
- None
- S
- false
- true
Entry.publish (Entry.fs lines 48–106): accepts outcome (inl v for Result.Ok v,
inr err for Result.Error err) if and only if not (qe_disposed qe) and flight_gen = qe_gen qe.
Definition qe_publish (flight_gen : nat) (outcome : Z + nat) (qe : query_entry_state) : query_entry_state :=
Definition qe_publish (flight_gen : nat) (outcome : Z + nat) (qe : query_entry_state) : query_entry_state :=
if decide (qe_disposed qe = false /\ flight_gen = qe_gen qe) then
match outcome with
| inl v =>
{| qe_data := Some v;
qe_status := FsIdle;
qe_error := None;
qe_stale := false;
qe_gen := qe_gen qe;
qe_disposed := false;
qe_gate_faulted := false |}
| inr err =>
{| qe_data := qe_data qe;
qe_status := FsIdle;
qe_error := Some err;
qe_stale := true;
qe_gen := qe_gen qe;
qe_disposed := false;
qe_gate_faulted := bool_decide (qe_data qe = None) |}
end
else qe.References
Uses
11 more
- qe_gate_faulted
- None
- Some
- false
- inl
- inr
- nat
- true
- Z
- decide
- bool_decide
Entry.Dispose (Entry.fs lines 275–281): marks qe_disposed = true and advances qe_gen.
Definition qe_dispose (qe : query_entry_state) : query_entry_state :=
Definition qe_dispose (qe : query_entry_state) : query_entry_state :=
if qe_disposed qe then qe
else
{| qe_data := qe_data qe;
qe_status := qe_status qe;
qe_error := qe_error qe;
qe_stale := qe_stale qe;
qe_gen := S (qe_gen qe);
qe_disposed := true;
qe_gate_faulted := qe_gate_faulted qe |}.References
Used by
qe_publish mutates the entry only for the active generation of a live entry; superseded or post-disposal completions are no-ops.
Proves the generation-fencing contract (Entry.fs lines 48–106, 151–158, 275–281):
- Any completion whose
flight_gen <> qe_gen qeor that arrives afterqe_disposeleavesqeuntouched. - In particular, starting a refresh (
qe_start) or disposing the entry (qe_dispose) advancesqe_genfromgtoS g, so any late reply from generationgis ignored.
Arguments
inl v or inr err).Theorem query_publish_fenced (flight_gen : nat) (outcome : Z + nat) (qe : query_entry_state) :
Theorem query_publish_fenced (flight_gen : nat) (outcome : Z + nat) (qe : query_entry_state) :
(qe_disposed qe = true \/ flight_gen <> qe_gen qe ->
qe_publish flight_gen outcome qe = qe) /\
(qe_publish (qe_gen qe) outcome (qe_start qe) = qe_start qe) /\
(qe_publish (qe_gen qe) outcome (qe_dispose qe) = qe_dispose qe).
Arguments
inl v or inr err).Qed
Proof.
split_and!.
- intros Hbad. unfold qe_publish.
rewrite decide_False; [done|].
intros [Hlive Hgen]. destruct Hbad as [Hdisp|Hne]; congruence.
- unfold qe_publish, qe_start.
destruct (qe_disposed qe) eqn:Edisp.
+ rewrite decide_False; [done|]. intros [Hfalse _]. congruence.
+ simpl. rewrite decide_False; [done|]. intros [_ Hgen]. lia.
- unfold qe_publish, qe_dispose.
destruct (qe_disposed qe) eqn:Edisp.
+ rewrite decide_False; [done|]. intros [Hfalse _]. congruence.
+ simpl. done.
Qed.References
Used by
Refreshing a loaded QueryEntry (qe_data = Some v) or failing a refresh retains qe_data = Some v and never faults the initial-load gate.
Proves the stale-while-revalidate contract (Entry.fs lines 81–100, 111–115, 167–185):
- When
qe_data qe = Some v,qe_startpreservesqe_data = Some vwhile settingqe_status = FsFetchingandqe_stale = true. - When
qe_data qe = Some vand the active flight fails (outcome = inr err),qe_publishpreservesqe_data = Some v, recordsqe_error = Some errandqe_stale = true, and keepsqe_gate_faulted = false(only an initial load failure withqe_data = Nonefaults the gate).
Arguments
Theorem query_refresh_retains_data (v : Z) (err : nat) (qe : query_entry_state) :
Theorem query_refresh_retains_data (v : Z) (err : nat) (qe : query_entry_state) :
qe_disposed qe = false ->
qe_data qe = Some v ->
let qe_refresh := qe_start qe in
let qe_failed := qe_publish (qe_gen qe_refresh) (inr err) qe_refresh in
qe_data qe_refresh = Some v /\
qe_status qe_refresh = FsFetching /\
qe_data qe_failed = Some v /\
qe_status qe_failed = FsIdle /\
qe_error qe_failed = Some err /\
qe_stale qe_failed = true /\
qe_gate_faulted qe_failed = false.
Arguments
Qed
Proof.
intros Hlive Hdata. simpl.
unfold qe_start, qe_publish.
rewrite Hlive. simpl.
rewrite decide_True by done. simpl.
rewrite Hdata.
rewrite bool_decide_eq_false_2; [done|discriminate].
Qed.References
Uses
12 more
- qe_disposed
- qe_gate_faulted
- qe_start
- qe_publish
- Some
- false
- inr
- nat
- true
- Z
- bool_decide_eq_false_2
- decide_True
Used by
3. Reference-counted QueryLease lifecycle
State of a QueryFamily entry slot and a QueryLease (Queries.fs lines 11–83, 113–144):
ql_lease_disposed: whether thisQueryLeasehas already been disposed.ql_ref_count: number of active leases holding the key'sQueryEntry.ql_entry_alive: whether the key remains inentrieswith an activeQueryEntry.
Record query_lease_state := {
Record query_lease_state := {
ql_lease_disposed : bool;
ql_ref_count : nat;
ql_entry_alive : bool;
}.QueryLease.Dispose (Queries.fs lines 66–79, 127–132): if ql_lease_disposed = false, sets
ql_lease_disposed := true, decrements ql_ref_count, and evicts/disposes the entry when the
decremented count reaches 0.
Definition query_lease_dispose (st : query_lease_state) : query_lease_state :=
Definition query_lease_dispose (st : query_lease_state) : query_lease_state :=
if ql_lease_disposed st then st
else
let c' := ql_ref_count st - 1 in
{| ql_lease_disposed := true;
ql_ref_count := c';
ql_entry_alive := bool_decide (0 < c') && ql_entry_alive st |}.References
Uses
- query_lease_state
- ql_lease_disposed
- ql_ref_count
- ql_entry_alive
- true
- bool_decide
QueryLease.Dispose is idempotent, decrements the family reference count at most once, and evicts the shared QueryEntry iff the last active lease releases.
Proves the QueryLease ownership contract (Queries.fs lines 66–79, 125–133):
- Disposing a lease twice equals disposing it once (
query_lease_dispose (query_lease_dispose st) = query_lease_dispose st). - When
ql_lease_disposed st = falseandql_ref_count st = S kwithql_entry_alive st = true,query_lease_disposesetsql_ref_counttokand keepsql_entry_alive = trueiffk > 0(evicting and disposing the entry exactly whenk = 0, i.e.,ql_ref_count st = 1).
Arguments
Theorem query_lease_dispose_idempotent_refcount (st : query_lease_state) (k : nat) :
Theorem query_lease_dispose_idempotent_refcount (st : query_lease_state) (k : nat) :
query_lease_dispose (query_lease_dispose st) = query_lease_dispose st /\
(ql_lease_disposed st = false ->
ql_ref_count st = S k ->
ql_entry_alive st = true ->
ql_ref_count (query_lease_dispose st) = k /\
ql_entry_alive (query_lease_dispose st) = bool_decide (0 < k)).
Arguments
Qed
Proof.
split.
- unfold query_lease_dispose.
destruct (ql_lease_disposed st) eqn:E; simpl; [rewrite E; reflexivity | reflexivity].
- intros Hlive Hcnt Halive.
unfold query_lease_dispose.
rewrite Hlive, Hcnt, Halive. simpl.
rewrite Nat.sub_0_r, andb_true_r. split; reflexivity.
Qed.References
Uses
4 more
- true
- Nat.sub_0_r
- andb_true_r
- bool_decide
4. Two-phase atomic QueryStaging commit and reentrancy guard
A staged edit on a single QueryDraft (Types.fs lines 52–69):
DraftUpdate f: patches a loaded valueSome vtoSome (f v)and marksstale = false, updated = true; leaves an unloaded entry (None) asNonewithstale = true.DraftInvalidate: marks the draftstale = truewhile preserving its data.
Inductive draft_edit :=
Inductive draft_edit :=
| DraftUpdate (f : Z -> Z)
| DraftInvalidate.Record query_draft_state := {
Record query_draft_state := {
qd_data : option Z;
qd_stale : bool;
qd_updated : bool;
}.References
Uses
- bool
- option
- Z
Definition init_draft (initial : option Z) : query_draft_state :=
Definition init_draft (initial : option Z) : query_draft_state :=
{| qd_data := initial; qd_stale := true; qd_updated := false |}.References
Uses
- query_draft_state
- qd_data
- qd_stale
- qd_updated
- false
- option
- true
- Z
Definition apply_draft_edit (e : draft_edit) (d : query_draft_state) : query_draft_state :=
Definition apply_draft_edit (e : draft_edit) (d : query_draft_state) : query_draft_state :=
match e with
| DraftUpdate f =>
match qd_data d with
| Some v => {| qd_data := Some (f v); qd_stale := false; qd_updated := true |}
| None => d
end
| DraftInvalidate =>
{| qd_data := qd_data d; qd_stale := true; qd_updated := qd_updated d |}
end.References
Uses
3 more
- Some
- false
- true
Used by
Fixpoint apply_draft_edits (es : list draft_edit) (d : query_draft_state) : query_draft_state :=
Fixpoint apply_draft_edits (es : list draft_edit) (d : query_draft_state) : query_draft_state :=
match es with
| [] => d
| e :: rest => apply_draft_edits rest (apply_draft_edit e d)
end.Two-phase commit (Queries.fs lines 252–273): prepare_all runs all draft validations while
staging = true. If prepare_all returns None (an updater or guard threw during staging),
commit_staging leaves cache untouched; only when prepare_all succeeds (Some next_cache)
does Publish() replace cache with next_cache.
Definition client_reentrancy_allowed (disposed staging : bool) : bool :=
Definition client_reentrancy_allowed (disposed staging : bool) : bool :=
negb disposed && negb staging.Definition commit_staging {A : Type} (prepare_all : option A) (cache : A) : A :=
Definition commit_staging {A : Type} (prepare_all : option A) (cache : A) : A :=
match prepare_all with
| Some published => published
| None => cache
end.QueryDraft edits compose in order on loaded data, leave unloaded entries empty, reject reentrant client calls during staging, and leave the cache untouched if Prepare() fails.
Proves the QueryStaging and Commit contracts (Types.fs lines 52–80, Queries.fs lines 163–207, 234–273):
- Applying
[DraftUpdate f; DraftUpdate g]to a loaded draft (Some v) yieldsSome (g (f v))withqd_stale = falseandqd_updated = true. - Applying any sequence of
DraftUpdateandDraftInvalidateedits to an unloaded draft (None) preservesqd_data = Noneandqd_stale = true(unloaded entries are invalidated, never fabricated). - While
staging = true,client_reentrancy_allowedisfalse. - If
prepare_all = None,commit_stagingreturns the originalcacheunmodified.
Arguments
Theorem query_commit_atomic_staging (v : Z) (f g : Z -> Z) (es : list draft_edit) :
Theorem query_commit_atomic_staging (v : Z) (f g : Z -> Z) (es : list draft_edit) :
apply_draft_edits [DraftUpdate f; DraftUpdate g] (init_draft (Some v)) =
{| qd_data := Some (g (f v)); qd_stale := false; qd_updated := true |} /\
(let d_none := apply_draft_edits es (init_draft None) in
qd_data d_none = None /\ qd_stale d_none = true) /\
(forall disp, client_reentrancy_allowed disp true = false) /\
(forall (A : Type) (cache : A), commit_staging None cache = cache).
Arguments
Qed
Proof.
split_and!.
- reflexivity.
- assert (Hinv : forall d, qd_data d = None -> qd_stale d = true ->
qd_data (apply_draft_edits es d) = None /\ qd_stale (apply_draft_edits es d) = true).
{ induction es as [|e rest IH]; intros d Hd Hst; [ done |].
destruct e as [h|]; simpl; rewrite Hd; apply IH; simpl; done. }
apply Hinv; reflexivity.
- intros disp. unfold client_reentrancy_allowed. by rewrite andb_false_r.
- intros A cache. reflexivity.
Qed.5. Ranvier.Elmish (Mvu.fs) scope-gated dispatch and command ordering
State of an Mvu<'Model, 'Msg> loop (Mvu.fs lines 27–68):
mvu_model: current value of therootmodel signal.mvu_disposed: set totruewhen the constructing scope'sonCleanupruns.mvu_trace: sequence of(observed_model, cmd_id)pairs recording the model value visible to each executed command.
Record mvu_state := {
Record mvu_state := {
mvu_model : Z;
mvu_disposed : bool;
mvu_trace : list (Z * nat);
}.Mvu.Run (Mvu.fs lines 60–65): while not disposed && not rest.IsEmpty do rest.Head dispatch; rest <- rest.Tail.
Fixpoint mvu_run_cmds (cmds : list mvu_cmd) (st : mvu_state) : mvu_state :=
Fixpoint mvu_run_cmds (cmds : list mvu_cmd) (st : mvu_state) : mvu_state :=
match cmds with
| [] => st
| c :: rest =>
if mvu_disposed st then st
else mvu_run_cmds rest (c st)
end.Mvu.Apply (Mvu.fs lines 38–46): if not disposed, computes (next_model, cmds) := step msg (mvu_model st),
writes mvu_model := next_model, and then runs mvu_run_cmds cmds.
Definition mvu_apply (step : nat -> Z -> Z * list mvu_cmd) (msg : nat) (st : mvu_state) : mvu_state :=
Definition mvu_apply (step : nat -> Z -> Z * list mvu_cmd) (msg : nat) (st : mvu_state) : mvu_state :=
if mvu_disposed st then st
else
let (next_model, cmds) := step msg (mvu_model st) in
let st_written := {| mvu_model := next_model;
mvu_disposed := false;
mvu_trace := mvu_trace st |} in
mvu_run_cmds cmds st_written.References
Once the constructing scope is torn down (mvu_disposed = true), mvu_apply drops every message and mvu_run_cmds skips all remaining commands.
Proves the scope-bound lifetime contract of Ranvier.Elmish (Mvu.fs lines 17–20, 38–46, 63–65):
- When
mvu_disposed st = true,mvu_apply step msg st = standmvu_run_cmds cmds st = st. - If a command
ctears down the owning scope (mvu_disposed (c st) = true),mvu_run_cmds (c :: rest) strunscand immediately halts without executing any command inrest.
Arguments
Theorem mvu_disposed_drops_dispatch
Theorem mvu_disposed_drops_dispatch
(step : nat -> Z -> Z * list mvu_cmd) (msg : nat)
(cmds : list mvu_cmd) (c : mvu_cmd) (rest : list mvu_cmd) (st : mvu_state) :
(mvu_disposed st = true ->
mvu_apply step msg st = st /\ mvu_run_cmds cmds st = st) /\
(mvu_disposed st = false ->
mvu_disposed (c st) = true ->
mvu_run_cmds (c :: rest) st = c st).
Arguments
Qed
Proof.
split.
- intros Hdisp. split.
+ unfold mvu_apply. by rewrite Hdisp.
+ destruct cmds as [|c0 cs]; simpl; [done|by rewrite Hdisp].
- intros Hlive Hc_disp. simpl.
rewrite Hlive.
destruct rest as [|r rs]; simpl; [done|by rewrite Hc_disp].
Qed.References
Used by
An observational command obs_cmd cid that records (mvu_model st, cid) into mvu_trace.
Definition obs_cmd (cid : nat) (st : mvu_state) : mvu_state :=
Definition obs_cmd (cid : nat) (st : mvu_state) : mvu_state :=
{| mvu_model := mvu_model st;
mvu_disposed := mvu_disposed st;
mvu_trace := mvu_trace st ++ [(mvu_model st, cid)] |}.mvu_apply writes the updated model before running commands (root.Value <- model; this.Run commands), so every command observes the post-update model in list order.
Proves the command-ordering contract of Ranvier.Elmish (Mvu.fs lines 43–45, 62–65, 131–132):
when mvu_disposed st = false and step msg (mvu_model st) returns (next_model, [obs_cmd c1; obs_cmd c2]),
mvu_apply updates mvu_model to next_model first and executes obs_cmd c1 then obs_cmd c2 against
next_model.
Arguments
Theorem mvu_apply_writes_before_commands
Theorem mvu_apply_writes_before_commands
(step : nat -> Z -> Z * list mvu_cmd) (msg : nat) (next_model : Z) (c1 c2 : nat) (st : mvu_state) :
mvu_disposed st = false ->
step msg (mvu_model st) = (next_model, [obs_cmd c1; obs_cmd c2]) ->
let st' := mvu_apply step msg st in
mvu_model st' = next_model /\
mvu_trace st' = mvu_trace st ++ [(next_model, c1); (next_model, c2)].
Arguments
References
Used by
6. Elmish untracked/unjournaled bypass, lazy gate, inline staging, QueryKey, and linked leases
Record arrive_env := {
Record arrive_env := {
ae_tracking : bool;
ae_host_set : bool;
}.Definition arrive_run_untracked (e : arrive_env) (apply : bool -> Z) : Z * arrive_env :=
Definition arrive_run_untracked (e : arrive_env) (apply : bool -> Z) : Z * arrive_env :=
if ae_tracking e then
let _e_inner := {| ae_tracking := false; ae_host_set := true |} in
(apply false, {| ae_tracking := true; ae_host_set := ae_host_set e |})
else
(apply false, e).References
Uses
- arrive_env
- ae_tracking
- ae_host_set
- bool
- false
- true
- Z
Definition arrive_fast (e : arrive_env) (apply : bool -> Z) : Z * arrive_env :=
Definition arrive_fast (e : arrive_env) (apply : bool -> Z) : Z * arrive_env :=
if ae_tracking e then arrive_run_untracked e apply
else (apply false, e).References
Uses
Inductive cmd_work :=
Inductive cmd_work :=
| WorkNone
| WorkJournaled.Definition run_cmds_journaled_spec (has_journal : bool) (cmds : list mvu_cmd) (st : mvu_state)
Definition run_cmds_journaled_spec (has_journal : bool) (cmds : list mvu_cmd) (st : mvu_state)
: mvu_state * cmd_work :=
if has_journal then (mvu_run_cmds cmds st, WorkJournaled)
else (mvu_run_cmds cmds st, WorkNone).References
Definition run_cmds_opt (has_journal : bool) (cmds : list mvu_cmd) (st : mvu_state)
Definition run_cmds_opt (has_journal : bool) (cmds : list mvu_cmd) (st : mvu_state)
: mvu_state * cmd_work :=
if negb has_journal then (mvu_run_cmds cmds st, WorkNone)
else (mvu_run_cmds cmds st, WorkJournaled).References
Mvu.Arrive bypassing RunUntracked when graph.IsTracking () = false and Mvu.RunCommands skipping JournalWork when graph.Options.Journal.IsNone agree identically with the full untracked and journaled paths.
Proves the Mvu.fs hot-path bypasses:
- For any tracking environment
eand callbackapply,arrive_fast e apply = arrive_run_untracked e apply, and whenae_tracking e = falseit returns(apply false, e)directly without touching host scope state. - For any
has_journalflag, command listcmds, andMvustatest,run_cmds_optagrees withrun_cmds_journaled_specwhile emittingWorkNonewhenhas_journal = false.
Arguments
graph.Options.Journal.IsSome.Mvu state.Theorem mvu_untracked_bypass_and_direct_cmd_eq
Theorem mvu_untracked_bypass_and_direct_cmd_eq
(e : arrive_env) (apply : bool -> Z) (has_journal : bool) (cmds : list mvu_cmd) (st : mvu_state) :
arrive_fast e apply = arrive_run_untracked e apply /\
(ae_tracking e = false -> arrive_fast e apply = (apply false, e)) /\
run_cmds_opt has_journal cmds st = run_cmds_journaled_spec has_journal cmds st /\
run_cmds_opt false cmds st = (mvu_run_cmds cmds st, WorkNone).
Arguments
graph.Options.Journal.IsSome.Mvu state.Qed
Proof.
split_and!.
- unfold arrive_fast, arrive_run_untracked. destruct (ae_tracking e); reflexivity.
- intros Hnt. unfold arrive_fast. rewrite Hnt. reflexivity.
- unfold run_cmds_opt, run_cmds_journaled_spec. destruct has_journal; reflexivity.
- reflexivity.
Qed.Inductive gate_state :=
Inductive gate_state :=
| GatePending
| GateSettled (v : Z)
| GateFailed (e : nat).References
Uses
- nat
- Z
Record eager_entry := {
Record eager_entry := {
ee_has_data : bool;
ee_data : Z;
ee_error : option nat;
ee_gate : gate_state;
}.Record lazy_entry := {
Record lazy_entry := {
le_has_data : bool;
le_data : Z;
le_error : option nat;
le_gate : option gate_state;
}.References
Uses
- gate_state
- bool
- nat
- option
- Z
Definition eager_init : eager_entry :=
Definition eager_init : eager_entry :=
{| ee_has_data := false; ee_data := 0%Z; ee_error := None; ee_gate := GatePending |}.References
Definition lazy_init : lazy_entry :=
Definition lazy_init : lazy_entry :=
{| le_has_data := false; le_data := 0%Z; le_error := None; le_gate := None |}.References
Uses
Inductive gate_op :=
Inductive gate_op :=
| OpStart
| OpOk (v : Z)
| OpErr (e : nat)
| OpReadValue.References
Uses
- nat
- Z
Definition eval_gate (g : gate_state) : Z + option nat :=
Definition eval_gate (g : gate_state) : Z + option nat :=
match g with
| GatePending => inr None
| GateSettled v => inl v
| GateFailed e => inr (Some e)
end.References
Used by
Definition step_eager (op : gate_op) (ee : eager_entry) : option (Z + option nat) * eager_entry :=
Definition step_eager (op : gate_op) (ee : eager_entry) : option (Z + option nat) * eager_entry :=
match op with
| OpStart =>
(None, {| ee_has_data := ee_has_data ee;
ee_data := ee_data ee;
ee_error := None;
ee_gate := if ee_has_data ee then ee_gate ee else GatePending |})
| OpOk v =>
(None, {| ee_has_data := true;
ee_data := v;
ee_error := None;
ee_gate := if ee_has_data ee then ee_gate ee else GateSettled v |})
| OpErr e =>
(None, {| ee_has_data := ee_has_data ee;
ee_data := ee_data ee;
ee_error := Some e;
ee_gate := if ee_has_data ee then ee_gate ee else GateFailed e |})
| OpReadValue =>
let res := if ee_has_data ee then inl (ee_data ee) else eval_gate (ee_gate ee) in
(Some res, ee)
end.References
Uses
Definition ensure_gate (le : lazy_entry) : gate_state * lazy_entry :=
Definition ensure_gate (le : lazy_entry) : gate_state * lazy_entry :=
match le_gate le with
| Some g => (g, le)
| None =>
let g := match le_error le with
| Some e => GateFailed e
| None => GatePending
end in
(g, {| le_has_data := le_has_data le;
le_data := le_data le;
le_error := le_error le;
le_gate := Some g |})
end.References
Definition step_lazy (op : gate_op) (le : lazy_entry) : option (Z + option nat) * lazy_entry :=
Definition step_lazy (op : gate_op) (le : lazy_entry) : option (Z + option nat) * lazy_entry :=
match op with
| OpStart =>
(None, {| le_has_data := le_has_data le;
le_data := le_data le;
le_error := None;
le_gate := if le_has_data le then le_gate le
else match le_gate le with
| Some _ => Some GatePending
| None => None
end |})
| OpOk v =>
(None, {| le_has_data := true;
le_data := v;
le_error := None;
le_gate := if le_has_data le then le_gate le
else match le_gate le with
| Some _ => Some (GateSettled v)
| None => None
end |})
| OpErr e =>
(None, {| le_has_data := le_has_data le;
le_data := le_data le;
le_error := Some e;
le_gate := if le_has_data le then le_gate le
else match le_gate le with
| Some _ => Some (GateFailed e)
| None => None
end |})
| OpReadValue =>
if le_has_data le then (Some (inl (le_data le)), le)
else let '(g, le') := ensure_gate le in (Some (eval_gate g), le')
end.References
Uses
14 more
- gate_op
- OpStart
- OpOk
- OpErr
- OpReadValue
- eval_gate
- ensure_gate
- None
- Some
- inl
- nat
- option
- true
- Z
Fixpoint run_eager (ops : list gate_op) (ee : eager_entry)
Fixpoint run_eager (ops : list gate_op) (ee : eager_entry)
: list (option (Z + option nat)) * eager_entry :=
match ops with
| [] => ([], ee)
| op :: rest =>
let '(r, ee1) := step_eager op ee in
let '(rs, ee') := run_eager rest ee1 in
(r :: rs, ee')
end.Fixpoint run_lazy (ops : list gate_op) (le : lazy_entry)
Fixpoint run_lazy (ops : list gate_op) (le : lazy_entry)
: list (option (Z + option nat)) * lazy_entry :=
match ops with
| [] => ([], le)
| op :: rest =>
let '(r, le1) := step_lazy op le in
let '(rs, le') := run_lazy rest le1 in
(r :: rs, le')
end.Definition entry_gate_rel (ee : eager_entry) (le : lazy_entry) : Prop :=
Definition entry_gate_rel (ee : eager_entry) (le : lazy_entry) : Prop :=
ee_has_data ee = le_has_data le /\
ee_data ee = le_data le /\
ee_error ee = le_error le /\
match le_gate le with
| Some g => ee_gate ee = g
| None =>
ee_has_data ee = false ->
ee_gate ee = match ee_error ee with
| Some e => GateFailed e
| None => GatePending
end
end.References
Uses
7 more
- le_has_data
- le_data
- le_error
- le_gate
- None
- Some
- false
Fixpoint reads_while_empty (ops : list gate_op) (has_data : bool) : bool :=
Fixpoint reads_while_empty (ops : list gate_op) (has_data : bool) : bool :=
match ops with
| [] => false
| OpStart :: rest => reads_while_empty rest has_data
| OpOk _ :: rest => reads_while_empty rest true
| OpErr _ :: rest => reads_while_empty rest has_data
| OpReadValue :: rest => if negb has_data then true else reads_while_empty rest has_data
end.References
Lazy initial-load gate allocation (EnsureGate) simulates eager AsyncSource allocation across every trace of entry operations and leaves le_gate = None whenever .Value is never read while empty.
Proves the lazy gate optimization in QueryEntry<'T> (Entry.fs):
- Across any sequence of
OpStart,OpOk,OpErr, andOpReadValue,run_lazypreservesentry_gate_reland produces the exact same sequence of read results asrun_eager. - On any trace whose
OpReadValuecalls occur only after data has loaded (reads_while_empty ops false = false),le_gatestaysNone(zeroAsyncSourceallocations).
Arguments
eager_init and lazy_init.Theorem lazy_query_gate_refines_eager (ops : list gate_op) :
Theorem lazy_query_gate_refines_eager (ops : list gate_op) :
(run_lazy ops lazy_init).1 = (run_eager ops eager_init).1 /\
entry_gate_rel (run_eager ops eager_init).2 (run_lazy ops lazy_init).2 /\
(reads_while_empty ops false = false -> le_gate (run_lazy ops lazy_init).2 = None).
Arguments
eager_init and lazy_init.Qed
Proof.
assert (Hsim : forall trace ee le,
entry_gate_rel ee le ->
(run_lazy trace le).1 = (run_eager trace ee).1 /\
entry_gate_rel (run_eager trace ee).2 (run_lazy trace le).2).
{ induction trace as [|op rest IH]; intros ee le Hrel.
- split; [reflexivity | exact Hrel].
- assert (Hstep :
(step_lazy op le).1 = (step_eager op ee).1 /\
entry_gate_rel (step_eager op ee).2 (step_lazy op le).2).
{ destruct ee as [ehd edata eerr egate], le as [lhd ldata lerr lgate].
destruct Hrel as [Hd [Hv [He Hg]]]; simpl in *.
subst lhd ldata lerr.
destruct op as [|v|e|]; unfold entry_gate_rel, ensure_gate; simpl.
- destruct ehd, lgate as [g|]; simpl in *;
split_and!; try reflexivity; try exact Hg; try (intros Hfalse; discriminate Hfalse); try (intros _; reflexivity).
- destruct ehd, lgate as [g|]; simpl in *;
split_and!; try reflexivity; try exact Hg; try (intros Hfalse; discriminate Hfalse).
- destruct ehd, lgate as [g|]; simpl in *;
split_and!; try reflexivity; try exact Hg; try (intros Hfalse; discriminate Hfalse); try (intros _; reflexivity).
- destruct ehd, lgate as [g|]; simpl in *.
+ split_and!; try reflexivity; exact Hg.
+ split_and!; try reflexivity; intros Hfalse; discriminate Hfalse.
+ rewrite Hg. split_and!; reflexivity.
+ rewrite (Hg eq_refl). split_and!; reflexivity. }
destruct Hstep as [Hr Hrel'].
simpl. destruct (step_lazy op le) as [rl le1] eqn:El.
destruct (step_eager op ee) as [re ee1] eqn:Ee.
simpl in Hr, Hrel'.
specialize (IH ee1 le1 Hrel') as [Hrs Hrel''].
destruct (run_lazy rest le1) as [rls le2] eqn:Erl.
destruct (run_eager rest ee1) as [res ee2] eqn:Ere.
simpl in Hrs, Hrel''.
simpl. split; [rewrite Hr, Hrs; reflexivity | exact Hrel'']. }
assert (Hnone : forall trace le,
le_gate le = None ->
reads_while_empty trace (le_has_data le) = false ->
le_gate (run_lazy trace le).2 = None).
{ induction trace as [|op rest IH]; intros [lhd ldata lerr lgate] Hgate Hno; simpl in *.
- exact Hgate.
- subst lgate. destruct op as [|v|e|]; simpl in *.
+ destruct lhd; simpl in *;
[ pose proof (IH {| le_has_data := true; le_data := ldata; le_error := None; le_gate := None |} eq_refl Hno) as Hrec;
destruct (run_lazy rest _) as [rs le']; exact Hrec
| pose proof (IH {| le_has_data := false; le_data := ldata; le_error := None; le_gate := None |} eq_refl Hno) as Hrec;
destruct (run_lazy rest _) as [rs le']; exact Hrec ].
+ destruct lhd; simpl in *;
[ pose proof (IH {| le_has_data := true; le_data := v; le_error := None; le_gate := None |} eq_refl Hno) as Hrec;
destruct (run_lazy rest _) as [rs le']; exact Hrec
| pose proof (IH {| le_has_data := true; le_data := v; le_error := None; le_gate := None |} eq_refl Hno) as Hrec;
destruct (run_lazy rest _) as [rs le']; exact Hrec ].
+ destruct lhd; simpl in *;
[ pose proof (IH {| le_has_data := true; le_data := ldata; le_error := Some e; le_gate := None |} eq_refl Hno) as Hrec;
destruct (run_lazy rest _) as [rs le']; exact Hrec
| pose proof (IH {| le_has_data := false; le_data := ldata; le_error := Some e; le_gate := None |} eq_refl Hno) as Hrec;
destruct (run_lazy rest _) as [rs le']; exact Hrec ].
+ destruct lhd; [|discriminate Hno]. simpl in *.
pose proof (IH {| le_has_data := true; le_data := ldata; le_error := lerr; le_gate := None |} eq_refl Hno) as Hrec.
destruct (run_lazy rest _) as [rs le']; exact Hrec. }
assert (Hinit_rel : entry_gate_rel eager_init lazy_init) by (repeat split; reflexivity).
destruct (Hsim ops eager_init lazy_init Hinit_rel) as [Hout Hfinal].
split; [exact Hout|].
split; [exact Hfinal|].
apply (Hnone ops lazy_init eq_refl).
Qed.References
Uses
12 more
- ensure_gate
- step_lazy
- run_eager
- run_lazy
- entry_gate_rel
- reads_while_empty
- None
- Some
- false
- list
- true
- eq_refl
Used by
Inductive ext_draft_edit :=
Inductive ext_draft_edit :=
| ExtUpdate (f : Z -> Z)
| ExtSet (v : Z)
| ExtInvalidate.Record inline_draft := {
Record inline_draft := {
id_staged : bool;
id_has_value : bool;
id_value : Z;
id_stale : bool;
id_updated : bool;
}.Definition init_inline_draft (has_data : bool) (val : Z) : inline_draft :=
Definition init_inline_draft (has_data : bool) (val : Z) : inline_draft :=
{| id_staged := true; id_has_value := has_data; id_value := val; id_stale := true; id_updated := false |}.References
Definition step_inline_draft (e : ext_draft_edit) (d : inline_draft) : inline_draft :=
Definition step_inline_draft (e : ext_draft_edit) (d : inline_draft) : inline_draft :=
match e with
| ExtUpdate f =>
if id_has_value d then
{| id_staged := true; id_has_value := true; id_value := f (id_value d); id_stale := false; id_updated := true |}
else d
| ExtSet v =>
if id_has_value d then
{| id_staged := true; id_has_value := true; id_value := v; id_stale := false; id_updated := true |}
else d
| ExtInvalidate =>
{| id_staged := true; id_has_value := id_has_value d; id_value := id_value d; id_stale := true; id_updated := id_updated d |}
end.Fixpoint apply_inline_drafts (es : list ext_draft_edit) (d : inline_draft) : inline_draft :=
Fixpoint apply_inline_drafts (es : list ext_draft_edit) (d : inline_draft) : inline_draft :=
match es with
| [] => d
| e :: rest => apply_inline_drafts rest (step_inline_draft e d)
end.References
Definition to_model_edit (e : ext_draft_edit) : draft_edit :=
Definition to_model_edit (e : ext_draft_edit) : draft_edit :=
match e with
| ExtUpdate f => DraftUpdate f
| ExtSet v => DraftUpdate (fun _ => v)
| ExtInvalidate => DraftInvalidate
end.Definition decode_draft (d : inline_draft) : query_draft_state :=
Definition decode_draft (d : inline_draft) : query_draft_state :=
{| qd_data := if id_has_value d then Some (id_value d) else None;
qd_stale := id_stale d;
qd_updated := id_updated d |}.References
Uses
3 more
- id_updated
- None
- Some
Definition inline_prepare (has_data : bool) (cur : Z) (eqb : Z -> Z -> bool) (d : inline_draft) : bool :=
Definition inline_prepare (has_data : bool) (cur : Z) (eqb : Z -> Z -> bool) (d : inline_draft) : bool :=
if negb (id_updated d) || negb (id_has_value d) then false
else if negb has_data then true
else negb (eqb cur (id_value d)).References
Definition model_prepare (initial : option Z) (eqb : Z -> Z -> bool) (d : query_draft_state) : bool :=
Definition model_prepare (initial : option Z) (eqb : Z -> Z -> bool) (d : query_draft_state) : bool :=
match qd_updated d, initial, qd_data d with
| true, Some old, Some v => negb (eqb old v)
| true, None, None => false
| true, _, _ => true
| false, _, _ => false
end.References
Definition commit_reset_draft (publish : bool) (has_data : bool) (cur : Z) (d : inline_draft)
Definition commit_reset_draft (publish : bool) (has_data : bool) (cur : Z) (d : inline_draft)
: bool * (bool * Z) :=
let next := if publish && id_has_value d then (true, id_value d) else (has_data, cur) in
(false, next).References
Uses
- inline_draft
- id_has_value
- id_value
- bool
- false
- true
- Z
Unboxed (hasData, data) and per-entry inline draftStaged staging (with DraftSet fusion and pre-batch / rollback reset) refine map-allocated QueryDraft over 'T option for arbitrary edit sequences.
Proves the Entry.fs / Queries.fs inline staging optimization:
- For any initial
(has_data, cur)and arbitrary sequenceesofExtUpdate,ExtSet, andExtInvalidateedits,decode_draft (apply_inline_drafts es (init_inline_draft has_data cur))equalsapply_draft_edits (map to_model_edit es) (init_draft (if has_data then Some cur else None)). - Under any edit sequence
es,inline_preparecomputes the exact samechangedbit asmodel_prepare. - Both successful
Publish(publish = true) and rollbackResetDraft(publish = false) clearid_stagedtofalse, while rollback leaves(has_data, cur)unmodified.
Arguments
data signal when has_data = true.Theorem unboxed_data_and_inline_draft_refines_staged_map
Theorem unboxed_data_and_inline_draft_refines_staged_map
(has_data : bool) (cur : Z) (eqb : Z -> Z -> bool) (es : list ext_draft_edit) :
let initial_opt := if has_data then Some cur else None in
let final_inline := apply_inline_drafts es (init_inline_draft has_data cur) in
decode_draft final_inline = apply_draft_edits (map to_model_edit es) (init_draft initial_opt) /\
inline_prepare has_data cur eqb final_inline = model_prepare initial_opt eqb (decode_draft final_inline) /\
(commit_reset_draft true has_data cur final_inline).1 = false /\
commit_reset_draft false has_data cur final_inline = (false, (has_data, cur)).
Arguments
data signal when has_data = true.Qed
Proof.
assert (Hstep : forall edits d,
decode_draft (apply_inline_drafts edits d) =
apply_draft_edits (map to_model_edit edits) (decode_draft d) /\
id_has_value (apply_inline_drafts edits d) = id_has_value d /\
(id_has_value d = false -> id_updated d = false -> id_updated (apply_inline_drafts edits d) = false)).
{ induction edits as [|e rest IH]; intros d.
- split; [reflexivity | split; [reflexivity | intros _ Hu; exact Hu]].
- destruct e as [f|v|]; simpl.
+ destruct (id_has_value d) eqn:Ehv; simpl.
* destruct (IH {| id_staged := true; id_has_value := true; id_value := f (id_value d); id_stale := false; id_updated := true |})
as [Hdec [Hh Hupd]].
split; [exact Hdec | split; [exact Hh | intros Hfalse; discriminate Hfalse]].
* destruct (IH d) as [Hdec [Hh Hupd]].
split; [exact Hdec | split; [rewrite Hh, Ehv; reflexivity | intros _ Hu; exact (Hupd Ehv Hu)]].
+ destruct (id_has_value d) eqn:Ehv; simpl.
* destruct (IH {| id_staged := true; id_has_value := true; id_value := v; id_stale := false; id_updated := true |})
as [Hdec [Hh Hupd]].
split; [exact Hdec | split; [exact Hh | intros Hfalse; discriminate Hfalse]].
* destruct (IH d) as [Hdec [Hh Hupd]].
split; [exact Hdec | split; [rewrite Hh, Ehv; reflexivity | intros _ Hu; exact (Hupd Ehv Hu)]].
+ destruct (IH {| id_staged := true; id_has_value := id_has_value d; id_value := id_value d; id_stale := true; id_updated := id_updated d |})
as [Hdec [Hh Hupd]].
split; [exact Hdec | split; [exact Hh | exact Hupd]]. }
specialize (Hstep es (init_inline_draft has_data cur)).
destruct Hstep as [Hdec [Hh Hupd]].
split_and!.
- rewrite Hdec. unfold init_inline_draft, decode_draft, init_draft. simpl. reflexivity.
- unfold inline_prepare, model_prepare, decode_draft. simpl.
rewrite Hh. destruct has_data eqn:Ehd; simpl.
+ destruct (id_updated (apply_inline_drafts es (init_inline_draft true cur))); reflexivity.
+ rewrite (Hupd eq_refl eq_refl). reflexivity.
- reflexivity.
- reflexivity.
Qed.References
Uses
16 more
- init_inline_draft
- apply_inline_drafts
- to_model_edit
- decode_draft
- inline_prepare
- model_prepare
- commit_reset_draft
- None
- Some
- bool
- false
- list
- true
- eq_refl
- map
- Z
Used by
Definition qk_default_eq (eqZ : Z -> Z -> bool) (k1 k2 : option Z) : bool :=
Definition qk_default_eq (eqZ : Z -> Z -> bool) (k1 k2 : option Z) : bool :=
match k1, k2 with
| Some a, Some b => eqZ a b
| None, None => true
| _, _ => false
end.Definition qk_default_hash (hashZ : Z -> Z) (k : option Z) : Z :=
Definition qk_default_hash (hashZ : Z -> Z) (k : option Z) : Z :=
match k with
| Some a => hashZ a
| None => 0%Z
end.Definition session_guard_ok (on_thread disposed_client staging : bool) : bool :=
Definition session_guard_ok (on_thread disposed_client staging : bool) : bool :=
on_thread && negb disposed_client && negb staging.References
Uses
- bool
- negb
Definition single_checked_op {A : Type}
Definition single_checked_op {A : Type}
(on_thread disposed_client staging disposed_lease disposed_entry : bool) (op : A) : option A :=
if session_guard_ok on_thread disposed_client staging && negb disposed_lease && negb disposed_entry
then Some op
else None.References
Uses
- session_guard_ok
- None
- Some
- bool
- negb
- option
Definition double_checked_op {A : Type}
Definition double_checked_op {A : Type}
(on_thread disposed_client staging disposed_lease disposed_entry : bool) (op : A) : option A :=
if session_guard_ok on_thread disposed_client staging && negb disposed_lease then
if session_guard_ok on_thread disposed_client staging && negb disposed_entry then Some op
else None
else None.References
Uses
- session_guard_ok
- None
- Some
- bool
- negb
- option
QueryKey default-comparer equality/hashing handles nullable and unit (None) keys consistently, and checking QuerySession.Guard once at QueryLease matches double-checked QueryLease + QueryEntry guards.
Proves the Queries.fs QueryKey devirtualization and QuerySession single-guard elimination:
- Whenever
eqZis reflexive (eqZ x x = true) and hash-compatible (eqZ x y = true -> hashZ x = hashZ y),qk_default_eq eqZis reflexive on alloption Z(includingNoneforunit/null) and preservesqk_default_hash hashZwithout invoking a null dereference onNone. - For all thread, disposal, and staging flags,
single_checked_opagrees withdouble_checked_op.
Arguments
None represents () / null).Theorem query_key_default_equatable_and_session_guard_eq
Theorem query_key_default_equatable_and_session_guard_eq
(eqZ : Z -> Z -> bool) (hashZ : Z -> Z) (k1 k2 : option Z) :
(forall x, eqZ x x = true) ->
(forall x y, eqZ x y = true -> hashZ x = hashZ y) ->
qk_default_eq eqZ k1 k1 = true /\
(qk_default_eq eqZ k1 k2 = true -> qk_default_hash hashZ k1 = qk_default_hash hashZ k2) /\
forall (A : Type) (on_thread dc st dl de : bool) (op : A),
single_checked_op on_thread dc st dl de op = double_checked_op on_thread dc st dl de op.
Arguments
None represents () / null).Qed
Proof.
intros Hrefl Hhash. split_and!.
- destruct k1; simpl; [apply Hrefl | reflexivity].
- destruct k1, k2; simpl; try discriminate; [apply Hhash | intros _; reflexivity].
- intros A on_thread dc st dl de op.
unfold single_checked_op, double_checked_op, session_guard_ok.
destruct on_thread, dc, st, dl, de; reflexivity.
Qed.References
Uses
1 more
- Z
Used by
Inductive await_outcome :=
Inductive await_outcome :=
| AwaitOk (v : Z)
| AwaitErr (err : nat)
| AwaitCanceled.Definition await_immediate_decision (err : option nat) (has_data stale : bool) (data_val : Z) : await_outcome :=
Definition await_immediate_decision (err : option nat) (has_data stale : bool) (data_val : Z) : await_outcome :=
match err with
| Some e => AwaitErr e
| None => if has_data && negb stale then AwaitOk data_val else AwaitCanceled
end.References
Definition await_waiter_spec
Definition await_waiter_spec
(status : fetch_status) (err : option nat) (has_data stale : bool) (data_val : Z)
: bool * option await_outcome :=
match status with
| FsFetching => (true, None)
| FsIdle => (false, Some (await_immediate_decision err has_data stale data_val))
end.References
Uses
5 more
- false
- nat
- option
- true
- Z
Definition await_fast_opt
Definition await_fast_opt
(status : fetch_status) (err : option nat) (has_data stale : bool) (data_val : Z)
: bool * option await_outcome :=
match status with
| FsFetching => (true, None)
| FsIdle => (false, Some (await_immediate_decision err has_data stale data_val))
end.References
Uses
5 more
- false
- nat
- option
- true
- Z
Record linked_lease_state := {
Record linked_lease_state := {
ll_lease_state : query_lease_state;
ll_owner_attached : bool;
ll_waiter_detached : bool;
}.Definition linked_lease_dispose (st : linked_lease_state) : linked_lease_state :=
Definition linked_lease_dispose (st : linked_lease_state) : linked_lease_state :=
{| ll_lease_state := query_lease_dispose (ll_lease_state st);
ll_owner_attached := false;
ll_waiter_detached := true |}.QueryEntry.AwaitImmediate allocates zero waiters when FetchStatus = FsIdle with identical outcome, QueryAwaiter.TryClaim is idempotent, and OwnerLink-backed QueryLease.Dispose detaches cleanly and decrements refcount at most once.
Proves the Entry.fs / Queries.fs waiter and lease-link optimizations:
- When
status = FsIdle,await_fast_optmatchesawait_waiter_specand requires zero waiter allocation (fst = false). - Disposing a
linked_lease_stateis idempotent (linked_lease_dispose (linked_lease_dispose st) = linked_lease_dispose st), setsll_owner_attached = falseandll_waiter_detached = true, and decrements the entry's reference count once (query_lease_dispose_idempotent_refcount).
Arguments
FetchStatus of the entry.Error option in metadata.Theorem waiter_fast_task_and_linked_lease_eq
Theorem waiter_fast_task_and_linked_lease_eq
(status : fetch_status) (err : option nat) (has_data stale : bool) (data_val : Z)
(st : linked_lease_state) (k : nat) :
await_fast_opt status err has_data stale data_val = await_waiter_spec status err has_data stale data_val /\
fst (await_fast_opt FsIdle err has_data stale data_val) = false /\
linked_lease_dispose (linked_lease_dispose st) = linked_lease_dispose st /\
ll_owner_attached (linked_lease_dispose st) = false /\
ll_waiter_detached (linked_lease_dispose st) = true /\
(ql_lease_disposed (ll_lease_state st) = false ->
ql_ref_count (ll_lease_state st) = S k ->
ql_entry_alive (ll_lease_state st) = true ->
ql_ref_count (ll_lease_state (linked_lease_dispose st)) = k /\
ql_entry_alive (ll_lease_state (linked_lease_dispose st)) = bool_decide (0 < k)).
Arguments
FetchStatus of the entry.Error option in metadata.Qed
Proof.
split_and!.
- reflexivity.
- reflexivity.
- unfold linked_lease_dispose. simpl.
destruct (query_lease_dispose_idempotent_refcount (ll_lease_state st) k) as [Hid _].
rewrite Hid. reflexivity.
- reflexivity.
- reflexivity.
- intros Hlive Hcnt Halive. simpl.
destruct (query_lease_dispose_idempotent_refcount (ll_lease_state st) k) as [_ Hdec].
exact (Hdec Hlive Hcnt Halive).
Qed.References
Uses
- fetch_status
- FsIdle
- ql_lease_disposed
- ql_ref_count
- ql_entry_alive
- query_lease_dispose_idempotent_refcount
- await_waiter_spec
- await_fast_opt
14 more
- linked_lease_state
- ll_lease_state
- ll_owner_attached
- ll_waiter_detached
- linked_lease_dispose
- S
- bool
- false
- fst
- nat
- option
- true
- Z
- bool_decide
Used by
7. Wave 6 CSharp, Wire, Mcp, and Dom optimisations
Inductive bound_status := BStNone | BStPending | BStError.Inductive bound_reading :=
Inductive bound_reading :=
| BRReady (v : Z)
| BRPending
| BRFailed (e : nat).Definition decode_struct_reading (st : bound_status) (v : Z) (err : option nat) : bound_reading :=
Definition decode_struct_reading (st : bound_status) (v : Z) (err : option nat) : bound_reading :=
match st, err with
| BStNone, _ => BRReady v
| BStPending, _ => BRPending
| BStError, Some e => BRFailed e
| BStError, None => BRFailed 0
end.References
Uses
5 more
- None
- Some
- nat
- option
- Z
Record bound_state := {
Record bound_state := {
bs_val : Z;
bs_has : bool;
bs_loading : bool;
bs_error : option nat;
}.References
Uses
- bool
- nat
- option
- Z
Definition eq_opt_nat (a b : option nat) : bool :=
Definition eq_opt_nat (a b : option nat) : bool :=
match a, b with
| None, None => true
| Some x, Some y => Nat.eqb x y
| _, _ => false
end.Definition bound_refresh_flags (eqZ : Z -> Z -> bool) (old : bound_state) (r : bound_reading)
Definition bound_refresh_flags (eqZ : Z -> Z -> bool) (old : bound_state) (r : bound_reading)
: bool * bool * bool :=
match r with
| BRReady v =>
(negb (bs_has old) || negb (eqZ (bs_val old) v),
bs_loading old,
match bs_error old with None => false | Some _ => true end)
| BRPending =>
(false,
negb (bs_loading old),
match bs_error old with None => false | Some _ => true end)
| BRFailed e =>
(false,
bs_loading old,
negb (eq_opt_nat (bs_error old) (Some e)))
end.References
Uses
9 more
- bs_error
- eq_opt_nat
- None
- Some
- bool
- false
- negb
- true
- Z
Definition bound_refresh_alloc (eqZ : Z -> Z -> bool) (old : bound_state) (r : bound_reading)
Definition bound_refresh_alloc (eqZ : Z -> Z -> bool) (old : bound_state) (r : bound_reading)
: bound_state * (bool * bool * bool) :=
let '(vc, lc, ec) := bound_refresh_flags eqZ old r in
let next :=
match r with
| BRReady v => {| bs_val := v; bs_has := true; bs_loading := false; bs_error := None |}
| BRPending => {| bs_val := bs_val old; bs_has := bs_has old; bs_loading := true; bs_error := None |}
| BRFailed e => {| bs_val := bs_val old; bs_has := bs_has old; bs_loading := false; bs_error := Some e |}
end in
(next, (vc, lc, ec)).References
Uses
8 more
- bs_error
- bound_refresh_flags
- None
- Some
- bool
- false
- true
- Z
Definition bound_refresh_reuse (custom_cmp : bool) (eqZ : Z -> Z -> bool) (old : bound_state) (r : bound_reading)
Definition bound_refresh_reuse (custom_cmp : bool) (eqZ : Z -> Z -> bool) (old : bound_state) (r : bound_reading)
: bound_state * (bool * bool * bool) :=
let '(vc, lc, ec) := bound_refresh_flags eqZ old r in
let next :=
match r with
| BRReady v =>
if vc || lc || ec || custom_cmp then
{| bs_val := v; bs_has := true; bs_loading := false; bs_error := None |}
else old
| BRPending =>
if lc || ec then
{| bs_val := bs_val old; bs_has := bs_has old; bs_loading := true; bs_error := None |}
else old
| BRFailed e =>
if lc || ec then
{| bs_val := bs_val old; bs_has := bs_has old; bs_loading := false; bs_error := Some e |}
else old
end in
(next, (vc, lc, ec)).References
Uses
8 more
- bs_error
- bound_refresh_flags
- None
- Some
- bool
- false
- true
- Z
Definition direct_signal_dispatch (on_thread : bool) (inbox : list Z) (v : Z) : option Z * list Z :=
Definition direct_signal_dispatch (on_thread : bool) (inbox : list Z) (v : Z) : option Z * list Z :=
if on_thread then (Some v, inbox) else (None, inbox ++ [v]).Definition queued_signal_dispatch (on_thread : bool) (inbox : list Z) (v : Z) : option Z * list Z :=
Definition queued_signal_dispatch (on_thread : bool) (inbox : list Z) (v : Z) : option Z * list Z :=
if on_thread then (Some v, inbox) else (None, inbox ++ [v]).BoundValue / BoundSignal struct reads and unchanged-BoundState reuse match fresh allocations under default equality, and BoundSignal.set_Value direct on-thread dispatch matches Graph.Dispatch.
Proves the Memo.TryReadStruct, BoundValue/BoundSignal unchanged-state reuse, and BoundSignal.set_Value optimizations (Core.fs, Bindings.fs):
decode_struct_readingfaithfully decodesTryReadStruct(Status * 'T * exn)tuples intoBRReady,BRPending, andBRFailed.- Whenever
eqZrespects strict equality whencustom_cmp = false(forall a b, eqZ a b = true -> a = b),bound_refresh_reuse false eqZ old r = bound_refresh_alloc eqZ old racross all prior statesoldand readingsr, and forcustom_cmp = trueboth also agree unconditionally (bound_refresh_reuse true eqZ old r = bound_refresh_alloc eqZ old r). direct_signal_dispatch on_thread inbox v = queued_signal_dispatch on_thread inbox v.
Arguments
bound_state snapshot.Memo / Signal reading.IEqualityComparer was configured on the graph.BoundSignal.Value <- v.Theorem bound_slot_inplace_refresh_and_direct_dispatch_eq
Theorem bound_slot_inplace_refresh_and_direct_dispatch_eq
(eqZ : Z -> Z -> bool) (old : bound_state) (r : bound_reading)
(custom_cmp on_thread : bool) (inbox : list Z) (v : Z) :
(custom_cmp = false -> forall a b, eqZ a b = true -> a = b) ->
bound_refresh_reuse custom_cmp eqZ old r = bound_refresh_alloc eqZ old r /\
direct_signal_dispatch on_thread inbox v = queued_signal_dispatch on_thread inbox v /\
decode_struct_reading BStNone v None = BRReady v /\
decode_struct_reading BStPending v None = BRPending /\
forall err, decode_struct_reading BStError v (Some err) = BRFailed err.
Arguments
bound_state snapshot.Memo / Signal reading.IEqualityComparer was configured on the graph.BoundSignal.Value <- v.Qed
Proof.
intros Hdef. split_and!.
- destruct old as [ov ohas oload oerr], r as [rv | | re], custom_cmp;
unfold bound_refresh_reuse, bound_refresh_alloc, bound_refresh_flags; simpl.
+ rewrite orb_true_r. reflexivity.
+ destruct ohas eqn:Ehas; simpl; [|reflexivity].
destruct (eqZ ov rv) eqn:Eeq; simpl; [|reflexivity].
destruct oload eqn:Eload; simpl; [reflexivity|].
destruct oerr as [e|] eqn:Eerr; simpl; [reflexivity|].
rewrite (Hdef eq_refl ov rv Eeq). reflexivity.
+ destruct oload; destruct oerr; reflexivity.
+ destruct oload; destruct oerr; reflexivity.
+ destruct oload; simpl; [reflexivity|].
destruct oerr as [e|]; simpl; [|reflexivity].
destruct (Nat.eqb e re) eqn:Een; simpl; [rewrite (proj1 (Nat.eqb_eq e re) Een); reflexivity | reflexivity].
+ destruct oload; simpl; [reflexivity|].
destruct oerr as [e|]; simpl; [|reflexivity].
destruct (Nat.eqb e re) eqn:Een; simpl; [rewrite (proj1 (Nat.eqb_eq e re) Een); reflexivity | reflexivity].
- reflexivity.
- reflexivity.
- reflexivity.
- intros err. reflexivity.
Qed.References
Uses
18 more
- bound_state
- bound_refresh_flags
- bound_refresh_alloc
- bound_refresh_reuse
- direct_signal_dispatch
- queued_signal_dispatch
- None
- Some
- bool
- false
- list
- true
- eq_refl
- proj1
- Z
- Nat.eqb
- Nat.eqb_eq
- orb_true_r
Used by
Record rc_state := {
Record rc_state := {
rc_running : nat;
rc_error : option nat;
rc_journaled : bool;
rc_flights : nat;
}.References
Uses
- bool
- nat
- option
Inductive rc_task_outcome :=
Inductive rc_task_outcome :=
| RcCompleted
| RcFaulted (e : nat)
| RcCanceled.Global Instance rc_task_outcome_eq_dec : EqDecision rc_task_outcome.
Defined
Proof. solve_decision. Defined.References
Uses
- rc_task_outcome
- EqDecision
Definition rc_sync_with_cts (failure : option nat) (st : rc_state) : rc_state * rc_task_outcome :=
Definition rc_sync_with_cts (failure : option nat) (st : rc_state) : rc_state * rc_task_outcome :=
let r1 := S (rc_running st) in
let r2 := r1 - 1 in
let err' := failure in
let task := match failure with Some e => RcFaulted e | None => RcCompleted end in
({| rc_running := r2; rc_error := err'; rc_journaled := rc_journaled st; rc_flights := rc_flights st |}, task).References
Uses
5 more
- None
- S
- Some
- nat
- option
Definition rc_sync_direct (failure : option nat) (st : rc_state) : rc_state * rc_task_outcome :=
Definition rc_sync_direct (failure : option nat) (st : rc_state) : rc_state * rc_task_outcome :=
let r1 := S (rc_running st) in
let write_err := negb (eq_opt_nat (rc_error st) failure) || rc_journaled st in
let err' := if write_err then failure else rc_error st in
let task := match failure with Some e => RcFaulted e | None => RcCompleted end in
({| rc_running := r1 - 1; rc_error := err'; rc_journaled := rc_journaled st; rc_flights := rc_flights st |}, task).References
Uses
7 more
- RcFaulted
- None
- S
- Some
- nat
- negb
- option
Definition rc_onthread_task (need_task : bool) (out : rc_task_outcome) : rc_task_outcome :=
Definition rc_onthread_task (need_task : bool) (out : rc_task_outcome) : rc_task_outcome :=
if need_task then out else RcCompleted.Definition notify_delivered (has_changes has_handlers : bool) (notes : list nat) : bool * list nat :=
Definition notify_delivered (has_changes has_handlers : bool) (notes : list nat) : bool * list nat :=
if has_changes && has_handlers then (true, notes) else (false, []).Definition notify_eager (has_changes has_handlers : bool) (notes : list nat) : list nat :=
Definition notify_eager (has_changes has_handlers : bool) (notes : list nat) : list nat :=
if has_changes then (if has_handlers then notes else []) else [].Synchronous ReactiveCommand execution without CancellationTokenSource preserves exact running-count, error, and task-outcome semantics, and skipping RunUntracked without handlers emits identical events.
Proves the ReactiveCommand and ReactiveBindings.notify optimizations (Bindings.fs):
rc_sync_direct failure stproduces the exact same post-executionrc_state(including restoringrc_runningtorc_running st, updatingrc_errortofailure, and leavingrc_flightsunchanged) andrc_task_outcomeasrc_sync_with_cts failure st.rc_onthread_task need_task outmatches immediate completed task return whenneed_task = falseand exact faulted/canceled propagation whenneed_task = true.notify_deliveredskipsRunUntracked(fst = false) wheneverhas_handlers = falseand produces the exact same delivered notificationssndasnotify_eager.
Arguments
ReactiveCommand state before execution.ExecuteAsync vs Execute) observes the returned task.notify.PropertyChanged, ErrorsChanged, or CanExecuteChanged listener is subscribed.Theorem reactive_command_inline_exec_and_lazy_notify_eq
Theorem reactive_command_inline_exec_and_lazy_notify_eq
(failure : option nat) (st : rc_state)
(need_task has_changes has_handlers : bool) (out : rc_task_outcome) (notes : list nat) :
rc_sync_direct failure st = rc_sync_with_cts failure st /\
rc_running (rc_sync_direct failure st).1 = rc_running st /\
(rc_onthread_task need_task out = if need_task then out else RcCompleted) /\
(notify_delivered has_changes has_handlers notes).2 = notify_eager has_changes has_handlers notes /\
(has_handlers = false -> (notify_delivered has_changes false notes).1 = false).
Arguments
ReactiveCommand state before execution.ExecuteAsync vs Execute) observes the returned task.notify.PropertyChanged, ErrorsChanged, or CanExecuteChanged listener is subscribed.Qed
Proof.
split_and!.
- unfold rc_sync_direct, rc_sync_with_cts.
destruct (rc_error st) as [e1|] eqn:E1, failure as [e2|]; simpl.
+ destruct (Nat.eqb e1 e2) eqn:Eeq; simpl;
[rewrite (proj1 (Nat.eqb_eq e1 e2) Eeq); destruct (rc_journaled st); reflexivity | reflexivity].
+ reflexivity.
+ reflexivity.
+ destruct (rc_journaled st); reflexivity.
- unfold rc_sync_direct. simpl. lia.
- reflexivity.
- unfold notify_delivered, notify_eager. destruct has_changes, has_handlers; reflexivity.
- intros _. unfold notify_delivered. destruct has_changes; reflexivity.
Qed.References
Uses
11 more
- rc_onthread_task
- notify_delivered
- notify_eager
- bool
- false
- list
- nat
- option
- proj1
- Nat.eqb
- Nat.eqb_eq
Used by
Fixpoint any_pending_loop (is_pending : nat -> bool) (xs : list nat) : bool * list nat :=
Fixpoint any_pending_loop (is_pending : nat -> bool) (xs : list nat) : bool * list nat :=
match xs with
| [] => (false, [])
| x :: rest =>
if is_pending x then (true, [x])
else
let '(res, vis) := any_pending_loop is_pending rest in
(res, x :: vis)
end.Definition exposure_rev_diff (pairs : list (nat * Z * Z)) : list nat :=
Definition exposure_rev_diff (pairs : list (nat * Z * Z)) : list nat :=
fold_right (fun '(nm, oldv, newv) acc => if Z.eqb oldv newv then acc else nm :: acc) [] pairs.Definition exposure_filter_diff (pairs : list (nat * Z * Z)) : list nat :=
Definition exposure_filter_diff (pairs : list (nat * Z * Z)) : list nat :=
map (fun '(nm, _, _) => nm) (List.filter (fun '(_, oldv, newv) => negb (Z.eqb oldv newv)) pairs).Definition modifier_key_names : list string :=
Definition modifier_key_names : list string :=
[ "Shift"; "Control"; "Alt"; "Meta"; "AltGraph";
"CapsLock"; "Fn"; "FnLock"; "Hyper"; "Super";
"Symbol"; "SymbolLock"; "NumLock"; "ScrollLock"; "OS" ]%string.Definition is_modifier_key_match (k : string) : bool :=
Definition is_modifier_key_match (k : string) : bool :=
match k with
| "Shift"%string | "Control"%string | "Alt"%string | "Meta"%string | "AltGraph"%string
| "CapsLock"%string | "Fn"%string | "FnLock"%string | "Hyper"%string | "Super"%string
| "Symbol"%string | "SymbolLock"%string | "NumLock"%string | "ScrollLock"%string | "OS"%string => true
| _ => false
end.Definition dispatch_dom_observers {A : Type} (obs : list A) : list A :=
Definition dispatch_dom_observers {A : Type} (obs : list A) : list A :=
if Nat.eqb (length obs) 0 then [] else obs.Reactive.AnyPending while loop short-circuits cleanly, Exposure.publish backwards scan preserves registration order with zero empty-diff changes, InputState.isModifierKey matches the 15 DOM modifier names, and empty-observer DOM fast-paths match full iteration.
Proves the loop, publishing, and observer-guard optimizations in Reactive.fs, Exposure.fs, and Ranvier.Dom:
any_pending_loop is_pending xsreturns(existsb is_pending xs, vis)wherevisis a prefix ofxsthat visitsxsstrictly in order up to the first pending node (all prior nodes non-pending, stopping immediately attrue).exposure_rev_diff pairsmatchesexposure_filter_diff pairsand is[]iff every entry text equals its previous text (Forall (fun '(_, a, b) => a = b) pairs).is_modifier_key_match k = existsb (String.eqb k) modifier_key_namesfor every stringk.dispatch_dom_observers obs = obsfor every observer snapshotobs.
Arguments
AnyPending.(entry_id, old_text, new_text) in registration order.key string inspected by InputState.Ranvier.Dom.Theorem any_pending_loop_and_unsubscribed_publish_eq
Theorem any_pending_loop_and_unsubscribed_publish_eq
(is_pending : nat -> bool) (xs : list nat) (pairs : list (nat * Z * Z))
(k : string) {A : Type} (obs : list A) :
(any_pending_loop is_pending xs).1 = existsb is_pending xs /\
(exists tail,
(any_pending_loop is_pending xs).2 ++ tail = xs /\
((any_pending_loop is_pending xs).1 = false ->
(any_pending_loop is_pending xs).2 = xs /\ Forall (fun x => is_pending x = false) xs)) /\
exposure_rev_diff pairs = exposure_filter_diff pairs /\
(exposure_rev_diff pairs = [] <-> Forall (fun '(_, a, b) => a = b) pairs) /\
is_modifier_key_match k = existsb (String.eqb k) modifier_key_names /\
dispatch_dom_observers obs = obs.
Arguments
AnyPending.(entry_id, old_text, new_text) in registration order.key string inspected by InputState.Ranvier.Dom.Qed
Proof.
split_and!.
- induction xs as [|x rest IH]; simpl.
+ reflexivity.
+ destruct (is_pending x); simpl; [reflexivity|].
destruct (any_pending_loop is_pending rest) as [res vis] eqn:Eloop.
simpl in *. exact IH.
- induction xs as [|x rest IH]; simpl.
+ exists []. split; [reflexivity | intros _; split; [reflexivity | constructor]].
+ destruct (is_pending x) eqn:Hx; simpl.
* exists rest. split; [reflexivity | intros Hfalse; discriminate Hfalse].
* destruct (any_pending_loop is_pending rest) as [res vis] eqn:Eloop.
destruct IH as [tail [Happ Hfalse]]. simpl in *.
exists tail. split.
-- rewrite <- Happ. reflexivity.
-- intros Hres. destruct (Hfalse Hres) as [Hvis Hall].
subst vis. split; [reflexivity | constructor; assumption].
- unfold exposure_rev_diff, exposure_filter_diff.
induction pairs as [|[[nm oldv] newv] rest IH]; simpl; [reflexivity|].
destruct (Z.eqb oldv newv); simpl; rewrite IH; reflexivity.
- split.
+ unfold exposure_rev_diff.
induction pairs as [|[[nm oldv] newv] rest IH]; simpl; [intros _; constructor|].
destruct (Z.eqb oldv newv) eqn:Eeq.
* intros Hnil. constructor; [exact (proj1 (Z.eqb_eq oldv newv) Eeq) | exact (IH Hnil)].
* intros Hcons. discriminate Hcons.
+ unfold exposure_rev_diff.
induction pairs as [|[[nm oldv] newv] rest IH]; intros Hall; simpl; [reflexivity|].
inversion Hall as [|? ? Heq Hrest]; simpl in Heq.
rewrite (proj2 (Z.eqb_eq oldv newv) Heq). exact (IH Hrest).
- unfold is_modifier_key_match, modifier_key_names.
repeat (simpl; try reflexivity;
lazymatch goal with
| |- (match ?x with _ => _ end = _) =>
destruct x
end).
- unfold dispatch_dom_observers. destruct obs; reflexivity.
Qed.References
Uses
- any_pending_loop
- exposure_rev_diff
- exposure_filter_diff
- modifier_key_names
- is_modifier_key_match
- dispatch_dom_observers
- bool
- false
11 more
- list
- nat
- proj1
- proj2
- Forall
- Z
- existsb
- eqb
- string
- Z.eqb
- Z.eqb_eq
Used by
Definition is_high_surr (c : Z) : bool :=
Definition is_high_surr (c : Z) : bool :=
bool_decide (55296 <= c /\ c <= 56319)%Z.References
Uses
- bool
- Z
- bool_decide
Definition is_low_surr (c : Z) : bool :=
Definition is_low_surr (c : Z) : bool :=
bool_decide (56320 <= c /\ c <= 57343)%Z.References
Uses
- bool
- Z
- bool_decide
Definition is_any_surr (c : Z) : bool :=
Definition is_any_surr (c : Z) : bool :=
is_high_surr c || is_low_surr c.Fixpoint lone_surr_from (xs : list Z) (idx : nat) : option nat :=
Fixpoint lone_surr_from (xs : list Z) (idx : nat) : option nat :=
match xs with
| [] => None
| c :: rest =>
if is_high_surr c then
match rest with
| d :: rest' => if is_low_surr d then lone_surr_from rest' (idx + 2) else Some idx
| [] => Some idx
end
else if is_low_surr c then Some idx
else lone_surr_from rest (S idx)
end.References
Fixpoint prescan_plain_loop (in_str : bool) (pending : nat) (xs : list Z) : option (bool * nat) :=
Fixpoint prescan_plain_loop (in_str : bool) (pending : nat) (xs : list Z) : option (bool * nat) :=
match xs with
| [] => Some (in_str, pending)
| c :: rest =>
if in_str then
if Z.eqb c 92%Z then None
else if Z.eqb c 34%Z then
if Nat.eqb pending 0 then prescan_plain_loop false 0 rest else None
else
if negb (Nat.eqb pending 0) then
if is_low_surr c then prescan_plain_loop true 0 rest else None
else if is_high_surr c then prescan_plain_loop true 1 rest
else if is_low_surr c then None
else prescan_plain_loop true 0 rest
else None
end.References
Skipping any surrogate-free prefix in loneSurrogate, validating single char scalars in-place, and skipping plain BMP runs inside Prescan.check strings preserve exact scanner results.
Proves the UTF-16 scalar validation and JSON string pre-scan optimizations (Helpers.fs, Prescan.fs):
- For any surrogate-free prefix
pref(Forall (fun c => is_any_surr c = false) pref) and any suffixsuf,lone_surr_from (pref ++ suf) idx = lone_surr_from suf (idx + length pref)(andNonewhensuf = []). - For a single UTF-16 code unit
c(encodeChar),lone_surr_from [c] 0 = (if is_any_surr c then Some 0 else None). - Whenever
pending = 0inside a JSON string, skipping a contiguous runplainof unescaped non-quote characters below0xD800(55296%Z) leavesprescan_plain_loop true 0 (plain ++ suf) = prescan_plain_loop true 0 suf.
Arguments
IndexOfAnyInRange.encodeChar.c <> 92, c <> 34, c < 55296).Theorem wire_surrogate_prefix_skip_and_char_scalar_eq
Theorem wire_surrogate_prefix_skip_and_char_scalar_eq
(pref suf plain : list Z) (idx : nat) (c : Z) :
(Forall (fun u => is_any_surr u = false) pref ->
lone_surr_from (pref ++ suf) idx = lone_surr_from suf (idx + length pref)) /\
(Forall (fun u => is_any_surr u = false) pref ->
lone_surr_from pref idx = None) /\
lone_surr_from [c] 0 = (if is_any_surr c then Some 0 else None) /\
(Forall (fun u => u <> 92%Z /\ u <> 34%Z /\ (u < 55296)%Z) plain ->
prescan_plain_loop true 0 (plain ++ suf) = prescan_plain_loop true 0 suf).
Arguments
IndexOfAnyInRange.encodeChar.c <> 92, c <> 34, c < 55296).Qed
Proof.
split_and!.
- revert idx. induction pref as [|u rest IH]; intros i Hall; simpl.
+ rewrite Nat.add_0_r. reflexivity.
+ inversion Hall as [|? ? Hu Hrest]; subst.
unfold is_any_surr in Hu. apply orb_false_iff in Hu as [Hh Hl].
rewrite Hh, Hl. rewrite (IH (S i) Hrest). rewrite Nat.add_succ_r. reflexivity.
- revert idx. induction pref as [|u rest IH]; intros i Hall; simpl; [reflexivity|].
inversion Hall as [|? ? Hu Hrest]; subst.
unfold is_any_surr in Hu. apply orb_false_iff in Hu as [Hh Hl].
rewrite Hh, Hl. exact (IH (S i) Hrest).
- unfold is_any_surr. simpl. destruct (is_high_surr c), (is_low_surr c); reflexivity.
- induction plain as [|u rest IH]; intros Hall; simpl; [reflexivity|].
inversion Hall as [|? ? [Hbs [Hq Hbmp]] Hrest]; subst.
rewrite (proj2 (Z.eqb_neq u 92%Z) Hbs).
rewrite (proj2 (Z.eqb_neq u 34%Z) Hq).
assert (Hh : is_high_surr u = false)
by (unfold is_high_surr; apply bool_decide_eq_false_2; lia).
assert (Hl : is_low_surr u = false)
by (unfold is_low_surr; apply bool_decide_eq_false_2; lia).
rewrite Hh, Hl. simpl. exact (IH Hrest).
Qed.References
Uses
13 more
- false
- length
- list
- nat
- true
- proj2
- Forall
- Z
- Nat.add_0_r
- Nat.add_succ_r
- orb_false_iff
- Z.eqb_neq
- bool_decide_eq_false_2
Used by
Fixpoint strip_leading_zeros (xs : list Z) : list Z :=
Fixpoint strip_leading_zeros (xs : list Z) : list Z :=
match xs with
| [] => []
| c :: rest => if Z.eqb c 48%Z then strip_leading_zeros rest else c :: rest
end.Definition mantissa_digits (xs : list Z) : list Z :=
Definition mantissa_digits (xs : list Z) : list Z :=
strip_leading_zeros (List.filter (fun c => negb (Z.eqb c 46%Z)) xs).References
Uses
- strip_leading_zeros
- list
- negb
- Z
- filter
- Z.eqb
Definition z_cmp (x y : Z) : Z :=
Definition z_cmp (x y : Z) : Z :=
match Z.compare x y with
| Lt => (-1)%Z
| Eq => 0%Z
| Gt => 1%Z
end.References
Uses
- Eq
- Gt
- Lt
- Z
- Z.compare
Fixpoint list_lex_cmp (a b : list Z) : Z :=
Fixpoint list_lex_cmp (a b : list Z) : Z :=
match a, b with
| x :: xs, y :: ys =>
let c := z_cmp x y in
if Z.eqb c 0%Z then list_lex_cmp xs ys else c
| [], _ :: _ => (-1)%Z
| _ :: _, [] => 1%Z
| [], [] => 0%Z
end.References
Uses
- z_cmp
- list
- Z
- Z.eqb
Definition step_mantissa_scan (max_digits : list Z) (st : nat * Z) (c : Z) : nat * Z :=
Definition step_mantissa_scan (max_digits : list Z) (st : nat * Z) (c : Z) : nat * Z :=
let '(sig_len, cmp) := st in
if Z.eqb c 46%Z || (Nat.eqb sig_len 0 && Z.eqb c 48%Z) then st
else
let cmp' :=
if (sig_len <? length max_digits) && Z.eqb cmp 0%Z
then z_cmp c (nth sig_len max_digits 0%Z)
else cmp in
(S sig_len, cmp').References
Definition scan_mantissa (max_digits xs : list Z) : nat * Z :=
Definition scan_mantissa (max_digits xs : list Z) : nat * Z :=
foldl (step_mantissa_scan max_digits) (0, 0%Z) xs.References
Uses
- step_mantissa_scan
- list
- nat
- Z
- list.foldl
Definition ref_fits_mantissa (max_digits ds : list Z) : bool :=
Definition ref_fits_mantissa (max_digits ds : list Z) : bool :=
(length ds <? length max_digits) ||
((length ds =? length max_digits) && (list_lex_cmp ds max_digits <=? 0)%Z).References
Uses
- list_lex_cmp
- bool
- length
- list
- Z
Definition scan_fits_mantissa (max_digits xs : list Z) : bool :=
Definition scan_fits_mantissa (max_digits xs : list Z) : bool :=
let '(sig_len, cmp) := scan_mantissa max_digits xs in
(sig_len <? length max_digits) || ((sig_len =? length max_digits) && (cmp <=? 0)%Z).References
Uses
- scan_mantissa
- bool
- length
- list
- Z
inPropertyOrder without array-index keys is the identity, Dictionary.Count increase characterizes first-time member insertion, and fitsDecimal in-place mantissa scanning matches string-allocating normalization and ordinal comparison.
Proves the Helpers.fs and Codecs.fs zero-allocation algorithms:
- Whenever
is_idxisfalseon all elements ofxs,filter is_idx xs ++ filter (negb ∘ is_idx) xs = xs. - For any finite dictionary
m : gmap nat Z, inserting(k, v)strictly increasessizeiffm !! k = None. - On any digit/dot list
xs,scan_mantissa max_digits xscomputes(length (mantissa_digits xs), cmp)such thatscan_fits_mantissa max_digits xs = ref_fits_mantissa max_digits (mantissa_digits xs)with zero intermediate list or string allocations.
Arguments
Dictionary<string, JsonElement>).Decimal.MaxValue).Theorem wire_property_order_member_dedup_and_decimal_scan_eq
Theorem wire_property_order_member_dedup_and_decimal_scan_eq
(is_idx : Z -> bool) (xs max_digits : list Z) (m : gmap nat Z) (k : nat) (v : Z) :
(Forall (fun x => is_idx x = false) xs ->
List.filter is_idx xs ++ List.filter (fun x => negb (is_idx x)) xs = xs) /\
bool_decide (size m < size (<[k := v]> m)) = bool_decide (m !! k = None) /\
(scan_mantissa max_digits xs).1 = length (mantissa_digits xs) /\
scan_fits_mantissa max_digits xs = ref_fits_mantissa max_digits (mantissa_digits xs).
Arguments
Dictionary<string, JsonElement>).Decimal.MaxValue).Qed
Proof.
assert (Hfilt_empty : forall ys, Forall (fun x => is_idx x = false) ys -> List.filter is_idx ys = []).
{ induction ys as [|x rest IH]; intros Hall; simpl; [reflexivity|].
inversion Hall as [|? ? Hx Hrest]; subst. rewrite Hx. exact (IH Hrest). }
assert (Hfilt_all : forall ys, Forall (fun x => is_idx x = false) ys -> List.filter (fun x => negb (is_idx x)) ys = ys).
{ induction ys as [|x rest IH]; intros Hall; simpl; [reflexivity|].
inversion Hall as [|? ? Hx Hrest]; subst. rewrite Hx. simpl. rewrite (IH Hrest). reflexivity. }
assert (Hfilter : Forall (fun x => is_idx x = false) xs ->
List.filter is_idx xs ++ List.filter (fun x => negb (is_idx x)) xs = xs).
{ intros Hall. rewrite (Hfilt_empty xs Hall), (Hfilt_all xs Hall). reflexivity. }
assert (Hsize : bool_decide (size m < size (<[k := v]> m)) = bool_decide (m !! k = None)).
{ destruct (m !! k) as [z|] eqn:Hk.
- rewrite map_size_insert_Some; [|exists z; exact Hk].
rewrite bool_decide_eq_false_2; [reflexivity | lia].
- rewrite map_size_insert_None by exact Hk.
rewrite bool_decide_eq_true_2; [reflexivity | lia]. }
assert (Hdots : forall max_d ys st,
foldl (step_mantissa_scan max_d) st ys =
foldl (step_mantissa_scan max_d) st (List.filter (fun c => negb (Z.eqb c 46%Z)) ys)).
{ intros max_d ys. induction ys as [|y rest IH]; intros [sl cmp]; [reflexivity|].
destruct (Z.eqb y 46%Z) eqn:Ed; cbn [foldl List.filter].
- replace (step_mantissa_scan max_d (sl, cmp) y) with (sl, cmp)
by (unfold step_mantissa_scan; rewrite Ed; reflexivity).
rewrite Ed. simpl. apply IH.
- rewrite Ed. simpl. apply IH. }
assert (Hzeros : forall max_d ys cmp,
Forall (fun c => c <> 46%Z) ys ->
foldl (step_mantissa_scan max_d) (0, cmp) ys =
foldl (step_mantissa_scan max_d) (0, cmp) (strip_leading_zeros ys)).
{ intros max_d ys cmp Hall. induction ys as [|y rest IH]; simpl; [reflexivity|].
inversion Hall as [|? ? Hne46 Hrest]; subst.
destruct (Z.eqb y 48%Z) eqn:Ez; simpl; [|rewrite ?Ez; reflexivity].
rewrite (proj2 (Z.eqb_neq y 46%Z) Hne46), ?Ez. simpl.
exact (IH Hrest). }
assert (Hfilt_no46 : forall ys, Forall (fun c => c <> 46%Z) (List.filter (fun c => negb (Z.eqb c 46%Z)) ys)).
{ induction ys as [|y rest IH]; simpl; [constructor|].
destruct (Z.eqb y 46%Z) eqn:Ed; simpl; [exact IH|].
constructor; [exact (proj1 (Z.eqb_neq y 46%Z) Ed) | exact IH]. }
assert (Hstrip_prop : forall ys,
Forall (fun c => c <> 46%Z) ys ->
Forall (fun c => c <> 46%Z) (strip_leading_zeros ys) /\
match strip_leading_zeros ys with [] => True | d0 :: _ => d0 <> 48%Z end).
{ induction ys as [|y rest IH]; intros Hall; simpl; [split; [constructor | trivial]|].
inversion Hall as [|? ? Hy Hrest]; subst.
destruct (Z.eqb y 48%Z) eqn:Ez; [exact (IH Hrest)|].
split; [constructor; assumption | exact (proj1 (Z.eqb_neq y 48%Z) Ez)]. }
assert (Hlen_ds : forall max_d ds sl cmp,
Forall (fun c => c <> 46%Z) ds ->
(0 < sl \/ match ds with [] => True | d0 :: _ => d0 <> 48%Z end) ->
(foldl (step_mantissa_scan max_d) (sl, cmp) ds).1 = sl + length ds).
{ intros max_d ds. induction ds as [|d rest IH]; intros sl cmp Hall Hguard; cbn [foldl length]; [simpl; lia|].
inversion Hall as [|? ? Hd Hrest]; subst.
assert (Hsl0 : (Nat.eqb sl 0 && Z.eqb d 48%Z) = false).
{ destruct Hguard as [Hpos | Hnz].
- destruct sl; [lia | reflexivity].
- rewrite (proj2 (Z.eqb_neq d 48%Z) Hnz). rewrite andb_false_r. reflexivity. }
replace (step_mantissa_scan max_d (sl, cmp) d)
with (S sl, if (sl <? length max_d) && Z.eqb cmp 0%Z then z_cmp d (nth sl max_d 0%Z) else cmp)
by (unfold step_mantissa_scan; rewrite (proj2 (Z.eqb_neq d 46%Z) Hd), Hsl0; reflexivity).
rewrite (IH (S sl) _ Hrest (or_introl (Nat.lt_0_succ sl))). lia. }
assert (Hcmp_ds : forall ds pref max_rem cmp,
Forall (fun c => c <> 46%Z) ds ->
(0 < length pref \/ match ds with [] => True | d0 :: _ => d0 <> 48%Z end) ->
length ds = length max_rem ->
(foldl (step_mantissa_scan (pref ++ max_rem)) (length pref, cmp) ds).2 =
(if Z.eqb cmp 0%Z then list_lex_cmp ds max_rem else cmp)).
{ induction ds as [|d rest IH]; intros pref max_rem cmp Hall Hguard Heqlen; cbn [foldl length list_lex_cmp] in *.
- destruct max_rem; [|discriminate Heqlen].
simpl. destruct (Z.eqb cmp 0%Z) eqn:E; [apply Z.eqb_eq in E; exact E | reflexivity].
- destruct max_rem as [|mx max_rem']; [discriminate Heqlen|].
injection Heqlen as Hrestlen.
inversion Hall as [|? ? Hd Hrest]; subst.
assert (Hsl0 : (Nat.eqb (length pref) 0 && Z.eqb d 48%Z) = false).
{ destruct Hguard as [Hpos | Hnz].
- destruct (length pref); [lia | reflexivity].
- rewrite (proj2 (Z.eqb_neq d 48%Z) Hnz). rewrite andb_false_r. reflexivity. }
assert (Hlt : (length pref <? length (pref ++ mx :: max_rem')) = true).
{ apply Nat.ltb_lt. rewrite length_app. simpl. lia. }
assert (Hnth : nth (length pref) (pref ++ mx :: max_rem') 0%Z = mx).
{ rewrite app_nth2 by lia. rewrite Nat.sub_diag. reflexivity. }
replace (step_mantissa_scan (pref ++ mx :: max_rem') (length pref, cmp) d)
with (S (length pref), if Z.eqb cmp 0%Z then z_cmp d mx else cmp)
by (unfold step_mantissa_scan; rewrite (proj2 (Z.eqb_neq d 46%Z) Hd), Hsl0, Hlt, Hnth; simpl; reflexivity).
assert (Happ : pref ++ mx :: max_rem' = (pref ++ [mx]) ++ max_rem')
by (change (mx :: max_rem') with ([mx] ++ max_rem'); apply app_assoc).
rewrite Happ.
assert (Hnext_len : S (length pref) = length (pref ++ [mx]))
by (rewrite length_app; simpl; lia).
rewrite Hnext_len.
assert (Hpref'_pos : 0 < length (pref ++ [mx])) by (rewrite length_app; simpl; lia).
specialize (IH (pref ++ [mx]) max_rem'
(if Z.eqb cmp 0%Z then z_cmp d mx else cmp)
Hrest (or_introl Hpref'_pos) Hrestlen).
rewrite IH.
destruct (Z.eqb cmp 0%Z) eqn:Ecmp; simpl.
+ destruct (Z.eqb (z_cmp d mx) 0%Z); reflexivity.
+ rewrite ?Ecmp. reflexivity. }
assert (Hm_props := Hstrip_prop _ (Hfilt_no46 xs)).
destruct Hm_props as [Hm_no46 Hm_nz].
split_and!.
- exact Hfilter.
- exact Hsize.
- unfold scan_mantissa, mantissa_digits.
rewrite Hdots, Hzeros by apply Hfilt_no46.
exact (Hlen_ds max_digits _ 0 0%Z Hm_no46 (or_intror Hm_nz)).
- unfold scan_fits_mantissa, ref_fits_mantissa, scan_mantissa.
assert (Hlen_m : (foldl (step_mantissa_scan max_digits) (0, 0%Z) xs).1 = length (mantissa_digits xs)).
{ unfold mantissa_digits. rewrite Hdots, Hzeros by apply Hfilt_no46.
exact (Hlen_ds max_digits _ 0 0%Z Hm_no46 (or_intror Hm_nz)). }
destruct (foldl (step_mantissa_scan max_digits) (0, 0%Z) xs) as [sl cmp] eqn:Efold.
simpl in Hlen_m. rewrite Hlen_m.
destruct (length (mantissa_digits xs) <? length max_digits) eqn:Elt; simpl; [reflexivity|].
destruct (length (mantissa_digits xs) =? length max_digits) eqn:Eeq; simpl; [|reflexivity].
apply Nat.eqb_eq in Eeq.
assert (Hcmp_m : cmp = list_lex_cmp (mantissa_digits xs) max_digits).
{ replace cmp with (foldl (step_mantissa_scan max_digits) (0, 0%Z) xs).2 by (rewrite Efold; reflexivity).
unfold mantissa_digits in *.
rewrite Hdots, Hzeros by apply Hfilt_no46.
exact (Hcmp_ds _ [] max_digits 0%Z Hm_no46 (or_intror Hm_nz) Eeq). }
rewrite Hcmp_m. reflexivity.
Qed.References
Uses
- strip_leading_zeros
- mantissa_digits
- z_cmp
- list_lex_cmp
- step_mantissa_scan
- scan_mantissa
- ref_fits_mantissa
- scan_fits_mantissa
37 more
- None
- S
- bool
- false
- length
- list
- nat
- negb
- true
- or_introl
- or_intror
- proj1
- proj2
- Forall
- nth
- Z
- Nat.eqb
- Nat.eqb_eq
- Nat.lt_0_succ
- Nat.ltb_lt
- Nat.sub_diag
- andb_false_r
- app_assoc
- app_nth2
- filter
- length_app
- Z.eqb
- Z.eqb_eq
- Z.eqb_neq
- size
- bool_decide
- bool_decide_eq_false_2
- bool_decide_eq_true_2
- map_size_insert_None
- map_size_insert_Some
- gmap
- list.foldl
Used by
Definition wire_stop_lane (c : Z) :=
Definition wire_stop_lane (c : Z) :=
Z.eqb c 34 || Z.eqb c 92 || Z.leb 55296 c.Fixpoint wire_scalar_stop (xs : list Z) :=
Fixpoint wire_scalar_stop (xs : list Z) :=
match xs with
| [] => 0
| c :: rest => if wire_stop_lane c then 0 else S (wire_scalar_stop rest)
end.Fixpoint trailing_clear (bits : list bool) :=
Fixpoint trailing_clear (bits : list bool) :=
match bits with
| [] => 0
| true :: _ => 0
| false :: rest => S (trailing_clear rest)
end.Definition wire_block_stop (block : list Z) next :=
Definition wire_block_stop (block : list Z) next :=
let mask := map wire_stop_lane block in
if existsb id mask then trailing_clear mask else length block + next.References
Uses
- wire_stop_lane
- trailing_clear
- id
- length
- list
- map
- Z
- existsb
Lemma wire_block_stop_app block rest :
Lemma wire_block_stop_app block rest :
wire_block_stop block (wire_scalar_stop rest) = wire_scalar_stop (block ++ rest).
Qed
Proof.
unfold wire_block_stop. induction block as [|c cs IH]; simpl; [reflexivity|].
destruct (wire_stop_lane c); simpl; [reflexivity|].
destruct (existsb id (map wire_stop_lane cs)); simpl in *; by rewrite IH.
Qed.Scanning successive vector masks and a scalar tail returns the first special UTF-16 lane. The block identity holds for any partition, including 32-, 16- and 8-lane blocks and skipped hardware tiers.
Theorem wire_vector_stop_eq (blocks : list (list Z)) tail :
Theorem wire_vector_stop_eq (blocks : list (list Z)) tail :
fold_right wire_block_stop (wire_scalar_stop tail) blocks =
wire_scalar_stop (concat blocks ++ tail).
Qed
Proof.
induction blocks as [|b bs IH]; simpl; [reflexivity|].
rewrite IH, wire_block_stop_app, app_assoc. reflexivity.
Qed.References
Uses
- wire_scalar_stop
- wire_block_stop
- wire_block_stop_app
- list
- Z
- app_assoc
- concat
- fold_right
Used by
A unit selector preserves the result and tracked reads across model updates. The selector returns both its value and the sources it read for that model.
Theorem mvu_select_unit_history {A : Type} (select : Z -> A * list node_id)
Theorem mvu_select_unit_history {A : Type} (select : Z -> A * list node_id)
(states : list mvu_state) (previous : option A) :
fold_right (fun st tail => (fun _ : option A => select (mvu_model st)) previous :: tail) [] states =
map (fun st => (fun _ : unit => select (mvu_model st)) tt) states.
Qed
Proof. induction states; simpl; congruence. Qed.