Ranvier.Pure.Deltas

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

Collection delta coalescing and ProjectionReader contracts1. KeyChange and KeyChanges.Record coalescing algebrakey_changekey_change_eq_deckc_merge_optkc_recordkey_changes_added_removed_cancelskey_changes_removed_added_replaceskey_changes_membership_precedes_changed2. Dense swap-remove optimization refinementswap_remove_atkey_changes_swap_remove_refines_delete3. ProjectionReader bounded cap, reset recovery, and cursor advancementproj_reader_stateproj_delta_statepr_recordpr_readprojection_reader_cap_resetsprojection_reader_read_advances_cursor4. Delta-driven ProjectionFold membership sync and non-invertible reorder completenessfold_detach_onefold_attach_onefold_apply_deltafold_sync_membershipfold_detach_lookupfold_attach_lookupfold_delta_sync_refines_difffold_pure_reorder_invariants5. CollectionProjection tail-append/remove order preservation on cancelled batchescol_opcol_stepcol_invfilter_ne_not_elemelem_of_filter_ne_iffcol_step_preserves_invappend_remove_empty_changes_preserves_order6. Positional.diff prefix/suffix framing and contiguous fast pathspos_editoffset_pos_editremove_atinsert_atapply_pos_editapply_pos_editsremove_at_frameinsert_at_frameapply_pos_edit_framepositional_frame_prefix_suffixapply_pure_inserts_accfmap_imapoffset_imap_insertpositional_pure_inserts_correctapply_pure_removes_midpositional_pure_removes_correctpositional_nodup_trimmed_disjointapply_single_move_right_midpositional_single_move_right_correctremove_at_endapply_single_move_left_midpositional_single_move_left_correctapply_pos_edit_of_singleapply_distant_swap_midpositional_distant_swap_correct7. AsObservableCollection O(Delta) value patchingoc_patch_stepoc_patch_step_lengthoc_patch_step_preservesoc_patch_step_updatesoc_patch_fold_invobservable_collection_delta_value_patch_refines_scansmall_slotsmall_slot_refines_changessmall_slot_promotionsmall_slot_swap_removesurvivor_rankscompact_cellscompact_survivor_prefix
This definition

Ranvier.Pure.Deltas

Collection delta coalescing and ProjectionReader contracts

Deltas.fs implements KeyChange, KeyChanges<'K>, ProjectionDelta<'K>, ProjectionReader<'K>, and KeyLog<'K> for incremental membership, order, and settled-value observation over projections and editable keyed collections. To keep the underlying dense-array and hash-table representation open to optimization while guaranteeing the documented consumer contracts, this module proves the exact minimum specifications required by delta readers:

  1. KeyChanges.Record coalescing algebra (Deltas.fs lines 7–69):
  2. Dense swap-remove optimization refinement (Deltas.fs lines 47–55):
    • key_changes_swap_remove_refines_delete: the dense ResizeArray swap-remove implementation of Added-then-Removed cancellation preserves key uniqueness (NoDup) and refines map deletion (list_to_map), justifying why ProjectionDelta.Changes enumerates in an unspecified order.
  3. ProjectionReader bounded cap, reset recovery, and cursor advancement (Deltas.fs lines 160–236):
  4. Delta-driven ProjectionFold membership sync and non-invertible reorder completeness (Combinators.fs lines 1004–1085):
    • fold_delta_sync_refines_diff: applying two-phase KcRemoved/KcReplaced detach and KcAdded/KcReplaced attach over any NoDup enumeration of pd_changes yields the exact upstream cur_entries map in $O(\Delta)$, matching the $O(N)$ Diff fallback used when pd_is_reset = true.
    • fold_pure_reorder_invariants: on a pure upstream reorder (pd_is_reset = false, pairs = [], pd_order_changed = true), foldGroup (invertible = true) performs zero row-map or fold updates, whereas fold (invertible = false) marks full = true so Recompute re-folds in the new key order.
  5. CollectionProjection tail-append/remove order preservation on cancelled batches (Collections.fs lines 38–60):
    • append_remove_empty_changes_preserves_order: after any sequence of tail-append ColAdd and arbitrary-position ColRemove operations on a NoDup key list init, if the coalesced KeyChanges map is ∅, then the resulting key list is identically equal to init — certifying the zero-allocation changes.Size = 0 fast path in CollectionProjection.ReadDelta.
  6. Positional.diff shared prefix/suffix framing and contiguous fast paths (Positional.fs):
    • positional_frame_prefix_suffix: any valid middle-slice positional edit sequence es that rewrites M into M' rewrites P ++ M ++ S into P ++ M' ++ S when each edit index is shifted by length P.
    • positional_pure_inserts_correct & positional_pure_removes_correct: emitting InsertAt forward over a trimmed insertion block and RemoveAt back-to-front over a trimmed removal block rewrite P ++ S -> P ++ Ins ++ S and P ++ Rem ++ S -> P ++ S directly with zero intermediate allocation.
    • positional_nodup_trimmed_disjoint: under the NoDup distinct-key precondition on P ++ M1 ++ S and P ++ M2 ++ S, the trimmed middle slices M1 and M2 are disjoint from P and S, so survivors cannot cross out of the middle slice.
4
From stdpp Require Import prelude gmap.
From Stdlib Require Import ZArith.
From Ranvier.Base Require Import Prelude Syntax.
Open Scope nat_scope.

1. KeyChange and KeyChanges.Record coalescing algebra

Inductive key_change :=
  | KcAdded
  | KcRemoved
  | KcReplaced
  | KcChanged.
References
Global Instance key_change_eq_dec : EqDecision key_change.
Defined
Proof. solve_decision. Defined.
References

Uses

Pure transition for a single key's pending entry in KeyChanges.Record (Deltas.fs lines 37–69): returns None when KcAdded followed by KcRemoved cancels out, and Some next otherwise.

Definition kc_merge_opt (prev : option key_change) (c : key_change) : option key_change :=
  match prev with
  | None => Some c
  | Some p =>
      if decide (c = KcRemoved /\ p = KcAdded) then None
      else if decide (c = KcAdded /\ p = KcRemoved) then Some KcReplaced
      else if decide (c = KcChanged) then
        if decide (p = KcChanged) then Some KcChanged else Some p
      else Some c
  end.
References

Uses

1 more
  • decide

Map-level KeyChanges.Record over kc : gmap nat key_change.

Definition kc_record (k : nat) (c : key_change) (kc : gmap nat key_change) : gmap nat key_change :=
  match kc_merge_opt (kc !! k) c with
  | None => delete k kc
  | Some next => <[k := next]> kc
  end.
References

Uses

✓ No axioms

Recording KcAdded on an absent key k followed by KcRemoved on k cancels out and restores kc (Deltas.fs lines 43–55).

Arguments

k : nat
the key added and then removed between two reads.
kc : gmap nat key_change
the pending changes map with kc !! k = None.
Theorem key_changes_added_removed_cancels (k : nat) (kc : gmap nat key_change) :
  kc !! k = None ->
  kc_record k KcRemoved (kc_record k KcAdded kc) = kc /\
  kc_record k KcRemoved (kc_record k KcAdded kc) !! k = None.

Arguments

k : nat
the key added and then removed between two reads.
kc : gmap nat key_change
the pending changes map with kc !! k = None.
Qed
Proof.
  intros Habs.
  unfold kc_record.
  rewrite Habs. simpl.
  rewrite lookup_insert_eq. simpl.
  rewrite delete_insert_id; [|exact Habs].
  split; [reflexivity | exact Habs].
Qed.
References

Uses

1 more
  • gmap
✓ No axioms

Recording KcRemoved followed by KcAdded on the same key coalesces to Some KcReplaced (Deltas.fs lines 57–60).

Arguments

k : nat
the key removed and re-added between two reads.
kc : gmap nat key_change
the pending changes map ( provided kc !! k <> Some KcAdded, as a live key before removal is either absent from kc or not freshly KcAdded).
Theorem key_changes_removed_added_replaces (k : nat) (kc : gmap nat key_change) :
  kc !! k <> Some KcAdded ->
  kc_record k KcAdded (kc_record k KcRemoved kc) !! k = Some KcReplaced /\
  (forall k', k' <> k -> kc_record k KcAdded (kc_record k KcRemoved kc) !! k' = kc !! k').

Arguments

k : nat
the key removed and re-added between two reads.
kc : gmap nat key_change
the pending changes map ( provided kc !! k <> Some KcAdded, as a live key before removal is either absent from kc or not freshly KcAdded).
Qed
Proof.
  intros Hnot_add.
  unfold kc_record.
  assert (Hstep1 : kc_merge_opt (kc !! k) KcRemoved = Some KcRemoved).
  { destruct (kc !! k) as [p|]; simpl; [|done].
    rewrite decide_False; [|intros [_ Hp]; exact (Hnot_add (f_equal Some Hp))].
    simpl. reflexivity. }
  rewrite Hstep1.
  rewrite lookup_insert_eq. simpl.
  rewrite insert_insert_eq.
  split.
  - by rewrite lookup_insert_eq.
  - intros k' Hne. by rewrite lookup_insert_ne.
Qed.
References

Uses

6 more
  • f_equal
  • decide_False
  • insert_insert_eq
  • lookup_insert_eq
  • lookup_insert_ne
  • gmap
✓ No axioms

Membership changes (KcAdded, KcRemoved, KcReplaced) take precedence over KcChanged, while KcChanged on an absent or KcChanged key records Some KcChanged (Deltas.fs lines 61–63).

Arguments

k : nat
the key whose row value settled to a new value.
kc : gmap nat key_change
the pending changes map.
Theorem key_changes_membership_precedes_changed (k : nat) (kc : gmap nat key_change) :
  (kc !! k = None -> kc_record k KcChanged kc !! k = Some KcChanged) /\
  (forall p,
     p = KcAdded \/ p = KcRemoved \/ p = KcReplaced ->
     kc !! k = Some p ->
     kc_record k KcChanged kc = kc) /\
  (kc !! k = Some KcChanged ->
   kc_record k KcChanged kc = kc).

Arguments

k : nat
the key whose row value settled to a new value.
kc : gmap nat key_change
the pending changes map.
Qed
Proof.
  split_and!.
  - intros Habs. unfold kc_record. rewrite Habs. simpl. by rewrite lookup_insert_eq.
  - intros p Hp Hk. unfold kc_record. rewrite Hk. simpl.
    destruct Hp as [->|[->| ->]]; simpl; apply insert_id, Hk.
  - intros Hk. unfold kc_record. rewrite Hk. simpl.
    apply insert_id, Hk.
Qed.
References

Uses

4 more
  • nat
  • insert_id
  • lookup_insert_eq
  • gmap

2. Dense swap-remove optimization refinement

Models the dense pairs array swap-remove in KeyChanges.Record (Deltas.fs lines 47–55): when k is at index idx of pairs ++ [last_pair], moving last_pair into idx and dropping the last element produces <[idx := last_pair]> pairs.

Definition swap_remove_at {A : Type} (idx : nat) (prefix : list A) (last_elem : A) : list A :=
  <[idx := last_elem]> prefix.
References

Uses

  • list
  • nat
✓ No axioms

Replacing index idx of prefix (where prefix !! idx = Some (k, c)) with last_pair and dropping the tail element refines delete k (list_to_map (prefix ++ [last_pair])) and preserves NoDup.

Certifies the Deltas.fs lines 47–55 optimization: KeyChanges<'K> avoids O(N) shifting on Added-then-Removed cancellation by overwriting slot idx with the final entry last_pair and truncating the ResizeArray, which permutes enumeration order while preserving the exact gmap of changes.

Arguments

k : nat
the cancelled key at idx.
the previous change at idx.
last_pair : nat * key_change
the final (k_last, c_last) pair in pairs before truncation.
prefix : list (nat * key_change)
the prefix of pairs before last_pair.
idx : nat
the index of (k, c) in prefix.
Theorem key_changes_swap_remove_refines_delete
    (k : nat) (c : key_change) (last_pair : nat * key_change)
    (prefix : list (nat * key_change)) (idx : nat) :
  NoDup (fst <$> (prefix ++ [last_pair])) ->
  prefix !! idx = Some (k, c) ->
  NoDup (fst <$> swap_remove_at idx prefix last_pair) /\
  (list_to_map (swap_remove_at idx prefix last_pair) : gmap nat key_change) =
    delete k (list_to_map (prefix ++ [last_pair])).

Arguments

k : nat
the cancelled key at idx.
the previous change at idx.
last_pair : nat * key_change
the final (k_last, c_last) pair in pairs before truncation.
prefix : list (nat * key_change)
the prefix of pairs before last_pair.
idx : nat
the index of (k, c) in prefix.
Qed
Proof.
  intros Hnd Hidx.
  unfold swap_remove_at.
  pose proof (lookup_lt_Some _ _ _ Hidx) as Hlt.
  apply take_drop_middle in Hidx.
  set (before := take idx prefix) in *.
  set (after := drop (S idx) prefix) in *.
  assert (Hlen : length before = idx).
  { subst before. apply length_take_le. lia. }
  rewrite <- Hidx in Hnd |- *.
  rewrite <- app_assoc in Hnd |- *.
  rewrite <- app_comm_cons in Hnd |- *.
  rewrite insert_app_r_alt; [|lia].
  rewrite Hlen, Nat.sub_diag. simpl.
  rewrite !fmap_app, !fmap_cons, !fmap_app, !fmap_cons in Hnd.
  rewrite fmap_app, fmap_cons.
  simpl in Hnd |- *.
  apply NoDup_app in Hnd as (Hnd_b & Hdisj_b & Hnd_rest).
  inversion Hnd_rest as [|x l Hk_nin Hnd_after]; subst x l.
  apply NoDup_app in Hnd_after as (Hnd_a & Hdisj_a & _).
  split.
  - apply NoDup_app. split_and!; [exact Hnd_b| |].
    + intros x Hxb Hxrest.
      apply elem_of_cons in Hxrest as [->|Hxa].
      * apply (Hdisj_b last_pair.1 Hxb).
        apply elem_of_cons. right. apply elem_of_app. right. by left.
      * apply (Hdisj_b x Hxb).
        apply elem_of_cons. right. apply elem_of_app. by left.
    + constructor.
      * intros Hlast_a. apply (Hdisj_a last_pair.1 Hlast_a). by left.
      * exact Hnd_a.
  - apply map_eq. intros q.
    destruct (decide (q = k)) as [->|Hqk].
    + rewrite lookup_delete_eq.
      apply not_elem_of_list_to_map_1.
      rewrite fmap_app, fmap_cons. simpl.
      intros Hk_in.
      apply elem_of_app in Hk_in as [Hkb|Hkrest].
      * apply (Hdisj_b k Hkb). by left.
      * apply elem_of_cons in Hkrest as [Hklast|Hka]; apply Hk_nin; apply elem_of_app.
        -- right. rewrite <- Hklast. by left.
        -- by left.
    + rewrite lookup_delete_ne; [|symmetry; exact Hqk].
      rewrite !list_to_map_app. simpl. rewrite list_to_map_app. simpl.
      destruct ((list_to_map before : gmap nat key_change) !! q) as [vq|] eqn:Eb.
      * rewrite !(lookup_union_Some_l _ _ _ _ Eb). reflexivity.
      * rewrite !lookup_union_r; [|exact Eb | exact Eb].
        simpl. rewrite (lookup_insert_ne _ k q c); [|symmetry; exact Hqk].
        destruct (decide (q = last_pair.1)) as [->|Hql].
        -- rewrite lookup_insert_eq.
           assert (Hla : (list_to_map after : gmap nat key_change) !! last_pair.1 = None).
           { apply not_elem_of_list_to_map_1. intros Hla.
             apply (Hdisj_a last_pair.1 Hla). by left. }
           rewrite lookup_union_r; [|exact Hla].
           rewrite lookup_insert_eq. reflexivity.
        -- rewrite lookup_insert_ne; [|symmetry; exact Hql].
           destruct ((list_to_map after : gmap nat key_change) !! q) as [va|] eqn:Ea.
           ++ rewrite (lookup_union_Some_l _ _ _ _ Ea). reflexivity.
           ++ rewrite lookup_union_r; [|exact Ea].
              rewrite lookup_insert_ne; [|symmetry; exact Hql].
              rewrite lookup_empty. reflexivity.
Qed.
References

Uses

30 more
  • nat
  • Nat.sub_diag
  • app_assoc
  • app_comm_cons
  • NoDup
  • decide
  • delete
  • list_to_map
  • list_to_map_app
  • lookup_delete_eq
  • lookup_delete_ne
  • lookup_empty
  • lookup_insert_eq
  • lookup_insert_ne
  • lookup_union_Some_l
  • lookup_union_r
  • map_eq
  • not_elem_of_list_to_map_1
  • gmap
  • list.drop
  • list.elem_of_app
  • list.elem_of_cons
  • list.insert_app_r_alt
  • list.length_take_le
  • list.lookup_lt_Some
  • list.take
  • list.take_drop_middle
  • list.fmap_app
  • list.fmap_cons
  • list.NoDup_app

3. ProjectionReader bounded cap, reset recovery, and cursor advancement

Record proj_reader_state := {
  pr_changes : gmap nat key_change;
  pr_cursor : list nat;
  pr_reset : bool;
}.
References

Uses

Record proj_delta_state := {
  pd_changes : gmap nat key_change;
  pd_keys : list nat;
  pd_prev_keys : list nat;
  pd_is_reset : bool;
  pd_order_changed : bool;
  pd_is_empty : bool;
}.
References

Uses

ProjectionReader.Record (Deltas.fs lines 187–194): records (k, c) while not reset, and resets changes to ∅ with reset := true if size changes > max 64 live_count.

Definition pr_record (live_count : nat) (k : nat) (c : key_change) (pr : proj_reader_state)
    : proj_reader_state :=
  if pr_reset pr then pr
  else
    let kc' := kc_record k c (pr_changes pr) in
    if decide ( Nat.max 64 live_count < size kc' ) then
      {| pr_changes := ∅; pr_cursor := pr_cursor pr; pr_reset := true |}
    else
      {| pr_changes := kc'; pr_cursor := pr_cursor pr; pr_reset := false |}.
References

ProjectionReader.Read (Deltas.fs lines 207–236): returns a ProjectionDelta and advances pr_cursor to current_keys, clearing pr_reset and pr_changes.

Definition pr_read (current_keys : list nat) (pr : proj_reader_state)
    : proj_delta_state * proj_reader_state :=
  let ord_changed := bool_decide (current_keys <> pr_cursor pr) in
  let next_pr := {| pr_changes := ∅; pr_cursor := current_keys; pr_reset := false |} in
  if pr_reset pr then
    ({| pd_changes := ∅;
        pd_keys := current_keys;
        pd_prev_keys := pr_cursor pr;
        pd_is_reset := true;
        pd_order_changed := ord_changed;
        pd_is_empty := false |},
     next_pr)
  else
    let emp := bool_decide (size (pr_changes pr) = 0) && negb ord_changed in
    ({| pd_changes := pr_changes pr;
        pd_keys := current_keys;
        pd_prev_keys := pr_cursor pr;
        pd_is_reset := false;
        pd_order_changed := ord_changed;
        pd_is_empty := emp |},
     next_pr).
References
✓ No axioms

pr_record keeps size (pr_changes pr) <= Nat.max 64 live_count, and when a new change exceeds that cap it clears pr_changes to ∅ and flags pr_reset = true so the next pr_read reports a reset.

Proves the bounded-memory contract of ProjectionReader (Deltas.fs lines 150–152, 187–194, 213–219).

Arguments

live_count : nat
the current live key count host.LiveCount.
k : nat
the key being recorded.
the change being recorded.
current_keys : list nat
the key array at the next read.
the reader state before pr_record.
Theorem projection_reader_cap_resets
    (live_count k : nat) (c : key_change) (current_keys : list nat) (pr : proj_reader_state) :
  size (pr_changes pr) <= Nat.max 64 live_count ->
  let pr' := pr_record live_count k c pr in
  size (pr_changes pr') <= Nat.max 64 live_count /\
  (pr_reset pr = false ->
   Nat.max 64 live_count < size (kc_record k c (pr_changes pr)) ->
   pr_reset pr' = true /\
   pr_changes pr' = ∅ /\
   pd_is_reset (fst (pr_read current_keys pr')) = true /\
   pd_changes (fst (pr_read current_keys pr')) = ∅).

Arguments

live_count : nat
the current live key count host.LiveCount.
k : nat
the key being recorded.
the change being recorded.
current_keys : list nat
the key array at the next read.
the reader state before pr_record.
Qed
Proof.
  intros Hle. simpl.
  unfold pr_record.
  destruct (pr_reset pr) eqn:Eres.
  - split; [exact Hle | intros Hfalse; congruence].
  - destruct (decide (Nat.max 64 live_count < size (kc_record k c (pr_changes pr)))) as [Hgt|Hng].
    + simpl. split.
      * rewrite map_size_empty. lia.
      * intros _ _. repeat split; reflexivity.
    + simpl. split; [lia|].
      intros _ Hgt. contradiction.
Qed.
References

Uses

10 more
  • pr_read
  • false
  • fst
  • list
  • nat
  • true
  • Nat.max
  • decide
  • size
  • map_size_empty
✓ No axioms

pr_read delivers (current_keys, pr_cursor pr), clears pr_reset and pr_changes, and advances pr_cursor to current_keys; an immediate second read with no intervening changes reports pd_is_empty = true.

Proves the cursor-advancement and idle-read contracts of ProjectionReader.Read (Deltas.fs lines 200–236).

Arguments

current_keys : list nat
the key array returned by host.ReadKeys().
the reader state before the first Read().
Theorem projection_reader_read_advances_cursor
    (current_keys : list nat) (pr : proj_reader_state) :
  let (d1, pr1) := pr_read current_keys pr in
  let (d2, pr2) := pr_read current_keys pr1 in
  pd_keys d1 = current_keys /\
  pd_prev_keys d1 = pr_cursor pr /\
  pr_cursor pr1 = current_keys /\
  pr_reset pr1 = false /\
  pr_changes pr1 = ∅ /\
  pd_is_reset d2 = false /\
  pd_changes d2 = ∅ /\
  pd_order_changed d2 = false /\
  pd_is_empty d2 = true /\
  pr2 = pr1.

Arguments

current_keys : list nat
the key array returned by host.ReadKeys().
the reader state before the first Read().
Qed
Proof.
  unfold pr_read.
  destruct (pr_reset pr); simpl;
    rewrite (bool_decide_eq_false_2 (current_keys ≠ current_keys) (fun H => H eq_refl));
    rewrite map_size_empty; simpl;
    repeat split; reflexivity.
Qed.
References

4. Delta-driven ProjectionFold membership sync and non-invertible reorder completeness

Definition fold_detach_one {E : Type} (m : gmap nat E) (kc : nat * key_change) : gmap nat E :=
  match kc.2 with
  | KcRemoved | KcReplaced => delete kc.1 m
  | KcAdded | KcChanged => m
  end.
References
Definition fold_attach_one {E : Type} (cur_entries : gmap nat E)
    (m : gmap nat E) (kc : nat * key_change) : gmap nat E :=
  match kc.2 with
  | KcAdded | KcReplaced =>
      match cur_entries !! kc.1 with
      | Some e => <[kc.1 := e]> m
      | None => m
      end
  | KcRemoved | KcChanged => m
  end.
References
Definition fold_apply_delta {E : Type} (cur_entries : gmap nat E)
    (pairs : list (nat * key_change)) (rows : gmap nat E) : gmap nat E :=
  let m1 := foldl fold_detach_one rows pairs in
  foldl (fold_attach_one cur_entries) m1 pairs.
References
Definition fold_sync_membership {E : Type}
    (invertible had_keys : bool) (cur_entries : gmap nat E)
    (pairs : list (nat * key_change)) (d : proj_delta_state)
    (rows : gmap nat E) (full : bool) : gmap nat E * bool :=
  let rows' :=
    if pd_is_reset d then cur_entries
    else if decide (length pairs = 0) then rows
    else fold_apply_delta cur_entries pairs rows in
  let full' :=
    if negb invertible && had_keys && pd_order_changed d then true else full in
  (rows', full').
References
Lemma fold_detach_lookup {E : Type}
    (pairs : list (nat * key_change)) (rows : gmap nat E) (q : nat) :
  NoDup (fst <$> pairs) ->
  foldl fold_detach_one rows pairs !! q =
    match (list_to_map pairs : gmap nat key_change) !! q with
    | Some KcRemoved | Some KcReplaced => None
    | _ => rows !! q
    end.
Qed
Proof.
  revert rows.
  induction pairs as [|[k c] rest IH]; intros rows Hnd; simpl in *.
  - by rewrite lookup_empty.
  - inversion Hnd as [|x l Hnin Hnd_rest]; subst x l.
    rewrite (IH _ Hnd_rest).
    destruct (decide (q = k)) as [->|Hne].
    + rewrite lookup_insert_eq.
      rewrite (not_elem_of_list_to_map_1 rest k Hnin).
      unfold fold_detach_one; simpl.
      destruct c; simpl; try reflexivity; by rewrite lookup_delete_eq.
    + rewrite lookup_insert_ne; [|symmetry; exact Hne].
      assert (Hq : fold_detach_one rows (k, c) !! q = rows !! q).
      { unfold fold_detach_one; simpl.
        destruct c; try reflexivity; apply lookup_delete_ne; symmetry; exact Hne. }
      by rewrite Hq.
Qed.
References

Uses

12 more
  • nat
  • NoDup
  • decide
  • list_to_map
  • lookup_delete_eq
  • lookup_delete_ne
  • lookup_empty
  • lookup_insert_eq
  • lookup_insert_ne
  • not_elem_of_list_to_map_1
  • gmap
  • list.foldl
Lemma fold_attach_lookup {E : Type}
    (cur_entries : gmap nat E) (pairs : list (nat * key_change)) (m1 : gmap nat E) (q : nat) :
  NoDup (fst <$> pairs) ->
  foldl (fold_attach_one cur_entries) m1 pairs !! q =
    match (list_to_map pairs : gmap nat key_change) !! q with
    | Some KcAdded | Some KcReplaced =>
        match cur_entries !! q with
        | Some e => Some e
        | None => m1 !! q
        end
    | _ => m1 !! q
    end.
Qed
Proof.
  revert m1.
  induction pairs as [|[k c] rest IH]; intros m1 Hnd; simpl in *.
  - by rewrite lookup_empty.
  - inversion Hnd as [|x l Hnin Hnd_rest]; subst x l.
    rewrite (IH _ Hnd_rest).
    destruct (decide (q = k)) as [->|Hne].
    + rewrite lookup_insert_eq.
      rewrite (not_elem_of_list_to_map_1 rest k Hnin).
      unfold fold_attach_one; simpl.
      destruct c; simpl; try reflexivity;
        destruct (cur_entries !! k) as [e|]; try reflexivity;
        by rewrite lookup_insert_eq.
    + rewrite lookup_insert_ne; [|symmetry; exact Hne].
      assert (Hq : fold_attach_one cur_entries m1 (k, c) !! q = m1 !! q).
      { unfold fold_attach_one; simpl.
        destruct c; try reflexivity;
          destruct (cur_entries !! k) as [e|]; try reflexivity;
          apply lookup_insert_ne; symmetry; exact Hne. }
      by rewrite Hq.
Qed.
References

Uses

10 more
  • nat
  • NoDup
  • decide
  • list_to_map
  • lookup_empty
  • lookup_insert_eq
  • lookup_insert_ne
  • not_elem_of_list_to_map_1
  • gmap
  • list.foldl
✓ No axioms

ProjectionFold.Sync refines upstream.Entries in $O(\Delta)$ on normal deltas (for any NoDup enumeration order of pd_changes) and via Diff when pd_is_reset = true (Combinators.fs lines 1004–1085).

Arguments

E : Type
the upstream row-entry type (RowEntry<'K, 'V>).
invertible : bool
true for foldGroup, false for fold.
had_keys : bool
true after the fold's initial read.
cur_entries : gmap nat E
the current upstream.Entries map.
rows : gmap nat E
the fold's rows map from the previous read.
pairs : list (nat * key_change)
the dense KeyChanges array entries enumerated by 0 .. delta.ChangeCount - 1.
the ProjectionDelta returned by keyReader.Read().
full : bool
the full recompute flag entering Sync.
Theorem fold_delta_sync_refines_diff {E : Type}
    (invertible had_keys : bool) (cur_entries rows : gmap nat E)
    (pairs : list (nat * key_change)) (d : proj_delta_state) (full : bool) :
  (pd_is_reset d = false ->
   NoDup (fst <$> pairs) /\
   pd_changes d = list_to_map pairs /\
   (forall q,
      (pd_changes d !! q = Some KcRemoved -> cur_entries !! q = None) /\
      (pd_changes d !! q = Some KcAdded -> is_Some (cur_entries !! q)) /\
      (pd_changes d !! q = Some KcReplaced -> is_Some (cur_entries !! q)) /\
      (pd_changes d !! q = None \/ pd_changes d !! q = Some KcChanged ->
       cur_entries !! q = rows !! q))) ->
  fst (fold_sync_membership invertible had_keys cur_entries pairs d rows full) = cur_entries.

Arguments

E : Type
the upstream row-entry type (RowEntry<'K, 'V>).
invertible : bool
true for foldGroup, false for fold.
had_keys : bool
true after the fold's initial read.
cur_entries : gmap nat E
the current upstream.Entries map.
rows : gmap nat E
the fold's rows map from the previous read.
pairs : list (nat * key_change)
the dense KeyChanges array entries enumerated by 0 .. delta.ChangeCount - 1.
the ProjectionDelta returned by keyReader.Read().
full : bool
the full recompute flag entering Sync.
Qed
Proof.
  intros Hcoh.
  unfold fold_sync_membership; simpl.
  destruct (pd_is_reset d) eqn:Eres; [reflexivity|].
  destruct (Hcoh eq_refl) as (Hnd & Hmap & Hkeys).
  destruct (decide (length pairs = 0)) as [Hlen|Hlen].
  - apply nil_length_inv in Hlen; subst pairs.
    simpl in Hmap.
    apply map_eq; intros q.
    destruct (Hkeys q) as (_ & _ & _ & Hsame).
    symmetry. apply Hsame. left. rewrite Hmap. apply lookup_empty.
  - unfold fold_apply_delta.
    apply map_eq; intros q.
    rewrite (fold_attach_lookup cur_entries pairs _ q Hnd).
    rewrite (fold_detach_lookup pairs rows q Hnd).
    rewrite <- Hmap.
    destruct (Hkeys q) as (Hrem & Hadd & Hrep & Hsame).
    destruct (pd_changes d !! q) as [c|] eqn:Eqc.
    + destruct c.
      * destruct (Hadd eq_refl) as [e He]. by rewrite He.
      * symmetry. exact (Hrem eq_refl).
      * destruct (Hrep eq_refl) as [e He]. by rewrite He.
      * symmetry. apply Hsame. by right.
    + symmetry. apply Hsame. by left.
Qed.
References

Uses

21 more
✓ No axioms

On a pure upstream reorder (pd_is_reset d = false, pairs = [], had_keys = true, pd_order_changed d = true), foldGroup (invertible = true) leaves (rows, full) untouched, whereas fold (invertible = false) sets full = true so Recompute folds in the new key order (Combinators.fs lines 1072–1085).

Arguments

E : Type
the upstream row-entry type.
cur_entries : gmap nat E
the current upstream.Entries map.
rows : gmap nat E
the fold's rows map.
a pure-reorder ProjectionDelta.
full : bool
the full recompute flag entering Sync.
Theorem fold_pure_reorder_invariants {E : Type}
    (cur_entries rows : gmap nat E) (d : proj_delta_state) (full : bool) :
  pd_is_reset d = false ->
  pd_order_changed d = true ->
  fold_sync_membership true true cur_entries [] d rows full = (rows, full) /\
  fold_sync_membership false true cur_entries [] d rows full = (rows, true).

Arguments

E : Type
the upstream row-entry type.
cur_entries : gmap nat E
the current upstream.Entries map.
rows : gmap nat E
the fold's rows map.
a pure-reorder ProjectionDelta.
full : bool
the full recompute flag entering Sync.
Qed
Proof.
  intros Hres Hord.
  unfold fold_sync_membership.
  rewrite Hres, Hord; simpl.
  split; reflexivity.
Qed.
References

5. CollectionProjection tail-append/remove order preservation on cancelled batches

Inductive col_op :=
  | ColAdd (k : nat)
  | ColRemove (k : nat).
References

Uses

  • nat
Definition col_step (st : list nat * gmap nat key_change) (op : col_op)
    : list nat * gmap nat key_change :=
  let (cur, kc) := st in
  match op with
  | ColAdd k =>
      if decide (k ∈ cur) then (cur, kc)
      else (cur ++ [k], kc_record k KcAdded kc)
  | ColRemove k =>
      if decide (k ∈ cur) then (filter (fun x => x <> k) cur, kc_record k KcRemoved kc)
      else (cur, kc)
  end.
References
Definition col_inv (init cur : list nat) (kc : gmap nat key_change) : Prop :=
  NoDup cur /\
  (forall x, x ∉ init -> x ∈ cur -> kc !! x = Some KcAdded \/ kc !! x = Some KcReplaced) /\
  (forall x, x ∈ init -> kc !! x <> Some KcAdded) /\
  (forall x, x ∈ init -> x ∉ cur -> kc !! x = Some KcRemoved) /\
  ((forall x, x ∈ init -> kc !! x = None) ->
   exists sfx, cur = init ++ sfx /\ (forall y, y ∈ sfx -> y ∉ init)).
References

Uses

2 more
  • NoDup
  • gmap
Lemma filter_ne_not_elem (k : nat) (l : list nat) :
  k ∉ l ->
  filter (fun x => x <> k) l = l.
Qed
Proof.
  induction l as [|x rest IH]; intros Hnin; [reflexivity|].
  apply not_elem_of_cons in Hnin as [Hne Hnin_rest].
  rewrite filter_cons_True; [|symmetry; exact Hne].
  f_equal. exact (IH Hnin_rest).
Qed.
References

Uses

  • list
  • nat
  • filter
  • list.filter_cons_True
  • list.not_elem_of_cons
Lemma elem_of_filter_ne_iff (k x : nat) (l : list nat) :
  x ∈ filter (fun y => y <> k) l <-> x <> k /\ x ∈ l.
Qed
Proof.
  induction l as [|y rest IH]; [set_solver|].
  destruct (decide (y <> k)) as [Hne|Hne].
  - rewrite filter_cons_True by exact Hne. set_solver.
  - rewrite filter_cons_False by exact Hne.
    assert (y = k) by lia; subst y. set_solver.
Qed.
References

Uses

  • list
  • nat
  • decide
  • filter
  • list.filter_cons_False
  • list.filter_cons_True
Lemma col_step_preserves_inv (init cur : list nat) (kc : gmap nat key_change) (op : col_op) :
  col_inv init cur kc ->
  let (cur', kc') := col_step (cur, kc) op in
  col_inv init cur' kc'.
Qed
Proof.
  intros (Hnd & Hfresh & Hno_add & Hrem_init & Hord).
  destruct op as [k | k]; simpl.
  - destruct (decide (k ∈ cur)) as [Hin|Hnin].
    + exact (conj Hnd (conj Hfresh (conj Hno_add (conj Hrem_init Hord)))).
    + split_and!.
      * apply NoDup_app; split_and!; [exact Hnd| |apply NoDup_singleton].
        set_solver.
      * intros x Hx_ninit Hx_cur'.
        apply elem_of_app in Hx_cur' as [Hx_cur | Hxk].
        -- destruct (decide (x = k)) as [->|Hne]; [contradiction|].
           unfold kc_record. destruct (kc_merge_opt (kc !! k) KcAdded) as [nxt|].
           ++ rewrite lookup_insert_ne; [|symmetry; exact Hne].
              exact (Hfresh x Hx_ninit Hx_cur).
           ++ rewrite lookup_delete_ne; [|symmetry; exact Hne].
              exact (Hfresh x Hx_ninit Hx_cur).
        -- assert (x = k) by set_solver; subst x.
           unfold kc_record.
           destruct (kc !! k) as [p|] eqn:Ekc; simpl.
           ++ destruct p; simpl; rewrite lookup_insert_eq; [by left | by right | by left | by left].
           ++ rewrite lookup_insert_eq. by left.
      * intros x Hx_init.
        destruct (decide (x = k)) as [->|Hne].
        -- specialize (Hrem_init k Hx_init Hnin).
           unfold kc_record. rewrite Hrem_init; simpl.
           rewrite lookup_insert_eq. discriminate.
        -- unfold kc_record. destruct (kc_merge_opt (kc !! k) KcAdded) as [nxt|].
           ++ rewrite lookup_insert_ne; [|symmetry; exact Hne].
              exact (Hno_add x Hx_init).
           ++ rewrite lookup_delete_ne; [|symmetry; exact Hne].
              exact (Hno_add x Hx_init).
      * intros x Hx_init Hx_ncur'.
        assert (Hne : x <> k) by set_solver.
        assert (Hx_ncur : x ∉ cur) by set_solver.
        unfold kc_record. destruct (kc_merge_opt (kc !! k) KcAdded) as [nxt|].
        -- rewrite lookup_insert_ne; [|symmetry; exact Hne].
           exact (Hrem_init x Hx_init Hx_ncur).
        -- rewrite lookup_delete_ne; [|symmetry; exact Hne].
           exact (Hrem_init x Hx_init Hx_ncur).
      * intros Hall_none.
        assert (Hk_ninit : k ∉ init).
        { intros Hk_init.
          pose proof (Hrem_init k Hk_init Hnin) as Hkr.
          pose proof (Hall_none k Hk_init) as Hkn.
          unfold kc_record in Hkn. rewrite Hkr in Hkn; simpl in Hkn.
          rewrite lookup_insert_eq in Hkn. discriminate. }
        assert (Hall_prev : forall x, x ∈ init -> kc !! x = None).
        { intros x Hx_init.
          assert (Hne : x <> k) by (intros ->; contradiction).
          pose proof (Hall_none x Hx_init) as Hxn.
          unfold kc_record in Hxn.
          destruct (kc_merge_opt (kc !! k) KcAdded) as [nxt|].
          - rewrite lookup_insert_ne in Hxn; [exact Hxn | symmetry; exact Hne].
          - rewrite lookup_delete_ne in Hxn; [exact Hxn | symmetry; exact Hne]. }
        destruct (Hord Hall_prev) as (sfx & Hcur_eq & Hsfx).
        exists (sfx ++ [k]).
        split.
        -- rewrite Hcur_eq, <- app_assoc. reflexivity.
        -- intros y Hy. apply elem_of_app in Hy as [Hy | Hy].
           ++ exact (Hsfx y Hy).
           ++ assert (y = k) by set_solver; subst y; exact Hk_ninit.
  - destruct (decide (k ∈ cur)) as [Hin|Hnin].
    + assert (Hrem_step : forall q, q <> k -> kc_record k KcRemoved kc !! q = kc !! q).
      { intros q Hne. unfold kc_record.
        destruct (kc_merge_opt (kc !! k) KcRemoved) as [nxt|].
        - apply lookup_insert_ne; symmetry; exact Hne.
        - apply lookup_delete_ne; symmetry; exact Hne. }
      assert (Hrem_init_k : k ∈ init -> kc_record k KcRemoved kc !! k = Some KcRemoved).
      { intros Hk_init. pose proof (Hno_add k Hk_init) as Hna.
        unfold kc_record. destruct (kc !! k) as [p|] eqn:Ep; simpl.
        - destruct p; [exfalso; exact (Hna eq_refl) | | |]; simpl; by rewrite lookup_insert_eq.
        - by rewrite lookup_insert_eq. }
      split_and!.
      * apply NoDup_filter, Hnd.
      * intros x Hx_ninit Hx_cur'.
        apply elem_of_filter_ne_iff in Hx_cur' as [Hne Hx_cur].
        rewrite (Hrem_step x Hne).
        exact (Hfresh x Hx_ninit Hx_cur).
      * intros x Hx_init.
        destruct (decide (x = k)) as [->|Hne].
        -- rewrite (Hrem_init_k Hx_init). discriminate.
        -- rewrite (Hrem_step x Hne). exact (Hno_add x Hx_init).
      * intros x Hx_init Hx_ncur'.
        destruct (decide (x = k)) as [->|Hne].
        -- exact (Hrem_init_k Hx_init).
        -- rewrite (Hrem_step x Hne). apply Hrem_init; [exact Hx_init|].
           intros Hx_cur. apply Hx_ncur', elem_of_filter_ne_iff. split; [exact Hne | exact Hx_cur].
      * intros Hall_none.
        assert (Hk_ninit : k ∉ init).
        { intros Hk_init.
          pose proof (Hrem_init_k Hk_init) as Hkr.
          pose proof (Hall_none k Hk_init) as Hkn. congruence. }
        assert (Hall_prev : forall x, x ∈ init -> kc !! x = None).
        { intros x Hx_init.
          assert (Hne : x <> k) by (intros ->; contradiction).
          rewrite <- (Hrem_step x Hne). exact (Hall_none x Hx_init). }
        destruct (Hord Hall_prev) as (sfx & Hcur_eq & Hsfx).
        exists (filter (fun x => x <> k) sfx).
        split.
        -- rewrite Hcur_eq, filter_app, (filter_ne_not_elem k init Hk_ninit). reflexivity.
        -- intros y Hy. apply elem_of_filter_ne_iff in Hy as [_ Hy]. exact (Hsfx y Hy).
    + exact (conj Hnd (conj Hfresh (conj Hno_add (conj Hrem_init Hord)))).
Qed.
References

Uses

20 more
  • filter_ne_not_elem
  • elem_of_filter_ne_iff
  • None
  • Some
  • list
  • nat
  • conj
  • eq_refl
  • app_assoc
  • decide
  • filter
  • lookup_delete_ne
  • lookup_insert_eq
  • lookup_insert_ne
  • gmap
  • list.elem_of_app
  • list.filter_app
  • list.NoDup_app
  • list.NoDup_filter
  • list.NoDup_singleton
✓ No axioms

After any sequence of tail-append ColAdd and arbitrary-position ColRemove operations on a NoDup key list init, if the coalesced KeyChanges map is ∅, the resulting key list equals init (Collections.fs lines 38–60).

Arguments

init : list nat
the ordered key list previous from the prior ReadDelta.
ops : list col_op
any sequence of AddOrUpdate (new-key append) and Remove operations within a batch.
Theorem append_remove_empty_changes_preserves_order (init : list nat) (ops : list col_op) :
  NoDup init ->
  let (cur, kc) := foldl col_step (init, ∅) ops in
  kc = ∅ ->
  cur = init.

Arguments

init : list nat
the ordered key list previous from the prior ReadDelta.
ops : list col_op
any sequence of AddOrUpdate (new-key append) and Remove operations within a batch.
Qed
Proof.
  intros Hnd.
  assert (Hinv0 : col_inv init init ∅).
  { split_and!.
    - exact Hnd.
    - intros x Hni Hi; contradiction.
    - intros x _. rewrite lookup_empty. discriminate.
    - intros x Hi Hni; contradiction.
    - intros _. exists []. rewrite app_nil_r. split; [reflexivity | intros y Hy; inversion Hy]. }
  assert (Hinv : forall st ops',
            col_inv init st.1 st.2 ->
            let (cur, kc) := foldl col_step st ops' in
            col_inv init cur kc).
  { intros st ops'. revert st.
    induction ops' as [|op rest IH]; intros [c m] Hinv_cm; cbn [foldl].
    - exact Hinv_cm.
    - pose proof (col_step_preserves_inv init c m op Hinv_cm) as Hnext.
      destruct (col_step (c, m) op) as [c' m'].
      exact (IH (c', m') Hnext). }
  specialize (Hinv (init, ∅) ops Hinv0).
  destruct (foldl col_step (init, ∅) ops) as [cur kc].
  intros Hkc_emp. subst kc.
  destruct Hinv as (_ & Hfresh & _ & _ & Hord).
  assert (Hall_none : forall x, x ∈ init -> (∅ : gmap nat key_change) !! x = None).
  { intros x _. apply lookup_empty. }
  destruct (Hord Hall_none) as (sfx & Hcur_eq & Hsfx).
  destruct sfx as [|y sfx'].
  - rewrite app_nil_r in Hcur_eq. exact Hcur_eq.
  - exfalso.
    assert (Hy_sfx : y ∈ y :: sfx') by left.
    pose proof (Hsfx y Hy_sfx) as Hy_ninit.
    assert (Hy_cur : y ∈ cur).
    { rewrite Hcur_eq. apply elem_of_app; right; exact Hy_sfx. }
    destruct (Hfresh y Hy_ninit Hy_cur) as [Hy1 | Hy2];
      [rewrite lookup_empty in Hy1; discriminate | rewrite lookup_empty in Hy2; discriminate].
Qed.
References

Uses

6 more
  • app_nil_r
  • NoDup
  • lookup_empty
  • gmap
  • list.elem_of_app
  • list.foldl

6. Positional.diff prefix/suffix framing and contiguous fast paths

Inductive pos_edit (A : Type) :=
  | PosRemoveAt (idx : nat)
  | PosInsertAt (idx : nat) (x : A)
  | PosMove (old_idx new_idx : nat).
References

Uses

  • nat
Arguments PosRemoveAt {A} idx.
Arguments PosInsertAt {A} idx x.
Arguments PosMove {A} old_idx new_idx.
Definition offset_pos_edit {A : Type} (off : nat) (e : pos_edit A) : pos_edit A :=
  match e with
  | PosRemoveAt idx => PosRemoveAt (off + idx)
  | PosInsertAt idx x => PosInsertAt (off + idx) x
  | PosMove old_idx new_idx => PosMove (off + old_idx) (off + new_idx)
  end.
References
Definition remove_at {A : Type} (idx : nat) (xs : list A) : option (A * list A) :=
  match xs !! idx with
  | Some x => Some (x, take idx xs ++ drop (S idx) xs)
  | None => None
  end.
References

Uses

  • None
  • S
  • Some
  • list
  • nat
  • option
  • list.drop
  • list.take
Definition insert_at {A : Type} (idx : nat) (x : A) (xs : list A) : option (list A) :=
  if decide (idx <= length xs) then
    Some (take idx xs ++ x :: drop idx xs)
  else
    None.
References

Uses

  • None
  • Some
  • length
  • list
  • nat
  • option
  • decide
  • list.drop
1 more
  • list.take
Definition apply_pos_edit {A : Type} (xs : list A) (e : pos_edit A) : option (list A) :=
  match e with
  | PosRemoveAt idx => snd <$> remove_at idx xs
  | PosInsertAt idx x => insert_at idx x xs
  | PosMove old_idx new_idx =>
      match remove_at old_idx xs with
      | Some (x, xs') => insert_at new_idx x xs'
      | None => None
      end
  end.
References
Fixpoint apply_pos_edits {A : Type} (xs : list A) (es : list (pos_edit A)) : option (list A) :=
  match es with
  | [] => Some xs
  | e :: es' =>
      match apply_pos_edit xs e with
      | Some xs' => apply_pos_edits xs' es'
      | None => None
      end
  end.
References

Uses

Lemma remove_at_frame {A : Type} (P M M' Sfx : list A) (idx : nat) (x : A) :
  remove_at idx M = Some (x, M') ->
  remove_at (length P + idx) (P ++ M ++ Sfx) = Some (x, P ++ M' ++ Sfx).
Qed
Proof.
  unfold remove_at.
  destruct (M !! idx) as [y|] eqn:Hm; [|discriminate].
  intros Hinj. injection Hinj as <- <-.
  pose proof (lookup_lt_Some _ _ _ Hm) as Hlt.
  rewrite lookup_app_r; [|lia].
  replace (length P + idx - length P) with idx by lia.
  rewrite lookup_app_l; [|exact Hlt].
  rewrite Hm. f_equal. f_equal.
  rewrite take_app_ge; [|lia].
  replace (length P + idx - length P) with idx by lia.
  rewrite take_app_le; [|lia].
  rewrite drop_app_ge; [|lia].
  replace (S (length P + idx) - length P) with (S idx) by lia.
  rewrite drop_app_le; [|lia].
  rewrite <- !app_assoc. reflexivity.
Qed.
References

Uses

  • remove_at
  • S
  • Some
  • length
  • list
  • nat
  • app_assoc
  • list.drop_app_ge
6 more
  • list.drop_app_le
  • list.lookup_app_l
  • list.lookup_app_r
  • list.lookup_lt_Some
  • list.take_app_ge
  • list.take_app_le
Lemma insert_at_frame {A : Type} (P M M' Sfx : list A) (idx : nat) (x : A) :
  insert_at idx x M = Some M' ->
  insert_at (length P + idx) x (P ++ M ++ Sfx) = Some (P ++ M' ++ Sfx).
Qed
Proof.
  unfold insert_at.
  destruct (decide (idx <= length M)) as [Hle|Hgt]; [|discriminate].
  intros Hinj. injection Hinj as <-.
  rewrite decide_True; [|rewrite !length_app; lia].
  f_equal.
  rewrite take_app_ge; [|lia].
  replace (length P + idx - length P) with idx by lia.
  rewrite take_app_le; [|exact Hle].
  rewrite drop_app_ge; [|lia].
  replace (length P + idx - length P) with idx by lia.
  rewrite drop_app_le; [|exact Hle].
  rewrite <- app_assoc. simpl. rewrite <- app_assoc. reflexivity.
Qed.
References

Uses

  • insert_at
  • Some
  • length
  • list
  • nat
  • app_assoc
  • length_app
  • decide
5 more
  • decide_True
  • list.drop_app_ge
  • list.drop_app_le
  • list.take_app_ge
  • list.take_app_le
Lemma apply_pos_edit_frame {A : Type} (P M M' Sfx : list A) (e : pos_edit A) :
  apply_pos_edit M e = Some M' ->
  apply_pos_edit (P ++ M ++ Sfx) (offset_pos_edit (length P) e) = Some (P ++ M' ++ Sfx).
Qed
Proof.
  destruct e as [idx | idx x | old_idx new_idx]; simpl.
  - destruct (remove_at idx M) as [[x rest]|] eqn:Hr; simpl; [|discriminate].
    intros Hinj. injection Hinj as <-.
    rewrite (remove_at_frame P M rest Sfx idx x Hr). reflexivity.
  - apply insert_at_frame.
  - destruct (remove_at old_idx M) as [[x rest]|] eqn:Hr; [|discriminate].
    intros Hins.
    rewrite (remove_at_frame P M rest Sfx old_idx x Hr).
    exact (insert_at_frame P rest M' Sfx new_idx x Hins).
Qed.
References
✓ No axioms

Shifting every edit index in a valid middle-slice script es by length P rewrites P ++ M ++ Sfx into P ++ M' ++ Sfx (Positional.fs).

Arguments

P : list A
common prefix slice shared by previous and next.
M : list A
changed middle slice of previous.
M' : list A
changed middle slice of next.
Sfx : list A
common suffix slice shared by previous and next.
es : list (pos_edit A)
positional edits valid over the unshifted middle slice M.
Theorem positional_frame_prefix_suffix
    {A : Type} (P M M' Sfx : list A) (es : list (pos_edit A)) :
  apply_pos_edits M es = Some M' ->
  apply_pos_edits (P ++ M ++ Sfx) (offset_pos_edit (length P) <$> es) = Some (P ++ M' ++ Sfx).

Arguments

P : list A
common prefix slice shared by previous and next.
M : list A
changed middle slice of previous.
M' : list A
changed middle slice of next.
Sfx : list A
common suffix slice shared by previous and next.
es : list (pos_edit A)
positional edits valid over the unshifted middle slice M.
Qed
Proof.
  revert M.
  induction es as [|e es' IH]; intros M; simpl.
  - intros Hinj. injection Hinj as <-. reflexivity.
  - destruct (apply_pos_edit M e) as [M1|] eqn:He; [|discriminate].
    intros Hrest.
    rewrite (apply_pos_edit_frame P M M1 Sfx e He).
    exact (IH M1 Hrest).
Qed.
References
Lemma apply_pure_inserts_acc {A : Type} (acc Ins : list A) :
  apply_pos_edits acc (imap (fun k x => PosInsertAt (length acc + k) x) Ins) =
  Some (acc ++ Ins).
Qed
Proof.
  revert acc.
  induction Ins as [|x rest IH]; intros acc; simpl.
  - rewrite app_nil_r. reflexivity.
  - unfold insert_at. rewrite decide_True; [|lia].
    rewrite Nat.add_0_r, take_ge, drop_ge; [|lia|lia].
    simpl.
    set (acc' := acc ++ [x]).
    assert (Hmap :
      imap ((fun k y => PosInsertAt (length acc + k) y) ∘ S) rest =
      imap (fun k y => PosInsertAt (length acc' + k) y) rest).
    { apply imap_ext. intros k y _. unfold compose, acc'. rewrite length_app. simpl. f_equal. lia. }
    rewrite Hmap.
    rewrite (IH acc').
    unfold acc'. rewrite <- app_assoc. reflexivity.
Qed.
References

Uses

9 more
  • Nat.add_0_r
  • app_assoc
  • app_nil_r
  • length_app
  • decide_True
  • list.drop_ge
  • list.take_ge
  • list.imap
  • list.imap_ext
Lemma fmap_imap {A B C : Type} (g : B -> C) (f : nat -> A -> B) (l : list A) :
  g <$> imap f l = imap (fun k x => g (f k x)) l.
Qed
Proof.
  revert f. induction l as [|x rest IH]; intros f; simpl; [reflexivity|].
  f_equal. rewrite IH. apply imap_ext. intros k y _. reflexivity.
Qed.
References

Uses

  • list
  • nat
  • list.imap
  • list.imap_ext
Lemma offset_imap_insert {A : Type} (off : nat) (Ins : list A) :
  offset_pos_edit off <$> imap (fun k x => PosInsertAt k x) Ins =
  imap (fun k x => PosInsertAt (off + k) x) Ins.
Qed
Proof.
  rewrite fmap_imap. apply imap_ext. intros k x _. reflexivity.
Qed.
References

Uses

✓ No axioms

Emitting InsertAt (length P + k, x) for each inserted element x at offset k transforms P ++ Sfx directly into P ++ Ins ++ Sfx (Positional.fs).

Arguments

P : list A
common prefix slice.
Ins : list A
contiguous block inserted after P.
Sfx : list A
common suffix slice.
Theorem positional_pure_inserts_correct {A : Type} (P Ins Sfx : list A) :
  apply_pos_edits (P ++ Sfx) (imap (fun k x => PosInsertAt (length P + k) x) Ins) =
  Some (P ++ Ins ++ Sfx).

Arguments

P : list A
common prefix slice.
Ins : list A
contiguous block inserted after P.
Sfx : list A
common suffix slice.
Qed
Proof.
  pose proof (positional_frame_prefix_suffix P [] Ins Sfx (imap (fun k x => PosInsertAt k x) Ins)) as Hframe.
  rewrite offset_imap_insert in Hframe.
  simpl in Hframe.
  apply Hframe.
  pose proof (apply_pure_inserts_acc [] Ins) as Hacc.
  simpl in Hacc. exact Hacc.
Qed.
References
Lemma apply_pure_removes_mid {A : Type} (Rem : list A) :
  apply_pos_edits Rem (PosRemoveAt <$> rev (seq 0 (length Rem))) = Some [].
Qed
Proof.
  induction Rem as [|x Rem' IH] using rev_ind; simpl.
  - reflexivity.
  - rewrite length_app. simpl.
    rewrite Nat.add_1_r, seq_S, rev_unit.
    simpl. unfold remove_at.
    rewrite lookup_app_r; [|lia].
    rewrite Nat.sub_diag. simpl.
    rewrite take_app_le; [|lia].
    rewrite take_ge; [|lia].
    rewrite drop_app_ge; [|lia].
    replace (S (length Rem') - length Rem') with 1 by lia.
    simpl. rewrite app_nil_r.
    exact IH.
Qed.
References

Uses

12 more
  • Nat.add_1_r
  • Nat.sub_diag
  • app_nil_r
  • length_app
  • rev
  • rev_ind
  • rev_unit
  • seq_S
  • list.drop_app_ge
  • list.lookup_app_r
  • list.take_app_le
  • list.take_ge
✓ No axioms

Emitting back-to-front RemoveAt edits from length P + length Rem - 1 down to length P transforms P ++ Rem ++ Sfx directly into P ++ Sfx (Positional.fs).

Arguments

P : list A
common prefix slice.
Rem : list A
contiguous block removed after P.
Sfx : list A
common suffix slice.
Theorem positional_pure_removes_correct {A : Type} (P Rem Sfx : list A) :
  apply_pos_edits (P ++ Rem ++ Sfx)
    (offset_pos_edit (length P) <$> (PosRemoveAt <$> rev (seq 0 (length Rem)))) =
  Some (P ++ Sfx).

Arguments

P : list A
common prefix slice.
Rem : list A
contiguous block removed after P.
Sfx : list A
common suffix slice.
Qed
Proof.
  pose proof (positional_frame_prefix_suffix P Rem [] Sfx
                (PosRemoveAt <$> rev (seq 0 (length Rem)))
                (apply_pure_removes_mid Rem)) as Hframe.
  simpl in Hframe. exact Hframe.
Qed.
References
✓ No axioms

Under the distinct-key invariant on both input arrays, trimmed middle slices M1 and M2 contain no keys from P or Sfx, so all matching survivors remain strictly inside the middle window (Positional.fs).

Arguments

P : list A
common prefix slice.
M1 : list A
changed middle slice of previous.
M2 : list A
changed middle slice of next.
Sfx : list A
common suffix slice.
Theorem positional_nodup_trimmed_disjoint {A : Type} (P M1 M2 Sfx : list A) :
  NoDup (P ++ M1 ++ Sfx) ->
  NoDup (P ++ M2 ++ Sfx) ->
  (forall x, x ∈ M1 -> x ∉ P /\ x ∉ Sfx) /\
  (forall x, x ∈ M2 -> x ∉ P /\ x ∉ Sfx).

Arguments

P : list A
common prefix slice.
M1 : list A
changed middle slice of previous.
M2 : list A
changed middle slice of next.
Sfx : list A
common suffix slice.
Qed
Proof.
  intros Hnd1 Hnd2.
  apply NoDup_app in Hnd1 as (_ & HdisjP1 & Hnd1').
  apply NoDup_app in Hnd1' as (_ & HdisjS1 & _).
  apply NoDup_app in Hnd2 as (_ & HdisjP2 & Hnd2').
  apply NoDup_app in Hnd2' as (_ & HdisjS2 & _).
  split; intros x Hx; split.
  - intros Hxp. apply (HdisjP1 x Hxp). apply elem_of_app. by left.
  - intros Hxs. apply (HdisjS1 x Hx). exact Hxs.
  - intros Hxp. apply (HdisjP2 x Hxp). apply elem_of_app. by left.
  - intros Hxs. apply (HdisjS2 x Hx). exact Hxs.
Qed.
References

Uses

  • list
  • NoDup
  • list.elem_of_app
  • list.NoDup_app
Lemma apply_single_move_right_mid {A : Type} (mid : list A) (x : A) :
  apply_pos_edits (x :: mid) [PosMove 0 (length mid)] = Some (mid ++ [x]).
Qed
Proof.
  unfold apply_pos_edits, apply_pos_edit, remove_at, insert_at.
  simpl. rewrite drop_0.
  rewrite decide_True; [|lia].
  rewrite take_ge, drop_ge; [reflexivity | lia | lia].
Qed.
References

Uses

4 more
  • decide_True
  • list.drop_0
  • list.drop_ge
  • list.take_ge
✓ No axioms

A single Move(length P, length P + length mid) transforms P ++ (x :: mid) ++ Sfx directly into P ++ (mid ++ [x]) ++ Sfx (Positional.fs).

Arguments

P : list A
common prefix slice.
mid : list A
middle slice shifted left by one position.
Sfx : list A
common suffix slice.
x : A
element moved to the end of the middle slice.
Theorem positional_single_move_right_correct {A : Type} (P mid Sfx : list A) (x : A) :
  apply_pos_edits (P ++ (x :: mid) ++ Sfx) [PosMove (length P) (length P + length mid)] =
  Some (P ++ (mid ++ [x]) ++ Sfx).

Arguments

P : list A
common prefix slice.
mid : list A
middle slice shifted left by one position.
Sfx : list A
common suffix slice.
x : A
element moved to the end of the middle slice.
Qed
Proof.
  pose proof (positional_frame_prefix_suffix P (x :: mid) (mid ++ [x]) Sfx
                [PosMove 0 (length mid)] (apply_single_move_right_mid mid x)) as Hframe.
  simpl in Hframe. rewrite Nat.add_0_r in Hframe. exact Hframe.
Qed.
References
Lemma remove_at_end {A : Type} (xs : list A) (x : A) :
  remove_at (length xs) (xs ++ [x]) = Some (x, xs).
Qed
Proof.
  unfold remove_at.
  rewrite lookup_app_r; [|lia].
  rewrite Nat.sub_diag. simpl.
  rewrite take_app_le; [|lia].
  rewrite take_ge; [|lia].
  rewrite drop_app_ge; [|lia].
  replace (S (length xs) - length xs) with 1 by lia.
  simpl. rewrite app_nil_r. reflexivity.
Qed.
References

Uses

  • remove_at
  • S
  • Some
  • length
  • list
  • Nat.sub_diag
  • app_nil_r
  • list.drop_app_ge
3 more
  • list.lookup_app_r
  • list.take_app_le
  • list.take_ge
Lemma apply_single_move_left_mid {A : Type} (mid : list A) (x : A) :
  apply_pos_edits (mid ++ [x]) [PosMove (length mid) 0] = Some (x :: mid).
Qed
Proof.
  unfold apply_pos_edits, apply_pos_edit.
  rewrite remove_at_end.
  unfold insert_at.
  rewrite decide_True; [|lia].
  simpl. rewrite drop_0.
  reflexivity.
Qed.
References

Uses

2 more
  • decide_True
  • list.drop_0
✓ No axioms

A single Move(length P + length mid, length P) transforms P ++ (mid ++ [x]) ++ Sfx directly into P ++ (x :: mid) ++ Sfx (Positional.fs).

Arguments

P : list A
common prefix slice.
mid : list A
middle slice shifted right by one position.
Sfx : list A
common suffix slice.
x : A
element moved to the start of the middle slice.
Theorem positional_single_move_left_correct {A : Type} (P mid Sfx : list A) (x : A) :
  apply_pos_edits (P ++ (mid ++ [x]) ++ Sfx) [PosMove (length P + length mid) (length P)] =
  Some (P ++ (x :: mid) ++ Sfx).

Arguments

P : list A
common prefix slice.
mid : list A
middle slice shifted right by one position.
Sfx : list A
common suffix slice.
x : A
element moved to the start of the middle slice.
Qed
Proof.
  pose proof (positional_frame_prefix_suffix P (mid ++ [x]) (x :: mid) Sfx
                [PosMove (length mid) 0] (apply_single_move_left_mid mid x)) as Hframe.
  simpl in Hframe. rewrite Nat.add_0_r in Hframe. exact Hframe.
Qed.
References
Lemma apply_pos_edit_of_single {A : Type} (xs ys : list A) (e : pos_edit A) :
  apply_pos_edits xs [e] = Some ys ->
  apply_pos_edit xs e = Some ys.
Qed
Proof.
  unfold apply_pos_edits.
  destruct (apply_pos_edit xs e); [intro H; exact H | discriminate].
Qed.
References
Lemma apply_distant_swap_mid {A : Type} (mid : list A) (a b : A) :
  apply_pos_edits (a :: mid ++ [b])
    [PosMove (S (length mid)) 0; PosMove 1 (S (length mid))] =
  Some (b :: mid ++ [a]).
Qed
Proof.
  cbn [apply_pos_edits].
  pose proof (apply_pos_edit_of_single ((a :: mid) ++ [b]) (b :: a :: mid) (PosMove (length (a :: mid)) 0)
                (apply_single_move_left_mid (a :: mid) b)) as Hleft.
  cbn [app length] in Hleft. rewrite Hleft.
  pose proof (positional_single_move_right_correct [b] mid [] a) as Hright.
  cbn [app length] in Hright. rewrite !app_nil_r in Hright.
  exact Hright.
Qed.
References
✓ No axioms

Two Move edits swap the first and last elements of a :: mid ++ [b] inside P ++ (a :: mid ++ [b]) ++ Sfx (Positional.fs).

Arguments

P : list A
common prefix slice.
mid : list A
interior elements unchanged by the endpoint swap.
Sfx : list A
common suffix slice.
a : A
original first element of the trimmed middle slice.
b : A
original last element of the trimmed middle slice.
Theorem positional_distant_swap_correct {A : Type} (P mid Sfx : list A) (a b : A) :
  apply_pos_edits (P ++ (a :: mid ++ [b]) ++ Sfx)
    [PosMove (length P + S (length mid)) (length P);
     PosMove (length P + 1) (length P + S (length mid))] =
  Some (P ++ (b :: mid ++ [a]) ++ Sfx).

Arguments

P : list A
common prefix slice.
mid : list A
interior elements unchanged by the endpoint swap.
Sfx : list A
common suffix slice.
a : A
original first element of the trimmed middle slice.
b : A
original last element of the trimmed middle slice.
Qed
Proof.
  pose proof (positional_frame_prefix_suffix P (a :: mid ++ [b]) (b :: mid ++ [a]) Sfx
                [PosMove (S (length mid)) 0; PosMove 1 (S (length mid))]
                (apply_distant_swap_mid mid a b)) as Hframe.
  simpl in Hframe. rewrite Nat.add_0_r in Hframe. exact Hframe.
Qed.
References

7. AsObservableCollection O(Delta) value patching

Definition oc_patch_step {K V : Type} `{Countable K, EqDecision V}
    (index_of : gmap K nat) (cur_val : K -> V) (items : list V) (kc : K * key_change) : list V :=
  match kc.2 with
  | KcChanged | KcReplaced =>
      match index_of !! kc.1 with
      | Some idx =>
          match items !! idx with
          | Some prev => if decide (prev = cur_val kc.1) then items else <[idx := cur_val kc.1]> items
          | None => items
          end
      | None => items
      end
  | _ => items
  end.
References

Uses

3 more
  • decide
  • Countable
  • gmap
Lemma oc_patch_step_length {K V : Type} `{Countable K, EqDecision V}
    (index_of : gmap K nat) (cur_val : K -> V) (items : list V) (kc : K * key_change) :
  length (oc_patch_step index_of cur_val items kc) = length items.
Qed
Proof.
  unfold oc_patch_step.
  destruct (kc.2); try reflexivity;
    destruct (index_of !! kc.1) as [idx|]; try reflexivity;
    destruct (items !! idx) as [prev|]; try reflexivity;
    destruct (decide (prev = cur_val kc.1)); try reflexivity;
    apply length_insert.
Qed.
References

Uses

2 more
  • gmap
  • list.length_insert
Lemma oc_patch_step_preserves {K V : Type} `{Countable K, EqDecision V}
    (visible : list K) (index_of : gmap K nat) (cur_val : K -> V)
    (items : list V) (kc : K * key_change) (i : nat) (k : K) :
  (forall j x, visible !! j = Some x <-> index_of !! x = Some j) ->
  visible !! i = Some k ->
  items !! i = Some (cur_val k) ->
  oc_patch_step index_of cur_val items kc !! i = Some (cur_val k).
Qed
Proof.
  intros Hinv Hvis Hcur.
  unfold oc_patch_step.
  destruct (kc.2); try exact Hcur;
    destruct (index_of !! kc.1) as [idx|] eqn:Hidx; try exact Hcur;
    destruct (items !! idx) as [prev|] eqn:Hprev; try exact Hcur;
    destruct (decide (prev = cur_val kc.1)) as [->|Hne]; try exact Hcur;
    (destruct (decide (idx = i)) as [->|Hnei];
      [assert (Heqk : kc.1 = k)
        by (pose proof (proj2 (Hinv i kc.1) Hidx) as Hvi; congruence);
       rewrite Heqk; rewrite list_lookup_insert_eq;
       [reflexivity | eapply lookup_lt_Some; exact Hcur]
      |rewrite list_lookup_insert_ne; [exact Hcur | lia]]).
Qed.
References

Uses

5 more
  • Countable
  • gmap
  • list.list_lookup_insert_eq
  • list.list_lookup_insert_ne
  • list.lookup_lt_Some
Lemma oc_patch_step_updates {K V : Type} `{Countable K, EqDecision V}
    (visible : list K) (index_of : gmap K nat) (cur_val : K -> V)
    (items : list V) (k : K) (c : key_change) (i : nat) :
  (forall j x, visible !! j = Some x <-> index_of !! x = Some j) ->
  visible !! i = Some k ->
  length items = length visible ->
  c = KcChanged \/ c = KcReplaced ->
  oc_patch_step index_of cur_val items (k, c) !! i = Some (cur_val k).
Qed
Proof.
  intros Hinv Hvis Hlen Hc.
  assert (Hidx : index_of !! k = Some i) by (apply Hinv; exact Hvis).
  assert (Hlt : i < length items) by (rewrite Hlen; eapply lookup_lt_Some; exact Hvis).
  destruct (lookup_lt_is_Some_2 items i Hlt) as [prev Hprev].
  unfold oc_patch_step; simpl.
  destruct Hc as [->| ->]; rewrite Hidx, Hprev;
    destruct (decide (prev = cur_val k)) as [->|Hne];
    [exact Hprev
    |rewrite list_lookup_insert_eq; [reflexivity | exact Hlt]
    |exact Hprev
    |rewrite list_lookup_insert_eq; [reflexivity | exact Hlt]].
Qed.
References

Uses

7 more
  • EqDecision
  • decide
  • Countable
  • gmap
  • list.list_lookup_insert_eq
  • list.lookup_lt_Some
  • list.lookup_lt_is_Some_2
Lemma oc_patch_fold_inv {K V : Type} `{Countable K, EqDecision V}
    (visible : list K) (index_of : gmap K nat) (cur_val : K -> V)
    (pairs : list (K * key_change)) (items : list V) :
  (forall j x, visible !! j = Some x <-> index_of !! x = Some j) ->
  length items = length visible ->
  (forall i k, visible !! i = Some k ->
    items !! i = Some (cur_val k) \/ (k, KcChanged) ∈ pairs \/ (k, KcReplaced) ∈ pairs) ->
  let res := foldl (oc_patch_step index_of cur_val) items pairs in
  length res = length visible /\
  forall i k, visible !! i = Some k -> res !! i = Some (cur_val k).
Qed
Proof.
  revert items.
  induction pairs as [|kc rest IH]; intros items Hinv Hlen Hcover; simpl.
  - split; [exact Hlen|].
    intros i k Hvis.
    destruct (Hcover i k Hvis) as [Hcur | [Hin | Hin]];
      [exact Hcur | inversion Hin | inversion Hin].
  - apply IH; [exact Hinv | rewrite oc_patch_step_length; exact Hlen |].
    intros i k Hvis.
    destruct (Hcover i k Hvis) as [Hcur | [Hin | Hin]].
    + left. eapply oc_patch_step_preserves; eauto.
    + apply elem_of_cons in Hin as [<- | Hrest].
      * left. eapply oc_patch_step_updates; eauto.
      * right. left. exact Hrest.
    + apply elem_of_cons in Hin as [<- | Hrest].
      * left. eapply oc_patch_step_updates; eauto.
      * right. right. exact Hrest.
Qed.
References

Uses

8 more
  • length
  • list
  • nat
  • EqDecision
  • Countable
  • gmap
  • list.elem_of_cons
  • list.foldl
✓ No axioms

On any non-reset ProjectionDelta, patching view only over delta.Changes entries with KcChanged or KcReplaced yields the exact same sequence as scanning all 0 .. length visible - 1 visible elements (Projections.fs).

Arguments

visible : list K
settled visible key order after applying structural positional edits.
index_of : gmap K nat
inverse map sending each key in visible to its index.
cur_val : K -> V
settled value lookup per visible key.
items : list V
current ObservableCollection items prior to value patching.
pairs : list (K * key_change)
delta.Changes key-change pairs.
Theorem observable_collection_delta_value_patch_refines_scan
    {K V : Type} `{Countable K, EqDecision V}
    (visible : list K) (index_of : gmap K nat) (cur_val : K -> V)
    (items : list V) (pairs : list (K * key_change)) :
  (forall j x, visible !! j = Some x <-> index_of !! x = Some j) ->
  length items = length visible ->
  (forall i k, visible !! i = Some k ->
    items !! i = Some (cur_val k) \/ (k, KcChanged) ∈ pairs \/ (k, KcReplaced) ∈ pairs) ->
  foldl (oc_patch_step index_of cur_val) items pairs = cur_val <$> visible.

Arguments

visible : list K
settled visible key order after applying structural positional edits.
index_of : gmap K nat
inverse map sending each key in visible to its index.
cur_val : K -> V
settled value lookup per visible key.
items : list V
current ObservableCollection items prior to value patching.
pairs : list (K * key_change)
delta.Changes key-change pairs.
Qed
Proof.
  intros Hinv Hlen Hcover.
  pose proof (oc_patch_fold_inv visible index_of cur_val pairs items Hinv Hlen Hcover)
    as [Hlen_res Hlook].
  apply list_eq. intros i.
  rewrite list_lookup_fmap.
  destruct (visible !! i) as [k|] eqn:Hvis.
  - simpl. apply (Hlook i k Hvis).
  - simpl. apply lookup_ge_None_2.
    rewrite Hlen_res. apply lookup_ge_None_1. exact Hvis.
Qed.
References

Uses

9 more
  • nat
  • EqDecision
  • Countable
  • gmap
  • list.foldl
  • list.list_eq
  • list.lookup_ge_None_1
  • list.lookup_ge_None_2
  • list.list_lookup_fmap
Definition small_slot (keys : list nat) (k : nat) :=
  match keys with
  | [] => 0
  | a :: tail => if decide (a = k) then 1 else
      match tail with b :: _ => if decide (b = k) then 2 else 0 | [] => 0 end
  end.
References

Uses

  • list
  • nat
  • decide
✓ No axioms

A one-based small slot retrieves exactly the change stored in the abstract map.

Theorem small_slot_refines_changes (pairs : list (nat * key_change)) k :
  length pairs <= 2 ->
  match small_slot (fst <$> pairs) k with
  | 0 => None
  | S index => snd <$> (pairs !! index)
  end = (list_to_map pairs : gmap nat key_change) !! k.
Qed
Proof.
  destruct pairs as [|[a x] [|[b y] [|p rest]]]; simpl; intros;
    try lia; repeat case_decide; simplify_eq;
    repeat (rewrite lookup_insert || rewrite lookup_insert_ne by congruence);
    repeat case_decide; simplify_eq; reflexivity.
Qed.
References

Uses

5 more
  • snd
  • list_to_map
  • lookup_insert
  • lookup_insert_ne
  • gmap
✓ No axioms

Scanning the first two keys agrees with their promoted one-based slots.

Theorem small_slot_promotion a b c k :
  a <> b -> a <> c -> b <> c ->
  let slots := (<[c:=3]> (<[b:=2]> (<[a:=1]> ∅)) : gmap nat nat) in
  default 0 (slots !! k) =
    (if decide (c = k) then 3 else small_slot [a;b] k).
Qed
Proof.
  intros Hab Hac Hbc. simpl. unfold small_slot.
  repeat case_decide; subst; simplify_eq;
    repeat (rewrite lookup_insert || rewrite lookup_insert_ne by congruence);
    repeat case_decide; simplify_eq; reflexivity.
Qed.
References

Uses

  • small_slot
  • nat
  • decide
  • lookup_insert
  • lookup_insert_ne
  • gmap
  • default
✓ No axioms

Cancelling the first unpromoted key moves the last key to slot one.

Theorem small_slot_swap_remove a b k :
  a <> b -> small_slot [b] k =
    (if decide (k = a) then 0 else if decide (k = b) then 1 else 0).
Qed
Proof. intros. unfold small_slot. repeat case_decide; congruence. Qed.
References

Uses

Fixpoint survivor_ranks (raw : list nat) :=
  match raw with
  | [] => []
  | 0 :: rest => survivor_ranks rest
  | S t :: rest => t :: survivor_ranks rest
  end.
References

Uses

  • S
  • list
  • nat

The gap holds consumed cells between the write cursor and the unread suffix.

Fixpoint compact_cells (gap raw : list nat) : list nat :=
  match raw with
  | [] => gap
  | 0 :: rest => compact_cells (gap ++ [0]) rest
  | S t :: rest => t :: compact_cells (tl (gap ++ [S t])) rest
  end.
References

Uses

  • S
  • list
  • nat
  • tl
✓ No axioms

The compacted array prefix contains the zero-based survivor ranks in read order.

Theorem compact_survivor_prefix raw gap :
  take (length (survivor_ranks raw)) (compact_cells gap raw) = survivor_ranks raw.
Qed
Proof.
  revert gap. induction raw as [|[|t] rest IH]; intros gap; simpl;
    [reflexivity | apply IH | f_equal; apply IH].
Qed.
References

Uses