` and +`ProfiledDictionaryContainer
` bind them when a user-facing typed boundary +is desired. + +Legacy names such as `DynamicDawgChar` remain source-compatible. New code can +use the generic core (`DynamicDawgGeneric`) and provide a profile witness +with `profile_descriptor::
()`. Specialized UTF-8 and ULEB128 wrappers are
+appropriate when they improve ergonomics or enforce validation at the boundary.
+
+## Internalization and vocabulary IDs
+
+Interned dictionaries map logical atoms to dense local IDs and store sequences of
+those IDs. The mapping, profile descriptor, vocabulary generation, and snapshot
+identity travel together. IDs are capsule-local compression handles; they are
+not stable public identities and must never be interpreted without the matching
+vocabulary metadata.
+
+## Consumer contract
+
+Consumers should request logical traversal APIs or profile-aware zippers. They
+must not inspect physical codec nodes as semantic transitions. A serialized
+dictionary is readable only when its topology, profile identity, and vocabulary
+metadata validate together. This keeps backend substitution observationally
+equivalent even when one implementation stores bytes and another stores native
+logical units.
diff --git a/docs/architecture/optimization-roadmap.md b/docs/architecture/optimization-roadmap.md
index 0f2a027d..20ea2b26 100644
--- a/docs/architecture/optimization-roadmap.md
+++ b/docs/architecture/optimization-roadmap.md
@@ -100,7 +100,7 @@ Unicode node stays sorted or sparse-indexed.
| Decision | Consequence |
|----------|-------------|
-| Volatile mutable dictionaries use internal synchronization. | Public callers do not need an outer `RwLock` for `DynamicDawg`, `PathMapDictionary`, `SuffixAutomaton`, `Scdawg`, or `BijectiveMap`. |
+| Volatile mutable dictionaries own their publication/synchronization policy. | Public callers do not need an outer `RwLock` for `DynamicDawg`, `PathMapDictionary`, `SuffixAutomaton`, `Scdawg`, or `BijectiveMap`; `PathMapDictionary` uses immutable-root ArcSwap publication. |
| Reader handles and zippers carry stable snapshots. | Compaction and mutation cannot invalidate traversal state. |
| Writers use CAS publication or per-node atomic edge/value replacement. | Contended writers may retry, but readers do not block behind writers. |
| Static backends keep compact array layouts. | Lookup and traversal stay cache-local for read-heavy dictionaries. |
diff --git a/docs/diagrams/eviction-pipeline.svg b/docs/diagrams/eviction-pipeline.svg
index 7a66516e..0776de97 100644
--- a/docs/diagrams/eviction-pipeline.svg
+++ b/docs/diagrams/eviction-pipeline.svg
@@ -1 +1 @@
-
\ No newline at end of file
+
\ No newline at end of file
diff --git a/docs/integration/pathmap/README.md b/docs/integration/pathmap/README.md
index 6d68505e..1e700bb4 100644
--- a/docs/integration/pathmap/README.md
+++ b/docs/integration/pathmap/README.md
@@ -832,7 +832,8 @@ Where:
### Concurrent Access
-PathMap supports concurrent reads via memory mapping:
+The adapter supports concurrent reads by loading immutable roots; a retained
+snapshot is independent of later publications:
```rust
use std::sync::Arc;
@@ -966,8 +967,10 @@ On 32-bit systems, use file-based PathMap instead of mmap.
**Issue**: Concurrent write conflicts
```
-Solution: PathMap supports concurrent reads but single writer.
-Use write locks or process-level coordination for updates.
+Solution: `PathMapDictionary` clones a persistent root and CAS-publishes the
+candidate. Competing writers retry against the winning root; callers do not add
+an outer write lock. A successful mutation is visible to later root loads,
+while retained snapshots intentionally remain on their captured revision.
```
---
diff --git a/formal-verification/Cargo.toml b/formal-verification/Cargo.toml
new file mode 100644
index 00000000..e762415b
--- /dev/null
+++ b/formal-verification/Cargo.toml
@@ -0,0 +1,15 @@
+[package]
+name = "libdictenstein-variable-width-harness"
+version = "0.1.0"
+edition = "2021"
+publish = false
+rust-version = "1.95"
+
+[dev-dependencies]
+proptest = "1.11"
+
+[[test]]
+name = "variable_width_formal_harness"
+path = "../tests/variable_width_formal_harness.rs"
+
+[workspace]
diff --git a/formal-verification/rocq/Makefile b/formal-verification/rocq/Makefile
index 53d8e3f7..b700661b 100644
--- a/formal-verification/rocq/Makefile
+++ b/formal-verification/rocq/Makefile
@@ -10,7 +10,7 @@ COQFLAGS = -Q . ARTrie
DIRS = Spec Model Invariants Operations Proofs
# Source files in dependency order
-SPEC_FILES = Spec/MapSpec.v Spec/DictionaryLawSpec.v Spec/DynamicDawgMutationSpec.v Spec/DynamicDawgU64Spec.v Spec/PersistentARTrieU64Spec.v Spec/DoubleArrayTrieSpec.v Spec/ZipperLanguageSpec.v Spec/ValuedSetCombinatorSpec.v Spec/BloomFilterSpec.v Spec/PersistentMergeSpec.v Spec/PersistentPrefixSpec.v Spec/PersistentReadTraversalSpec.v Spec/PersistentSuffixAutomatonSpec.v Spec/PersistentScdawgSpec.v Spec/PersistentCharNodeLayoutSpec.v Spec/PathMapFactorySpec.v Spec/PathMapSnapshotSpec.v Spec/RelativeEncodingSpec.v Spec/ArenaReservationSpec.v Spec/DedupArenaSpec.v Spec/RootDescriptorReopenSpec.v Spec/PersistentLazyMutationSpec.v Spec/PersistentWalAtomicitySpec.v Spec/LockFreeCounterMergeSpec.v Spec/OverlayReestablishSpec.v Spec/SharedPersistentConcurrencySpec.v Spec/PublicDurabilityPolicySpec.v Spec/PersistentPublicWalLifecycleSpec.v Spec/PersistentEndToEndTraceSpec.v Spec/PersistentVocabWalAtomicitySpec.v Spec/PersistentVocabCheckpointSpec.v Spec/PersistentCheckpointRetentionSpec.v Spec/PersistentDirtyCheckpointSpec.v Spec/PersistentWalSegmentLifecycleSpec.v Spec/PersistentRecoveryPlannerSpec.v Spec/PersistentRecoveryReplayCompletenessSpec.v Spec/PersistentCompactionSpec.v Spec/PersistentRewriteCompactionSpec.v Spec/SubstringSearchSpec.v Spec/ScdawgOccurrenceSpec.v Spec/FuzzyCandidateCoverageSpec.v Spec/SerializationRoundtripSpec.v Spec/OverlayArborescenceSerializationSpec.v Spec/ARTrieSpec.v Spec/ReplicatedMapSpec.v Spec/PersistentCharEvictionRegistrySpec.v Spec/EvictionExactRootPublicationSpec.v Spec/HelpedRootResidencySpec.v Spec/PackedResidencyRefinementSpec.v Spec/HelpedCheckpointStampSpec.v Spec/DetachedCallbackSeparationSpec.v Spec/ResidentBudgetEvictionSpec.v Spec/OverlayFaultProvenanceSpec.v Spec/DictionaryNodeReopenTraversalSpec.v Spec/PersistentCharEpochReclamationSpec.v Spec/CharV3TypeEncodingSpec.v Spec/ApiFeatureVisibilitySpec.v Spec/TlcDiagnosticClassifierSpec.v Spec/OverlayDenseCodecSpec.v Spec/AbiTraversalSnapshotSpec.v Spec/AbiPagingProducerSpec.v Spec/AbiStatusMappingSpec.v Spec/AbiDictionaryAlgebraSpec.v
+SPEC_FILES = Spec/MapSpec.v Spec/DictionaryLawSpec.v Spec/DynamicDawgMutationSpec.v Spec/DynamicDawgU64Spec.v Spec/VariableWidthCodecSpec.v Spec/VariableWidthInterningSpec.v Spec/VariableWidthFamilyRefinementSpec.v Spec/PersistentARTrieU64Spec.v Spec/DoubleArrayTrieSpec.v Spec/ZipperLanguageSpec.v Spec/ValuedSetCombinatorSpec.v Spec/BloomFilterSpec.v Spec/PersistentMergeSpec.v Spec/PersistentPrefixSpec.v Spec/PersistentReadTraversalSpec.v Spec/PersistentSuffixAutomatonSpec.v Spec/PersistentScdawgSpec.v Spec/PersistentCharNodeLayoutSpec.v Spec/PathMapFactorySpec.v Spec/PathMapSnapshotSpec.v Spec/RelativeEncodingSpec.v Spec/ArenaReservationSpec.v Spec/DedupArenaSpec.v Spec/RootDescriptorReopenSpec.v Spec/PersistentLazyMutationSpec.v Spec/PersistentWalAtomicitySpec.v Spec/LockFreeCounterMergeSpec.v Spec/OverlayReestablishSpec.v Spec/SharedPersistentConcurrencySpec.v Spec/PublicDurabilityPolicySpec.v Spec/PersistentPublicWalLifecycleSpec.v Spec/PersistentEndToEndTraceSpec.v Spec/PersistentVocabWalAtomicitySpec.v Spec/PersistentVocabCheckpointSpec.v Spec/PersistentCheckpointRetentionSpec.v Spec/PersistentDirtyCheckpointSpec.v Spec/PersistentWalSegmentLifecycleSpec.v Spec/PersistentRecoveryPlannerSpec.v Spec/PersistentRecoveryReplayCompletenessSpec.v Spec/PersistentCompactionSpec.v Spec/PersistentRewriteCompactionSpec.v Spec/SubstringSearchSpec.v Spec/ScdawgOccurrenceSpec.v Spec/FuzzyCandidateCoverageSpec.v Spec/SerializationRoundtripSpec.v Spec/OverlayArborescenceSerializationSpec.v Spec/ARTrieSpec.v Spec/ReplicatedMapSpec.v Spec/PersistentCharEvictionRegistrySpec.v Spec/EvictionExactRootPublicationSpec.v Spec/HelpedRootResidencySpec.v Spec/PackedResidencyRefinementSpec.v Spec/HelpedCheckpointStampSpec.v Spec/DetachedCallbackSeparationSpec.v Spec/ResidentBudgetEvictionSpec.v Spec/OverlayFaultProvenanceSpec.v Spec/DictionaryNodeReopenTraversalSpec.v Spec/PersistentCharEpochReclamationSpec.v Spec/CharV3TypeEncodingSpec.v Spec/ApiFeatureVisibilitySpec.v Spec/TlcDiagnosticClassifierSpec.v Spec/OverlayDenseCodecSpec.v Spec/AbiTraversalSnapshotSpec.v Spec/AbiPagingProducerSpec.v Spec/AbiStatusMappingSpec.v Spec/AbiDictionaryAlgebraSpec.v
MODEL_FILES = Model/ListCompat.v Model/Key.v Model/NodeTypes.v Model/Bucket.v Model/HotStuff.v Model/PathCompression.v Model/PrefixChunking.v Model/ArenaManager.v Model/SequentialSiblings.v Model/FileSystem.v
INVARIANT_FILES = Invariants/StructuralInvariants.v Invariants/TransitionInvariants.v Invariants/ArenaInvariants.v Invariants/SequentialSiblingsInvariants.v
OPERATION_FILES = # Operations/Lookup.v Operations/Insert.v Operations/Delete.v
@@ -51,8 +51,10 @@ clean:
# Build with resource limits (for memory-intensive proofs)
# Per CLAUDE.md recommendations
build-safe:
- systemd-run --user --scope -p MemoryMax=32G -p CPUQuota=1800% \
- -p IOWeight=30 -p TasksMax=200 $(MAKE) -j1
+ systemd-run --user --unit=libdictenstein-rocq-build-$$$$ \
+ --wait --pipe --quiet --collect --working-directory=$(CURDIR) \
+ -p MemoryHigh=1G -p MemoryMax=2G -p MemorySwapMax=0 \
+ -p CPUQuota=200% -p IOWeight=30 -p TasksMax=64 $(MAKE) -j1
# Display build order
show-order:
diff --git a/formal-verification/rocq/Spec/PersistentARTrieU64Spec.v b/formal-verification/rocq/Spec/PersistentARTrieU64Spec.v
index a852433c..19be351d 100644
--- a/formal-verification/rocq/Spec/PersistentARTrieU64Spec.v
+++ b/formal-verification/rocq/Spec/PersistentARTrieU64Spec.v
@@ -245,7 +245,7 @@ Proof.
pose proof
(@NoDup_incl_length nat (map fst frames) (seq 0 node_count)
Hunique Hincl) as Hlength.
- rewrite length_map, seq_length_portable in Hlength.
+ rewrite map_length, seq_length_portable in Hlength.
exact Hlength.
Qed.
diff --git a/formal-verification/rocq/Spec/SerializationRoundtripSpec.v b/formal-verification/rocq/Spec/SerializationRoundtripSpec.v
index 8e2e01a8..1b5fa40d 100644
--- a/formal-verification/rocq/Spec/SerializationRoundtripSpec.v
+++ b/formal-verification/rocq/Spec/SerializationRoundtripSpec.v
@@ -1439,7 +1439,7 @@ Proof.
intros first later pending direct resulting_pending Hscheduled.
cbn [tail_child_schedule] in Hscheduled.
inversion Hscheduled; subst.
- rewrite app_length_portable, length_rev.
+ rewrite app_length_portable, rev_length.
reflexivity.
Qed.
@@ -1536,7 +1536,7 @@ Proof.
lia.
- unfold bounded_tail_child_schedule, counted_batch_capacity.
simpl.
- rewrite app_length_portable, length_rev.
+ rewrite app_length_portable, rev_length.
apply Nat.add_le_mono_l.
apply firstn_le_length.
Qed.
diff --git a/formal-verification/rocq/Spec/VariableWidthCodecSpec.v b/formal-verification/rocq/Spec/VariableWidthCodecSpec.v
new file mode 100644
index 00000000..3ad94230
--- /dev/null
+++ b/formal-verification/rocq/Spec/VariableWidthCodecSpec.v
@@ -0,0 +1,2524 @@
+(** * Variable-width codec and logical-transition laws
+
+ This module fixes the representation-independent contract for dictionary
+ profiles before a Rust codec is introduced. Variable-width bytes are a
+ storage grammar only. A dictionary transition observed by a language
+ consumer denotes exactly one logical atom.
+
+ Canonical ULEB128 is modeled as an arbitrary-length, little-endian sequence
+ of seven-bit digits. Rocq naturals are unbounded, so no theorem silently
+ restricts a value to a Rust primitive. UTF-8 codewords are canonical
+ encodings of Unicode scalar values. Direct profiles expose a single fixed
+ unit. F64Bits preserves raw IEEE-754 bit identity and orders those bits by
+ the monotone key used by Rust's total_cmp rather than numeric equality.
+
+ Stable theorem names beginning with [VWENC_] are machine-readable invariant
+ IDs. The
+ conformance ledger and property tests consume these exact identifiers.
+*)
+
+From Coq Require Import Arith Bool Lia List PeanoNat.
+Require Import ARTrie.Spec.DynamicDawgMutationSpec.
+Require Import ARTrie.Spec.DynamicDawgU64Spec.
+Import ListNotations.
+
+Module VariableWidthCodecSpec.
+
+(** ** Canonical arbitrary-width ULEB128 *)
+
+Definition PhysicalByte := nat.
+Definition UlebDigit := nat.
+
+Definition valid_byte (byte : PhysicalByte) : Prop := byte < 256.
+Definition valid_uleb_digit (digit : UlebDigit) : Prop := digit < 128.
+
+Fixpoint encode_uleb_digits (digits : list UlebDigit) : list PhysicalByte :=
+ match digits with
+ | [] => []
+ | [digit] => [digit]
+ | digit :: rest => (128 + digit) :: encode_uleb_digits rest
+ end.
+
+Definition uleb_payload (byte : PhysicalByte) : UlebDigit := byte mod 128.
+Definition decode_uleb_payloads (bytes : list PhysicalByte) : list UlebDigit :=
+ map uleb_payload bytes.
+
+(** Every non-final byte continues; the final byte terminates. *)
+Inductive uleb_continuation_shape : list PhysicalByte -> Prop :=
+| UlebShapeLast : forall byte,
+ byte < 128 ->
+ uleb_continuation_shape [byte]
+| UlebShapeMore : forall byte rest,
+ 128 <= byte ->
+ byte < 256 ->
+ uleb_continuation_shape rest ->
+ uleb_continuation_shape (byte :: rest).
+
+(** A multi-byte zero high digit is an overlong spelling. The singleton zero
+ remains the canonical spelling of logical zero. *)
+Definition canonical_uleb_digits (digits : list UlebDigit) : Prop :=
+ digits <> [] /\
+ Forall valid_uleb_digit digits /\
+ (2 <= length digits -> last digits 0 <> 0).
+
+Definition canonical_uleb_codeword (bytes : list PhysicalByte) : Prop :=
+ uleb_continuation_shape bytes /\
+ canonical_uleb_digits (decode_uleb_payloads bytes).
+
+Lemma uleb_terminal_payload_identity :
+ forall digit, valid_uleb_digit digit -> uleb_payload digit = digit.
+Proof.
+ intros digit Hdigit.
+ unfold valid_uleb_digit, uleb_payload in *.
+ apply Nat.mod_small. exact Hdigit.
+Qed.
+
+Lemma uleb_continuing_payload_identity :
+ forall digit,
+ valid_uleb_digit digit -> uleb_payload (128 + digit) = digit.
+Proof.
+ intros digit Hdigit.
+ unfold valid_uleb_digit, uleb_payload in *.
+ replace (128 + digit) with (digit + 128) by lia.
+ rewrite Nat.Div0.add_mod by lia.
+ rewrite Nat.Div0.mod_same by lia.
+ rewrite Nat.add_0_r.
+ rewrite Nat.Div0.mod_mod by lia.
+ apply Nat.mod_small. exact Hdigit.
+Qed.
+
+Theorem VWENC_01_ULEB_PAYLOAD_ROUNDTRIP :
+ forall digits,
+ Forall valid_uleb_digit digits ->
+ decode_uleb_payloads (encode_uleb_digits digits) = digits.
+Proof.
+ induction digits as [| digit rest IH]; intros Hvalid.
+ - reflexivity.
+ - inversion Hvalid as [| ? ? Hdigit Hrest]; subst.
+ destruct rest as [| next tail].
+ + change ([uleb_payload digit] = [digit]).
+ rewrite uleb_terminal_payload_identity by exact Hdigit.
+ reflexivity.
+ + change
+ (uleb_payload (128 + digit) ::
+ decode_uleb_payloads (encode_uleb_digits (next :: tail)) =
+ digit :: next :: tail).
+ rewrite uleb_continuing_payload_identity by exact Hdigit.
+ f_equal. apply IH. exact Hrest.
+Qed.
+
+Theorem VWENC_88_ULEB_CANONICAL_DIGIT_ENCODER_IS_INJECTIVE :
+ forall left right,
+ Forall valid_uleb_digit left ->
+ Forall valid_uleb_digit right ->
+ encode_uleb_digits left = encode_uleb_digits right ->
+ left = right.
+Proof.
+ intros left right Hleft Hright Hencoded.
+ apply (f_equal decode_uleb_payloads) in Hencoded.
+ rewrite (VWENC_01_ULEB_PAYLOAD_ROUNDTRIP left Hleft) in Hencoded.
+ rewrite (VWENC_01_ULEB_PAYLOAD_ROUNDTRIP right Hright) in Hencoded.
+ exact Hencoded.
+Qed.
+
+Lemma encode_uleb_has_continuation_shape :
+ forall digits,
+ digits <> [] ->
+ Forall valid_uleb_digit digits ->
+ uleb_continuation_shape (encode_uleb_digits digits).
+Proof.
+ induction digits as [| digit rest IH]; intros Hnonempty Hvalid.
+ - contradiction.
+ - inversion Hvalid as [| ? ? Hdigit Hrest]; subst.
+ unfold valid_uleb_digit in Hdigit.
+ destruct rest as [| next tail].
+ + simpl. constructor. exact Hdigit.
+ + simpl. apply UlebShapeMore; [lia | lia |].
+ apply IH; [discriminate | exact Hrest].
+Qed.
+
+Theorem VWENC_02_ULEB_CANONICAL_ENCODE :
+ forall digits,
+ canonical_uleb_digits digits ->
+ canonical_uleb_codeword (encode_uleb_digits digits).
+Proof.
+ intros digits Hcanonical.
+ destruct Hcanonical as [Hnonempty [Hvalid Hminimal]].
+ split.
+ - apply encode_uleb_has_continuation_shape; assumption.
+ - unfold canonical_uleb_digits.
+ rewrite VWENC_01_ULEB_PAYLOAD_ROUNDTRIP by exact Hvalid.
+ repeat split; assumption.
+Qed.
+
+Theorem VWENC_03_ULEB_CODEWORDS_NONEMPTY :
+ forall bytes, canonical_uleb_codeword bytes -> bytes <> [].
+Proof.
+ intros bytes [Hshape _] ->. inversion Hshape.
+Qed.
+
+Lemma uleb_continuing_byte_payload_identity :
+ forall byte,
+ 128 <= byte -> byte < 256 -> 128 + uleb_payload byte = byte.
+Proof.
+ intros byte Hlower Hupper.
+ assert (exists digit, byte = 128 + digit /\ digit < 128) as
+ [digit [-> Hdigit]].
+ { exists (byte - 128). split; lia. }
+ rewrite uleb_continuing_payload_identity by exact Hdigit.
+ reflexivity.
+Qed.
+
+Lemma decode_uleb_payloads_nonempty :
+ forall bytes,
+ uleb_continuation_shape bytes -> decode_uleb_payloads bytes <> [].
+Proof.
+ intros bytes Hshape.
+ inversion Hshape; discriminate.
+Qed.
+
+Lemma encode_uleb_cons_with_nonempty_tail :
+ forall digit tail,
+ tail <> [] ->
+ encode_uleb_digits (digit :: tail) =
+ (128 + digit) :: encode_uleb_digits tail.
+Proof.
+ intros digit tail Hnonempty.
+ destruct tail; [contradiction | reflexivity].
+Qed.
+
+Lemma uleb_shape_reencodes_payloads :
+ forall bytes,
+ uleb_continuation_shape bytes ->
+ encode_uleb_digits (decode_uleb_payloads bytes) = bytes.
+Proof.
+ intros bytes Hshape.
+ induction Hshape as [byte Hterminal | byte rest Hlower Hupper Hrest IH].
+ - change ([uleb_payload byte] = [byte]).
+ rewrite uleb_terminal_payload_identity by exact Hterminal.
+ reflexivity.
+ - change
+ (encode_uleb_digits
+ (uleb_payload byte :: decode_uleb_payloads rest) =
+ byte :: rest).
+ rewrite encode_uleb_cons_with_nonempty_tail.
+ + rewrite uleb_continuing_byte_payload_identity by assumption.
+ f_equal. exact IH.
+ + apply decode_uleb_payloads_nonempty. exact Hrest.
+Qed.
+
+Theorem VWENC_04_ULEB_UNIQUE_DECODING :
+ forall left right,
+ uleb_continuation_shape left ->
+ uleb_continuation_shape right ->
+ decode_uleb_payloads left = decode_uleb_payloads right ->
+ left = right.
+Proof.
+ intros left right Hleft Hright Hpayloads.
+ rewrite <- (uleb_shape_reencodes_payloads left Hleft).
+ rewrite <- (uleb_shape_reencodes_payloads right Hright).
+ now rewrite Hpayloads.
+Qed.
+
+Lemma uleb_shape_final_byte_terminates :
+ forall bytes default,
+ uleb_continuation_shape bytes -> last bytes default < 128.
+Proof.
+ intros bytes default Hshape.
+ induction Hshape as [byte Hterminal | byte rest Hlower Hupper Hrest IH].
+ - exact Hterminal.
+ - destruct Hrest; simpl; apply IH.
+Qed.
+
+Definition unterminated_uleb (bytes : list PhysicalByte) : Prop :=
+ bytes <> [] /\ 128 <= last bytes 0.
+
+Theorem VWENC_05_ULEB_UNTERMINATED_REJECTED :
+ forall bytes,
+ canonical_uleb_codeword bytes -> ~ unterminated_uleb bytes.
+Proof.
+ intros bytes [Hshape _] [_ Hcontinues].
+ pose proof (uleb_shape_final_byte_terminates bytes 0 Hshape).
+ lia.
+Qed.
+
+Definition overlong_uleb (bytes : list PhysicalByte) : Prop :=
+ 2 <= length bytes /\ last (decode_uleb_payloads bytes) 0 = 0.
+
+Theorem VWENC_06_ULEB_OVERLONG_REJECTED :
+ forall bytes,
+ canonical_uleb_codeword bytes -> ~ overlong_uleb bytes.
+Proof.
+ intros bytes [_ [_ [_ Hminimal]]] [Hlength Hzero].
+ apply Hminimal.
+ - unfold decode_uleb_payloads. rewrite map_length. exact Hlength.
+ - exact Hzero.
+Qed.
+
+Lemma uleb_shape_tail :
+ forall byte rest,
+ rest <> [] ->
+ uleb_continuation_shape (byte :: rest) ->
+ uleb_continuation_shape rest.
+Proof.
+ intros byte rest Hnonempty Hshape.
+ inversion Hshape; subst.
+ - contradiction.
+ - assumption.
+Qed.
+
+Theorem VWENC_07_ULEB_EARLY_TERMINATOR_REJECTED :
+ forall prefix terminal suffix,
+ suffix <> [] ->
+ terminal < 128 ->
+ ~ uleb_continuation_shape (prefix ++ terminal :: suffix).
+Proof.
+ induction prefix as [| byte prefix IH]; intros terminal suffix Hsuffix Hterminal Hshape.
+ - inversion Hshape; subst.
+ + contradiction.
+ + lia.
+ - apply (IH terminal suffix Hsuffix Hterminal).
+ apply (uleb_shape_tail byte (prefix ++ terminal :: suffix)).
+ + destruct prefix; discriminate.
+ + exact Hshape.
+Qed.
+
+Theorem VWENC_08_ULEB_EACH_BYTE_IS_U8 :
+ forall bytes,
+ uleb_continuation_shape bytes -> Forall valid_byte bytes.
+Proof.
+ intros bytes Hshape.
+ induction Hshape as [byte Hterminal | byte rest Hlower Hupper Hrest IH].
+ - constructor; [unfold valid_byte; lia | constructor].
+ - constructor; [exact Hupper | exact IH].
+Qed.
+
+Theorem VWENC_09_ULEB_DECODING_IS_INPUT_BOUNDED :
+ forall bytes,
+ length (decode_uleb_payloads bytes) = length bytes.
+Proof.
+ intros bytes. apply map_length.
+Qed.
+
+Fixpoint byte_sequence_eqb
+ (left right : list PhysicalByte) : bool :=
+ match left, right with
+ | [], [] => true
+ | left_byte :: left_rest, right_byte :: right_rest =>
+ (left_byte =? right_byte) &&
+ byte_sequence_eqb left_rest right_rest
+ | _, _ => false
+ end.
+
+Lemma byte_sequence_eqb_reflects_equality :
+ forall left right,
+ byte_sequence_eqb left right = true <-> left = right.
+Proof.
+ induction left as [| left_byte left_rest IH];
+ destruct right as [| right_byte right_rest]; simpl.
+ - tauto.
+ - split; [discriminate | discriminate].
+ - split; [discriminate | discriminate].
+ - rewrite andb_true_iff, Nat.eqb_eq, IH.
+ split.
+ + intros [-> ->]. reflexivity.
+ + intros Hequal. inversion Hequal. tauto.
+Qed.
+
+Fixpoint uleb_continuation_shapeb
+ (bytes : list PhysicalByte) : bool :=
+ match bytes with
+ | [] => false
+ | [byte] => byte 128
+ | byte :: rest =>
+ (128 <=? byte) && (byte 256) &&
+ uleb_continuation_shapeb rest
+ end.
+
+Lemma uleb_continuation_shapeb_reflects_shape :
+ forall bytes,
+ uleb_continuation_shapeb bytes = true <->
+ uleb_continuation_shape bytes.
+Proof.
+ induction bytes as [| byte rest IH].
+ - simpl. split; [discriminate | intros Hshape; inversion Hshape].
+ - destruct rest as [| next tail].
+ + simpl. rewrite Nat.ltb_lt.
+ split.
+ * intros Hterminal. constructor. exact Hterminal.
+ * intros Hshape.
+ exact (uleb_shape_final_byte_terminates [byte] 0 Hshape).
+ + change
+ (((128 <=? byte) && (byte 256) &&
+ uleb_continuation_shapeb (next :: tail)) = true <->
+ uleb_continuation_shape (byte :: next :: tail)).
+ rewrite !andb_true_iff, Nat.leb_le, Nat.ltb_lt, IH.
+ split.
+ * intros [[Hlower Hupper] Htail].
+ now apply UlebShapeMore.
+ * intros Hshape. inversion Hshape; subst. tauto.
+Qed.
+
+Definition canonical_uleb_minimalb (digits : list UlebDigit) : bool :=
+ (length digits 2) || negb (last digits 0 =? 0).
+
+Lemma canonical_uleb_minimalb_reflects_minimality :
+ forall digits,
+ canonical_uleb_minimalb digits = true <->
+ (2 <= length digits -> last digits 0 <> 0).
+Proof.
+ intros digits.
+ unfold canonical_uleb_minimalb.
+ rewrite orb_true_iff, negb_true_iff, Nat.ltb_lt, Nat.eqb_neq.
+ split.
+ - intros [Hshort | Hlast] Hmultiple; [lia | exact Hlast].
+ - intros Hminimal.
+ destruct (Nat.lt_ge_cases (length digits) 2) as [Hshort | Hmultiple].
+ + now left.
+ + right. apply Hminimal. exact Hmultiple.
+Qed.
+
+Lemma uleb_payloads_are_digits :
+ forall bytes,
+ Forall valid_uleb_digit (decode_uleb_payloads bytes).
+Proof.
+ induction bytes as [| byte rest IH].
+ - constructor.
+ - constructor.
+ + unfold valid_uleb_digit, uleb_payload.
+ apply Nat.mod_upper_bound. lia.
+ + exact IH.
+Qed.
+
+Definition canonical_uleb_codewordb
+ (bytes : list PhysicalByte) : bool :=
+ uleb_continuation_shapeb bytes &&
+ canonical_uleb_minimalb (decode_uleb_payloads bytes).
+
+Theorem VWENC_33_ULEB_CANONICAL_RECOGNIZER_IS_EXACT :
+ forall bytes,
+ canonical_uleb_codewordb bytes = true <->
+ canonical_uleb_codeword bytes.
+Proof.
+ intros bytes.
+ unfold canonical_uleb_codewordb, canonical_uleb_codeword.
+ rewrite andb_true_iff,
+ uleb_continuation_shapeb_reflects_shape,
+ canonical_uleb_minimalb_reflects_minimality.
+ split.
+ - intros [Hshape Hminimal]. split; [exact Hshape |].
+ unfold canonical_uleb_digits.
+ repeat split.
+ + apply decode_uleb_payloads_nonempty. exact Hshape.
+ + apply uleb_payloads_are_digits.
+ + exact Hminimal.
+ - intros [Hshape [_ [_ Hminimal]]]. tauto.
+Qed.
+
+Definition decode_canonical_uleb
+ (bytes : list PhysicalByte) : option (list UlebDigit) :=
+ if canonical_uleb_codewordb bytes
+ then Some (decode_uleb_payloads bytes)
+ else None.
+
+Theorem VWENC_34_ULEB_DECODER_ACCEPTS_EXACTLY_CANONICAL_CODEWORDS :
+ forall bytes,
+ canonical_uleb_codeword bytes <->
+ decode_canonical_uleb bytes = Some (decode_uleb_payloads bytes).
+Proof.
+ intros bytes.
+ unfold decode_canonical_uleb.
+ destruct (canonical_uleb_codewordb bytes) eqn:Hcanonical.
+ - rewrite VWENC_33_ULEB_CANONICAL_RECOGNIZER_IS_EXACT in Hcanonical.
+ tauto.
+ - split.
+ + intros Hcodeword.
+ apply VWENC_33_ULEB_CANONICAL_RECOGNIZER_IS_EXACT in Hcodeword.
+ rewrite Hcodeword in Hcanonical. discriminate.
+ + discriminate.
+Qed.
+
+Theorem VWENC_89_ULEB_DECODER_ROUNDTRIPS_CANONICAL_ENCODER :
+ forall digits,
+ canonical_uleb_digits digits ->
+ decode_canonical_uleb (encode_uleb_digits digits) = Some digits.
+Proof.
+ intros digits Hcanonical.
+ assert (canonical_uleb_codeword (encode_uleb_digits digits))
+ as Hcodeword.
+ { now apply VWENC_02_ULEB_CANONICAL_ENCODE. }
+ apply VWENC_34_ULEB_DECODER_ACCEPTS_EXACTLY_CANONICAL_CODEWORDS
+ in Hcodeword.
+ rewrite Hcodeword.
+ destruct Hcanonical as [Hnonempty [Hvalid Hminimal]].
+ now rewrite VWENC_01_ULEB_PAYLOAD_ROUNDTRIP.
+Qed.
+
+Theorem VWENC_35_ULEB_NONCANONICAL_AND_MALFORMED_INPUT_IS_REJECTED :
+ forall bytes,
+ ~ canonical_uleb_codeword bytes ->
+ decode_canonical_uleb bytes = None.
+Proof.
+ intros bytes Hnoncanonical.
+ unfold decode_canonical_uleb.
+ destruct (canonical_uleb_codewordb bytes) eqn:Hcanonical.
+ - apply VWENC_33_ULEB_CANONICAL_RECOGNIZER_IS_EXACT in Hcanonical.
+ contradiction.
+ - reflexivity.
+Qed.
+
+Theorem VWENC_36_ULEB_ENCODER_HAS_NO_BUILTIN_WIDTH_LIMIT :
+ forall digits,
+ length (encode_uleb_digits digits) = length digits.
+Proof.
+ induction digits as [| digit rest IH].
+ - reflexivity.
+ - destruct rest as [| next tail].
+ + reflexivity.
+ + simpl. f_equal. exact IH.
+Qed.
+
+Fixpoint uleb_value (digits : list UlebDigit) : nat :=
+ match digits with
+ | [] => 0
+ | digit :: rest => digit + 128 * uleb_value rest
+ end.
+
+(** Compare equal-width canonical codewords from their most-significant
+ payloads toward their least-significant payloads. The recursion visits
+ the physical bytes themselves and never materializes a bounded integer or
+ a BigUint. The unequal-list cases make the function total; the public
+ comparator below selects them only after an explicit width comparison. *)
+Fixpoint compare_equal_width_uleb_bytes
+ (left right : list PhysicalByte) : comparison :=
+ match left, right with
+ | [], [] => Eq
+ | [], _ => Lt
+ | _, [] => Gt
+ | left_byte :: left_rest, right_byte :: right_rest =>
+ match compare_equal_width_uleb_bytes left_rest right_rest with
+ | Eq => Nat.compare
+ (uleb_payload left_byte) (uleb_payload right_byte)
+ | Lt => Lt
+ | Gt => Gt
+ end
+ end.
+
+Definition compare_uleb_codewords_structural
+ (left right : list PhysicalByte) : comparison :=
+ match Nat.compare (length left) (length right) with
+ | Eq => compare_equal_width_uleb_bytes left right
+ | Lt => Lt
+ | Gt => Gt
+ end.
+
+(** Reverse-index machine used as the production correspondence. A Rust
+ implementation is a [while remaining != 0] loop over two borrowed slices:
+ decrement [remaining], mask the two indexed bytes, and return at the first
+ difference. It owns one index and one comparison only: O(n) time, O(1)
+ auxiliary state, no allocation, and no call-stack growth. The tail-recursive
+ Rocq evaluator below is a mathematical iterator; it is not an instruction
+ to extract recursive Rust. *)
+Fixpoint compare_equal_width_uleb_reverse_index
+ (remaining : nat)
+ (left right : list PhysicalByte) : comparison :=
+ match remaining with
+ | 0 => Eq
+ | S index =>
+ match Nat.compare
+ (uleb_payload (nth index left 0))
+ (uleb_payload (nth index right 0)) with
+ | Eq => compare_equal_width_uleb_reverse_index index left right
+ | Lt => Lt
+ | Gt => Gt
+ end
+ end.
+
+Lemma compare_reverse_index_cons :
+ forall remaining left_byte left_rest right_byte right_rest,
+ compare_equal_width_uleb_reverse_index
+ (S remaining) (left_byte :: left_rest) (right_byte :: right_rest) =
+ match compare_equal_width_uleb_reverse_index
+ remaining left_rest right_rest with
+ | Eq => Nat.compare
+ (uleb_payload left_byte) (uleb_payload right_byte)
+ | Lt => Lt
+ | Gt => Gt
+ end.
+Proof.
+ induction remaining as [| remaining IH];
+ intros left_byte left_rest right_byte right_rest.
+ - simpl.
+ destruct
+ (Nat.compare (uleb_payload left_byte) (uleb_payload right_byte));
+ reflexivity.
+ - change
+ (match Nat.compare
+ (uleb_payload (nth remaining left_rest 0))
+ (uleb_payload (nth remaining right_rest 0)) with
+ | Eq =>
+ compare_equal_width_uleb_reverse_index
+ (S remaining) (left_byte :: left_rest)
+ (right_byte :: right_rest)
+ | Lt => Lt
+ | Gt => Gt
+ end =
+ match
+ (match Nat.compare
+ (uleb_payload (nth remaining left_rest 0))
+ (uleb_payload (nth remaining right_rest 0)) with
+ | Eq =>
+ compare_equal_width_uleb_reverse_index
+ remaining left_rest right_rest
+ | Lt => Lt
+ | Gt => Gt
+ end)
+ with
+ | Eq => Nat.compare
+ (uleb_payload left_byte) (uleb_payload right_byte)
+ | Lt => Lt
+ | Gt => Gt
+ end).
+ destruct
+ (Nat.compare
+ (uleb_payload (nth remaining left_rest 0))
+ (uleb_payload (nth remaining right_rest 0))) eqn:Hhighest;
+ [apply IH | reflexivity | reflexivity].
+Qed.
+
+Lemma compare_reverse_index_agrees_with_structural :
+ forall left right,
+ length left = length right ->
+ compare_equal_width_uleb_reverse_index (length left) left right =
+ compare_equal_width_uleb_bytes left right.
+Proof.
+ induction left as [| left_byte left_rest IH];
+ destruct right as [| right_byte right_rest];
+ intros Hlength; try discriminate; [reflexivity |].
+ simpl in Hlength. injection Hlength as Hrest_length.
+ change
+ (compare_equal_width_uleb_reverse_index
+ (S (length left_rest)) (left_byte :: left_rest)
+ (right_byte :: right_rest) =
+ match compare_equal_width_uleb_bytes left_rest right_rest with
+ | Eq => Nat.compare
+ (uleb_payload left_byte) (uleb_payload right_byte)
+ | Lt => Lt
+ | Gt => Gt
+ end).
+ rewrite compare_reverse_index_cons.
+ rewrite (IH right_rest Hrest_length).
+ reflexivity.
+Qed.
+
+Definition compare_uleb_codewords
+ (left right : list PhysicalByte) : comparison :=
+ match Nat.compare (length left) (length right) with
+ | Eq => compare_equal_width_uleb_reverse_index (length left) left right
+ | Lt => Lt
+ | Gt => Gt
+ end.
+
+Theorem VWENC_95_REVERSE_INDEX_ULEB_COMPARATOR_REFINES_STRUCTURAL_SPEC :
+ forall left right,
+ compare_uleb_codewords left right =
+ compare_uleb_codewords_structural left right.
+Proof.
+ intros left right.
+ unfold compare_uleb_codewords, compare_uleb_codewords_structural.
+ destruct (Nat.compare (length left) (length right))
+ eqn:Hlength; try reflexivity.
+ apply Nat.compare_eq_iff in Hlength.
+ now apply compare_reverse_index_agrees_with_structural.
+Qed.
+
+Record ReverseIndexMachineState := {
+ reverse_index_remaining : nat;
+ reverse_index_outcome : option comparison;
+}.
+
+Definition reverse_index_machine_step
+ (left right : list PhysicalByte)
+ (state : ReverseIndexMachineState) : ReverseIndexMachineState :=
+ match state.(reverse_index_outcome), state.(reverse_index_remaining) with
+ | Some outcome, _ => state
+ | None, 0 =>
+ {| reverse_index_remaining := 0;
+ reverse_index_outcome := Some Eq |}
+ | None, S index =>
+ match Nat.compare
+ (uleb_payload (nth index left 0))
+ (uleb_payload (nth index right 0)) with
+ | Eq =>
+ {| reverse_index_remaining := index;
+ reverse_index_outcome := None |}
+ | outcome =>
+ {| reverse_index_remaining := index;
+ reverse_index_outcome := Some outcome |}
+ end
+ end.
+
+Theorem VWENC_96_REVERSE_INDEX_MACHINE_PENDING_STEP_STRICTLY_DESCENDS :
+ forall left right remaining next,
+ reverse_index_machine_step left right
+ {| reverse_index_remaining := S remaining;
+ reverse_index_outcome := None |} = next ->
+ reverse_index_remaining next = remaining.
+Proof.
+ intros left right remaining next Hstep.
+ unfold reverse_index_machine_step in Hstep. simpl in Hstep.
+ destruct
+ (Nat.compare
+ (uleb_payload (nth remaining left 0))
+ (uleb_payload (nth remaining right 0)));
+ inversion Hstep; reflexivity.
+Qed.
+
+Lemma compare_equal_width_uleb_bytes_agrees_with_value :
+ forall left right,
+ length left = length right ->
+ compare_equal_width_uleb_bytes left right =
+ Nat.compare
+ (uleb_value (decode_uleb_payloads left))
+ (uleb_value (decode_uleb_payloads right)).
+Proof.
+ induction left as [| left_byte left_rest IH];
+ destruct right as [| right_byte right_rest];
+ intros Hlength; try discriminate; [reflexivity |].
+ simpl in Hlength. injection Hlength as Hrest_length.
+ change
+ (match compare_equal_width_uleb_bytes left_rest right_rest with
+ | Eq => Nat.compare
+ (uleb_payload left_byte) (uleb_payload right_byte)
+ | Lt => Lt
+ | Gt => Gt
+ end =
+ Nat.compare
+ (uleb_payload left_byte +
+ 128 * uleb_value (decode_uleb_payloads left_rest))
+ (uleb_payload right_byte +
+ 128 * uleb_value (decode_uleb_payloads right_rest))).
+ rewrite (IH right_rest Hrest_length).
+ pose proof (Nat.mod_upper_bound left_byte 128 ltac:(lia)) as Hleft_digit.
+ pose proof (Nat.mod_upper_bound right_byte 128 ltac:(lia)) as Hright_digit.
+ unfold uleb_payload in *.
+ destruct
+ (Nat.compare
+ (uleb_value (decode_uleb_payloads left_rest))
+ (uleb_value (decode_uleb_payloads right_rest)))
+ eqn:Htail.
+ - apply Nat.compare_eq_iff in Htail.
+ destruct
+ (Nat.compare (left_byte mod 128) (right_byte mod 128))
+ eqn:Hlow.
+ + apply Nat.compare_eq_iff in Hlow.
+ symmetry. apply Nat.compare_eq_iff. lia.
+ + apply Nat.compare_lt_iff in Hlow.
+ symmetry. apply Nat.compare_lt_iff. lia.
+ + apply Nat.compare_gt_iff in Hlow.
+ symmetry. apply Nat.compare_gt_iff. lia.
+ - apply Nat.compare_lt_iff in Htail.
+ symmetry. apply Nat.compare_lt_iff. nia.
+ - apply Nat.compare_gt_iff in Htail.
+ symmetry. apply Nat.compare_gt_iff. nia.
+Qed.
+
+Lemma uleb_value_below_width :
+ forall digits,
+ Forall valid_uleb_digit digits ->
+ uleb_value digits < 128 ^ length digits.
+Proof.
+ induction digits as [| digit rest IH]; intros Hvalid.
+ - simpl. lia.
+ - inversion Hvalid as [| ? ? Hdigit Hrest]; subst.
+ specialize (IH Hrest).
+ unfold valid_uleb_digit in Hdigit.
+ simpl. nia.
+Qed.
+
+Lemma uleb_value_reaches_highest_place :
+ forall digits,
+ digits <> [] ->
+ Forall valid_uleb_digit digits ->
+ last digits 0 <> 0 ->
+ 128 ^ (length digits - 1) <= uleb_value digits.
+Proof.
+ induction digits as [| digit rest IH];
+ intros Hnonempty Hvalid Hhighest; [contradiction |].
+ inversion Hvalid as [| ? ? Hdigit Hrest]; subst.
+ destruct rest as [| next tail].
+ - simpl in *. unfold valid_uleb_digit in Hdigit. lia.
+ - specialize
+ (IH ltac:(discriminate) Hrest ltac:(simpl in Hhighest; exact Hhighest)).
+ cbn [length] in IH.
+ replace (S (length tail) - 1) with (length tail) in IH by lia.
+ change (128 ^ length tail <= uleb_value (next :: tail)) in IH.
+ change
+ (128 * 128 ^ length tail <=
+ digit + 128 * uleb_value (next :: tail)).
+ nia.
+Qed.
+
+Lemma radix_128_power_monotone :
+ forall lower upper,
+ lower <= upper -> 128 ^ lower <= 128 ^ upper.
+Proof.
+ intros lower upper Hle. revert lower Hle.
+ induction upper as [| upper IH]; intros lower Hle.
+ - assert (lower = 0) by lia. subst. reflexivity.
+ - destruct (Nat.eq_dec lower (S upper)) as [-> | Hneq];
+ [reflexivity |].
+ assert (lower <= upper) as Hlower by lia.
+ specialize (IH lower Hlower).
+ change (128 ^ lower <= 128 * 128 ^ upper).
+ eapply Nat.le_trans; [exact IH |].
+ set (power := 128 ^ upper).
+ change (power <= 128 * power).
+ lia.
+Qed.
+
+Lemma canonical_uleb_shorter_width_has_smaller_value :
+ forall left right,
+ canonical_uleb_digits left ->
+ canonical_uleb_digits right ->
+ length left < length right ->
+ uleb_value left < uleb_value right.
+Proof.
+ intros left right
+ [Hleft_nonempty [Hleft_valid Hleft_minimal]]
+ [Hright_nonempty [Hright_valid Hright_minimal]]
+ Hwidth.
+ pose proof (uleb_value_below_width left Hleft_valid) as Hleft_upper.
+ assert (1 <= length left) as Hleft_positive.
+ { destruct left; [contradiction | simpl; lia]. }
+ assert (2 <= length right) as Hright_multiple by lia.
+ pose proof (Hright_minimal Hright_multiple) as Hright_highest.
+ pose proof
+ (uleb_value_reaches_highest_place
+ right Hright_nonempty Hright_valid Hright_highest)
+ as Hright_lower.
+ pose proof
+ (radix_128_power_monotone
+ (length left) (length right - 1) ltac:(lia))
+ as Hpowers.
+ lia.
+Qed.
+
+Theorem VWENC_10_ULEB_ORDER_IS_LOGICAL_NUMERIC_ORDER :
+ forall left right,
+ canonical_uleb_codeword left ->
+ canonical_uleb_codeword right ->
+ compare_uleb_codewords left right =
+ Nat.compare
+ (uleb_value (decode_uleb_payloads left))
+ (uleb_value (decode_uleb_payloads right)).
+Proof.
+ intros left right [Hleft_shape Hleft_digits]
+ [Hright_shape Hright_digits].
+ unfold compare_uleb_codewords.
+ destruct (Nat.compare (length left) (length right)) eqn:Hwidth.
+ - apply Nat.compare_eq_iff in Hwidth.
+ rewrite compare_reverse_index_agrees_with_structural by exact Hwidth.
+ now apply compare_equal_width_uleb_bytes_agrees_with_value.
+ - apply Nat.compare_lt_iff in Hwidth.
+ symmetry. apply Nat.compare_lt_iff.
+ apply canonical_uleb_shorter_width_has_smaller_value.
+ + exact Hleft_digits.
+ + exact Hright_digits.
+ + unfold decode_uleb_payloads. now rewrite !map_length.
+ - apply Nat.compare_gt_iff in Hwidth.
+ symmetry. apply Nat.compare_gt_iff.
+ apply canonical_uleb_shorter_width_has_smaller_value.
+ + exact Hright_digits.
+ + exact Hleft_digits.
+ + unfold decode_uleb_payloads. now rewrite !map_length.
+Qed.
+
+Lemma compare_equal_width_uleb_bytes_eq_payloads :
+ forall left right,
+ length left = length right ->
+ compare_equal_width_uleb_bytes left right = Eq ->
+ decode_uleb_payloads left = decode_uleb_payloads right.
+Proof.
+ induction left as [| left_byte left_rest IH];
+ destruct right as [| right_byte right_rest];
+ intros Hlength Hcompare; try discriminate; [reflexivity |].
+ simpl in Hlength. injection Hlength as Hrest_length.
+ simpl in Hcompare.
+ destruct
+ (compare_equal_width_uleb_bytes left_rest right_rest)
+ eqn:Hrest_compare; try discriminate.
+ apply Nat.compare_eq_iff in Hcompare.
+ unfold decode_uleb_payloads. simpl.
+ f_equal.
+ - exact Hcompare.
+ - apply IH; assumption.
+Qed.
+
+Theorem VWENC_57_ULEB_COMPARATOR_EQUAL_IFF_CANONICAL_BYTES_EQUAL :
+ forall left right,
+ canonical_uleb_codeword left ->
+ canonical_uleb_codeword right ->
+ (compare_uleb_codewords left right = Eq <-> left = right).
+Proof.
+ intros left right [Hleft_shape Hleft_digits]
+ [Hright_shape Hright_digits].
+ split.
+ - intros Hcompare.
+ unfold compare_uleb_codewords in Hcompare.
+ destruct (Nat.compare (length left) (length right))
+ eqn:Hlength; try discriminate.
+ apply Nat.compare_eq_iff in Hlength.
+ rewrite compare_reverse_index_agrees_with_structural in Hcompare
+ by exact Hlength.
+ apply VWENC_04_ULEB_UNIQUE_DECODING; [exact Hleft_shape | exact Hright_shape |].
+ now apply compare_equal_width_uleb_bytes_eq_payloads.
+ - intros ->.
+ unfold compare_uleb_codewords.
+ rewrite Nat.compare_refl.
+ rewrite compare_reverse_index_agrees_with_structural by reflexivity.
+ rewrite compare_equal_width_uleb_bytes_agrees_with_value by reflexivity.
+ apply Nat.compare_refl.
+Qed.
+
+Theorem VWENC_58_ULEB_CANONICAL_SEMANTIC_VALUE_IS_INJECTIVE :
+ forall left right,
+ canonical_uleb_codeword left ->
+ canonical_uleb_codeword right ->
+ uleb_value (decode_uleb_payloads left) =
+ uleb_value (decode_uleb_payloads right) ->
+ left = right.
+Proof.
+ intros left right Hleft Hright Hvalue.
+ apply (proj1
+ (VWENC_57_ULEB_COMPARATOR_EQUAL_IFF_CANONICAL_BYTES_EQUAL
+ left right Hleft Hright)).
+ rewrite (VWENC_10_ULEB_ORDER_IS_LOGICAL_NUMERIC_ORDER
+ left right Hleft Hright), Hvalue.
+ apply Nat.compare_refl.
+Qed.
+
+Definition uleb_byte_identity
+ (bytes : list PhysicalByte) : list PhysicalByte := bytes.
+
+Definition uleb_hash_material
+ (bytes : list PhysicalByte) : list PhysicalByte := bytes.
+
+Definition uleb_biguint_view (bytes : list PhysicalByte) : nat :=
+ uleb_value (decode_uleb_payloads bytes).
+
+Definition decode_uleb_bounded
+ (exclusive_bound : nat) (bytes : list PhysicalByte) : option nat :=
+ match decode_canonical_uleb bytes with
+ | None => None
+ | Some digits =>
+ let value := uleb_value digits in
+ if value exclusive_bound then Some value else None
+ end.
+
+Theorem VWENC_37_ULEB_EQUALITY_IS_CANONICAL_BYTE_EQUALITY :
+ forall left right,
+ canonical_uleb_codeword left ->
+ canonical_uleb_codeword right ->
+ byte_sequence_eqb left right = true <->
+ uleb_byte_identity left = uleb_byte_identity right.
+Proof.
+ intros left right Hleft Hright.
+ unfold uleb_byte_identity.
+ apply byte_sequence_eqb_reflects_equality.
+Qed.
+
+(** [uleb_hash_material] is collision-free input material, not the output of a
+ finite hash function. Actual hash outputs may collide; consumers rely on
+ equality checks after hash-table bucket selection. *)
+Theorem VWENC_38_ULEB_HASH_MATERIAL_IS_INJECTIVE :
+ forall left right,
+ canonical_uleb_codeword left ->
+ canonical_uleb_codeword right ->
+ uleb_hash_material left = uleb_hash_material right -> left = right.
+Proof. intros left right Hleft Hright Hequal. exact Hequal. Qed.
+
+Theorem VWENC_90_FINITE_HASH_OUTPUT_REQUIRES_ONLY_EQUALITY_CONGRUENCE :
+ forall (finite_hash : list PhysicalByte -> nat) left right,
+ left = right -> finite_hash left = finite_hash right.
+Proof. intros finite_hash left right ->. reflexivity. Qed.
+
+Theorem VWENC_39_ULEB_BIGUINT_VIEW_AGREES_WITH_NUMERIC_ORDER :
+ forall left right,
+ canonical_uleb_codeword left ->
+ canonical_uleb_codeword right ->
+ compare_uleb_codewords left right =
+ Nat.compare (uleb_biguint_view left) (uleb_biguint_view right).
+Proof.
+ intros left right Hleft Hright.
+ unfold uleb_biguint_view.
+ now apply VWENC_10_ULEB_ORDER_IS_LOGICAL_NUMERIC_ORDER.
+Qed.
+
+Theorem VWENC_40_ULEB_BOUNDED_ADAPTER_AGREES_WHEN_REPRESENTABLE :
+ forall exclusive_bound bytes,
+ canonical_uleb_codeword bytes ->
+ uleb_biguint_view bytes < exclusive_bound ->
+ decode_uleb_bounded exclusive_bound bytes =
+ Some (uleb_biguint_view bytes).
+Proof.
+ intros exclusive_bound bytes Hcanonical Hbounded.
+ unfold decode_uleb_bounded, uleb_biguint_view.
+ apply VWENC_34_ULEB_DECODER_ACCEPTS_EXACTLY_CANONICAL_CODEWORDS
+ in Hcanonical.
+ rewrite Hcanonical.
+ unfold uleb_biguint_view in Hbounded.
+ apply Nat.ltb_lt in Hbounded.
+ now rewrite Hbounded.
+Qed.
+
+Theorem VWENC_41_ULEB_BOUNDED_ADAPTER_REJECTS_REPRESENTATION_OVERFLOW :
+ forall exclusive_bound bytes,
+ canonical_uleb_codeword bytes ->
+ exclusive_bound <= uleb_biguint_view bytes ->
+ decode_uleb_bounded exclusive_bound bytes = None.
+Proof.
+ intros exclusive_bound bytes Hcanonical Hoverflow.
+ unfold decode_uleb_bounded, uleb_biguint_view.
+ apply VWENC_34_ULEB_DECODER_ACCEPTS_EXACTLY_CANONICAL_CODEWORDS
+ in Hcanonical.
+ rewrite Hcanonical.
+ unfold uleb_biguint_view in Hoverflow.
+ destruct
+ (uleb_value (decode_uleb_payloads bytes) exclusive_bound)
+ eqn:Hrepresentable.
+ - rewrite Nat.ltb_lt in Hrepresentable. lia.
+ - reflexivity.
+Qed.
+
+(** ** Unicode scalar and canonical UTF-8 profile *)
+
+(** Factor Unicode boundaries instead of expanding large decimal Peano
+ numerals. [unicode_limit] is U+110000, [surrogate_start] is U+D800,
+ and [surrogate_end] is the exclusive U+E000 boundary. *)
+Definition utf8_one_byte_limit : nat := 128.
+Definition utf8_two_byte_limit : nat := 8 * 256.
+Definition utf8_three_byte_limit : nat := 256 ^ 2.
+Definition unicode_limit : nat := 17 * utf8_three_byte_limit.
+Definition surrogate_start : nat := 216 * 256.
+Definition surrogate_end : nat := 224 * 256.
+
+Definition unicode_scalar (codepoint : nat) : Prop :=
+ codepoint < unicode_limit /\
+ (codepoint < surrogate_start \/ surrogate_end <= codepoint).
+
+Definition unicode_scalarb (codepoint : nat) : bool :=
+ (codepoint unicode_limit) &&
+ ((codepoint surrogate_start) || (surrogate_end <=? codepoint)).
+
+Definition utf8_width (codepoint : nat) : nat :=
+ if codepoint utf8_one_byte_limit then 1
+ else if codepoint utf8_two_byte_limit then 2
+ else if codepoint utf8_three_byte_limit then 3
+ else 4.
+
+Definition encode_utf8_scalar (codepoint : nat) : list PhysicalByte :=
+ if codepoint utf8_one_byte_limit then
+ [codepoint]
+ else if codepoint utf8_two_byte_limit then
+ [codepoint / 64 + 192;
+ codepoint mod 64 + 128]
+ else if codepoint utf8_three_byte_limit then
+ [(codepoint / 64) / 64 + 224;
+ (codepoint / 64) mod 64 + 128;
+ codepoint mod 64 + 128]
+ else
+ [((codepoint / 64) / 64) / 64 + 240;
+ ((codepoint / 64) / 64) mod 64 + 128;
+ (codepoint / 64) mod 64 + 128;
+ codepoint mod 64 + 128].
+
+Definition canonical_utf8_codeword
+ (codepoint : nat) (bytes : list PhysicalByte) : Prop :=
+ unicode_scalar codepoint /\ bytes = encode_utf8_scalar codepoint.
+
+Definition decode_utf8_value
+ (bytes : list PhysicalByte) : option nat :=
+ match bytes with
+ | [first] => Some first
+ | [first; second] =>
+ Some ((first - 192) * 64 + (second - 128))
+ | [first; second; third] =>
+ Some
+ (((first - 224) * 64 + (second - 128)) * 64 +
+ (third - 128))
+ | [first; second; third; fourth] =>
+ Some
+ (((((first - 240) * 64 + (second - 128)) * 64 +
+ (third - 128)) * 64) +
+ (fourth - 128))
+ | _ => None
+ end.
+
+Definition decode_utf8_scalar
+ (bytes : list PhysicalByte) : option nat :=
+ match decode_utf8_value bytes with
+ | None => None
+ | Some codepoint =>
+ if unicode_scalarb codepoint &&
+ byte_sequence_eqb bytes (encode_utf8_scalar codepoint)
+ then Some codepoint
+ else None
+ end.
+
+Lemma radix64_reconstruct :
+ forall value,
+ (value / 64) * 64 + value mod 64 = value.
+Proof.
+ intros value.
+ pose proof (Nat.div_mod value 64) as Hdivision.
+ specialize (Hdivision ltac:(lia)). nia.
+Qed.
+
+Lemma decode_utf8_value_encode_roundtrip :
+ forall codepoint,
+ decode_utf8_value (encode_utf8_scalar codepoint) = Some codepoint.
+Proof.
+ intros codepoint.
+ unfold encode_utf8_scalar, decode_utf8_value.
+ destruct (codepoint utf8_one_byte_limit);
+ [| destruct (codepoint utf8_two_byte_limit);
+ [| destruct (codepoint utf8_three_byte_limit)]].
+ - reflexivity.
+ - cbn [decode_utf8_value].
+ repeat rewrite Nat.add_sub.
+ f_equal. apply radix64_reconstruct.
+ - cbn [decode_utf8_value].
+ repeat rewrite Nat.add_sub.
+ f_equal.
+ pose proof (radix64_reconstruct codepoint) as Hlow.
+ pose proof (radix64_reconstruct (codepoint / 64)) as Hmiddle.
+ nia.
+ - cbn [decode_utf8_value].
+ repeat rewrite Nat.add_sub.
+ f_equal.
+ pose proof (radix64_reconstruct codepoint) as Hlow.
+ pose proof (radix64_reconstruct (codepoint / 64)) as Hmiddle.
+ pose proof
+ (radix64_reconstruct ((codepoint / 64) / 64)) as Hhigh.
+ nia.
+Qed.
+
+Theorem VWENC_11_UTF8_SCALAR_BOOLEAN_REFLECTION :
+ forall codepoint,
+ unicode_scalarb codepoint = true <-> unicode_scalar codepoint.
+Proof.
+ intros codepoint.
+ unfold unicode_scalarb, unicode_scalar.
+ rewrite andb_true_iff, orb_true_iff.
+ rewrite !Nat.leb_le, !Nat.ltb_lt.
+ tauto.
+Qed.
+
+Theorem VWENC_12_UTF8_CODEWORDS_NONEMPTY_AND_AT_MOST_FOUR_BYTES :
+ forall codepoint,
+ unicode_scalar codepoint ->
+ encode_utf8_scalar codepoint <> [] /\
+ 1 <= length (encode_utf8_scalar codepoint) <= 4.
+Proof.
+ intros codepoint Hscalar.
+ unfold encode_utf8_scalar.
+ destruct (codepoint utf8_one_byte_limit);
+ [| destruct (codepoint utf8_two_byte_limit);
+ [| destruct (codepoint utf8_three_byte_limit)]].
+ all: simpl.
+ all: split.
+ all: try discriminate.
+ all: lia.
+Qed.
+
+Theorem VWENC_13_UTF8_WIDTH_MATCHES_CANONICAL_CODEWORD :
+ forall codepoint,
+ unicode_scalar codepoint ->
+ length (encode_utf8_scalar codepoint) = utf8_width codepoint.
+Proof.
+ intros codepoint Hscalar.
+ unfold encode_utf8_scalar, utf8_width.
+ destruct (codepoint utf8_one_byte_limit);
+ [| destruct (codepoint utf8_two_byte_limit);
+ [| destruct (codepoint utf8_three_byte_limit)]];
+ reflexivity.
+Qed.
+
+Theorem VWENC_14_UTF8_REJECTS_NONSCALARS :
+ forall codepoint,
+ ~ unicode_scalar codepoint ->
+ forall bytes, ~ canonical_utf8_codeword codepoint bytes.
+Proof.
+ intros codepoint Hinvalid bytes [Hscalar _]. contradiction.
+Qed.
+
+Theorem VWENC_42_UTF8_CANONICAL_DECODE_ROUNDTRIP :
+ forall codepoint,
+ unicode_scalar codepoint ->
+ decode_utf8_scalar (encode_utf8_scalar codepoint) = Some codepoint.
+Proof.
+ intros codepoint Hscalar.
+ unfold decode_utf8_scalar.
+ rewrite decode_utf8_value_encode_roundtrip.
+ assert (Hscalarb : unicode_scalarb codepoint = true).
+ { apply VWENC_11_UTF8_SCALAR_BOOLEAN_REFLECTION. exact Hscalar. }
+ assert
+ (Hequal :
+ byte_sequence_eqb
+ (encode_utf8_scalar codepoint)
+ (encode_utf8_scalar codepoint) = true).
+ { apply byte_sequence_eqb_reflects_equality. reflexivity. }
+ now rewrite Hscalarb, Hequal.
+Qed.
+
+Theorem VWENC_43_UTF8_DECODER_ACCEPTANCE_IS_CANONICAL :
+ forall bytes codepoint,
+ decode_utf8_scalar bytes = Some codepoint ->
+ canonical_utf8_codeword codepoint bytes.
+Proof.
+ intros bytes codepoint Hdecode.
+ unfold decode_utf8_scalar in Hdecode.
+ destruct (decode_utf8_value bytes) as [candidate |] eqn:Hcandidate;
+ [| discriminate].
+ destruct
+ (unicode_scalarb candidate &&
+ byte_sequence_eqb bytes (encode_utf8_scalar candidate))
+ eqn:Haccepted; [| discriminate].
+ inversion Hdecode; subst candidate.
+ apply andb_true_iff in Haccepted.
+ destruct Haccepted as [Hscalar Hequal].
+ apply VWENC_11_UTF8_SCALAR_BOOLEAN_REFLECTION in Hscalar.
+ apply byte_sequence_eqb_reflects_equality in Hequal.
+ split; assumption.
+Qed.
+
+Theorem VWENC_44_UTF8_DECODER_ACCEPTS_CANONICAL_CODEWORDS :
+ forall bytes codepoint,
+ canonical_utf8_codeword codepoint bytes ->
+ decode_utf8_scalar bytes = Some codepoint.
+Proof.
+ intros bytes codepoint [Hscalar ->].
+ apply VWENC_42_UTF8_CANONICAL_DECODE_ROUNDTRIP.
+ exact Hscalar.
+Qed.
+
+Theorem VWENC_45_UTF8_CANONICAL_ENCODING_IS_INJECTIVE :
+ forall left right,
+ unicode_scalar left ->
+ unicode_scalar right ->
+ encode_utf8_scalar left = encode_utf8_scalar right ->
+ left = right.
+Proof.
+ intros left right Hleft Hright Hencoded.
+ pose proof (VWENC_42_UTF8_CANONICAL_DECODE_ROUNDTRIP left Hleft)
+ as Hdecode_left.
+ pose proof (VWENC_42_UTF8_CANONICAL_DECODE_ROUNDTRIP right Hright)
+ as Hdecode_right.
+ rewrite Hencoded in Hdecode_left.
+ rewrite Hdecode_right in Hdecode_left.
+ inversion Hdecode_left. reflexivity.
+Qed.
+
+Theorem VWENC_46_UTF8_MALFORMED_OR_NONCANONICAL_INPUT_IS_REJECTED :
+ forall bytes,
+ (forall codepoint, ~ canonical_utf8_codeword codepoint bytes) ->
+ decode_utf8_scalar bytes = None.
+Proof.
+ intros bytes Hnoncanonical.
+ destruct (decode_utf8_scalar bytes) as [codepoint |] eqn:Hdecode.
+ - exfalso. apply (Hnoncanonical codepoint).
+ now apply VWENC_43_UTF8_DECODER_ACCEPTANCE_IS_CANONICAL.
+ - reflexivity.
+Qed.
+
+Theorem VWENC_47_UTF8_REJECTS_CONTINUATION_OVERLONG_TRUNCATED_AND_SURROGATE :
+ decode_utf8_scalar [169] = None /\
+ decode_utf8_scalar [192; 128] = None /\
+ decode_utf8_scalar [195] = None /\
+ decode_utf8_scalar [237; 160; 128] = None.
+Proof. repeat split; reflexivity. Qed.
+
+(** ** Direct fixed-unit and logical-observation laws *)
+
+(** Keep machine-width bounds symbolic. Expanding 64-bit decimal literals into
+ Peano naturals is both semantically unnecessary and prohibitively expensive
+ for the proof checker. These factored definitions preserve the exact
+ values while proofs reason about their algebraic relationships. *)
+Definition two_to_32 : nat := 256 ^ 4.
+Definition two_to_63 : nat := 128 * 256 ^ 7.
+Definition two_to_64 : nat := 256 ^ 8.
+
+Lemma two_to_63_positive : 0 < two_to_63.
+Proof.
+ unfold two_to_63.
+ assert (256 ^ 7 <> 0).
+ { apply Nat.pow_nonzero. lia. }
+ nia.
+Qed.
+
+Lemma two_to_64_is_double_two_to_63 :
+ two_to_64 = 2 * two_to_63.
+Proof.
+ unfold two_to_64, two_to_63.
+ replace 8 with (S 7) by reflexivity.
+ rewrite Nat.pow_succ_r by lia.
+ set (power := 256 ^ 7).
+ change (256 * power = 2 * (128 * power)).
+ lia.
+Qed.
+
+(** Subsequent proofs use the checked positivity/doubling interface above.
+ Keeping the factored Peano definitions opaque prevents the kernel from
+ expanding machine-width bounds while closing unrelated theorems. *)
+Global Opaque two_to_32 two_to_63 two_to_64.
+
+Inductive DirectProfile :=
+| DirectBytes
+| DirectUnicodeScalar
+| DirectU32
+| DirectU64
+| DirectF64Bits.
+
+Definition direct_profile_tag (profile : DirectProfile) : nat :=
+ match profile with
+ | DirectBytes => 1
+ | DirectUnicodeScalar => 2
+ | DirectU32 => 3
+ | DirectU64 => 4
+ | DirectF64Bits => 5
+ end.
+
+Definition direct_byte_width (profile : DirectProfile) : nat :=
+ match profile with
+ | DirectBytes => 1
+ | DirectUnicodeScalar => 4
+ | DirectU32 => 4
+ | DirectU64 => 8
+ | DirectF64Bits => 8
+ end.
+
+Definition direct_profile_valid
+ (profile : DirectProfile) (unit : nat) : Prop :=
+ match profile with
+ | DirectBytes => unit < 256
+ | DirectUnicodeScalar => unicode_scalar unit
+ | DirectU32 => unit < 256 ^ 4
+ | DirectU64 => unit < 256 ^ 8
+ | DirectF64Bits => unit < 256 ^ 8
+ end.
+
+Definition direct_profile_validb
+ (profile : DirectProfile) (unit : nat) : bool :=
+ match profile with
+ | DirectBytes => unit 256
+ | DirectUnicodeScalar => unicode_scalarb unit
+ | DirectU32 => unit 256 ^ 4
+ | DirectU64 => unit 256 ^ 8
+ | DirectF64Bits => unit 256 ^ 8
+ end.
+
+Lemma direct_profile_validb_reflects_validity :
+ forall profile unit,
+ direct_profile_validb profile unit = true <->
+ direct_profile_valid profile unit.
+Proof.
+ intros profile unit.
+ destruct profile;
+ cbn [direct_profile_validb direct_profile_valid].
+ - apply Nat.ltb_lt.
+ - apply VWENC_11_UTF8_SCALAR_BOOLEAN_REFLECTION.
+ - apply Nat.ltb_lt.
+ - apply Nat.ltb_lt.
+ - apply Nat.ltb_lt.
+Qed.
+
+Fixpoint encode_fixed_little_endian
+ (byte_count value : nat) : list PhysicalByte :=
+ match byte_count with
+ | 0 => []
+ | S rest => value mod 256 ::
+ encode_fixed_little_endian rest (value / 256)
+ end.
+
+Fixpoint decode_fixed_little_endian
+ (bytes : list PhysicalByte) : nat :=
+ match bytes with
+ | [] => 0
+ | byte :: rest => byte + decode_fixed_little_endian rest * 256
+ end.
+
+Definition serialize_direct_unit
+ (profile : DirectProfile) (unit : nat)
+ : nat * list PhysicalByte :=
+ (direct_profile_tag profile,
+ encode_fixed_little_endian (direct_byte_width profile) unit).
+
+Fixpoint all_valid_bytesb (bytes : list PhysicalByte) : bool :=
+ match bytes with
+ | [] => true
+ | byte :: rest => (byte 256) && all_valid_bytesb rest
+ end.
+
+Lemma all_valid_bytesb_reflects_validity :
+ forall bytes,
+ all_valid_bytesb bytes = true <-> Forall valid_byte bytes.
+Proof.
+ induction bytes as [| byte rest IH]; simpl.
+ - split; constructor.
+ - rewrite andb_true_iff, Nat.ltb_lt, IH.
+ unfold valid_byte.
+ split.
+ + intros [Hbyte Hrest]. constructor; assumption.
+ + intros Hvalid. inversion Hvalid; subst. tauto.
+Qed.
+
+(** This checked record is the prospective canonical direct-profile codec.
+ It is not a claim about the byte layout of any existing serde/bincode or
+ persistent-ARTrie image. Migration of a persistent backend may select
+ this record only under a new, explicit format identity. *)
+Definition decode_direct_unit
+ (expected_profile : DirectProfile)
+ (serialized : nat * list PhysicalByte) : option nat :=
+ let '(profile_tag, bytes) := serialized in
+ if profile_tag =? direct_profile_tag expected_profile then
+ if length bytes =? direct_byte_width expected_profile then
+ if all_valid_bytesb bytes then
+ let unit := decode_fixed_little_endian bytes in
+ if direct_profile_validb expected_profile unit
+ then Some unit
+ else None
+ else None
+ else None
+ else None.
+
+Definition direct_codeword (unit : nat) : list nat := [unit].
+
+Lemma fixed_little_endian_length :
+ forall byte_count value,
+ length (encode_fixed_little_endian byte_count value) = byte_count.
+Proof.
+ induction byte_count; intros value; simpl; [reflexivity |].
+ now rewrite IHbyte_count.
+Qed.
+
+Lemma fixed_little_endian_bytes_are_valid :
+ forall byte_count value,
+ Forall valid_byte (encode_fixed_little_endian byte_count value).
+Proof.
+ induction byte_count as [| byte_count IH]; intros value.
+ - change (Forall valid_byte []). constructor.
+ - change
+ (Forall valid_byte
+ (value mod 256 ::
+ encode_fixed_little_endian byte_count (value / 256))).
+ constructor.
+ + unfold valid_byte. apply Nat.mod_upper_bound. lia.
+ + apply IH.
+Qed.
+
+Lemma fixed_little_endian_roundtrip :
+ forall byte_count value,
+ value < 256 ^ byte_count ->
+ decode_fixed_little_endian
+ (encode_fixed_little_endian byte_count value) = value.
+Proof.
+ induction byte_count as [| byte_count IH]; intros value Hbounded.
+ - simpl in *. lia.
+ - cbn [encode_fixed_little_endian decode_fixed_little_endian].
+ rewrite IH.
+ + pose proof (Nat.div_mod value 256 ltac:(lia)) as Hdivision.
+ nia.
+ + pose proof (Nat.div_mod value 256 ltac:(lia)) as Hdivision.
+ pose proof (Nat.mod_upper_bound value 256 ltac:(lia)) as Hremainder.
+ change (value < 256 * 256 ^ byte_count) in Hbounded.
+ nia.
+Qed.
+
+Lemma direct_profile_value_fits_serialization :
+ forall profile unit,
+ direct_profile_valid profile unit ->
+ unit < 256 ^ direct_byte_width profile.
+Proof.
+ intros profile unit Hvalid.
+ destruct profile; cbn [direct_profile_valid direct_byte_width] in Hvalid |- *.
+ - exact Hvalid.
+ - destruct Hvalid as [Hupper _].
+ unfold unicode_limit, utf8_three_byte_limit in Hupper.
+ assert (Hbase : 17 < 256 ^ 2).
+ { change (17 < 256 * (256 * 1)). rewrite Nat.mul_1_r. lia. }
+ replace 4 with (2 + 2) by lia.
+ rewrite Nat.pow_add_r.
+ assert (0 < 256 ^ 2).
+ { apply Nat.neq_0_lt_0. apply Nat.pow_nonzero. lia. }
+ assert
+ (Hunicode_fits :
+ 17 * 256 ^ 2 < 256 ^ 2 * 256 ^ 2) by nia.
+ eapply Nat.lt_trans; [exact Hupper | exact Hunicode_fits].
+ - exact Hvalid.
+ - exact Hvalid.
+ - exact Hvalid.
+Qed.
+
+Theorem VWENC_48_DIRECT_PROFILE_TAGS_ARE_INJECTIVE :
+ forall left right,
+ direct_profile_tag left = direct_profile_tag right -> left = right.
+Proof.
+ intros left right Hequal.
+ destruct left, right; simpl in Hequal; try reflexivity; discriminate.
+Qed.
+
+Theorem VWENC_49_DIRECT_SERIALIZATION_HAS_EXACT_FIXED_WIDTH :
+ forall profile unit,
+ length (snd (serialize_direct_unit profile unit)) =
+ direct_byte_width profile.
+Proof.
+ intros profile unit.
+ unfold serialize_direct_unit. simpl.
+ apply fixed_little_endian_length.
+Qed.
+
+Theorem VWENC_50_DIRECT_SERIALIZATION_ROUNDTRIPS_VALID_UNITS :
+ forall profile unit,
+ direct_profile_valid profile unit ->
+ decode_fixed_little_endian
+ (snd (serialize_direct_unit profile unit)) = unit.
+Proof.
+ intros profile unit Hvalid.
+ unfold serialize_direct_unit. simpl.
+ apply fixed_little_endian_roundtrip.
+ now apply direct_profile_value_fits_serialization.
+Qed.
+
+Theorem VWENC_59_CHECKED_DIRECT_DECODER_ACCEPTS_CANONICAL_RECORD :
+ forall profile unit,
+ direct_profile_valid profile unit ->
+ decode_direct_unit profile (serialize_direct_unit profile unit) =
+ Some unit.
+Proof.
+ intros profile unit Hvalid.
+ unfold decode_direct_unit, serialize_direct_unit.
+ rewrite Nat.eqb_refl, fixed_little_endian_length, Nat.eqb_refl.
+ pose proof
+ (fixed_little_endian_bytes_are_valid
+ (direct_byte_width profile) unit) as Hbytes.
+ apply all_valid_bytesb_reflects_validity in Hbytes.
+ rewrite Hbytes.
+ rewrite fixed_little_endian_roundtrip.
+ - apply direct_profile_validb_reflects_validity in Hvalid.
+ now rewrite Hvalid.
+ - now apply direct_profile_value_fits_serialization.
+Qed.
+
+Theorem VWENC_60_CHECKED_DIRECT_DECODER_REJECTS_WRONG_PROFILE_TAG :
+ forall expected_profile supplied_tag bytes,
+ supplied_tag <> direct_profile_tag expected_profile ->
+ decode_direct_unit expected_profile (supplied_tag, bytes) = None.
+Proof.
+ intros expected_profile supplied_tag bytes Hwrong.
+ unfold decode_direct_unit.
+ apply Nat.eqb_neq in Hwrong. now rewrite Hwrong.
+Qed.
+
+Theorem VWENC_61_CHECKED_DIRECT_DECODER_REJECTS_WRONG_WIDTH :
+ forall profile bytes,
+ length bytes <> direct_byte_width profile ->
+ decode_direct_unit profile (direct_profile_tag profile, bytes) = None.
+Proof.
+ intros profile bytes Hwrong.
+ unfold decode_direct_unit. rewrite Nat.eqb_refl.
+ apply Nat.eqb_neq in Hwrong. now rewrite Hwrong.
+Qed.
+
+Theorem VWENC_62_CHECKED_DIRECT_DECODER_REJECTS_NONBYTE_PAYLOAD :
+ forall profile bytes,
+ length bytes = direct_byte_width profile ->
+ ~ Forall valid_byte bytes ->
+ decode_direct_unit profile (direct_profile_tag profile, bytes) = None.
+Proof.
+ intros profile bytes Hwidth Hinvalid.
+ unfold decode_direct_unit. rewrite Nat.eqb_refl.
+ apply Nat.eqb_eq in Hwidth. rewrite Hwidth.
+ destruct (all_valid_bytesb bytes) eqn:Hbytes; [| reflexivity].
+ apply all_valid_bytesb_reflects_validity in Hbytes. contradiction.
+Qed.
+
+Theorem VWENC_63_CHECKED_DIRECT_DECODER_SUCCESS_IS_EXACT :
+ forall profile supplied_tag bytes unit,
+ decode_direct_unit profile (supplied_tag, bytes) = Some unit ->
+ supplied_tag = direct_profile_tag profile /\
+ length bytes = direct_byte_width profile /\
+ Forall valid_byte bytes /\
+ direct_profile_valid profile unit /\
+ decode_fixed_little_endian bytes = unit.
+Proof.
+ intros profile supplied_tag bytes unit Hdecode.
+ unfold decode_direct_unit in Hdecode.
+ destruct (supplied_tag =? direct_profile_tag profile)
+ eqn:Htag; [| discriminate].
+ destruct (length bytes =? direct_byte_width profile)
+ eqn:Hwidth; [| discriminate].
+ destruct (all_valid_bytesb bytes) eqn:Hbytes; [| discriminate].
+ destruct
+ (direct_profile_validb profile (decode_fixed_little_endian bytes))
+ eqn:Hvalid; [| discriminate].
+ inversion Hdecode; subst.
+ repeat split.
+ - now apply Nat.eqb_eq.
+ - now apply Nat.eqb_eq.
+ - now apply all_valid_bytesb_reflects_validity.
+ - now apply direct_profile_validb_reflects_validity.
+Qed.
+
+Theorem VWENC_64_CHECKED_DIRECT_DECODER_REJECTS_INVALID_LOGICAL_UNIT :
+ forall profile bytes,
+ length bytes = direct_byte_width profile ->
+ Forall valid_byte bytes ->
+ ~ direct_profile_valid profile (decode_fixed_little_endian bytes) ->
+ decode_direct_unit profile (direct_profile_tag profile, bytes) = None.
+Proof.
+ intros profile bytes Hwidth Hbytes Hinvalid.
+ unfold decode_direct_unit. rewrite Nat.eqb_refl.
+ apply Nat.eqb_eq in Hwidth. rewrite Hwidth.
+ apply all_valid_bytesb_reflects_validity in Hbytes. rewrite Hbytes.
+ destruct
+ (direct_profile_validb profile (decode_fixed_little_endian bytes))
+ eqn:Hvalid; [| reflexivity].
+ apply direct_profile_validb_reflects_validity in Hvalid.
+ contradiction.
+Qed.
+
+Theorem VWENC_51_UNICODE_SCALAR_DIRECT_STORAGE_IS_NOT_UTF8_STORAGE :
+ forall codepoint,
+ unicode_scalar codepoint ->
+ direct_codeword codepoint = [codepoint] /\
+ decode_utf8_scalar (encode_utf8_scalar codepoint) = Some codepoint.
+Proof.
+ intros codepoint Hscalar. split; [reflexivity |].
+ now apply VWENC_42_UTF8_CANONICAL_DECODE_ROUNDTRIP.
+Qed.
+
+Theorem VWENC_15_DIRECT_PROFILE_IS_ONE_UNIT_PER_TRANSITION :
+ forall unit, length (direct_codeword unit) = 1.
+Proof. reflexivity. Qed.
+
+(** A variable-width ULEB atom retains its canonical bytes as its identity.
+ No built-in integer is required at the consumer boundary. UTF-8 instead
+ denotes a Unicode scalar, so its public logical identity is the decoded
+ scalar value. Direct atoms are already one native edge unit. *)
+Inductive LogicalAtom :=
+| DirectAtom : DirectProfile -> nat -> LogicalAtom
+| UlebAtom : list PhysicalByte -> LogicalAtom
+| UnicodeAtom : nat -> LogicalAtom.
+
+Definition direct_logical_atom
+ (profile : DirectProfile) (unit : nat) : LogicalAtom :=
+ match profile with
+ | DirectUnicodeScalar => UnicodeAtom unit
+ | _ => DirectAtom profile unit
+ end.
+
+(** Native direct labels match the existing [CharUnit]-generic DAWG cores.
+ An opaque codeword is one edge label carrying canonical bytes. A byte-path
+ adapter may use several third-party physical edges internally, but it has
+ the same logical projection and must not expose its intermediate nodes to
+ [DictionaryNode], zipper, or cursor consumers. *)
+Inductive StorageRepresentation :=
+| NativeDirectEdge
+| OpaqueCodewordEdge
+| EncodedBytePathAdapter.
+
+Inductive StoredLogicalUnit :=
+| StoredDirect : DirectProfile -> nat -> StoredLogicalUnit
+| StoredUleb : list PhysicalByte -> StoredLogicalUnit
+| StoredUtf8 : list PhysicalByte -> StoredLogicalUnit.
+
+Definition representation_admits
+ (representation : StorageRepresentation)
+ (stored : StoredLogicalUnit) : Prop :=
+ match representation, stored with
+ | NativeDirectEdge, StoredDirect _ _ => True
+ | OpaqueCodewordEdge, StoredUleb _ => True
+ | OpaqueCodewordEdge, StoredUtf8 _ => True
+ | EncodedBytePathAdapter, StoredUleb _ => True
+ | EncodedBytePathAdapter, StoredUtf8 _ => True
+ | _, _ => False
+ end.
+
+Definition representation_admitsb
+ (representation : StorageRepresentation)
+ (stored : StoredLogicalUnit) : bool :=
+ match representation, stored with
+ | NativeDirectEdge, StoredDirect _ _ => true
+ | OpaqueCodewordEdge, StoredUleb _ => true
+ | OpaqueCodewordEdge, StoredUtf8 _ => true
+ | EncodedBytePathAdapter, StoredUleb _ => true
+ | EncodedBytePathAdapter, StoredUtf8 _ => true
+ | _, _ => false
+ end.
+
+Lemma representation_admitsb_reflects_admission :
+ forall representation stored,
+ representation_admitsb representation stored = true <->
+ representation_admits representation stored.
+Proof.
+ intros representation stored.
+ destruct representation, stored;
+ cbn [representation_admitsb representation_admits]; easy.
+Qed.
+
+Definition decode_stored_logical_unit
+ (stored : StoredLogicalUnit) : option LogicalAtom :=
+ match stored with
+ | StoredDirect profile unit =>
+ if direct_profile_validb profile unit
+ then Some (direct_logical_atom profile unit)
+ else None
+ | StoredUleb bytes =>
+ match decode_canonical_uleb bytes with
+ | Some _ => Some (UlebAtom bytes)
+ | None => None
+ end
+ | StoredUtf8 bytes =>
+ match decode_utf8_scalar bytes with
+ | Some codepoint => Some (UnicodeAtom codepoint)
+ | None => None
+ end
+ end.
+
+Definition physical_codeword_of
+ (stored : StoredLogicalUnit) : list PhysicalByte :=
+ match stored with
+ | StoredDirect profile unit => snd (serialize_direct_unit profile unit)
+ | StoredUleb bytes => bytes
+ | StoredUtf8 bytes => bytes
+ end.
+
+Record StoredTransition := {
+ transition_representation : StorageRepresentation;
+ transition_unit : StoredLogicalUnit;
+}.
+
+Definition valid_stored_transition
+ (transition : StoredTransition) : Prop :=
+ representation_admits
+ transition.(transition_representation) transition.(transition_unit) /\
+ exists atom,
+ decode_stored_logical_unit transition.(transition_unit) = Some atom.
+
+Definition logical_transition
+ (transition : StoredTransition) : option LogicalAtom :=
+ if representation_admitsb
+ transition.(transition_representation) transition.(transition_unit)
+ then decode_stored_logical_unit transition.(transition_unit)
+ else None.
+
+Inductive ConsumerSurface :=
+| DictionaryNodeSurface
+| ZipperSurface
+| SnapshotCursorSurface.
+
+Definition consumer_observation
+ (_surface : ConsumerSurface)
+ (transition : StoredTransition) : list LogicalAtom :=
+ match logical_transition transition with
+ | Some atom => [atom]
+ | None => []
+ end.
+
+(** A concrete API surface discharges this refinement obligation in the
+ family-wide proof phase. The common target below deliberately abstracts
+ over how a node, zipper, or cursor obtains the transition. *)
+Record ConsumerSurfaceImplementation := {
+ implementation_surface : ConsumerSurface;
+ implementation_observation : StoredTransition -> list LogicalAtom;
+ implementation_refines_logical_target :
+ forall transition,
+ implementation_observation transition =
+ consumer_observation implementation_surface transition;
+}.
+
+Theorem VWENC_16_CODEC_BYTES_ARE_NOT_LOGICAL_TRANSITIONS :
+ forall surface transition atom,
+ logical_transition transition = Some atom ->
+ consumer_observation surface transition = [atom].
+Proof.
+ intros surface transition atom Hlogical.
+ unfold consumer_observation. now rewrite Hlogical.
+Qed.
+
+Theorem VWENC_17_ONE_LOGICAL_ATOM_PER_CONSUMER_TRANSITION :
+ forall surface transition,
+ valid_stored_transition transition ->
+ length (consumer_observation surface transition) = 1.
+Proof.
+ intros surface transition [Hadmitted [atom Hdecode]].
+ unfold consumer_observation, logical_transition.
+ apply representation_admitsb_reflects_admission in Hadmitted.
+ now rewrite Hadmitted, Hdecode.
+Qed.
+
+Theorem VWENC_65_ULEB_LOGICAL_IDENTITY_IS_CANONICAL_BYTES :
+ forall representation bytes,
+ representation_admits representation (StoredUleb bytes) ->
+ canonical_uleb_codeword bytes ->
+ logical_transition
+ {| transition_representation := representation;
+ transition_unit := StoredUleb bytes |} =
+ Some (UlebAtom bytes).
+Proof.
+ intros representation bytes Hadmitted Hcanonical.
+ unfold logical_transition. simpl.
+ apply representation_admitsb_reflects_admission in Hadmitted.
+ rewrite Hadmitted.
+ apply VWENC_34_ULEB_DECODER_ACCEPTS_EXACTLY_CANONICAL_CODEWORDS
+ in Hcanonical.
+ now rewrite Hcanonical.
+Qed.
+
+Theorem VWENC_66_UTF8_LOGICAL_IDENTITY_IS_UNICODE_SCALAR :
+ forall representation bytes codepoint,
+ representation_admits representation (StoredUtf8 bytes) ->
+ canonical_utf8_codeword codepoint bytes ->
+ logical_transition
+ {| transition_representation := representation;
+ transition_unit := StoredUtf8 bytes |} =
+ Some (UnicodeAtom codepoint).
+Proof.
+ intros representation bytes codepoint Hadmitted Hcanonical.
+ unfold logical_transition. simpl.
+ apply representation_admitsb_reflects_admission in Hadmitted.
+ rewrite Hadmitted.
+ apply VWENC_44_UTF8_DECODER_ACCEPTS_CANONICAL_CODEWORDS in Hcanonical.
+ now rewrite Hcanonical.
+Qed.
+
+Theorem VWENC_67_OPAQUE_AND_BYTE_PATH_ADAPTERS_HAVE_SAME_LOGICAL_VIEW :
+ forall stored,
+ representation_admits OpaqueCodewordEdge stored ->
+ representation_admits EncodedBytePathAdapter stored ->
+ logical_transition
+ {| transition_representation := OpaqueCodewordEdge;
+ transition_unit := stored |} =
+ logical_transition
+ {| transition_representation := EncodedBytePathAdapter;
+ transition_unit := stored |}.
+Proof.
+ intros stored Hopaque Hadapter.
+ apply representation_admitsb_reflects_admission in Hopaque.
+ apply representation_admitsb_reflects_admission in Hadapter.
+ change
+ ((if representation_admitsb OpaqueCodewordEdge stored
+ then decode_stored_logical_unit stored else None) =
+ (if representation_admitsb EncodedBytePathAdapter stored
+ then decode_stored_logical_unit stored else None)).
+ now rewrite Hopaque, Hadapter.
+Qed.
+
+Theorem VWENC_68_DICTIONARY_NODE_ZIPPER_CURSOR_SHARE_COMMON_TARGET_DEFINITION :
+ forall transition,
+ consumer_observation DictionaryNodeSurface transition =
+ consumer_observation ZipperSurface transition /\
+ consumer_observation ZipperSurface transition =
+ consumer_observation SnapshotCursorSurface transition.
+Proof. intros transition. split; reflexivity. Qed.
+
+Theorem VWENC_97_SURFACE_REFINEMENT_OBLIGATIONS_IMPLY_LOGICAL_AGREEMENT :
+ forall left right transition,
+ implementation_observation left transition =
+ implementation_observation right transition.
+Proof.
+ intros [left_surface left_observe Hleft]
+ [right_surface right_observe Hright] transition.
+ simpl.
+ rewrite (Hleft transition), (Hright transition).
+ destruct left_surface, right_surface; reflexivity.
+Qed.
+
+Theorem VWENC_69_MULTIBYTE_STORAGE_STILL_EMITS_ONE_LOGICAL_TRANSITION :
+ forall surface transition,
+ valid_stored_transition transition ->
+ 2 <= length (physical_codeword_of transition.(transition_unit)) ->
+ length (consumer_observation surface transition) = 1.
+Proof.
+ intros surface transition Hvalid Hmultibyte.
+ now apply VWENC_17_ONE_LOGICAL_ATOM_PER_CONSUMER_TRANSITION.
+Qed.
+
+(** Exact correspondence target for the baseline generic cores at revision
+ [6e8bb1d]: [CharUnit] supplies [u8], [char], and [u64] edge labels;
+ [DawgCore] and [LockFreeDawg] both store one [U] per edge. *)
+Inductive BaselineCharUnitKind :=
+| BaselineU8
+| BaselineChar
+| BaselineU64.
+
+Definition baseline_profile (kind : BaselineCharUnitKind) : DirectProfile :=
+ match kind with
+ | BaselineU8 => DirectBytes
+ | BaselineChar => DirectUnicodeScalar
+ | BaselineU64 => DirectU64
+ end.
+
+Inductive BaselineDawgCoreKind :=
+| IndexedDawgCore
+| LockFreeDawgCore.
+
+Definition baseline_transition
+ (kind : BaselineCharUnitKind) (unit : nat) : StoredTransition :=
+ {| transition_representation := NativeDirectEdge;
+ transition_unit := StoredDirect (baseline_profile kind) unit |}.
+
+Definition baseline_core_observations
+ (_core : BaselineDawgCoreKind)
+ (kind : BaselineCharUnitKind)
+ (units : list nat) : list (list LogicalAtom) :=
+ map
+ (fun unit =>
+ consumer_observation DictionaryNodeSurface
+ (baseline_transition kind unit))
+ units.
+
+Theorem VWENC_70_BASELINE_CHARUNIT_EDGE_IS_ONE_LOGICAL_ATOM :
+ forall kind unit,
+ direct_profile_valid (baseline_profile kind) unit ->
+ logical_transition (baseline_transition kind unit) =
+ Some (direct_logical_atom (baseline_profile kind) unit).
+Proof.
+ intros kind unit Hvalid.
+ unfold logical_transition, baseline_transition. simpl.
+ apply direct_profile_validb_reflects_validity in Hvalid.
+ now rewrite Hvalid.
+Qed.
+
+Theorem VWENC_71_INDEXED_AND_LOCKFREE_SHARE_REQUIRED_TARGET_DEFINITION :
+ forall kind units,
+ baseline_core_observations IndexedDawgCore kind units =
+ baseline_core_observations LockFreeDawgCore kind units.
+Proof. reflexivity. Qed.
+
+(** Existing persistent profiles are closed over the already implemented
+ [ByteKey], [CharKey], and [U64Key] units. Variable-width profiles and new
+ semantic interpretations require an explicit format/profile identity and
+ are not silently asserted to match an existing persistent image. *)
+Inductive ExistingPersistentUnitKind :=
+| PersistentByteKey
+| PersistentCharKey
+| PersistentU64Key.
+
+Definition persistent_baseline_kind
+ (kind : ExistingPersistentUnitKind) : BaselineCharUnitKind :=
+ match kind with
+ | PersistentByteKey => BaselineU8
+ | PersistentCharKey => BaselineChar
+ | PersistentU64Key => BaselineU64
+ end.
+
+Theorem VWENC_72_EXISTING_PERSISTENT_UNITS_MAP_TO_BASELINE_CHARUNITS :
+ forall kind unit,
+ direct_profile_valid
+ (baseline_profile (persistent_baseline_kind kind)) unit ->
+ logical_transition
+ (baseline_transition (persistent_baseline_kind kind) unit) =
+ Some
+ (direct_logical_atom
+ (baseline_profile (persistent_baseline_kind kind)) unit).
+Proof.
+ intros kind unit Hvalid.
+ now apply VWENC_70_BASELINE_CHARUNIT_EDGE_IS_ONE_LOGICAL_ATOM.
+Qed.
+
+Theorem VWENC_83_DYNAMIC_DAWG_CHAR_AND_UTF8_ADAPTER_OBSERVE_SAME_SCALAR :
+ forall representation codepoint bytes,
+ representation_admits representation (StoredUtf8 bytes) ->
+ canonical_utf8_codeword codepoint bytes ->
+ logical_transition (baseline_transition BaselineChar codepoint) =
+ logical_transition
+ {| transition_representation := representation;
+ transition_unit := StoredUtf8 bytes |}.
+Proof.
+ intros representation codepoint bytes Hadmitted Hcanonical.
+ assert (unicode_scalar codepoint) as Hscalar.
+ { now destruct Hcanonical. }
+ rewrite
+ (VWENC_70_BASELINE_CHARUNIT_EDGE_IS_ONE_LOGICAL_ATOM
+ BaselineChar codepoint Hscalar).
+ rewrite
+ (VWENC_66_UTF8_LOGICAL_IDENTITY_IS_UNICODE_SCALAR
+ representation bytes codepoint Hadmitted Hcanonical).
+ reflexivity.
+Qed.
+
+(** Correspondence with the existing Rocq graph models: [DawgTerm] is the
+ byte-label language of [DynamicDawgMutationSpec], while [U64Sequence] is
+ the native-label language of [DynamicDawgU64Spec]. These projections bind
+ the new logical-unit laws to the established mutation/zipper corpus rather
+ than defining a disconnected graph model. *)
+Definition existing_byte_term_observations
+ (term : DawgTerm) : list (list LogicalAtom) :=
+ map
+ (fun label =>
+ consumer_observation DictionaryNodeSurface
+ (baseline_transition BaselineU8 (MapSpec.byte_to_nat label)))
+ term.
+
+Theorem VWENC_91_EXISTING_DYNAMIC_DAWG_BYTE_LABEL_IS_DIRECT_BYTE_ATOM :
+ forall label : DawgLabel,
+ logical_transition
+ (baseline_transition BaselineU8 (MapSpec.byte_to_nat label)) =
+ Some (DirectAtom DirectBytes (MapSpec.byte_to_nat label)).
+Proof.
+ intros [label Hbyte].
+ apply VWENC_70_BASELINE_CHARUNIT_EDGE_IS_ONE_LOGICAL_ATOM.
+ exact Hbyte.
+Qed.
+
+Theorem VWENC_92_EXISTING_DYNAMIC_DAWG_TERM_PRESERVES_EDGE_COUNT :
+ forall term : DawgTerm,
+ length (existing_byte_term_observations term) = length term.
+Proof. intros term. apply map_length. Qed.
+
+Definition existing_u64_sequence_observations
+ (sequence : U64Sequence) : list (list LogicalAtom) :=
+ map
+ (fun label =>
+ consumer_observation DictionaryNodeSurface
+ (baseline_transition BaselineU64 label))
+ sequence.
+
+Theorem VWENC_93_EXISTING_U64_SEQUENCE_LABELS_ARE_DIRECT_U64_ATOMS :
+ forall sequence : U64Sequence,
+ Forall (fun label => direct_profile_valid DirectU64 label) sequence ->
+ existing_u64_sequence_observations sequence =
+ map (fun label => [DirectAtom DirectU64 label]) sequence.
+Proof.
+ induction sequence as [| label rest IH]; intros Hvalid; [reflexivity |].
+ inversion Hvalid as [| ? ? Hlabel Hrest]; subst.
+ assert
+ (logical_transition (baseline_transition BaselineU64 label) =
+ Some (DirectAtom DirectU64 label)) as Hlogical.
+ { exact
+ (VWENC_70_BASELINE_CHARUNIT_EDGE_IS_ONE_LOGICAL_ATOM
+ BaselineU64 label Hlabel). }
+ pose proof
+ (VWENC_16_CODEC_BYTES_ARE_NOT_LOGICAL_TRANSITIONS
+ DictionaryNodeSurface (baseline_transition BaselineU64 label)
+ (DirectAtom DirectU64 label) Hlogical) as Hobservation.
+ change
+ (consumer_observation DictionaryNodeSurface
+ (baseline_transition BaselineU64 label) ::
+ existing_u64_sequence_observations rest =
+ [DirectAtom DirectU64 label] ::
+ map (fun unit => [DirectAtom DirectU64 unit]) rest).
+ rewrite Hobservation, (IH Hrest). reflexivity.
+Qed.
+
+Theorem VWENC_94_EXISTING_U64_SEQUENCE_PRESERVES_EDGE_COUNT :
+ forall sequence : U64Sequence,
+ length (existing_u64_sequence_observations sequence) = length sequence.
+Proof. intros sequence. apply map_length. Qed.
+
+(** Open in-memory unit law carrier. This record does not enumerate the unit
+ type and therefore preserves downstream implementation of [CharUnit].
+ A consumer supplies ordinary equality, ordering, and hash-input laws; the
+ generic core then stores exactly one [U] per edge. Persistent identities
+ remain closed and separately certified below. *)
+Record OpenUnitProfile (U : Type) := {
+ open_unit_eqb : U -> U -> bool;
+ open_unit_compare : U -> U -> comparison;
+ open_unit_hash_material : U -> list nat;
+ open_unit_eqb_exact :
+ forall left right, open_unit_eqb left right = true <-> left = right;
+ open_unit_compare_equal_exact :
+ forall left right, open_unit_compare left right = Eq <-> left = right;
+ open_unit_compare_dual :
+ forall left right,
+ (open_unit_compare left right = Lt <->
+ open_unit_compare right left = Gt) /\
+ (open_unit_compare left right = Gt <->
+ open_unit_compare right left = Lt);
+ open_unit_compare_lt_transitive :
+ forall left middle right,
+ open_unit_compare left middle = Lt ->
+ open_unit_compare middle right = Lt ->
+ open_unit_compare left right = Lt;
+ open_unit_hash_congruent :
+ forall left right,
+ left = right ->
+ open_unit_hash_material left = open_unit_hash_material right;
+}.
+
+Inductive OpenConsumerSurface :=
+| OpenDictionaryNodeSurface
+| OpenZipperSurface
+| OpenSnapshotCursorSurface.
+
+Definition open_consumer_observation {U : Type}
+ (_profile : OpenUnitProfile U)
+ (_surface : OpenConsumerSurface)
+ (unit : U) : list U := [unit].
+
+Theorem VWENC_84_OPEN_CHARUNIT_PROFILE_REMAINS_ONE_UNIT_PER_EDGE :
+ forall (U : Type) (profile : OpenUnitProfile U) surface unit,
+ open_consumer_observation profile surface unit = [unit] /\
+ length (open_consumer_observation profile surface unit) = 1.
+Proof. intros. split; reflexivity. Qed.
+
+Theorem VWENC_100_OPEN_UNIT_COMPARATOR_IS_TOTAL_ON_DISTINCT_UNITS :
+ forall (U : Type) (profile : OpenUnitProfile U) left right,
+ left <> right ->
+ open_unit_compare U profile left right = Lt \/
+ open_unit_compare U profile left right = Gt.
+Proof.
+ intros U profile left right Hdistinct.
+ destruct (open_unit_compare U profile left right) eqn:Hcompare.
+ - exfalso. apply Hdistinct.
+ now apply
+ (proj1 (open_unit_compare_equal_exact U profile left right)).
+ - now left.
+ - now right.
+Qed.
+
+Theorem VWENC_85_OPEN_SURFACES_SHARE_REQUIRED_TARGET_DEFINITION :
+ forall (U : Type) (profile : OpenUnitProfile U) unit,
+ open_consumer_observation profile OpenDictionaryNodeSurface unit =
+ open_consumer_observation profile OpenZipperSurface unit /\
+ open_consumer_observation profile OpenZipperSurface unit =
+ open_consumer_observation profile OpenSnapshotCursorSurface unit.
+Proof. intros. split; reflexivity. Qed.
+
+(** Closed identities for persistence. Existing layouts and prospective codecs
+ are distinct constructors; equality can never silently reinterpret an old
+ image as a new UTF-8, ULEB, or semantic-F64 profile. *)
+Inductive PersistentLogicalProfile :=
+| PersistedByte
+| PersistedUnicodeScalar
+| PersistedU64
+| PersistedF64Bits
+| PersistedCanonicalUleb
+| PersistedCanonicalUtf8.
+
+Inductive PersistentCodecIdentity :=
+| ExistingByteCodec
+| ExistingCharU32Codec
+| ExistingU64Codec
+| ProspectiveF64BitsCodecV1
+| ProspectiveCanonicalUlebCodecV1
+| ProspectiveCanonicalUtf8CodecV1.
+
+Inductive PersistentLayoutIdentity :=
+| ExistingByteLayout
+| ExistingCharLayout
+| ExistingU64Layout
+| ProspectiveLogicalUnitLayoutV1.
+
+Record PersistentProfileDescriptor := {
+ persistent_logical_profile : PersistentLogicalProfile;
+ persistent_codec_identity : PersistentCodecIdentity;
+ persistent_layout_identity : PersistentLayoutIdentity;
+ persistent_abi_version : nat;
+}.
+
+Definition certified_persistent_profile
+ (descriptor : PersistentProfileDescriptor) : Prop :=
+ match descriptor.(persistent_logical_profile),
+ descriptor.(persistent_codec_identity),
+ descriptor.(persistent_layout_identity) with
+ | PersistedByte, ExistingByteCodec, ExistingByteLayout =>
+ 0 < descriptor.(persistent_abi_version)
+ | PersistedUnicodeScalar, ExistingCharU32Codec, ExistingCharLayout =>
+ 0 < descriptor.(persistent_abi_version)
+ | PersistedU64, ExistingU64Codec, ExistingU64Layout =>
+ 0 < descriptor.(persistent_abi_version)
+ | PersistedF64Bits, ProspectiveF64BitsCodecV1,
+ ProspectiveLogicalUnitLayoutV1 =>
+ 0 < descriptor.(persistent_abi_version)
+ | PersistedCanonicalUleb, ProspectiveCanonicalUlebCodecV1,
+ ProspectiveLogicalUnitLayoutV1 =>
+ 0 < descriptor.(persistent_abi_version)
+ | PersistedCanonicalUtf8, ProspectiveCanonicalUtf8CodecV1,
+ ProspectiveLogicalUnitLayoutV1 =>
+ 0 < descriptor.(persistent_abi_version)
+ | _, _, _ => False
+ end.
+
+Definition certified_profile_identity
+ (profile : PersistentProfileDescriptor)
+ : PersistentLogicalProfile *
+ (PersistentCodecIdentity * (PersistentLayoutIdentity * nat)) :=
+ (profile.(persistent_logical_profile),
+ (profile.(persistent_codec_identity),
+ (profile.(persistent_layout_identity), profile.(persistent_abi_version)))).
+
+Theorem VWENC_86_CERTIFIED_PERSISTENT_PROFILE_IDENTITY_IS_INJECTIVE :
+ forall left right,
+ certified_profile_identity left = certified_profile_identity right ->
+ left = right.
+Proof.
+ intros [left_profile left_codec left_layout left_abi]
+ [right_profile right_codec right_layout right_abi] Hequal.
+ unfold certified_profile_identity in Hequal. simpl in Hequal.
+ now inversion Hequal.
+Qed.
+
+Definition profile_bound_payload
+ (profile : PersistentProfileDescriptor)
+ (payload : list PhysicalByte) :=
+ (certified_profile_identity profile, payload).
+
+Theorem VWENC_87_PROFILE_AND_PAYLOAD_IDENTITY_IS_JOINTLY_INJECTIVE :
+ forall left_profile left_payload right_profile right_payload,
+ profile_bound_payload left_profile left_payload =
+ profile_bound_payload right_profile right_payload ->
+ left_profile = right_profile /\ left_payload = right_payload.
+Proof.
+ intros
+ [left_profile left_codec left_layout left_abi] left_payload
+ [right_profile right_codec right_layout right_abi] right_payload Hequal.
+ unfold profile_bound_payload, certified_profile_identity in Hequal.
+ simpl in Hequal. inversion Hequal. split; reflexivity.
+Qed.
+
+Theorem VWENC_98_CERTIFICATION_REJECTS_INCOHERENT_PROFILE_CODEC_LAYOUT :
+ ~ certified_persistent_profile
+ {| persistent_logical_profile := PersistedCanonicalUleb;
+ persistent_codec_identity := ExistingCharU32Codec;
+ persistent_layout_identity := ExistingByteLayout;
+ persistent_abi_version := 1 |}.
+Proof. simpl. tauto. Qed.
+
+Theorem VWENC_99_CERTIFICATION_ACCEPTS_VERSIONED_CANONICAL_ULEB_PROFILE :
+ certified_persistent_profile
+ {| persistent_logical_profile := PersistedCanonicalUleb;
+ persistent_codec_identity := ProspectiveCanonicalUlebCodecV1;
+ persistent_layout_identity := ProspectiveLogicalUnitLayoutV1;
+ persistent_abi_version := 1 |}.
+Proof.
+ unfold certified_persistent_profile. simpl.
+ exact (Nat.lt_0_succ 0).
+Qed.
+
+(** ** F64Bits raw identity and total_cmp-compatible ordering *)
+
+Definition valid_f64_bits (bits : nat) : Prop := bits < two_to_64.
+
+(** Positive encodings occupy the upper half in increasing bit order. Signed
+ encodings occupy the lower half in reversed bit order. This is the
+ sortable-key form of Rust's [f64::total_cmp] transformation. *)
+Definition split_rank (half whole bits : nat) : nat :=
+ if bits half
+ then half + bits
+ else (whole - 1) - bits.
+
+Definition f64_total_rank (bits : nat) : nat :=
+ split_rank two_to_63 two_to_64 bits.
+
+Definition compare_f64_bits (left right : nat) : comparison :=
+ Nat.compare (f64_total_rank left) (f64_total_rank right).
+
+Definition f64_bits_identity (bits : nat) : nat := bits.
+
+Theorem VWENC_18_F64BITS_RAW_IDENTITY_IS_INJECTIVE :
+ forall (left right : nat),
+ f64_bits_identity left = f64_bits_identity right -> left = right.
+Proof. intros left right Hequal. exact Hequal. Qed.
+
+Theorem VWENC_19_F64BITS_SIGNED_ZEROES_ARE_DISTINCT :
+ 0 <> two_to_63 /\
+ f64_total_rank two_to_63 < f64_total_rank 0.
+Proof.
+ pose proof two_to_63_positive as Hhalf_positive.
+ pose proof two_to_64_is_double_two_to_63 as Hdouble.
+ split; [lia |].
+ unfold f64_total_rank, split_rank.
+ assert ((two_to_63 two_to_63) = false) as Hhalf.
+ { apply Nat.ltb_ge. lia. }
+ assert ((0 two_to_63) = true) as Hzero.
+ { apply Nat.ltb_lt. exact Hhalf_positive. }
+ rewrite Hhalf, Hzero. lia.
+Qed.
+
+Theorem VWENC_20_F64BITS_TOTAL_ORDER_IS_RANK_ORDER :
+ forall left right,
+ compare_f64_bits left right =
+ Nat.compare (f64_total_rank left) (f64_total_rank right).
+Proof. reflexivity. Qed.
+
+Lemma split_rank_injective :
+ forall half whole left right,
+ 0 < half ->
+ whole = 2 * half ->
+ left < whole ->
+ right < whole ->
+ split_rank half whole left = split_rank half whole right ->
+ left = right.
+Proof.
+ intros half whole left right Hhalf Hwhole Hleft Hright Hrank.
+ unfold split_rank in Hrank.
+ destruct (left half) eqn:Hleftsign;
+ destruct (right half) eqn:Hrightsign;
+ rewrite ?Nat.ltb_lt, ?Nat.ltb_ge in *; lia.
+Qed.
+
+Theorem VWENC_21_F64BITS_TOTAL_RANK_INJECTIVE :
+ forall left right,
+ valid_f64_bits left ->
+ valid_f64_bits right ->
+ f64_total_rank left = f64_total_rank right ->
+ left = right.
+Proof.
+ intros left right Hleft Hright Hrank.
+ unfold valid_f64_bits in Hleft, Hright.
+ unfold f64_total_rank in Hrank.
+ eapply split_rank_injective.
+ - exact two_to_63_positive.
+ - exact two_to_64_is_double_two_to_63.
+ - exact Hleft.
+ - exact Hright.
+ - exact Hrank.
+Qed.
+
+Definition f64_hash_material (bits : nat) : nat := bits.
+
+Theorem VWENC_52_F64BITS_ALL_DISTINCT_PATTERNS_REMAIN_DISTINCT :
+ forall left right,
+ valid_f64_bits left ->
+ valid_f64_bits right ->
+ left <> right ->
+ f64_bits_identity left <> f64_bits_identity right /\
+ f64_hash_material left <> f64_hash_material right /\
+ compare_f64_bits left right <> Eq.
+Proof.
+ intros left right Hleft Hright Hdistinct.
+ repeat split; try exact Hdistinct.
+ intros Hequal.
+ unfold compare_f64_bits in Hequal.
+ apply Nat.compare_eq_iff in Hequal.
+ apply Hdistinct.
+ now apply VWENC_21_F64BITS_TOTAL_RANK_INJECTIVE.
+Qed.
+
+Theorem VWENC_73_F64BITS_COMPARATOR_EQUAL_IFF_RAW_BITS_EQUAL :
+ forall left right,
+ valid_f64_bits left ->
+ valid_f64_bits right ->
+ (compare_f64_bits left right = Eq <-> left = right).
+Proof.
+ intros left right Hleft Hright. split.
+ - unfold compare_f64_bits. rewrite Nat.compare_eq_iff.
+ now apply VWENC_21_F64BITS_TOTAL_RANK_INJECTIVE.
+ - intros ->. unfold compare_f64_bits. apply Nat.compare_refl.
+Qed.
+
+Theorem VWENC_74_F64BITS_COMPARATOR_IS_TOTAL :
+ forall left right,
+ compare_f64_bits left right = Lt \/
+ compare_f64_bits left right = Eq \/
+ compare_f64_bits left right = Gt.
+Proof.
+ intros left right.
+ destruct (compare_f64_bits left right); tauto.
+Qed.
+
+Theorem VWENC_75_F64BITS_COMPARATOR_IS_ANTISYMMETRIC :
+ forall left right,
+ (compare_f64_bits left right = Lt <->
+ compare_f64_bits right left = Gt) /\
+ (compare_f64_bits left right = Gt <->
+ compare_f64_bits right left = Lt).
+Proof.
+ intros left right. unfold compare_f64_bits.
+ repeat split; intro Hcompare.
+ - apply Nat.compare_lt_iff in Hcompare.
+ apply Nat.compare_gt_iff. exact Hcompare.
+ - apply Nat.compare_gt_iff in Hcompare.
+ apply Nat.compare_lt_iff. exact Hcompare.
+ - apply Nat.compare_gt_iff in Hcompare.
+ apply Nat.compare_lt_iff. exact Hcompare.
+ - apply Nat.compare_lt_iff in Hcompare.
+ apply Nat.compare_gt_iff. exact Hcompare.
+Qed.
+
+Theorem VWENC_76_F64BITS_COMPARATOR_LT_IS_TRANSITIVE :
+ forall left middle right,
+ compare_f64_bits left middle = Lt ->
+ compare_f64_bits middle right = Lt ->
+ compare_f64_bits left right = Lt.
+Proof.
+ intros left middle right Hleft Hright.
+ unfold compare_f64_bits in *.
+ apply Nat.compare_lt_iff in Hleft.
+ apply Nat.compare_lt_iff in Hright.
+ apply Nat.compare_lt_iff. lia.
+Qed.
+
+(** Equivalent rank obtained by interpreting the high bit as the IEEE sign,
+ reversing the lower-half order for negative encodings, and then shifting
+ the signed key into naturals. This is the arithmetic form of Rust's
+ [f64::total_cmp] signed-key transform. *)
+Definition rust_total_cmp_shifted_rank
+ (half bits : nat) : nat :=
+ if bits half
+ then half + bits
+ else (half - 1) - (bits - half).
+
+Theorem VWENC_77_F64BITS_RANK_MATCHES_RUST_SIGNED_KEY_TRANSFORM :
+ forall bits,
+ valid_f64_bits bits ->
+ f64_total_rank bits = rust_total_cmp_shifted_rank two_to_63 bits.
+Proof.
+ intros bits Hvalid.
+ unfold valid_f64_bits in Hvalid.
+ unfold f64_total_rank, split_rank, rust_total_cmp_shifted_rank.
+ destruct (bits two_to_63) eqn:Hsign; [reflexivity |].
+ apply Nat.ltb_ge in Hsign.
+ pose proof two_to_63_positive.
+ pose proof two_to_64_is_double_two_to_63.
+ lia.
+Qed.
+
+(** Negative control: a numeric-equality representation that aliases signed
+ zero violates the raw-bit identity law. *)
+Definition f64_zero_alias_mutant (bits : nat) : nat :=
+ if bits =? two_to_63 then 0 else bits.
+
+Definition preserves_distinct_valid_f64_bits
+ (identity : nat -> nat) : Prop :=
+ forall left right,
+ valid_f64_bits left ->
+ valid_f64_bits right ->
+ left <> right ->
+ identity left <> identity right.
+
+Lemma f64_zero_alias_mutant_aliases_signed_zero :
+ 0 <> two_to_63 /\
+ f64_zero_alias_mutant 0 = f64_zero_alias_mutant two_to_63.
+Proof.
+ pose proof two_to_63_positive as Hpositive.
+ split; [lia |].
+ unfold f64_zero_alias_mutant.
+ rewrite Nat.eqb_refl.
+ assert ((0 =? two_to_63) = false) as Hdistinct.
+ { apply Nat.eqb_neq. lia. }
+ now rewrite Hdistinct.
+Qed.
+
+Theorem VWENC_78_NEGATIVE_CONTROL_NUMERIC_F64_IDENTITY_VIOLATES_RAW_BITS :
+ ~ preserves_distinct_valid_f64_bits f64_zero_alias_mutant.
+Proof.
+ intros Hpreserves.
+ destruct f64_zero_alias_mutant_aliases_signed_zero
+ as [Hdistinct Halias].
+ assert (valid_f64_bits 0) as Hzero.
+ { unfold valid_f64_bits.
+ pose proof two_to_63_positive.
+ pose proof two_to_64_is_double_two_to_63. lia. }
+ assert (valid_f64_bits two_to_63) as Hnegative_zero.
+ { unfold valid_f64_bits.
+ pose proof two_to_63_positive.
+ pose proof two_to_64_is_double_two_to_63. lia. }
+ specialize
+ (Hpreserves 0 two_to_63 Hzero Hnegative_zero Hdistinct).
+ exact (Hpreserves Halias).
+Qed.
+
+(** Negative control: comparing only the first encoded ULEB byte reverses the
+ adjacent numeric values 255 and 256. *)
+Definition compare_first_uleb_byte
+ (left right : list PhysicalByte) : comparison :=
+ match left, right with
+ | left_byte :: _, right_byte :: _ => Nat.compare left_byte right_byte
+ | [], [] => Eq
+ | [], _ => Lt
+ | _, [] => Gt
+ end.
+
+Theorem VWENC_79_NEGATIVE_CONTROL_ENCODED_BYTE_ORDER_REVERSES_255_AND_256 :
+ canonical_uleb_codeword [255; 1] /\
+ canonical_uleb_codeword [128; 2] /\
+ compare_uleb_codewords [255; 1] [128; 2] = Lt /\
+ compare_first_uleb_byte [255; 1] [128; 2] = Gt.
+Proof.
+ assert (canonical_uleb_codeword [255; 1]) as H255.
+ { split.
+ - apply UlebShapeMore; [lia | lia |].
+ apply UlebShapeLast. lia.
+ - unfold canonical_uleb_digits, decode_uleb_payloads,
+ uleb_payload, valid_uleb_digit.
+ simpl. repeat split.
+ + discriminate.
+ + constructor; [lia | constructor; [lia | constructor]].
+ + lia. }
+ assert (canonical_uleb_codeword [128; 2]) as H256.
+ { split.
+ - apply UlebShapeMore; [lia | lia |].
+ apply UlebShapeLast. lia.
+ - unfold canonical_uleb_digits, decode_uleb_payloads,
+ uleb_payload, valid_uleb_digit.
+ simpl. repeat split.
+ + discriminate.
+ + constructor; [lia | constructor; [lia | constructor]].
+ + lia. }
+ split; [exact H255 |].
+ split; [exact H256 |].
+ split; reflexivity.
+Qed.
+
+Definition direct_identity
+ (profile : DirectProfile) (unit : nat) : nat * nat :=
+ (direct_profile_tag profile, unit).
+
+Definition direct_hash_material
+ (profile : DirectProfile) (unit : nat) : nat * nat :=
+ direct_identity profile unit.
+
+Definition direct_order_key
+ (profile : DirectProfile) (unit : nat) : nat :=
+ match profile with
+ | DirectF64Bits => f64_total_rank unit
+ | _ => unit
+ end.
+
+Definition compare_direct_units
+ (profile : DirectProfile) (left right : nat) : comparison :=
+ Nat.compare (direct_order_key profile left) (direct_order_key profile right).
+
+Theorem VWENC_53_DIRECT_IDENTITY_AND_HASH_ARE_PROFILE_SCOPED_AND_INJECTIVE :
+ forall left_profile left_unit right_profile right_unit,
+ direct_hash_material left_profile left_unit =
+ direct_hash_material right_profile right_unit ->
+ left_profile = right_profile /\ left_unit = right_unit.
+Proof.
+ intros left_profile left_unit right_profile right_unit Hequal.
+ unfold direct_hash_material, direct_identity in Hequal.
+ inversion Hequal as [[Htag Hunit]].
+ split.
+ - now apply VWENC_48_DIRECT_PROFILE_TAGS_ARE_INJECTIVE.
+ - reflexivity.
+Qed.
+
+Theorem VWENC_54_UNSIGNED_DIRECT_ORDER_IS_LOGICAL_VALUE_ORDER :
+ forall profile left right,
+ profile <> DirectF64Bits ->
+ compare_direct_units profile left right = Nat.compare left right.
+Proof.
+ intros profile left right Hnotf64.
+ destruct profile; [reflexivity | reflexivity | reflexivity | reflexivity |].
+ contradiction.
+Qed.
+
+Theorem VWENC_55_F64BITS_DIRECT_ORDER_IS_TOTAL_CMP_ORDER :
+ forall left right,
+ compare_direct_units DirectF64Bits left right =
+ compare_f64_bits left right.
+Proof. reflexivity. Qed.
+
+Theorem VWENC_56_DIRECT_PROFILE_WIDTHS_ARE_EXPLICIT :
+ direct_byte_width DirectBytes = 1 /\
+ direct_byte_width DirectUnicodeScalar = 4 /\
+ direct_byte_width DirectU32 = 4 /\
+ direct_byte_width DirectU64 = 8 /\
+ direct_byte_width DirectF64Bits = 8.
+Proof. repeat split; reflexivity. Qed.
+
+End VariableWidthCodecSpec.
diff --git a/formal-verification/rocq/Spec/VariableWidthFamilyRefinementSpec.v b/formal-verification/rocq/Spec/VariableWidthFamilyRefinementSpec.v
new file mode 100644
index 00000000..723fb169
--- /dev/null
+++ b/formal-verification/rocq/Spec/VariableWidthFamilyRefinementSpec.v
@@ -0,0 +1,2421 @@
+(** * Family/profile refinement and consumer-observation laws
+
+ This module is the family-wide refinement layer for variable-width logical
+ units. It deliberately separates three concepts:
+
+ - a logical observation, which is visible to [liblevenshtein], [llattice],
+ and other traversing consumers;
+ - a storage/profile route, which selects a native kernel, a fixed-width ID
+ kernel, or the PathMap byte adapter before traversal begins; and
+ - physical state, including encoded staging bytes and node layout, which is
+ not a logical observation.
+
+ Arbitrary-width canonical ULEB128 values remain in the vocabulary owner.
+ A hot dictionary edge contains either one direct fixed-width unit or one
+ fixed-width [SymbolId]. Consequently the vocabulary binding is checked
+ once when a snapshot/query view is constructed, never by decoding an
+ arbitrary-width value at every node.
+
+ The closed family, profile, and surface inventories below are the
+ reviewable applicability matrix for this release. Open downstream unit
+ implementations remain possible in memory; persistent format identities
+ are separately certified and never inferred from Rust type names.
+
+ Stable theorem names beginning with [VWENC_] are machine-readable
+ invariant identifiers. They are extracted into the implementation
+ conformance ledger and property-test suite after this formal gate closes.
+*)
+
+From Coq Require Import Arith Bool Lia List PeanoNat ProofIrrelevance.
+Require Import ARTrie.Spec.VariableWidthCodecSpec.
+Require Import ARTrie.Spec.VariableWidthInterningSpec.
+Import ListNotations.
+Import VariableWidthCodecSpec VariableWidthInterning.
+
+Module VariableWidthFamilyRefinementSpec.
+
+(** ** Representation-independent logical observations *)
+
+Record LogicalObservations (Atom Value : Type) : Type := {
+ observe_membership : list Atom -> bool;
+ observe_terminality : list Atom -> bool;
+ observe_mapped_value : list Atom -> option Value;
+ observe_ordered_outgoing : list Atom -> list Atom;
+ observe_prefix_entries : list Atom -> list (list Atom * option Value);
+ observe_full_enumeration : list (list Atom * option Value);
+ observe_substring_applicable : bool;
+ observe_substring_results : list Atom -> list (list Atom * option Value);
+ observe_suffix_applicable : bool;
+ observe_suffix_results : list Atom -> list (list Atom * option Value)
+}.
+
+(** Equality of observations is deliberately extensional. It includes the
+ order of outgoing labels and enumeration results because deterministic
+ iteration is part of the public contract. *)
+Record SameLogicalObservations {Atom Value : Type}
+ (left right : LogicalObservations Atom Value) : Prop := {
+ same_membership :
+ forall word, observe_membership Atom Value left word =
+ observe_membership Atom Value right word;
+ same_terminality :
+ forall word, observe_terminality Atom Value left word =
+ observe_terminality Atom Value right word;
+ same_mapped_value :
+ forall word, observe_mapped_value Atom Value left word =
+ observe_mapped_value Atom Value right word;
+ same_ordered_outgoing :
+ forall prefix, observe_ordered_outgoing Atom Value left prefix =
+ observe_ordered_outgoing Atom Value right prefix;
+ same_prefix_entries :
+ forall prefix, observe_prefix_entries Atom Value left prefix =
+ observe_prefix_entries Atom Value right prefix;
+ same_full_enumeration :
+ observe_full_enumeration Atom Value left =
+ observe_full_enumeration Atom Value right;
+ same_substring_applicability :
+ observe_substring_applicable Atom Value left =
+ observe_substring_applicable Atom Value right;
+ same_substring_results :
+ forall query,
+ observe_substring_applicable Atom Value left = true ->
+ observe_substring_results Atom Value left query =
+ observe_substring_results Atom Value right query;
+ same_suffix_applicability :
+ observe_suffix_applicable Atom Value left =
+ observe_suffix_applicable Atom Value right;
+ same_suffix_results :
+ forall query,
+ observe_suffix_applicable Atom Value left = true ->
+ observe_suffix_results Atom Value left query =
+ observe_suffix_results Atom Value right query
+}.
+
+Lemma same_logical_observations_reflexive :
+ forall (Atom Value : Type) (view : LogicalObservations Atom Value),
+ SameLogicalObservations view view.
+Proof. intros. constructor; intros; reflexivity. Qed.
+
+Lemma same_logical_observations_symmetric :
+ forall (Atom Value : Type) (left right : LogicalObservations Atom Value),
+ SameLogicalObservations left right ->
+ SameLogicalObservations right left.
+Proof.
+ intros Atom Value left right Hsame.
+ destruct Hsame as
+ [Hmembership Hterminal Hvalue Houtgoing Hprefix Henumeration
+ Hsubstring_app Hsubstring Hsuffix_app Hsuffix].
+ constructor.
+ - intros. symmetry. auto.
+ - intros. symmetry. auto.
+ - intros. symmetry. auto.
+ - intros. symmetry. auto.
+ - intros. symmetry. auto.
+ - symmetry. exact Henumeration.
+ - symmetry. exact Hsubstring_app.
+ - intros query Hright_app. symmetry. apply Hsubstring.
+ rewrite Hsubstring_app. exact Hright_app.
+ - symmetry. exact Hsuffix_app.
+ - intros query Hright_app. symmetry. apply Hsuffix.
+ rewrite Hsuffix_app. exact Hright_app.
+Qed.
+
+Lemma same_logical_observations_transitive :
+ forall (Atom Value : Type)
+ (left middle right : LogicalObservations Atom Value),
+ SameLogicalObservations left middle ->
+ SameLogicalObservations middle right ->
+ SameLogicalObservations left right.
+Proof.
+ intros Atom Value left middle right Hleft Hright.
+ destruct Hleft as
+ [Hlm Hlt Hlv Hlo Hlp Hle Hlsa Hls Hlsua Hlsu].
+ destruct Hright as
+ [Hmm Hmt Hmv Hmo Hmp Hme Hmsa Hms Hmsua Hmsu].
+ constructor.
+ - intros. eauto using eq_trans.
+ - intros. eauto using eq_trans.
+ - intros. eauto using eq_trans.
+ - intros. eauto using eq_trans.
+ - intros. eauto using eq_trans.
+ - eauto using eq_trans.
+ - eauto using eq_trans.
+ - intros query Hleft_app.
+ assert (Hmiddle_app :
+ observe_substring_applicable Atom Value middle = true).
+ { rewrite <- Hlsa. exact Hleft_app. }
+ eapply eq_trans.
+ + now apply Hls.
+ + now apply Hms.
+ - eauto using eq_trans.
+ - intros query Hleft_app.
+ assert (Hmiddle_app :
+ observe_suffix_applicable Atom Value middle = true).
+ { rewrite <- Hlsua. exact Hleft_app. }
+ eapply eq_trans.
+ + now apply Hlsu.
+ + now apply Hmsu.
+Qed.
+
+Theorem VWENC_194_LOGICAL_OBSERVATIONAL_EQUIVALENCE_IS_AN_EQUIVALENCE :
+ (forall (Atom Value : Type) (view : LogicalObservations Atom Value),
+ SameLogicalObservations view view) /\
+ (forall (Atom Value : Type)
+ (left right : LogicalObservations Atom Value),
+ SameLogicalObservations left right ->
+ SameLogicalObservations right left) /\
+ (forall (Atom Value : Type)
+ (left middle right : LogicalObservations Atom Value),
+ SameLogicalObservations left middle ->
+ SameLogicalObservations middle right ->
+ SameLogicalObservations left right).
+Proof.
+ split.
+ - intros. apply same_logical_observations_reflexive.
+ - split.
+ + intros. now apply same_logical_observations_symmetric.
+ + intros. eapply same_logical_observations_transitive; eassumption.
+Qed.
+
+Theorem VWENC_195_MEMBERSHIP_AND_TERMINALITY_ARE_LOGICAL_OBSERVATIONS :
+ forall (Atom Value : Type)
+ (left right : LogicalObservations Atom Value) word,
+ SameLogicalObservations left right ->
+ observe_membership Atom Value left word =
+ observe_membership Atom Value right word /\
+ observe_terminality Atom Value left word =
+ observe_terminality Atom Value right word.
+Proof.
+ intros Atom Value left right word Hsame. split.
+ - now apply same_membership.
+ - now apply same_terminality.
+Qed.
+
+Theorem VWENC_196_MAPPED_VALUE_PRESENCE_AND_IDENTITY_ARE_OBSERVABLE :
+ forall (Atom Value : Type)
+ (left right : LogicalObservations Atom Value) word,
+ SameLogicalObservations left right ->
+ observe_mapped_value Atom Value left word =
+ observe_mapped_value Atom Value right word.
+Proof. intros. now apply same_mapped_value. Qed.
+
+Theorem VWENC_197_ORDERED_LOGICAL_OUTGOING_LABELS_ARE_OBSERVABLE :
+ forall (Atom Value : Type)
+ (left right : LogicalObservations Atom Value) prefix,
+ SameLogicalObservations left right ->
+ observe_ordered_outgoing Atom Value left prefix =
+ observe_ordered_outgoing Atom Value right prefix.
+Proof. intros. now apply same_ordered_outgoing. Qed.
+
+Theorem VWENC_198_PREFIX_ENTRIES_ARE_LOGICAL_OBSERVATIONS :
+ forall (Atom Value : Type)
+ (left right : LogicalObservations Atom Value) prefix,
+ SameLogicalObservations left right ->
+ observe_prefix_entries Atom Value left prefix =
+ observe_prefix_entries Atom Value right prefix.
+Proof. intros. now apply same_prefix_entries. Qed.
+
+Theorem VWENC_199_FULL_ENUMERATION_ORDER_IS_DETERMINISTIC_AND_OBSERVABLE :
+ forall (Atom Value : Type)
+ (left right : LogicalObservations Atom Value),
+ SameLogicalObservations left right ->
+ observe_full_enumeration Atom Value left =
+ observe_full_enumeration Atom Value right.
+Proof. intros. now apply same_full_enumeration. Qed.
+
+Theorem VWENC_200_APPLICABLE_SUBSTRING_RESULTS_ARE_LOGICAL_OBSERVATIONS :
+ forall (Atom Value : Type)
+ (left right : LogicalObservations Atom Value) query,
+ SameLogicalObservations left right ->
+ observe_substring_applicable Atom Value left = true ->
+ observe_substring_applicable Atom Value left =
+ observe_substring_applicable Atom Value right /\
+ observe_substring_results Atom Value left query =
+ observe_substring_results Atom Value right query.
+Proof.
+ intros Atom Value left right query Hsame Happlicable. split.
+ - now apply same_substring_applicability.
+ - now apply same_substring_results.
+Qed.
+
+Theorem VWENC_201_APPLICABLE_SUFFIX_RESULTS_ARE_LOGICAL_OBSERVATIONS :
+ forall (Atom Value : Type)
+ (left right : LogicalObservations Atom Value) query,
+ SameLogicalObservations left right ->
+ observe_suffix_applicable Atom Value left = true ->
+ observe_suffix_applicable Atom Value left =
+ observe_suffix_applicable Atom Value right /\
+ observe_suffix_results Atom Value left query =
+ observe_suffix_results Atom Value right query.
+Proof.
+ intros Atom Value left right query Hsame Happlicable. split.
+ - now apply same_suffix_applicability.
+ - now apply same_suffix_results.
+Qed.
+
+Record PhysicalImplementation (Atom Value : Type) : Type := {
+ implementation_logical_view : LogicalObservations Atom Value;
+ implementation_node_layout : list nat;
+ implementation_staging_bytes : list PhysicalByte;
+ implementation_hash_buckets : list nat;
+ implementation_wal_bytes : list PhysicalByte
+}.
+
+Definition replace_physical_state {Atom Value : Type}
+ (implementation : PhysicalImplementation Atom Value)
+ (node_layout hash_buckets : list nat)
+ (staging_bytes wal_bytes : list PhysicalByte)
+ : PhysicalImplementation Atom Value :=
+ {| implementation_logical_view :=
+ implementation_logical_view Atom Value implementation;
+ implementation_node_layout := node_layout;
+ implementation_staging_bytes := staging_bytes;
+ implementation_hash_buckets := hash_buckets;
+ implementation_wal_bytes := wal_bytes |}.
+
+Theorem VWENC_202_PHYSICAL_LAYOUT_AND_CODEC_STAGING_STATE_ARE_NONOBSERVABLE :
+ forall (Atom Value : Type)
+ (implementation : PhysicalImplementation Atom Value)
+ node_layout hash_buckets staging_bytes wal_bytes,
+ SameLogicalObservations
+ (implementation_logical_view Atom Value implementation)
+ (implementation_logical_view Atom Value
+ (replace_physical_state implementation node_layout hash_buckets
+ staging_bytes wal_bytes)).
+Proof. intros. apply same_logical_observations_reflexive. Qed.
+
+(** ** Closed family/profile/surface applicability matrix *)
+
+Inductive DictionaryFamily : Type :=
+| DynamicDawgFamily
+| DoubleArrayTrieFamily
+| SuffixAutomatonFamily
+| ScdawgFamily
+| PathMapAdapterFamily
+| PersistentARTrieFamily
+| PersistentSuffixAutomatonFamily
+| PersistentSuffixTreeFamily
+| PersistentScdawgFamily
+| BijectiveMapFamily
+| PersistentVocabARTrieFamily.
+
+Definition all_dictionary_families : list DictionaryFamily :=
+ [DynamicDawgFamily; DoubleArrayTrieFamily; SuffixAutomatonFamily;
+ ScdawgFamily; PathMapAdapterFamily; PersistentARTrieFamily;
+ PersistentSuffixAutomatonFamily; PersistentSuffixTreeFamily;
+ PersistentScdawgFamily; BijectiveMapFamily;
+ PersistentVocabARTrieFamily].
+
+Inductive DirectUnitDomain : Type :=
+| DirectBytesDomain
+| DirectUnicodeScalarDomain
+| DirectU32Domain
+| DirectU64Domain
+| DirectF64BitsDomain.
+
+Inductive InternedAtomDomain : Type :=
+| CanonicalUlebDomain
+| CanonicalUtf8Domain
+| OpaqueCanonicalBytesDomain.
+
+Inductive IdCarrier : Type :=
+| U32IdCarrier
+| U64IdCarrier.
+
+Inductive FamilyProfile : Type :=
+| DirectProfile : DirectUnitDomain -> FamilyProfile
+| InternedProfile : InternedAtomDomain -> IdCarrier -> FamilyProfile.
+
+Definition all_family_profiles : list FamilyProfile :=
+ [DirectProfile DirectBytesDomain;
+ DirectProfile DirectUnicodeScalarDomain;
+ DirectProfile DirectU32Domain;
+ DirectProfile DirectU64Domain;
+ DirectProfile DirectF64BitsDomain;
+ InternedProfile CanonicalUlebDomain U32IdCarrier;
+ InternedProfile CanonicalUlebDomain U64IdCarrier;
+ InternedProfile CanonicalUtf8Domain U32IdCarrier;
+ InternedProfile CanonicalUtf8Domain U64IdCarrier;
+ InternedProfile OpaqueCanonicalBytesDomain U32IdCarrier;
+ InternedProfile OpaqueCanonicalBytesDomain U64IdCarrier].
+
+(** The logical unit type is a function of the profile. An implementation
+ cannot independently choose an unrelated [Atom] type. *)
+Definition direct_codec_profile
+ (domain : DirectUnitDomain) : VariableWidthCodecSpec.DirectProfile :=
+ match domain with
+ | DirectBytesDomain => DirectBytes
+ | DirectUnicodeScalarDomain => DirectUnicodeScalar
+ | DirectU32Domain => DirectU32
+ | DirectU64Domain => DirectU64
+ | DirectF64BitsDomain => DirectF64Bits
+ end.
+
+Definition u32_id_profile : FixedWidthCarrierProfile :=
+ {| carrier_format_identity := 32;
+ carrier_width_bytes := 4;
+ carrier_width_positive := ltac:(lia) |}.
+
+Definition u64_id_profile : FixedWidthCarrierProfile :=
+ {| carrier_format_identity := 64;
+ carrier_width_bytes := 8;
+ carrier_width_positive := ltac:(lia) |}.
+
+Definition id_carrier_profile
+ (carrier : IdCarrier) : FixedWidthCarrierProfile :=
+ match carrier with
+ | U32IdCarrier => u32_id_profile
+ | U64IdCarrier => u64_id_profile
+ end.
+
+Definition DirectUnit (domain : DirectUnitDomain) : Type :=
+ { unit : nat | direct_profile_valid (direct_codec_profile domain) unit }.
+
+Definition ProfileUnit (profile : FamilyProfile) : Type :=
+ match profile with
+ | DirectProfile domain => DirectUnit domain
+ | InternedProfile _ carrier => SymbolId (id_carrier_profile carrier)
+ end.
+
+Inductive ExplicitLayoutContract : Type :=
+| GenericLogicalLayout
+| PathMapNativeByteLayout
+| PathMapUtf8BoundaryLayout
+| PathMapFixedWidthBoundaryLayout
+| PathMapInternedIdLayout : IdCarrier -> ExplicitLayoutContract
+| PersistentU64CompactLayout
+| PersistentU64Prefix3CompatibilityLayout
+| EncodedU64ByteCompatibilityLayout
+| ProspectiveInternedIdLayout : IdCarrier -> ExplicitLayoutContract.
+
+Inductive ProfileRoute : Type :=
+| GenericNativeKernel
+| RetainedSpecializedKernel
+| InternedFixedIdKernel : IdCarrier -> ProfileRoute
+| EncodedU64ByteAdapterKernel
+| PathMapNativeByteRoute
+| PathMapUtf8BoundaryAdapterRoute
+| PathMapFixedWidthBoundaryAdapterRoute
+| PathMapInternedIdAdapterRoute : IdCarrier -> ProfileRoute
+| BijectiveTermValueKernel
+| VocabularyOwnerRoute : IdCarrier -> ProfileRoute.
+
+(** Existing behavior and prospective work are deliberately distinct. There
+ is no "unknown" or implicit-support constructor. *)
+Inductive ProfileCell : Type :=
+| ExistingProfileCell : ProfileRoute -> ExplicitLayoutContract -> ProfileCell
+| ProspectiveProfileCell : ProfileRoute -> ExplicitLayoutContract -> ProfileCell.
+
+Definition family_profile_cell
+ (family : DictionaryFamily) (profile : FamilyProfile) : ProfileCell :=
+ match family, profile with
+ | DynamicDawgFamily, DirectProfile DirectBytesDomain
+ | DynamicDawgFamily, DirectProfile DirectUnicodeScalarDomain
+ | DynamicDawgFamily, DirectProfile DirectU64Domain
+ | DoubleArrayTrieFamily, DirectProfile DirectBytesDomain
+ | DoubleArrayTrieFamily, DirectProfile DirectUnicodeScalarDomain
+ | SuffixAutomatonFamily, DirectProfile DirectBytesDomain
+ | SuffixAutomatonFamily, DirectProfile DirectUnicodeScalarDomain
+ | ScdawgFamily, DirectProfile DirectBytesDomain
+ | ScdawgFamily, DirectProfile DirectUnicodeScalarDomain
+ | PersistentSuffixAutomatonFamily, DirectProfile DirectBytesDomain
+ | PersistentSuffixAutomatonFamily, DirectProfile DirectUnicodeScalarDomain
+ | PersistentSuffixTreeFamily, DirectProfile DirectBytesDomain
+ | PersistentSuffixTreeFamily, DirectProfile DirectUnicodeScalarDomain
+ | PersistentScdawgFamily, DirectProfile DirectBytesDomain
+ | PersistentScdawgFamily, DirectProfile DirectUnicodeScalarDomain =>
+ ExistingProfileCell RetainedSpecializedKernel GenericLogicalLayout
+ | PersistentARTrieFamily, DirectProfile DirectBytesDomain
+ | PersistentARTrieFamily, DirectProfile DirectUnicodeScalarDomain =>
+ ExistingProfileCell RetainedSpecializedKernel GenericLogicalLayout
+ | PersistentARTrieFamily, DirectProfile DirectU64Domain =>
+ ExistingProfileCell RetainedSpecializedKernel PersistentU64CompactLayout
+ | PathMapAdapterFamily, DirectProfile DirectBytesDomain =>
+ ExistingProfileCell PathMapNativeByteRoute PathMapNativeByteLayout
+ | PathMapAdapterFamily, DirectProfile DirectUnicodeScalarDomain =>
+ ExistingProfileCell PathMapUtf8BoundaryAdapterRoute
+ PathMapUtf8BoundaryLayout
+ | BijectiveMapFamily, DirectProfile DirectUnicodeScalarDomain =>
+ ExistingProfileCell BijectiveTermValueKernel GenericLogicalLayout
+ | PersistentVocabARTrieFamily,
+ DirectProfile DirectUnicodeScalarDomain =>
+ ExistingProfileCell (VocabularyOwnerRoute U64IdCarrier)
+ GenericLogicalLayout
+ | PathMapAdapterFamily, DirectProfile _ =>
+ ProspectiveProfileCell PathMapFixedWidthBoundaryAdapterRoute
+ PathMapFixedWidthBoundaryLayout
+ | PathMapAdapterFamily, InternedProfile _ carrier =>
+ ProspectiveProfileCell (PathMapInternedIdAdapterRoute carrier)
+ (PathMapInternedIdLayout carrier)
+ | BijectiveMapFamily, InternedProfile _ carrier
+ | PersistentVocabARTrieFamily, InternedProfile _ carrier =>
+ ProspectiveProfileCell (VocabularyOwnerRoute carrier)
+ (ProspectiveInternedIdLayout carrier)
+ | BijectiveMapFamily, DirectProfile _
+ | PersistentVocabARTrieFamily, DirectProfile _ =>
+ ProspectiveProfileCell BijectiveTermValueKernel GenericLogicalLayout
+ | _, DirectProfile _ =>
+ ProspectiveProfileCell GenericNativeKernel GenericLogicalLayout
+ | _, InternedProfile _ carrier =>
+ ProspectiveProfileCell (InternedFixedIdKernel carrier)
+ (ProspectiveInternedIdLayout carrier)
+ end.
+
+Definition profile_cell_route (cell : ProfileCell) : ProfileRoute :=
+ match cell with
+ | ExistingProfileCell route _ | ProspectiveProfileCell route _ => route
+ end.
+
+Definition profile_cell_layout
+ (cell : ProfileCell) : ExplicitLayoutContract :=
+ match cell with
+ | ExistingProfileCell _ layout | ProspectiveProfileCell _ layout => layout
+ end.
+
+Definition family_profile_route
+ (family : DictionaryFamily) (profile : FamilyProfile) : ProfileRoute :=
+ profile_cell_route (family_profile_cell family profile).
+
+Inductive ConsumerSurfaceClass : Type :=
+| DictionarySurface
+| DictionaryNodeSurfaceClass
+| ZipperSurfaceClass
+| SnapshotCursorSurfaceClass
+| FactorySurface
+| CollectionSurface
+| SerializationReopenSurface
+| SnapshotSurface
+| SetCombinatorSurface
+| ValueCombinatorSurface
+| PrefixSurface
+| SubstringSurface
+| SuffixSurface
+| ReverseLookupSurface.
+
+Definition all_consumer_surfaces : list ConsumerSurfaceClass :=
+ [DictionarySurface; DictionaryNodeSurfaceClass; ZipperSurfaceClass;
+ SnapshotCursorSurfaceClass; FactorySurface; CollectionSurface;
+ SerializationReopenSurface; SnapshotSurface; SetCombinatorSurface;
+ ValueCombinatorSurface; PrefixSurface; SubstringSurface; SuffixSurface;
+ ReverseLookupSurface].
+
+Inductive SurfaceRoute : Type :=
+| CommonDictionaryRoute
+| SuffixIndexRoute
+| VocabularyReverseLookupRoute.
+
+Inductive SurfaceInapplicability : Type :=
+| ExactTermFamilyHasNoSubstringIndex
+| TermIndexHasNoVocabularyReverseLookup
+| VocabularyOwnerHasNoSuffixIndex
+| PersistentConstructionRequiresExplicitStoreConfiguration.
+
+Inductive SurfaceCell : Type :=
+| ExistingSurface : SurfaceRoute -> SurfaceCell
+| ProspectiveSurface : SurfaceRoute -> SurfaceCell
+| SurfaceStructurallyInapplicable : SurfaceInapplicability -> SurfaceCell.
+
+Definition persistent_family (family : DictionaryFamily) : bool :=
+ match family with
+ | PersistentARTrieFamily | PersistentSuffixAutomatonFamily
+ | PersistentSuffixTreeFamily | PersistentScdawgFamily
+ | PersistentVocabARTrieFamily => true
+ | _ => false
+ end.
+
+Definition family_surface_cell
+ (family : DictionaryFamily) (surface : ConsumerSurfaceClass)
+ : SurfaceCell :=
+ match surface with
+ | ReverseLookupSurface =>
+ match family with
+ | BijectiveMapFamily | PersistentVocabARTrieFamily =>
+ ExistingSurface VocabularyReverseLookupRoute
+ | _ => SurfaceStructurallyInapplicable
+ TermIndexHasNoVocabularyReverseLookup
+ end
+ | SubstringSurface | SuffixSurface =>
+ match family with
+ | SuffixAutomatonFamily | ScdawgFamily
+ | PersistentSuffixAutomatonFamily | PersistentSuffixTreeFamily
+ | PersistentScdawgFamily => ExistingSurface SuffixIndexRoute
+ | BijectiveMapFamily | PersistentVocabARTrieFamily =>
+ SurfaceStructurallyInapplicable VocabularyOwnerHasNoSuffixIndex
+ | _ => SurfaceStructurallyInapplicable
+ ExactTermFamilyHasNoSubstringIndex
+ end
+ | FactorySurface =>
+ match family with
+ | PersistentARTrieFamily | PersistentSuffixAutomatonFamily
+ | PersistentSuffixTreeFamily | PersistentScdawgFamily
+ | PersistentVocabARTrieFamily =>
+ SurfaceStructurallyInapplicable
+ PersistentConstructionRequiresExplicitStoreConfiguration
+ | BijectiveMapFamily => ProspectiveSurface CommonDictionaryRoute
+ | _ => ExistingSurface CommonDictionaryRoute
+ end
+ | SerializationReopenSurface =>
+ if persistent_family family then ExistingSurface CommonDictionaryRoute
+ else ProspectiveSurface CommonDictionaryRoute
+ | DictionarySurface | DictionaryNodeSurfaceClass
+ | SnapshotCursorSurfaceClass | SnapshotSurface | PrefixSurface =>
+ ExistingSurface CommonDictionaryRoute
+ | CollectionSurface => ExistingSurface CommonDictionaryRoute
+ | ZipperSurfaceClass | SetCombinatorSurface | ValueCombinatorSurface =>
+ match family with
+ | DynamicDawgFamily | DoubleArrayTrieFamily | SuffixAutomatonFamily
+ | PathMapAdapterFamily | PersistentARTrieFamily =>
+ ExistingSurface CommonDictionaryRoute
+ | _ => ProspectiveSurface CommonDictionaryRoute
+ end
+ end.
+
+Inductive CapabilityInapplicability : Type :=
+| SurfaceCapabilityReason : SurfaceInapplicability ->
+ CapabilityInapplicability.
+
+Inductive CapabilityCell : Type :=
+| ExistingCapability : ProfileRoute -> ExplicitLayoutContract ->
+ SurfaceRoute -> CapabilityCell
+| ProspectiveCapability : ProfileRoute -> ExplicitLayoutContract ->
+ SurfaceRoute -> CapabilityCell
+| CapabilityStructurallyInapplicable :
+ CapabilityInapplicability -> CapabilityCell.
+
+Definition family_profile_surface_cell
+ (family : DictionaryFamily) (profile : FamilyProfile)
+ (surface : ConsumerSurfaceClass) : CapabilityCell :=
+ match family_profile_cell family profile,
+ family_surface_cell family surface with
+ | ExistingProfileCell route layout, ExistingSurface surface_route =>
+ ExistingCapability route layout surface_route
+ | ExistingProfileCell route layout, ProspectiveSurface surface_route
+ | ProspectiveProfileCell route layout, ExistingSurface surface_route
+ | ProspectiveProfileCell route layout, ProspectiveSurface surface_route =>
+ ProspectiveCapability route layout surface_route
+ | _, SurfaceStructurallyInapplicable reason =>
+ CapabilityStructurallyInapplicable (SurfaceCapabilityReason reason)
+ end.
+
+Theorem VWENC_203_DICTIONARY_FAMILY_INVENTORY_IS_EXHAUSTIVE :
+ length all_dictionary_families = 11 /\
+ forall family, In family all_dictionary_families.
+Proof.
+ split; [reflexivity |].
+ intros family. destruct family; simpl; tauto.
+Qed.
+
+Theorem VWENC_204_FAMILY_PROFILE_MATRIX_IS_TOTAL_AND_FUNCTIONAL :
+ length all_family_profiles = 11 /\
+ (forall profile, In profile all_family_profiles) /\
+ forall family profile,
+ (exists route layout,
+ family_profile_cell family profile =
+ ExistingProfileCell route layout) \/
+ (exists route layout,
+ family_profile_cell family profile =
+ ProspectiveProfileCell route layout).
+Proof.
+ split; [reflexivity |]. split.
+ - intros [direct | domain carrier].
+ + destruct direct; simpl; tauto.
+ + destruct domain, carrier; simpl; tauto.
+ - intros family profile.
+ destruct (family_profile_cell family profile) as [route layout|route layout]
+ eqn:Hcell.
+ + left. now exists route, layout.
+ + right. now exists route, layout.
+Qed.
+
+Theorem VWENC_205_FAMILY_SURFACE_MATRIX_IS_TOTAL_AND_FUNCTIONAL :
+ length all_consumer_surfaces = 14 /\
+ (forall surface, In surface all_consumer_surfaces) /\
+ forall family surface,
+ (exists route,
+ family_surface_cell family surface = ExistingSurface route) \/
+ (exists route,
+ family_surface_cell family surface = ProspectiveSurface route) \/
+ (exists reason,
+ family_surface_cell family surface =
+ SurfaceStructurallyInapplicable reason).
+Proof.
+ split; [reflexivity |]. split.
+ - intros surface. destruct surface; simpl; tauto.
+ - intros family surface.
+ destruct (family_surface_cell family surface) as [route|route|reason]
+ eqn:Hcell.
+ + left. now exists route.
+ + right. left. now exists route.
+ + right. right. now exists reason.
+Qed.
+
+Theorem VWENC_206_FAMILY_PROFILE_SURFACE_MATRIX_IS_TOTAL :
+ forall family profile surface,
+ (exists route layout surface_route,
+ family_profile_surface_cell family profile surface =
+ ExistingCapability route layout surface_route) \/
+ (exists route layout surface_route,
+ family_profile_surface_cell family profile surface =
+ ProspectiveCapability route layout surface_route) \/
+ (exists reason,
+ family_profile_surface_cell family profile surface =
+ CapabilityStructurallyInapplicable reason).
+Proof.
+ intros family profile surface.
+ destruct (family_profile_surface_cell family profile surface) as
+ [route layout surface_route|route layout surface_route|reason] eqn:Hcell.
+ - left. now exists route, layout, surface_route.
+ - right. left. now exists route, layout, surface_route.
+ - right. right. now exists reason.
+Qed.
+
+Theorem VWENC_207_EVERY_INAPPLICABLE_CELL_HAS_AN_EXPLICIT_STRUCTURAL_REASON :
+ forall family profile surface,
+ (exists reason,
+ family_profile_surface_cell family profile surface =
+ CapabilityStructurallyInapplicable
+ (SurfaceCapabilityReason reason)) ->
+ exists reason,
+ family_surface_cell family surface =
+ SurfaceStructurallyInapplicable reason.
+Proof.
+ intros family profile surface [reason Hcell].
+ unfold family_profile_surface_cell in Hcell.
+ destruct (family_profile_cell family profile);
+ destruct (family_surface_cell family surface) eqn:Hsurface;
+ inversion Hcell; subst; eauto.
+Qed.
+
+Definition pathmap_adapter_route (route : ProfileRoute) : Prop :=
+ match route with
+ | PathMapNativeByteRoute
+ | PathMapUtf8BoundaryAdapterRoute
+ | PathMapFixedWidthBoundaryAdapterRoute
+ | PathMapInternedIdAdapterRoute _ => True
+ | _ => False
+ end.
+
+Theorem VWENC_208_PATHMAP_REMAINS_AN_EXTERNAL_BYTE_KEYED_ADAPTER :
+ forall profile,
+ pathmap_adapter_route
+ (profile_cell_route
+ (family_profile_cell PathMapAdapterFamily profile)).
+Proof.
+ intros [direct | domain carrier].
+ - destruct direct; exact I.
+ - destruct domain, carrier; exact I.
+Qed.
+
+Definition family_profile_logical_domain
+ (profile : FamilyProfile) : option InternedAtomDomain :=
+ match profile with
+ | DirectProfile _ => None
+ | InternedProfile domain _ => Some domain
+ end.
+
+Theorem VWENC_209_PATHMAP_CANONICAL_ULEB_USES_ONLY_FIXED_WIDTH_INTERNED_IDS :
+ forall profile,
+ family_profile_logical_domain profile = Some CanonicalUlebDomain ->
+ exists carrier,
+ profile = InternedProfile CanonicalUlebDomain carrier /\
+ family_profile_cell PathMapAdapterFamily profile =
+ ProspectiveProfileCell (PathMapInternedIdAdapterRoute carrier)
+ (PathMapInternedIdLayout carrier) /\
+ carrier_width_bytes (id_carrier_profile carrier) =
+ match carrier with U32IdCarrier => 4 | U64IdCarrier => 8 end.
+Proof.
+ intros [direct | domain carrier] Hdomain.
+ - discriminate.
+ - destruct domain; inversion Hdomain; subst.
+ exists carrier. repeat split; destruct carrier; reflexivity.
+Qed.
+
+(** ** Naming, persistent identity, and specialization *)
+
+Inductive FamilyTypeSpelling : Type :=
+| CanonicalFamilySpelling : DictionaryFamily -> FamilyProfile ->
+ FamilyTypeSpelling
+| LegacyOneParameterSpelling : DictionaryFamily -> FamilyTypeSpelling.
+
+Definition legacy_default_profile (family : DictionaryFamily) : FamilyProfile :=
+ match family with
+ | BijectiveMapFamily | PersistentVocabARTrieFamily =>
+ DirectProfile DirectUnicodeScalarDomain
+ | _ => DirectProfile DirectBytesDomain
+ end.
+
+Definition legacy_family_defaults_to_bytes (family : DictionaryFamily) : bool :=
+ match family with
+ | BijectiveMapFamily | PersistentVocabARTrieFamily => false
+ | _ => true
+ end.
+
+Definition normalize_family_spelling
+ (spelling : FamilyTypeSpelling) : DictionaryFamily * FamilyProfile :=
+ match spelling with
+ | CanonicalFamilySpelling family profile => (family, profile)
+ | LegacyOneParameterSpelling family =>
+ (family, legacy_default_profile family)
+ end.
+
+Theorem VWENC_210_LEGACY_ONE_PARAMETER_FAMILY_SPELLING_DEFAULTS_TO_BYTES :
+ (forall family,
+ legacy_family_defaults_to_bytes family = true ->
+ normalize_family_spelling (LegacyOneParameterSpelling family) =
+ normalize_family_spelling
+ (CanonicalFamilySpelling family
+ (DirectProfile DirectBytesDomain))) /\
+ normalize_family_spelling (LegacyOneParameterSpelling BijectiveMapFamily) =
+ (BijectiveMapFamily, DirectProfile DirectUnicodeScalarDomain) /\
+ normalize_family_spelling
+ (LegacyOneParameterSpelling PersistentVocabARTrieFamily) =
+ (PersistentVocabARTrieFamily, DirectProfile DirectUnicodeScalarDomain).
+Proof.
+ split.
+ - intros family Hbyte. destruct family; simpl in *; try reflexivity;
+ discriminate.
+ - split; reflexivity.
+Qed.
+
+Inductive GenericParameterSlot : Type :=
+| MappedValueParameterSlot
+| LogicalProfileParameterSlot
+| RedundantWidthParameterSlot.
+
+Definition canonical_family_parameter_order : list GenericParameterSlot :=
+ [MappedValueParameterSlot; LogicalProfileParameterSlot].
+
+Theorem VWENC_211_MAPPED_VALUE_REMAINS_FIRST_AND_WIDTH_IS_NOT_A_PARAMETER :
+ hd_error canonical_family_parameter_order =
+ Some MappedValueParameterSlot /\
+ nth_error canonical_family_parameter_order 1 =
+ Some LogicalProfileParameterSlot /\
+ ~ In RedundantWidthParameterSlot canonical_family_parameter_order.
+Proof.
+ split; [reflexivity |].
+ split; [reflexivity |].
+ simpl. intuition discriminate.
+Qed.
+
+Inductive EdgeUnitKind : Type :=
+| ByteEdgeUnit
+| UnicodeScalarEdgeUnit
+| U32EdgeUnit
+| U64EdgeUnit
+| F64BitsEdgeUnit
+| SymbolIdEdgeUnit : IdCarrier -> EdgeUnitKind.
+
+Definition id_carrier_width (carrier : IdCarrier) : nat :=
+ match carrier with U32IdCarrier => 4 | U64IdCarrier => 8 end.
+
+Definition profile_edge_contract
+ (profile : FamilyProfile) : EdgeUnitKind * nat :=
+ match profile with
+ | DirectProfile DirectBytesDomain => (ByteEdgeUnit, 1)
+ | DirectProfile DirectUnicodeScalarDomain => (UnicodeScalarEdgeUnit, 4)
+ | DirectProfile DirectU32Domain => (U32EdgeUnit, 4)
+ | DirectProfile DirectU64Domain => (U64EdgeUnit, 8)
+ | DirectProfile DirectF64BitsDomain => (F64BitsEdgeUnit, 8)
+ | InternedProfile _ carrier =>
+ (SymbolIdEdgeUnit carrier, id_carrier_width carrier)
+ end.
+
+Theorem VWENC_212_PROFILE_ALONE_OWNS_EDGE_UNIT_AND_WIDTH_METADATA :
+ forall profile,
+ exists! contract,
+ contract = profile_edge_contract profile /\
+ 0 < snd contract.
+Proof.
+ intros profile.
+ exists (profile_edge_contract profile). split.
+ - split; [reflexivity |].
+ destruct profile as [direct | domain carrier].
+ + destruct direct; simpl; lia.
+ + destruct carrier; simpl; lia.
+ - intros contract [Hcontract _]. symmetry. exact Hcontract.
+Qed.
+
+Inductive FamilyCodecIdentity : Type :=
+| FamilyExistingByteCodec
+| FamilyExistingCharU32Codec
+| FamilyExistingNativeU64Codec
+| FamilyEncodedU64LittleEndianBytePathCodec
+| FamilyProspectiveU32CodecV1
+| FamilyProspectiveF64BitsCodecV1
+| FamilyFixedIdCarrierCodec : IdCarrier -> FamilyCodecIdentity.
+
+Definition codec_matches_profile
+ (profile : FamilyProfile) (codec : FamilyCodecIdentity) : Prop :=
+ match profile, codec with
+ | DirectProfile DirectBytesDomain, FamilyExistingByteCodec
+ | DirectProfile DirectUnicodeScalarDomain, FamilyExistingCharU32Codec
+ | DirectProfile DirectU64Domain, FamilyExistingNativeU64Codec
+ | DirectProfile DirectU64Domain,
+ FamilyEncodedU64LittleEndianBytePathCodec
+ | DirectProfile DirectU32Domain, FamilyProspectiveU32CodecV1
+ | DirectProfile DirectF64BitsDomain, FamilyProspectiveF64BitsCodecV1 => True
+ | InternedProfile _ expected, FamilyFixedIdCarrierCodec actual =>
+ expected = actual
+ | _, _ => False
+ end.
+
+Definition layout_matches_codec
+ (codec : FamilyCodecIdentity) (layout : ExplicitLayoutContract) : Prop :=
+ match codec, layout with
+ | FamilyExistingByteCodec, GenericLogicalLayout
+ | FamilyExistingByteCodec, PathMapNativeByteLayout
+ | FamilyExistingCharU32Codec, GenericLogicalLayout
+ | FamilyExistingCharU32Codec, PathMapUtf8BoundaryLayout
+ | FamilyExistingNativeU64Codec, GenericLogicalLayout
+ | FamilyExistingNativeU64Codec, PersistentU64CompactLayout
+ | FamilyExistingNativeU64Codec,
+ PersistentU64Prefix3CompatibilityLayout
+ | FamilyEncodedU64LittleEndianBytePathCodec,
+ EncodedU64ByteCompatibilityLayout
+ | FamilyProspectiveU32CodecV1, GenericLogicalLayout
+ | FamilyProspectiveU32CodecV1, PathMapFixedWidthBoundaryLayout
+ | FamilyProspectiveF64BitsCodecV1, GenericLogicalLayout
+ | FamilyProspectiveF64BitsCodecV1, PathMapFixedWidthBoundaryLayout => True
+ | FamilyFixedIdCarrierCodec expected, ProspectiveInternedIdLayout actual
+ | FamilyFixedIdCarrierCodec expected, PathMapInternedIdLayout actual =>
+ expected = actual
+ | _, _ => False
+ end.
+
+Definition backend_matches_layout
+ (family : DictionaryFamily) (layout : ExplicitLayoutContract) : Prop :=
+ match layout with
+ | PathMapNativeByteLayout | PathMapUtf8BoundaryLayout
+ | PathMapFixedWidthBoundaryLayout | PathMapInternedIdLayout _ =>
+ family = PathMapAdapterFamily
+ | PersistentU64CompactLayout
+ | PersistentU64Prefix3CompatibilityLayout
+ | EncodedU64ByteCompatibilityLayout =>
+ family = PersistentARTrieFamily
+ | GenericLogicalLayout | ProspectiveInternedIdLayout _ => True
+ end.
+
+(** Persistent/ABI certification is intentionally stricter than the abstract
+ codec/layout compatibility relations above. A format may be certified
+ only for an existing family/profile cell and its exact declared layout.
+ The two historical PersistentARTrie U64 byte layouts are explicit,
+ reviewed compatibility exceptions; prospective cells cannot mint a
+ persistent identity. *)
+Definition family_profile_layout_is_certifiable
+ (family : DictionaryFamily) (profile : FamilyProfile)
+ (codec : FamilyCodecIdentity) (layout : ExplicitLayoutContract) : Prop :=
+ (exists route,
+ family_profile_cell family profile = ExistingProfileCell route layout) \/
+ (family = PersistentARTrieFamily /\
+ profile = DirectProfile DirectU64Domain /\
+ codec = FamilyExistingNativeU64Codec /\
+ layout = PersistentU64Prefix3CompatibilityLayout) \/
+ (family = PersistentARTrieFamily /\
+ profile = DirectProfile DirectU64Domain /\
+ codec = FamilyEncodedU64LittleEndianBytePathCodec /\
+ layout = EncodedU64ByteCompatibilityLayout).
+
+Record CertifiedFamilyFormat : Type := {
+ certified_format_family : DictionaryFamily;
+ certified_format_profile : FamilyProfile;
+ certified_format_codec : FamilyCodecIdentity;
+ certified_format_layout : ExplicitLayoutContract;
+ certified_format_abi_version : nat;
+ certified_format_profile_codec_coherent :
+ codec_matches_profile certified_format_profile certified_format_codec;
+ certified_format_codec_layout_coherent :
+ layout_matches_codec certified_format_codec certified_format_layout;
+ certified_format_backend_layout_coherent :
+ backend_matches_layout certified_format_family certified_format_layout;
+ certified_format_family_profile_coherent :
+ family_profile_layout_is_certifiable
+ certified_format_family certified_format_profile
+ certified_format_codec certified_format_layout;
+ certified_format_version_positive : 0 < certified_format_abi_version
+}.
+
+Definition CertifiedProfileIdentity : Type :=
+ DictionaryFamily *
+ (FamilyProfile *
+ (FamilyCodecIdentity * (ExplicitLayoutContract * nat))).
+
+Definition certified_family_format_identity
+ (descriptor : CertifiedFamilyFormat) : CertifiedProfileIdentity :=
+ (certified_format_family descriptor,
+ (certified_format_profile descriptor,
+ (certified_format_codec descriptor,
+ (certified_format_layout descriptor,
+ certified_format_abi_version descriptor)))).
+
+Inductive ProfileReference : Type :=
+| OpenInMemoryProfileReference
+| CertifiedPersistentProfileReference : CertifiedFamilyFormat ->
+ ProfileReference.
+
+Definition persistent_identity_of
+ (reference : ProfileReference) : option CertifiedProfileIdentity :=
+ match reference with
+ | OpenInMemoryProfileReference => None
+ | CertifiedPersistentProfileReference descriptor =>
+ Some (certified_family_format_identity descriptor)
+ end.
+
+Theorem VWENC_213_OPEN_IN_MEMORY_UNITS_CANNOT_MINT_PERSISTENT_IDENTITIES :
+ persistent_identity_of OpenInMemoryProfileReference = None /\
+ forall descriptor,
+ persistent_identity_of
+ (CertifiedPersistentProfileReference descriptor) =
+ Some (certified_family_format_identity descriptor) /\
+ 0 < certified_format_abi_version descriptor.
+Proof.
+ split; [reflexivity |].
+ intros descriptor. split; [reflexivity |].
+ exact (certified_format_version_positive descriptor).
+Qed.
+
+(** Rust spelling is diagnostic text only. All semantic fields, including
+ codec and layout, come from the certified descriptor. *)
+Definition format_identity_with_rust_name
+ (_rust_type_name : list nat) (descriptor : CertifiedFamilyFormat)
+ : CertifiedProfileIdentity :=
+ certified_family_format_identity descriptor.
+
+Lemma certified_family_format_identity_injective :
+ forall left right,
+ certified_family_format_identity left =
+ certified_family_format_identity right ->
+ left = right.
+Proof.
+ intros
+ [lf lp lc ll lv lpc lcl lbl lfp lvp]
+ [rf rp rc rl rv rpc rcl rbl rfp rvp] Hequal.
+ unfold certified_family_format_identity in Hequal. simpl in Hequal.
+ inversion Hequal. subst.
+ f_equal; apply proof_irrelevance.
+Qed.
+
+Theorem VWENC_214_FORMAT_IDENTITY_IS_INDEPENDENT_OF_RUST_TYPE_NAMES :
+ (forall left_name right_name descriptor,
+ format_identity_with_rust_name left_name descriptor =
+ format_identity_with_rust_name right_name descriptor) /\
+ (forall left right,
+ certified_family_format_identity left =
+ certified_family_format_identity right ->
+ left = right).
+Proof.
+ split; [reflexivity |].
+ exact certified_family_format_identity_injective.
+Qed.
+
+Inductive KernelKind : Type :=
+| GenericLogicalKernel
+| SpecializedLogicalKernel
+| FixedIdLogicalKernel : IdCarrier -> KernelKind
+| EncodedU64AdapterLogicalKernel
+| PathMapAdapterKernel
+| BijectiveLogicalKernel
+| VocabularyOwnerKernel.
+
+Definition kernel_for_profile_route (route : ProfileRoute) : KernelKind :=
+ match route with
+ | GenericNativeKernel => GenericLogicalKernel
+ | RetainedSpecializedKernel => SpecializedLogicalKernel
+ | InternedFixedIdKernel carrier => FixedIdLogicalKernel carrier
+ | EncodedU64ByteAdapterKernel => EncodedU64AdapterLogicalKernel
+ | PathMapNativeByteRoute | PathMapUtf8BoundaryAdapterRoute
+ | PathMapFixedWidthBoundaryAdapterRoute
+ | PathMapInternedIdAdapterRoute _ => PathMapAdapterKernel
+ | BijectiveTermValueKernel => BijectiveLogicalKernel
+ | VocabularyOwnerRoute _ => VocabularyOwnerKernel
+ end.
+
+Definition selected_kernel
+ (family : DictionaryFamily) (profile : FamilyProfile) : KernelKind :=
+ kernel_for_profile_route (family_profile_route family profile).
+
+(** A nominal interned profile is usable only together with the certified atom
+ profile, expected and actual vocabulary fibers, their equality proof, and
+ the exact immutable vocabulary snapshot. This is a type-level prerequisite
+ of every family snapshot, rather than an optional hot-path side channel. *)
+Definition atom_profile_matches_interned_domain
+ (domain : InternedAtomDomain) (profile : CertifiedAtomProfile) : Prop :=
+ match domain with
+ | CanonicalUlebDomain =>
+ persistent_logical_profile (atom_profile_descriptor profile) =
+ PersistedCanonicalUleb
+ | CanonicalUtf8Domain =>
+ persistent_logical_profile (atom_profile_descriptor profile) =
+ PersistedCanonicalUtf8
+ | OpaqueCanonicalBytesDomain => True
+ end.
+
+Record InternedConsumerContext
+ (domain : InternedAtomDomain) (carrier : IdCarrier) : Type := {
+ interned_context_atom_profile : CertifiedAtomProfile;
+ interned_context_atom_profile_exact :
+ atom_profile_matches_interned_domain
+ domain interned_context_atom_profile;
+ interned_context_expected_fiber :
+ VocabularyFiber interned_context_atom_profile
+ (id_carrier_profile carrier);
+ interned_context_actual_fiber :
+ VocabularyFiber interned_context_atom_profile
+ (id_carrier_profile carrier);
+ interned_context_fiber_exact :
+ interned_context_expected_fiber = interned_context_actual_fiber;
+ interned_context_snapshot :
+ VocabularySnapshot interned_context_atom_profile
+ (id_carrier_profile carrier) interned_context_actual_fiber
+}.
+
+Definition FamilyConsumerContext (profile : FamilyProfile) : Type :=
+ match profile with
+ | DirectProfile _ => unit
+ | InternedProfile domain carrier => InternedConsumerContext domain carrier
+ end.
+
+(** Runtime payload is one fixed-width ID plus an erased proof of membership in
+ the exact bound snapshot. It does not duplicate the arbitrary-width atom. *)
+Record SnapshotBoundSymbolId
+ (P : CertifiedAtomProfile) (I : FixedWidthCarrierProfile)
+ (fiber : VocabularyFiber P I)
+ (snapshot : VocabularySnapshot P I fiber) : Type := {
+ snapshot_bound_symbol_id : SymbolId I;
+ snapshot_bound_live :
+ live_symbol (vocabulary_snapshot_live_entries P I fiber snapshot)
+ snapshot_bound_symbol_id
+}.
+
+Definition BoundProfileUnit
+ (profile : FamilyProfile) (context : FamilyConsumerContext profile) : Type.
+Proof.
+ destruct profile as [domain | domain carrier].
+ - exact (DirectUnit domain).
+ - exact
+ (SnapshotBoundSymbolId
+ (interned_context_atom_profile domain carrier context)
+ (id_carrier_profile carrier)
+ (interned_context_actual_fiber domain carrier context)
+ (interned_context_snapshot domain carrier context)).
+Defined.
+
+Definition snapshot_route_allowed
+ (family : DictionaryFamily) (profile : FamilyProfile)
+ (kernel : KernelKind) (layout : ExplicitLayoutContract) : Prop :=
+ (kernel = GenericLogicalKernel /\ layout = GenericLogicalLayout) \/
+ (kernel = selected_kernel family profile /\
+ layout = profile_cell_layout (family_profile_cell family profile)) \/
+ (family = PersistentARTrieFamily /\
+ profile = DirectProfile DirectU64Domain /\
+ kernel = EncodedU64AdapterLogicalKernel /\
+ layout = EncodedU64ByteCompatibilityLayout).
+
+Record FamilySnapshot
+ (family : DictionaryFamily) (profile : FamilyProfile)
+ (context : FamilyConsumerContext profile) (Value : Type) : Type := {
+ snapshot_revision : nat;
+ snapshot_kernel : KernelKind;
+ snapshot_layout : ExplicitLayoutContract;
+ snapshot_observations : LogicalObservations
+ (BoundProfileUnit profile context) Value;
+ snapshot_route_certificate :
+ snapshot_route_allowed family profile snapshot_kernel snapshot_layout
+}.
+
+(** Downstream [CharUnit]-like implementations remain open in memory. They
+ share the same family observation contract, but their profile reference is
+ definitionally non-persistent and therefore cannot be mistaken for a
+ certified ABI identity. *)
+Record OpenFamilySnapshot
+ (family : DictionaryFamily) (Unit Value : Type)
+ (profile : OpenUnitProfile Unit) : Type := {
+ open_snapshot_revision : nat;
+ open_snapshot_observations : LogicalObservations Unit Value
+}.
+
+Definition open_family_snapshot_profile_reference
+ {family Unit Value} {profile : OpenUnitProfile Unit}
+ (_snapshot : OpenFamilySnapshot family Unit Value profile)
+ : ProfileReference := OpenInMemoryProfileReference.
+
+Lemma open_family_snapshots_cannot_mint_persistent_identity :
+ forall family Unit Value (profile : OpenUnitProfile Unit)
+ (snapshot : OpenFamilySnapshot family Unit Value profile),
+ persistent_identity_of
+ (open_family_snapshot_profile_reference snapshot) = None.
+Proof. reflexivity. Qed.
+
+Record OpenFamilySpecializationRefinement
+ (family : DictionaryFamily) (Unit Value : Type)
+ (profile : OpenUnitProfile Unit)
+ (generic specialized : OpenFamilySnapshot family Unit Value profile)
+ : Prop := {
+ open_specialization_same_revision :
+ open_snapshot_revision _ _ _ _ generic =
+ open_snapshot_revision _ _ _ _ specialized;
+ open_specialization_same_observations :
+ SameLogicalObservations
+ (open_snapshot_observations _ _ _ _ generic)
+ (open_snapshot_observations _ _ _ _ specialized)
+}.
+
+Record SpecializationRefinement
+ (family : DictionaryFamily) (profile : FamilyProfile)
+ (context : FamilyConsumerContext profile) (Value : Type)
+ (generic specialized : FamilySnapshot family profile context Value) : Prop := {
+ specialization_generic_kernel :
+ snapshot_kernel family profile context Value generic = GenericLogicalKernel;
+ specialization_selected_kernel :
+ snapshot_kernel family profile context Value specialized =
+ selected_kernel family profile;
+ specialization_same_revision :
+ snapshot_revision family profile context Value generic =
+ snapshot_revision family profile context Value specialized;
+ specialization_same_observations :
+ SameLogicalObservations
+ (snapshot_observations family profile context Value generic)
+ (snapshot_observations family profile context Value specialized)
+}.
+
+Theorem VWENC_215_SPECIALIZATION_REFINES_THE_GENERIC_LOGICAL_VIEW :
+ forall family profile (context : FamilyConsumerContext profile) (Value : Type)
+ (generic specialized : FamilySnapshot family profile context Value),
+ SpecializationRefinement family profile context Value generic specialized ->
+ snapshot_revision family profile context Value generic =
+ snapshot_revision family profile context Value specialized /\
+ snapshot_kernel family profile context Value generic = GenericLogicalKernel /\
+ snapshot_kernel family profile context Value specialized =
+ selected_kernel family profile /\
+ SameLogicalObservations
+ (snapshot_observations family profile context Value generic)
+ (snapshot_observations family profile context Value specialized).
+Proof.
+ intros family profile context Value generic specialized Hrefinement.
+ split.
+ - exact (specialization_same_revision _ _ _ _ _ _ Hrefinement).
+ - split.
+ + exact (specialization_generic_kernel _ _ _ _ _ _ Hrefinement).
+ + split.
+ * exact (specialization_selected_kernel _ _ _ _ _ _ Hrefinement).
+ * exact (specialization_same_observations _ _ _ _ _ _ Hrefinement).
+Qed.
+
+Theorem VWENC_216_EVERY_RETAINED_SPECIALIZED_KERNEL_PRESERVES_ALL_OBSERVATIONS :
+ forall family profile (context : FamilyConsumerContext profile) (Value : Type)
+ (generic specialized : FamilySnapshot family profile context Value),
+ family_profile_route family profile = RetainedSpecializedKernel ->
+ SpecializationRefinement family profile context Value generic specialized ->
+ snapshot_kernel family profile context Value specialized =
+ SpecializedLogicalKernel /\
+ SameLogicalObservations
+ (snapshot_observations family profile context Value generic)
+ (snapshot_observations family profile context Value specialized).
+Proof.
+ intros family profile context Value generic specialized Hroute Hrefinement.
+ split.
+ - rewrite (specialization_selected_kernel _ _ _ _ _ _ Hrefinement).
+ unfold selected_kernel. now rewrite Hroute.
+ - exact (specialization_same_observations _ _ _ _ _ _ Hrefinement).
+Qed.
+
+(** A traversal batch is homogeneous in [Unit]. Kernel selection happens when
+ this record is built; its encoder cannot inspect a profile tag per edge. *)
+Record MonomorphicFixedWidthKernel (Unit : Type) : Type := {
+ monomorphic_width : nat;
+ monomorphic_width_positive : 0 < monomorphic_width;
+ monomorphic_encode : Unit -> list PhysicalByte;
+ monomorphic_encode_exact :
+ forall unit, length (monomorphic_encode unit) = monomorphic_width;
+ monomorphic_variable_decode_request : Unit -> option (list PhysicalByte);
+ monomorphic_has_no_variable_decode :
+ forall unit, monomorphic_variable_decode_request unit = None
+}.
+
+Definition run_bound_kernel {Unit : Type}
+ (kernel : MonomorphicFixedWidthKernel Unit) (units : list Unit)
+ : list (list PhysicalByte) :=
+ map (monomorphic_encode Unit kernel) units.
+
+Lemma bound_kernel_widths_are_constant :
+ forall (Unit : Type) (kernel : MonomorphicFixedWidthKernel Unit) units,
+ map (@length PhysicalByte) (run_bound_kernel kernel units) =
+ repeat (monomorphic_width Unit kernel) (length units).
+Proof.
+ intros Unit kernel units. induction units as [|unit rest IH]; simpl.
+ - reflexivity.
+ - rewrite (monomorphic_encode_exact Unit kernel unit), IH. reflexivity.
+Qed.
+
+Theorem VWENC_217_KERNEL_SELECTION_IS_BOUND_ONCE_NOT_BRANCHING_PER_EDGE :
+ forall (Unit : Type) (kernel : MonomorphicFixedWidthKernel Unit) units,
+ run_bound_kernel kernel units =
+ map (monomorphic_encode Unit kernel) units /\
+ map (@length PhysicalByte) (run_bound_kernel kernel units) =
+ repeat (monomorphic_width Unit kernel) (length units).
+Proof.
+ intros. split; [reflexivity |].
+ apply bound_kernel_widths_are_constant.
+Qed.
+
+(** ** Backward-compatible aliases and independent projections *)
+
+Inductive LegacyAlias : Type :=
+| LegacyDynamicDawg | LegacyDoubleArrayTrie | LegacySuffixAutomaton
+| LegacyScdawg | LegacyPathMapDictionary | LegacyPersistentARTrie
+| LegacyPersistentSuffixAutomaton | LegacyPersistentSuffixTree
+| LegacyPersistentScdawg
+| LegacyDynamicDawgChar | LegacyDoubleArrayTrieChar
+| LegacySuffixAutomatonChar | LegacyScdawgChar
+| LegacyPathMapDictionaryChar | LegacyPersistentARTrieChar
+| LegacyPersistentSuffixAutomatonChar | LegacyPersistentSuffixTreeChar
+| LegacyPersistentScdawgChar
+| LegacyDynamicDawgU64 | LegacyPersistentARTrieU64
+| LegacyPersistentARTrieU64Compact
+| LegacyPersistentARTrieU64Prefix3Compat
+| LegacyEncodedPersistentARTrieU64.
+
+Definition all_legacy_aliases : list LegacyAlias :=
+ [LegacyDynamicDawg; LegacyDoubleArrayTrie; LegacySuffixAutomaton;
+ LegacyScdawg; LegacyPathMapDictionary; LegacyPersistentARTrie;
+ LegacyPersistentSuffixAutomaton; LegacyPersistentSuffixTree;
+ LegacyPersistentScdawg; LegacyDynamicDawgChar;
+ LegacyDoubleArrayTrieChar; LegacySuffixAutomatonChar;
+ LegacyScdawgChar; LegacyPathMapDictionaryChar;
+ LegacyPersistentARTrieChar; LegacyPersistentSuffixAutomatonChar;
+ LegacyPersistentSuffixTreeChar; LegacyPersistentScdawgChar;
+ LegacyDynamicDawgU64; LegacyPersistentARTrieU64;
+ LegacyPersistentARTrieU64Compact;
+ LegacyPersistentARTrieU64Prefix3Compat;
+ LegacyEncodedPersistentARTrieU64].
+
+Definition legacy_alias_family (alias : LegacyAlias) : DictionaryFamily :=
+ match alias with
+ | LegacyDynamicDawg | LegacyDynamicDawgChar | LegacyDynamicDawgU64 =>
+ DynamicDawgFamily
+ | LegacyDoubleArrayTrie | LegacyDoubleArrayTrieChar =>
+ DoubleArrayTrieFamily
+ | LegacySuffixAutomaton | LegacySuffixAutomatonChar =>
+ SuffixAutomatonFamily
+ | LegacyScdawg | LegacyScdawgChar => ScdawgFamily
+ | LegacyPathMapDictionary | LegacyPathMapDictionaryChar =>
+ PathMapAdapterFamily
+ | LegacyPersistentARTrie | LegacyPersistentARTrieChar
+ | LegacyPersistentARTrieU64 | LegacyPersistentARTrieU64Compact
+ | LegacyPersistentARTrieU64Prefix3Compat
+ | LegacyEncodedPersistentARTrieU64 => PersistentARTrieFamily
+ | LegacyPersistentSuffixAutomaton
+ | LegacyPersistentSuffixAutomatonChar => PersistentSuffixAutomatonFamily
+ | LegacyPersistentSuffixTree | LegacyPersistentSuffixTreeChar =>
+ PersistentSuffixTreeFamily
+ | LegacyPersistentScdawg | LegacyPersistentScdawgChar =>
+ PersistentScdawgFamily
+ end.
+
+Inductive LegacyAliasClass : Type :=
+| LegacyByteClass | LegacyCharClass | LegacyU64Class.
+
+Definition legacy_alias_class (alias : LegacyAlias) : LegacyAliasClass :=
+ match alias with
+ | LegacyDynamicDawgChar | LegacyDoubleArrayTrieChar
+ | LegacySuffixAutomatonChar | LegacyScdawgChar
+ | LegacyPathMapDictionaryChar | LegacyPersistentARTrieChar
+ | LegacyPersistentSuffixAutomatonChar | LegacyPersistentSuffixTreeChar
+ | LegacyPersistentScdawgChar => LegacyCharClass
+ | LegacyDynamicDawgU64 | LegacyPersistentARTrieU64
+ | LegacyPersistentARTrieU64Compact
+ | LegacyPersistentARTrieU64Prefix3Compat
+ | LegacyEncodedPersistentARTrieU64 => LegacyU64Class
+ | _ => LegacyByteClass
+ end.
+
+Definition legacy_alias_profile (alias : LegacyAlias) : FamilyProfile :=
+ match legacy_alias_class alias with
+ | LegacyByteClass => DirectProfile DirectBytesDomain
+ | LegacyCharClass => DirectProfile DirectUnicodeScalarDomain
+ | LegacyU64Class => DirectProfile DirectU64Domain
+ end.
+
+Definition legacy_alias_layout
+ (alias : LegacyAlias) : ExplicitLayoutContract :=
+ match alias with
+ | LegacyPathMapDictionary => PathMapNativeByteLayout
+ | LegacyPathMapDictionaryChar => PathMapUtf8BoundaryLayout
+ | LegacyPersistentARTrieU64 | LegacyPersistentARTrieU64Compact =>
+ PersistentU64CompactLayout
+ | LegacyPersistentARTrieU64Prefix3Compat =>
+ PersistentU64Prefix3CompatibilityLayout
+ | LegacyEncodedPersistentARTrieU64 =>
+ EncodedU64ByteCompatibilityLayout
+ | _ => GenericLogicalLayout
+ end.
+
+Definition legacy_alias_route (alias : LegacyAlias) : ProfileRoute :=
+ match alias with
+ | LegacyEncodedPersistentARTrieU64 => EncodedU64ByteAdapterKernel
+ | _ => family_profile_route
+ (legacy_alias_family alias) (legacy_alias_profile alias)
+ end.
+
+Definition legacy_alias_codec (alias : LegacyAlias) : FamilyCodecIdentity :=
+ match legacy_alias_class alias with
+ | LegacyByteClass => FamilyExistingByteCodec
+ | LegacyCharClass => FamilyExistingCharU32Codec
+ | LegacyU64Class =>
+ match alias with
+ | LegacyEncodedPersistentARTrieU64 =>
+ FamilyEncodedU64LittleEndianBytePathCodec
+ | _ => FamilyExistingNativeU64Codec
+ end
+ end.
+
+Inductive VocabularyAlias : Type :=
+| PersistentVocabARTrieName
+| SharedVocabARTrieName
+| IndexedVocabularyPersistentName
+| SharedVocabTrieName
+| DiskBackedVocabTrieInnerName.
+
+Definition all_vocabulary_aliases : list VocabularyAlias :=
+ [PersistentVocabARTrieName; SharedVocabARTrieName;
+ IndexedVocabularyPersistentName; SharedVocabTrieName;
+ DiskBackedVocabTrieInnerName].
+
+Inductive PersistentHandleAlias : Type :=
+| SharedARTrieName
+| SharedCharARTrieName
+| SharedCharTrieName.
+
+Definition all_persistent_handle_aliases : list PersistentHandleAlias :=
+ [SharedARTrieName; SharedCharARTrieName; SharedCharTrieName].
+
+Inductive PublicCompatibilitySpelling : Type :=
+| LegacyPublicSpelling : LegacyAlias -> PublicCompatibilitySpelling
+| VocabularyPublicSpelling : VocabularyAlias -> PublicCompatibilitySpelling
+| PersistentHandlePublicSpelling : PersistentHandleAlias ->
+ PublicCompatibilitySpelling.
+
+Definition public_spelling_family
+ (spelling : PublicCompatibilitySpelling) : DictionaryFamily :=
+ match spelling with
+ | LegacyPublicSpelling alias => legacy_alias_family alias
+ | VocabularyPublicSpelling _ => PersistentVocabARTrieFamily
+ | PersistentHandlePublicSpelling _ => PersistentARTrieFamily
+ end.
+
+Definition public_spelling_profile
+ (spelling : PublicCompatibilitySpelling) : FamilyProfile :=
+ match spelling with
+ | LegacyPublicSpelling alias => legacy_alias_profile alias
+ | VocabularyPublicSpelling _ => DirectProfile DirectUnicodeScalarDomain
+ | PersistentHandlePublicSpelling SharedARTrieName =>
+ DirectProfile DirectBytesDomain
+ | PersistentHandlePublicSpelling SharedCharARTrieName
+ | PersistentHandlePublicSpelling SharedCharTrieName =>
+ DirectProfile DirectUnicodeScalarDomain
+ end.
+
+Definition public_spelling_layout
+ (spelling : PublicCompatibilitySpelling) : ExplicitLayoutContract :=
+ match spelling with
+ | LegacyPublicSpelling alias => legacy_alias_layout alias
+ | _ => GenericLogicalLayout
+ end.
+
+Definition public_spelling_route
+ (spelling : PublicCompatibilitySpelling) : ProfileRoute :=
+ match spelling with
+ | LegacyPublicSpelling alias => legacy_alias_route alias
+ | VocabularyPublicSpelling _ => VocabularyOwnerRoute U64IdCarrier
+ | PersistentHandlePublicSpelling _ =>
+ family_profile_route
+ (public_spelling_family spelling) (public_spelling_profile spelling)
+ end.
+
+Definition public_spelling_codec
+ (spelling : PublicCompatibilitySpelling) : FamilyCodecIdentity :=
+ match spelling with
+ | LegacyPublicSpelling alias => legacy_alias_codec alias
+ | VocabularyPublicSpelling _ => FamilyExistingCharU32Codec
+ | PersistentHandlePublicSpelling SharedARTrieName =>
+ FamilyExistingByteCodec
+ | PersistentHandlePublicSpelling SharedCharARTrieName
+ | PersistentHandlePublicSpelling SharedCharTrieName =>
+ FamilyExistingCharU32Codec
+ end.
+
+Definition public_spelling_is_persistent
+ (spelling : PublicCompatibilitySpelling) : bool :=
+ persistent_family (public_spelling_family spelling).
+
+Definition expected_public_format_identity
+ (spelling : PublicCompatibilitySpelling)
+ : option CertifiedProfileIdentity :=
+ if public_spelling_is_persistent spelling then
+ Some
+ (public_spelling_family spelling,
+ (public_spelling_profile spelling,
+ (public_spelling_codec spelling,
+ (public_spelling_layout spelling, 1))))
+ else None.
+
+Definition public_spelling_context
+ (spelling : PublicCompatibilitySpelling)
+ : FamilyConsumerContext (public_spelling_profile spelling).
+Proof.
+ destruct spelling as [alias | vocabulary | handle].
+ - destruct alias; exact tt.
+ - exact tt.
+ - destruct handle; exact tt.
+Defined.
+
+Record PublicFacadeState
+ (spelling : PublicCompatibilitySpelling) (Value : Type) : Type := {
+ facade_snapshot :
+ FamilySnapshot (public_spelling_family spelling)
+ (public_spelling_profile spelling) (public_spelling_context spelling) Value;
+ facade_profile_reference : ProfileReference;
+ facade_serialized_image : option (list PhysicalByte)
+}.
+
+Record PublicFacadeCompatibility
+ (spelling : PublicCompatibilitySpelling) (Value : Type)
+ (legacy canonical : PublicFacadeState spelling Value) : Prop := {
+ facade_legacy_layout_exact :
+ snapshot_layout _ _ _ _ (facade_snapshot spelling Value legacy) =
+ public_spelling_layout spelling;
+ facade_canonical_layout_exact :
+ snapshot_layout _ _ _ _ (facade_snapshot spelling Value canonical) =
+ public_spelling_layout spelling;
+ facade_legacy_kernel_exact :
+ snapshot_kernel _ _ _ _ (facade_snapshot spelling Value legacy) =
+ kernel_for_profile_route (public_spelling_route spelling);
+ facade_canonical_kernel_exact :
+ snapshot_kernel _ _ _ _ (facade_snapshot spelling Value canonical) =
+ kernel_for_profile_route (public_spelling_route spelling);
+ facade_same_revision :
+ snapshot_revision _ _ _ _ (facade_snapshot spelling Value legacy) =
+ snapshot_revision _ _ _ _ (facade_snapshot spelling Value canonical);
+ facade_same_observations :
+ SameLogicalObservations
+ (snapshot_observations _ _ _ _ (facade_snapshot spelling Value legacy))
+ (snapshot_observations _ _ _ _ (facade_snapshot spelling Value canonical));
+ facade_legacy_format_exact :
+ persistent_identity_of (facade_profile_reference spelling Value legacy) =
+ expected_public_format_identity spelling;
+ facade_canonical_format_exact :
+ persistent_identity_of
+ (facade_profile_reference spelling Value canonical) =
+ expected_public_format_identity spelling;
+ facade_serialization_exact :
+ facade_serialized_image spelling Value legacy =
+ facade_serialized_image spelling Value canonical
+}.
+
+Theorem VWENC_218_LEGACY_ALIAS_INVENTORIES_PRESERVE_CANONICAL_TARGETS :
+ length all_legacy_aliases = 23 /\
+ (forall alias, In alias all_legacy_aliases) /\
+ length all_vocabulary_aliases = 5 /\
+ (forall alias, In alias all_vocabulary_aliases) /\
+ length all_persistent_handle_aliases = 3 /\
+ (forall alias, In alias all_persistent_handle_aliases) /\
+ forall spelling (Value : Type)
+ (legacy canonical : PublicFacadeState spelling Value),
+ PublicFacadeCompatibility spelling Value legacy canonical ->
+ SameLogicalObservations
+ (snapshot_observations _ _ _ _ (facade_snapshot spelling Value legacy))
+ (snapshot_observations _ _ _ _ (facade_snapshot spelling Value canonical)) /\
+ facade_serialized_image spelling Value legacy =
+ facade_serialized_image spelling Value canonical /\
+ persistent_identity_of (facade_profile_reference spelling Value legacy) =
+ expected_public_format_identity spelling /\
+ persistent_identity_of
+ (facade_profile_reference spelling Value canonical) =
+ expected_public_format_identity spelling.
+Proof.
+ split; [reflexivity |]. split.
+ - intros alias. destruct alias; simpl; tauto.
+ - split; [reflexivity |]. split.
+ + intros alias. destruct alias; simpl; tauto.
+ + split; [reflexivity |]. split.
+ * intros alias. destruct alias; simpl; tauto.
+ * intros spelling Value legacy canonical Hcompatibility.
+ split.
+ -- exact (facade_same_observations _ _ _ _ Hcompatibility).
+ -- split.
+ ++ exact (facade_serialization_exact _ _ _ _ Hcompatibility).
+ ++ split.
+ ** exact (facade_legacy_format_exact _ _ _ _ Hcompatibility).
+ ** exact (facade_canonical_format_exact _ _ _ _ Hcompatibility).
+Qed.
+
+Theorem VWENC_219_EVERY_CHAR_ALIAS_TARGETS_UNICODE_SCALAR_UNITS :
+ forall alias,
+ legacy_alias_class alias = LegacyCharClass ->
+ legacy_alias_profile alias = DirectProfile DirectUnicodeScalarDomain /\
+ ProfileUnit (legacy_alias_profile alias) =
+ DirectUnit DirectUnicodeScalarDomain.
+Proof.
+ intros alias Hclass. unfold legacy_alias_profile. rewrite Hclass.
+ split; reflexivity.
+Qed.
+
+Definition direct_unit_value {domain : DirectUnitDomain}
+ (unit : DirectUnit domain) : nat := proj1_sig unit.
+
+Definition encoded_u64_unit_bytes
+ (unit : DirectUnit DirectU64Domain) : list PhysicalByte :=
+ encode_fixed_little_endian 8 (direct_unit_value unit).
+
+Fixpoint legacy_encoded_u64_sequence
+ (units : list (DirectUnit DirectU64Domain)) : list PhysicalByte :=
+ match units with
+ | [] => []
+ | unit :: rest => encoded_u64_unit_bytes unit ++
+ legacy_encoded_u64_sequence rest
+ end.
+
+Definition canonical_encoded_u64_sequence
+ (units : list (DirectUnit DirectU64Domain)) : list PhysicalByte :=
+ concat (map encoded_u64_unit_bytes units).
+
+Definition encoded_u64_logical_edges
+ (units : list (DirectUnit DirectU64Domain)) :=
+ map (fun unit => [unit]) units.
+
+Lemma legacy_and_canonical_encoded_u64_sequences_are_equal :
+ forall units,
+ legacy_encoded_u64_sequence units = canonical_encoded_u64_sequence units.
+Proof.
+ induction units as [|unit rest IH]; simpl; [reflexivity |].
+ now rewrite IH.
+Qed.
+
+Lemma encoded_u64_sequence_has_exact_physical_width :
+ forall units,
+ length (canonical_encoded_u64_sequence units) = 8 * length units.
+Proof.
+ induction units as [|unit rest IH]; [reflexivity |].
+ change
+ (length (encoded_u64_unit_bytes unit ++
+ canonical_encoded_u64_sequence rest) = 8 * S (length rest)).
+ rewrite app_length, IH.
+ assert (Hunit : length (encoded_u64_unit_bytes unit) = 8).
+ { unfold encoded_u64_unit_bytes. apply fixed_little_endian_length. }
+ rewrite Hunit. lia.
+Qed.
+
+Definition u64_alias_layout_and_route_are_exact (alias : LegacyAlias) : Prop :=
+ match alias with
+ | LegacyDynamicDawgU64 =>
+ legacy_alias_layout alias = GenericLogicalLayout /\
+ legacy_alias_route alias = RetainedSpecializedKernel
+ | LegacyPersistentARTrieU64 | LegacyPersistentARTrieU64Compact =>
+ legacy_alias_layout alias = PersistentU64CompactLayout /\
+ legacy_alias_route alias = RetainedSpecializedKernel
+ | LegacyPersistentARTrieU64Prefix3Compat =>
+ legacy_alias_layout alias =
+ PersistentU64Prefix3CompatibilityLayout /\
+ legacy_alias_route alias = RetainedSpecializedKernel
+ | LegacyEncodedPersistentARTrieU64 =>
+ legacy_alias_layout alias = EncodedU64ByteCompatibilityLayout /\
+ legacy_alias_route alias = EncodedU64ByteAdapterKernel
+ | _ => True
+ end.
+
+Theorem VWENC_220_EVERY_U64_ALIAS_PRESERVES_PROFILE_AND_EXPLICIT_LAYOUT :
+ (forall alias,
+ legacy_alias_class alias = LegacyU64Class ->
+ legacy_alias_profile alias = DirectProfile DirectU64Domain /\
+ u64_alias_layout_and_route_are_exact alias) /\
+ (forall units,
+ legacy_encoded_u64_sequence units =
+ canonical_encoded_u64_sequence units /\
+ length (canonical_encoded_u64_sequence units) = 8 * length units /\
+ length (encoded_u64_logical_edges units) = length units).
+Proof.
+ split.
+ - intros alias Hclass. split.
+ + unfold legacy_alias_profile. now rewrite Hclass.
+ + destruct alias; simpl in *; try discriminate; repeat split; reflexivity.
+ - intros units. repeat split.
+ + apply legacy_and_canonical_encoded_u64_sequences_are_equal.
+ + apply encoded_u64_sequence_has_exact_physical_width.
+ + apply map_length.
+Qed.
+
+Record DynamicToDatConversion
+ (profile : FamilyProfile) (context : FamilyConsumerContext profile)
+ (Value : Type) : Type := {
+ conversion_dynamic_source :
+ FamilySnapshot DynamicDawgFamily profile context Value;
+ conversion_dat_target :
+ FamilySnapshot DoubleArrayTrieFamily profile context Value;
+ conversion_same_revision :
+ snapshot_revision _ _ _ _ conversion_dynamic_source =
+ snapshot_revision _ _ _ _ conversion_dat_target;
+ conversion_same_observations :
+ SameLogicalObservations
+ (snapshot_observations _ _ _ _ conversion_dynamic_source)
+ (snapshot_observations _ _ _ _ conversion_dat_target)
+}.
+
+Theorem VWENC_221_DYNAMIC_TO_FROZEN_CONVERSION_PRESERVES_LOGICAL_OBSERVATIONS :
+ forall profile (context : FamilyConsumerContext profile) (Value : Type)
+ (conversion : DynamicToDatConversion profile context Value),
+ snapshot_revision _ _ _ _ (conversion_dynamic_source _ _ _ conversion) =
+ snapshot_revision _ _ _ _ (conversion_dat_target _ _ _ conversion) /\
+ SameLogicalObservations
+ (snapshot_observations _ _ _ _
+ (conversion_dynamic_source _ _ _ conversion))
+ (snapshot_observations _ _ _ _
+ (conversion_dat_target _ _ _ conversion)).
+Proof.
+ intros profile context Value conversion. split.
+ - exact (conversion_same_revision _ _ _ conversion).
+ - exact (conversion_same_observations _ _ _ conversion).
+Qed.
+
+Record TraversalProjectionBundle
+ (family : DictionaryFamily) (profile : FamilyProfile)
+ (context : FamilyConsumerContext profile) (Value : Type)
+ : Type := {
+ projection_revision : nat;
+ projection_reference_view :
+ LogicalObservations (BoundProfileUnit profile context) Value;
+ projection_node_view :
+ LogicalObservations (BoundProfileUnit profile context) Value;
+ projection_zipper_view :
+ LogicalObservations (BoundProfileUnit profile context) Value;
+ projection_cursor_view :
+ LogicalObservations (BoundProfileUnit profile context) Value;
+ projection_node_revision : nat;
+ projection_zipper_revision : nat;
+ projection_cursor_revision : nat;
+ projection_node_revision_exact : projection_node_revision = projection_revision;
+ projection_zipper_revision_exact : projection_zipper_revision = projection_revision;
+ projection_cursor_revision_exact : projection_cursor_revision = projection_revision;
+ projection_node_refines_reference :
+ SameLogicalObservations projection_node_view projection_reference_view;
+ projection_zipper_refines_reference :
+ SameLogicalObservations projection_zipper_view projection_reference_view;
+ projection_cursor_refines_reference :
+ SameLogicalObservations projection_cursor_view projection_reference_view
+}.
+
+Theorem VWENC_222_NODE_ZIPPER_AND_CURSOR_SHARE_ONE_REVISION_BOUND_VIEW :
+ forall family profile (context : FamilyConsumerContext profile) (Value : Type)
+ (bundle : TraversalProjectionBundle family profile context Value),
+ projection_node_revision _ _ _ _ bundle =
+ projection_zipper_revision _ _ _ _ bundle /\
+ projection_zipper_revision _ _ _ _ bundle =
+ projection_cursor_revision _ _ _ _ bundle /\
+ SameLogicalObservations
+ (projection_node_view _ _ _ _ bundle)
+ (projection_zipper_view _ _ _ _ bundle) /\
+ SameLogicalObservations
+ (projection_zipper_view _ _ _ _ bundle)
+ (projection_cursor_view _ _ _ _ bundle).
+Proof.
+ intros family profile context Value bundle. split.
+ - rewrite (projection_node_revision_exact _ _ _ _ bundle),
+ (projection_zipper_revision_exact _ _ _ _ bundle). reflexivity.
+ - split.
+ + rewrite (projection_zipper_revision_exact _ _ _ _ bundle),
+ (projection_cursor_revision_exact _ _ _ _ bundle). reflexivity.
+ + split.
+ * eapply same_logical_observations_transitive with
+ (middle := projection_reference_view
+ family profile context Value bundle).
+ -- exact (projection_node_refines_reference _ _ _ _ bundle).
+ -- apply same_logical_observations_symmetric.
+ exact (projection_zipper_refines_reference _ _ _ _ bundle).
+ * eapply same_logical_observations_transitive with
+ (middle := projection_reference_view
+ family profile context Value bundle).
+ -- exact (projection_zipper_refines_reference _ _ _ _ bundle).
+ -- apply same_logical_observations_symmetric.
+ exact (projection_cursor_refines_reference _ _ _ _ bundle).
+Qed.
+
+Definition surface_is_available
+ (family : DictionaryFamily) (surface : ConsumerSurfaceClass) : Prop :=
+ (exists route, family_surface_cell family surface = ExistingSurface route) \/
+ (exists route, family_surface_cell family surface = ProspectiveSurface route).
+
+Record LifecycleRefinement
+ (family : DictionaryFamily) (profile : FamilyProfile)
+ (context : FamilyConsumerContext profile) (Value : Type)
+ (surface : ConsumerSurfaceClass)
+ : Type := {
+ lifecycle_surface_available : surface_is_available family surface;
+ lifecycle_source : FamilySnapshot family profile context Value;
+ lifecycle_product : FamilySnapshot family profile context Value;
+ lifecycle_product_refines :
+ SameLogicalObservations
+ (snapshot_observations _ _ _ _ lifecycle_source)
+ (snapshot_observations _ _ _ _ lifecycle_product);
+ lifecycle_revision_exact :
+ snapshot_revision _ _ _ _ lifecycle_source =
+ snapshot_revision _ _ _ _ lifecycle_product
+}.
+
+Theorem VWENC_223_FACTORY_COLLECTION_AND_SERIALIZATION_PRESERVE_PROFILE_VIEW :
+ forall family profile (context : FamilyConsumerContext profile)
+ (Value : Type) surface
+ (lifecycle : LifecycleRefinement
+ family profile context Value surface),
+ In surface
+ [FactorySurface; CollectionSurface; SerializationReopenSurface] ->
+ surface_is_available family surface /\
+ SameLogicalObservations
+ (snapshot_observations _ _ _ _
+ (lifecycle_source _ _ _ _ _ lifecycle))
+ (snapshot_observations _ _ _ _
+ (lifecycle_product _ _ _ _ _ lifecycle)) /\
+ snapshot_revision _ _ _ _
+ (lifecycle_source _ _ _ _ _ lifecycle) =
+ snapshot_revision _ _ _ _
+ (lifecycle_product _ _ _ _ _ lifecycle).
+Proof.
+ intros family profile context Value surface lifecycle _.
+ split.
+ - exact (lifecycle_surface_available _ _ _ _ _ lifecycle).
+ - split.
+ + exact (lifecycle_product_refines _ _ _ _ _ lifecycle).
+ + exact (lifecycle_revision_exact _ _ _ _ _ lifecycle).
+Qed.
+
+Record ExtensionalSetCombinator (Atom Value : Type) : Type := {
+ combine_set_views :
+ LogicalObservations Atom Value -> LogicalObservations Atom Value ->
+ LogicalObservations Atom Value;
+ combine_set_views_extensional :
+ forall left left_refined right right_refined,
+ SameLogicalObservations left left_refined ->
+ SameLogicalObservations right right_refined ->
+ SameLogicalObservations
+ (combine_set_views left right)
+ (combine_set_views left_refined right_refined)
+}.
+
+Theorem VWENC_224_SET_COMBINATORS_COMMUTE_WITH_PROFILE_REFINEMENT :
+ forall (Atom Value : Type) (combine : ExtensionalSetCombinator Atom Value)
+ left left_refined right right_refined,
+ SameLogicalObservations left left_refined ->
+ SameLogicalObservations right right_refined ->
+ SameLogicalObservations
+ (combine_set_views Atom Value combine left right)
+ (combine_set_views Atom Value combine left_refined right_refined).
+Proof. intros. now apply combine_set_views_extensional. Qed.
+
+Record ExtensionalValueCombinator (Atom Value : Type) : Type := {
+ combine_value_views :
+ LogicalObservations Atom Value -> LogicalObservations Atom Value ->
+ LogicalObservations Atom Value;
+ combine_value_views_extensional :
+ forall left left_refined right right_refined,
+ SameLogicalObservations left left_refined ->
+ SameLogicalObservations right right_refined ->
+ SameLogicalObservations
+ (combine_value_views left right)
+ (combine_value_views left_refined right_refined)
+}.
+
+Theorem VWENC_225_VALUE_COMBINATORS_COMMUTE_WITH_PROFILE_REFINEMENT :
+ forall (Atom Value : Type)
+ (combine : ExtensionalValueCombinator Atom Value)
+ left left_refined right right_refined,
+ SameLogicalObservations left left_refined ->
+ SameLogicalObservations right right_refined ->
+ SameLogicalObservations
+ (combine_value_views Atom Value combine left right)
+ (combine_value_views Atom Value combine left_refined right_refined).
+Proof. intros. now apply combine_value_views_extensional. Qed.
+
+(** ** Encoded adapters and logical suffix boundaries *)
+
+Inductive PathMapTraceEvent : Type :=
+| PathMapPhysicalByteVisited : PhysicalByte -> PathMapTraceEvent
+| PathMapLogicalAtomEmitted : LogicalAtom -> PathMapTraceEvent.
+
+Definition pathmap_physical_trace
+ (stored : StoredLogicalUnit) (atom : LogicalAtom)
+ : list PathMapTraceEvent :=
+ map PathMapPhysicalByteVisited (physical_codeword_of stored) ++
+ [PathMapLogicalAtomEmitted atom].
+
+Fixpoint pathmap_logical_projection
+ (trace : list PathMapTraceEvent) : list LogicalAtom :=
+ match trace with
+ | [] => []
+ | PathMapPhysicalByteVisited _ :: rest => pathmap_logical_projection rest
+ | PathMapLogicalAtomEmitted atom :: rest =>
+ atom :: pathmap_logical_projection rest
+ end.
+
+Lemma pathmap_logical_projection_app :
+ forall left right,
+ pathmap_logical_projection (left ++ right) =
+ pathmap_logical_projection left ++ pathmap_logical_projection right.
+Proof.
+ induction left as [|event rest IH]; intros right; simpl; [reflexivity |].
+ destruct event; simpl; now rewrite IH.
+Qed.
+
+Lemma pathmap_physical_prefix_projects_to_no_logical_atoms :
+ forall bytes,
+ pathmap_logical_projection (map PathMapPhysicalByteVisited bytes) = [].
+Proof.
+ induction bytes; simpl; auto.
+Qed.
+
+Lemma pathmap_trace_projects_exactly_one_atom :
+ forall stored atom,
+ pathmap_logical_projection (pathmap_physical_trace stored atom) = [atom].
+Proof.
+ intros stored atom. unfold pathmap_physical_trace.
+ rewrite pathmap_logical_projection_app,
+ pathmap_physical_prefix_projects_to_no_logical_atoms.
+ reflexivity.
+Qed.
+
+Definition pathmap_node_projection := pathmap_logical_projection.
+Definition pathmap_zipper_projection := pathmap_logical_projection.
+Definition pathmap_snapshot_projection := pathmap_logical_projection.
+
+Theorem VWENC_226_ENCODED_ADAPTER_STAGING_BYTES_ARE_HIDDEN_FROM_CONSUMERS :
+ forall surface stored atom,
+ representation_admits EncodedBytePathAdapter stored ->
+ decode_stored_logical_unit stored = Some atom ->
+ consumer_observation surface
+ {| transition_representation := EncodedBytePathAdapter;
+ transition_unit := stored |} = [atom] /\
+ length
+ (consumer_observation surface
+ {| transition_representation := EncodedBytePathAdapter;
+ transition_unit := stored |}) = 1 /\
+ pathmap_node_projection (pathmap_physical_trace stored atom) = [atom] /\
+ pathmap_zipper_projection (pathmap_physical_trace stored atom) = [atom] /\
+ pathmap_snapshot_projection (pathmap_physical_trace stored atom) = [atom].
+Proof.
+ intros surface stored atom Hadmits Hdecode.
+ assert (Hvalid :
+ valid_stored_transition
+ {| transition_representation := EncodedBytePathAdapter;
+ transition_unit := stored |}).
+ { split; [exact Hadmits |]. exists atom. exact Hdecode. }
+ repeat split.
+ - apply VWENC_16_CODEC_BYTES_ARE_NOT_LOGICAL_TRANSITIONS.
+ change
+ ((if representation_admitsb EncodedBytePathAdapter stored
+ then decode_stored_logical_unit stored else None) = Some atom).
+ apply representation_admitsb_reflects_admission in Hadmits.
+ now rewrite Hadmits, Hdecode.
+ - now apply VWENC_17_ONE_LOGICAL_ATOM_PER_CONSUMER_TRANSITION.
+ - apply pathmap_trace_projects_exactly_one_atom.
+ - apply pathmap_trace_projects_exactly_one_atom.
+ - apply pathmap_trace_projects_exactly_one_atom.
+Qed.
+
+Theorem VWENC_227_PATHMAP_UTF8_GROUPING_EMITS_ONE_UNICODE_SCALAR :
+ forall surface bytes codepoint,
+ canonical_utf8_codeword codepoint bytes ->
+ family_profile_cell PathMapAdapterFamily
+ (DirectProfile DirectUnicodeScalarDomain) =
+ ExistingProfileCell PathMapUtf8BoundaryAdapterRoute
+ PathMapUtf8BoundaryLayout /\
+ consumer_observation surface
+ {| transition_representation := EncodedBytePathAdapter;
+ transition_unit := StoredUtf8 bytes |} = [UnicodeAtom codepoint] /\
+ pathmap_node_projection
+ (pathmap_physical_trace (StoredUtf8 bytes) (UnicodeAtom codepoint)) =
+ [UnicodeAtom codepoint] /\
+ pathmap_zipper_projection
+ (pathmap_physical_trace (StoredUtf8 bytes) (UnicodeAtom codepoint)) =
+ [UnicodeAtom codepoint] /\
+ pathmap_snapshot_projection
+ (pathmap_physical_trace (StoredUtf8 bytes) (UnicodeAtom codepoint)) =
+ [UnicodeAtom codepoint].
+Proof.
+ intros surface bytes codepoint Hcanonical.
+ split; [reflexivity |]. split.
+ - apply VWENC_16_CODEC_BYTES_ARE_NOT_LOGICAL_TRANSITIONS.
+ now apply VWENC_66_UTF8_LOGICAL_IDENTITY_IS_UNICODE_SCALAR.
+ - split; [apply pathmap_trace_projects_exactly_one_atom |].
+ split; apply pathmap_trace_projects_exactly_one_atom.
+Qed.
+
+Theorem VWENC_228_CANONICAL_ULEB_CODEWORD_EMITS_ONE_OPAQUE_LOGICAL_ATOM :
+ forall carrier surface bytes,
+ canonical_uleb_codeword bytes ->
+ family_profile_cell PathMapAdapterFamily
+ (InternedProfile CanonicalUlebDomain carrier) =
+ ProspectiveProfileCell (PathMapInternedIdAdapterRoute carrier)
+ (PathMapInternedIdLayout carrier) /\
+ consumer_observation surface
+ {| transition_representation := OpaqueCodewordEdge;
+ transition_unit := StoredUleb bytes |} = [UlebAtom bytes].
+Proof.
+ intros carrier surface bytes Hcanonical. split; [reflexivity |].
+ apply VWENC_16_CODEC_BYTES_ARE_NOT_LOGICAL_TRANSITIONS.
+ now apply VWENC_65_ULEB_LOGICAL_IDENTITY_IS_CANONICAL_BYTES.
+Qed.
+
+Fixpoint codeword_boundary_offsets_from
+ (start : nat) (codewords : list (list PhysicalByte)) : list nat :=
+ match codewords with
+ | [] => [start]
+ | codeword :: rest =>
+ start ::
+ codeword_boundary_offsets_from (start + length codeword) rest
+ end.
+
+Definition codeword_boundary_offsets
+ (codewords : list (list PhysicalByte)) : list nat :=
+ codeword_boundary_offsets_from 0 codewords.
+
+Lemma codeword_boundary_offsets_from_are_exact :
+ forall codewords start offset,
+ In offset (codeword_boundary_offsets_from start codewords) <->
+ exists prefix suffix,
+ codewords = prefix ++ suffix /\
+ offset = start + length (concat prefix).
+Proof.
+ induction codewords as [| codeword rest IH]; intros start offset.
+ - simpl. split.
+ + intros [Hequal | Himpossible]; [subst | contradiction].
+ exists [], []. simpl. split; [reflexivity | lia].
+ + intros [prefix [suffix [Hequal Hoffset]]].
+ destruct prefix as [| first prefix];
+ [simpl in Hoffset; left; lia | discriminate].
+ - simpl. split.
+ + intros [Hstart | Hlater].
+ * subst. exists [], (codeword :: rest). simpl.
+ split; [reflexivity | lia].
+ * apply IH in Hlater.
+ destruct Hlater as [prefix [suffix [Hrest Hoffset]]].
+ exists (codeword :: prefix), suffix. split.
+ -- simpl. now rewrite Hrest.
+ -- simpl. rewrite app_length. lia.
+ + intros [prefix [suffix [Hequal Hoffset]]].
+ destruct prefix as [| first prefix].
+ * simpl in Hoffset. left. lia.
+ * simpl in Hequal. inversion Hequal; subst first.
+ right. rewrite <- H1. apply IH.
+ exists prefix, suffix. split; [assumption |].
+ simpl in Hoffset. rewrite app_length in Hoffset. lia.
+Qed.
+
+Theorem VWENC_229_CODEWORD_BOUNDARY_OFFSETS_ARE_EXACTLY_LOGICAL_SPLITS :
+ forall codewords offset,
+ In offset (codeword_boundary_offsets codewords) <->
+ exists prefix suffix,
+ codewords = prefix ++ suffix /\
+ offset = length (concat prefix).
+Proof.
+ intros codewords offset.
+ unfold codeword_boundary_offsets.
+ rewrite codeword_boundary_offsets_from_are_exact.
+ split.
+ - intros [prefix [suffix [Hequal Hoffset]]].
+ exists prefix, suffix. split; [exact Hequal | lia].
+ - intros [prefix [suffix [Hequal Hoffset]]].
+ exists prefix, suffix. split; [exact Hequal | lia].
+Qed.
+
+Definition physical_suffix_at
+ (bytes : list PhysicalByte) (offset : nat)
+ (suffix : list PhysicalByte) : Prop :=
+ exists prefix,
+ bytes = prefix ++ suffix /\
+ length prefix = offset.
+
+Theorem VWENC_230_RAW_UTF8_SUFFIX_CAN_START_INSIDE_ONE_SCALAR_CODEWORD :
+ canonical_utf8_codeword 169 [194; 169] /\
+ physical_suffix_at [194; 169] 1 [169] /\
+ ~ In 1 (codeword_boundary_offsets [[194; 169]]).
+Proof.
+ split.
+ - split.
+ + unfold unicode_scalar. split.
+ * unfold unicode_limit, utf8_three_byte_limit.
+ change (169 < 17 * (256 * (256 * 1))). nia.
+ * unfold surrogate_start, surrogate_end.
+ change (169 < 216 * 256 \/ 224 * 256 <= 169).
+ left. nia.
+ + unfold encode_utf8_scalar, utf8_one_byte_limit,
+ utf8_two_byte_limit.
+ rewrite (proj2 (Nat.ltb_ge 169 128)) by lia.
+ rewrite (proj2 (Nat.ltb_lt 169 (8 * 256))) by lia.
+ reflexivity.
+ - split.
+ + exists [194]. split; reflexivity.
+ + simpl. lia.
+Qed.
+
+Theorem VWENC_231_RAW_ULEB_SUFFIX_CAN_START_INSIDE_ONE_CODEWORD :
+ canonical_uleb_codeword [128; 1] /\
+ physical_suffix_at [128; 1] 1 [1] /\
+ ~ In 1 (codeword_boundary_offsets [[128; 1]]).
+Proof.
+ split.
+ - split.
+ + apply UlebShapeMore; [lia | lia |].
+ apply UlebShapeLast. lia.
+ + change (canonical_uleb_digits [0; 1]).
+ unfold canonical_uleb_digits. split; [discriminate |].
+ split.
+ * constructor; [unfold valid_uleb_digit; lia |].
+ constructor; [unfold valid_uleb_digit; lia | constructor].
+ * intros. simpl. discriminate.
+ - split.
+ + exists [128]. split; reflexivity.
+ + simpl. lia.
+Qed.
+
+Definition logical_codeword_suffix
+ (codewords suffix : list (list PhysicalByte)) : Prop :=
+ exists prefix, codewords = prefix ++ suffix.
+
+Inductive SuffixSemanticDomain : Type :=
+| SuffixNotApplicable
+| RawByteSuffixSemantics
+| LogicalAtomSuffixSemantics.
+
+Definition suffix_family (family : DictionaryFamily) : bool :=
+ match family with
+ | SuffixAutomatonFamily | ScdawgFamily
+ | PersistentSuffixAutomatonFamily | PersistentSuffixTreeFamily
+ | PersistentScdawgFamily => true
+ | _ => false
+ end.
+
+Definition suffix_semantic_domain
+ (family : DictionaryFamily) (profile : FamilyProfile)
+ (layout : ExplicitLayoutContract) : SuffixSemanticDomain :=
+ if suffix_family family then
+ match profile, layout with
+ | DirectProfile DirectBytesDomain, _ => RawByteSuffixSemantics
+ | _, EncodedU64ByteCompatibilityLayout => RawByteSuffixSemantics
+ | _, PathMapNativeByteLayout => RawByteSuffixSemantics
+ | _, _ => LogicalAtomSuffixSemantics
+ end
+ else SuffixNotApplicable.
+
+Definition suffix_start_admissible
+ (domain : SuffixSemanticDomain)
+ (codewords : list (list PhysicalByte)) (offset : nat) : Prop :=
+ match domain with
+ | SuffixNotApplicable => False
+ | RawByteSuffixSemantics => offset <= length (concat codewords)
+ | LogicalAtomSuffixSemantics =>
+ In offset (codeword_boundary_offsets codewords)
+ end.
+
+Theorem VWENC_232_LOGICAL_SUFFIXES_BEGIN_ONLY_AT_CODEWORD_BOUNDARIES :
+ (forall codewords suffix,
+ logical_codeword_suffix codewords suffix ->
+ exists offset,
+ In offset (codeword_boundary_offsets codewords) /\
+ physical_suffix_at (concat codewords) offset (concat suffix)) /\
+ (forall family profile layout codewords offset,
+ suffix_semantic_domain family profile layout =
+ LogicalAtomSuffixSemantics ->
+ suffix_start_admissible
+ (suffix_semantic_domain family profile layout) codewords offset ->
+ In offset (codeword_boundary_offsets codewords)).
+Proof.
+ split.
+ - intros codewords suffix [prefix Hequal].
+ exists (length (concat prefix)). split.
+ + apply (proj2
+ (VWENC_229_CODEWORD_BOUNDARY_OFFSETS_ARE_EXACTLY_LOGICAL_SPLITS
+ codewords (length (concat prefix)))).
+ exists prefix, suffix. now split.
+ + unfold physical_suffix_at. exists (concat prefix). split.
+ * rewrite Hequal. apply concat_app.
+ * reflexivity.
+ - intros family profile layout codewords offset Hdomain Hadmissible.
+ rewrite Hdomain in Hadmissible. exact Hadmissible.
+Qed.
+
+Theorem VWENC_233_RAW_BYTE_SUFFIX_INDEXES_CLAIM_ONLY_BYTE_SEMANTICS :
+ forall family layout,
+ suffix_family family = true ->
+ suffix_semantic_domain family
+ (DirectProfile DirectBytesDomain) layout = RawByteSuffixSemantics /\
+ suffix_semantic_domain family
+ (DirectProfile DirectBytesDomain) layout <>
+ LogicalAtomSuffixSemantics /\
+ family_surface_cell family SuffixSurface =
+ ExistingSurface SuffixIndexRoute.
+Proof.
+ intros family layout Hsuffix.
+ unfold suffix_semantic_domain. rewrite Hsuffix. split; [reflexivity |].
+ split; [discriminate |].
+ destruct family; simpl in Hsuffix |- *; try discriminate; reflexivity.
+Qed.
+
+Definition serialized_direct_codewords
+ (profile : VariableWidthCodecSpec.DirectProfile) (units : list nat)
+ : list (list PhysicalByte) :=
+ map (fun unit => snd (serialize_direct_unit profile unit)) units.
+
+Theorem VWENC_234_DIRECT_UNITS_PRESERVE_ONE_CODEWORD_PER_LOGICAL_EDGE :
+ forall profile units,
+ length (serialized_direct_codewords profile units) = length units /\
+ Forall
+ (fun bytes => length bytes = direct_byte_width profile)
+ (serialized_direct_codewords profile units).
+Proof.
+ intros profile units. split.
+ - apply map_length.
+ - induction units as [| unit rest IH]; simpl; constructor.
+ + apply VWENC_49_DIRECT_SERIALIZATION_HAS_EXACT_FIXED_WIDTH.
+ + exact IH.
+Qed.
+
+Definition serialized_symbol_id_codewords (I : FixedWidthCarrierProfile)
+ (ids : list (SymbolId I)) : list (list PhysicalByte) :=
+ map (encode_symbol_id I) ids.
+
+Theorem VWENC_235_INTERNED_IDS_PRESERVE_ONE_FIXED_CODEWORD_PER_LOGICAL_EDGE :
+ forall I ids,
+ length (serialized_symbol_id_codewords I ids) = length ids /\
+ Forall
+ (fun bytes => length bytes = carrier_width_bytes I)
+ (serialized_symbol_id_codewords I ids).
+Proof.
+ intros I ids. split.
+ - apply map_length.
+ - induction ids as [| id rest IH]; simpl; constructor.
+ + exact (proj1 (symbol_id_fixed_width_encoding_roundtrips I id)).
+ + exact IH.
+Qed.
+
+(** ** One-time vocabulary binding and fixed-width hot traversal *)
+
+Record BoundConsumerFiber
+ (P : CertifiedAtomProfile) (I : FixedWidthCarrierProfile)
+ (expected actual : VocabularyFiber P I) : Type := {
+ consumer_fiber_binding_certificate : expected = actual
+}.
+
+Definition bind_consumer_fiber
+ (P : CertifiedAtomProfile) (I : FixedWidthCarrierProfile)
+ (expected actual : VocabularyFiber P I)
+ : option (BoundConsumerFiber P I expected actual).
+Proof.
+ destruct (vocabulary_fiber_eq_dec P I expected actual) as [Hequal | Hdifferent].
+ - exact (Some {| consumer_fiber_binding_certificate := Hequal |}).
+ - exact None.
+Defined.
+
+Theorem VWENC_236_CONSUMER_VOCABULARY_BINDING_IS_VALIDATED_ONCE :
+ forall P I (expected actual : VocabularyFiber P I),
+ bind_consumer_fiber P I expected actual <> None <->
+ expected = actual.
+Proof.
+ intros P I expected actual.
+ unfold bind_consumer_fiber.
+ destruct (vocabulary_fiber_eq_dec P I expected actual) as
+ [Hequal | Hdifferent].
+ - split; [intros; exact Hequal | intros; discriminate].
+ - split.
+ + intros Hpresent. exfalso. apply Hpresent. reflexivity.
+ + intros Hequal. contradiction.
+Qed.
+
+Theorem VWENC_237_MISMATCHED_VOCABULARY_FIBERS_ARE_REJECTED_BEFORE_TRAVERSAL :
+ forall P I (expected actual : VocabularyFiber P I),
+ expected <> actual ->
+ bind_consumer_fiber P I expected actual = None.
+Proof.
+ intros P I expected actual Hdifferent.
+ unfold bind_consumer_fiber.
+ destruct (vocabulary_fiber_eq_dec P I expected actual);
+ [contradiction | reflexivity].
+Qed.
+
+(** Direct and interned hot views remain separate. The interned unit type was
+ defined above the family snapshot so every consumer surfaceβnot only this
+ optimized viewβmust use the same snapshot-bound representation. *)
+
+Definition direct_hot_kernel (domain : DirectUnitDomain)
+ : MonomorphicFixedWidthKernel (DirectUnit domain).
+Proof.
+ refine
+ {| monomorphic_width := direct_byte_width (direct_codec_profile domain);
+ monomorphic_width_positive := _;
+ monomorphic_encode := fun unit =>
+ snd (serialize_direct_unit (direct_codec_profile domain)
+ (direct_unit_value unit));
+ monomorphic_encode_exact := _;
+ monomorphic_variable_decode_request := fun _ => None;
+ monomorphic_has_no_variable_decode := _ |}.
+ - destruct domain; simpl; lia.
+ - intros [unit Hvalid].
+ apply VWENC_49_DIRECT_SERIALIZATION_HAS_EXACT_FIXED_WIDTH.
+ - reflexivity.
+Defined.
+
+Definition interned_hot_kernel
+ (P : CertifiedAtomProfile) (I : FixedWidthCarrierProfile)
+ (fiber : VocabularyFiber P I)
+ (snapshot : VocabularySnapshot P I fiber)
+ : MonomorphicFixedWidthKernel
+ (SnapshotBoundSymbolId P I fiber snapshot).
+Proof.
+ refine
+ {| monomorphic_width := carrier_width_bytes I;
+ monomorphic_width_positive := carrier_width_positive I;
+ monomorphic_encode := fun bound =>
+ encode_symbol_id I
+ (snapshot_bound_symbol_id P I fiber snapshot bound);
+ monomorphic_encode_exact := _;
+ monomorphic_variable_decode_request := fun _ => None;
+ monomorphic_has_no_variable_decode := _ |}.
+ - intros bound.
+ exact (proj1 (symbol_id_fixed_width_encoding_roundtrips I
+ (snapshot_bound_symbol_id P I fiber snapshot bound))).
+ - reflexivity.
+Defined.
+
+Record DirectHotTraversalView (domain : DirectUnitDomain) : Type := {
+ direct_hot_view_units : list (DirectUnit domain)
+}.
+
+Definition run_direct_hot_view (domain : DirectUnitDomain)
+ (view : DirectHotTraversalView domain) : list (list PhysicalByte) :=
+ run_bound_kernel (direct_hot_kernel domain)
+ (direct_hot_view_units domain view).
+
+Record BoundHotTraversalView
+ (P : CertifiedAtomProfile) (I : FixedWidthCarrierProfile)
+ (expected actual : VocabularyFiber P I)
+ (snapshot : VocabularySnapshot P I actual) : Type := {
+ hot_view_binding : BoundConsumerFiber P I expected actual;
+ hot_view_units : list (SnapshotBoundSymbolId P I actual snapshot)
+}.
+
+Definition construct_bound_hot_traversal_view
+ (P : CertifiedAtomProfile) (I : FixedWidthCarrierProfile)
+ (expected actual : VocabularyFiber P I)
+ (snapshot : VocabularySnapshot P I actual)
+ (units : list (SnapshotBoundSymbolId P I actual snapshot))
+ : option (BoundHotTraversalView P I expected actual snapshot) :=
+ match bind_consumer_fiber P I expected actual with
+ | Some binding =>
+ Some {| hot_view_binding := binding; hot_view_units := units |}
+ | None => None
+ end.
+
+Definition run_interned_hot_view
+ (P : CertifiedAtomProfile) (I : FixedWidthCarrierProfile)
+ (expected actual : VocabularyFiber P I)
+ (snapshot : VocabularySnapshot P I actual)
+ (view : BoundHotTraversalView P I expected actual snapshot)
+ : list (list PhysicalByte) :=
+ run_bound_kernel (interned_hot_kernel P I actual snapshot)
+ (hot_view_units P I expected actual snapshot view).
+
+Theorem VWENC_238_EVERY_HOT_TRANSITION_HAS_AN_EXACT_FIXED_WIDTH_ENCODING :
+ forall (Unit : Type) (kernel : MonomorphicFixedWidthKernel Unit) unit,
+ length (monomorphic_encode Unit kernel unit) =
+ monomorphic_width Unit kernel /\
+ 0 < monomorphic_width Unit kernel.
+Proof.
+ intros Unit kernel unit. split.
+ - apply monomorphic_encode_exact.
+ - apply monomorphic_width_positive.
+Qed.
+
+Theorem VWENC_239_ARBITRARY_WIDTH_BIGUINT_BYTES_STAY_OUTSIDE_HOT_TRAVERSAL :
+ forall (Unit : Type) (kernel : MonomorphicFixedWidthKernel Unit) unit,
+ monomorphic_variable_decode_request Unit kernel unit = None.
+Proof. intros. apply monomorphic_has_no_variable_decode. Qed.
+
+Inductive SemanticOwnership : Type :=
+| LibdictensteinStorageSemantics
+| LlatticeAlgebraSemantics.
+
+Definition join_meet_semantics_owner
+ (_profile : FamilyProfile) : SemanticOwnership :=
+ LlatticeAlgebraSemantics.
+
+Theorem VWENC_240_DICTIONARY_PROFILES_DO_NOT_OWN_LLATTICE_ALGEBRA :
+ forall profile,
+ join_meet_semantics_owner profile = LlatticeAlgebraSemantics /\
+ join_meet_semantics_owner profile <>
+ LibdictensteinStorageSemantics.
+Proof. intros. split; discriminate || reflexivity. Qed.
+
+Theorem VWENC_247_HOT_TRAVERSAL_VIEW_EXISTS_IFF_FIBER_BINDING_SUCCEEDS :
+ forall P I (expected actual : VocabularyFiber P I)
+ (snapshot : VocabularySnapshot P I actual) units,
+ construct_bound_hot_traversal_view
+ P I expected actual snapshot units <> None <->
+ expected = actual.
+Proof.
+ intros P I expected actual snapshot units.
+ unfold construct_bound_hot_traversal_view.
+ destruct (bind_consumer_fiber P I expected actual) as
+ [binding |] eqn:Hbinding.
+ - split; [intros | intros; discriminate].
+ apply (proj1 (VWENC_236_CONSUMER_VOCABULARY_BINDING_IS_VALIDATED_ONCE
+ P I expected actual)).
+ rewrite Hbinding. discriminate.
+ - split.
+ + intros Hpresent. exfalso. apply Hpresent. reflexivity.
+ + intros Hequal.
+ apply (proj2 (VWENC_236_CONSUMER_VOCABULARY_BINDING_IS_VALIDATED_ONCE
+ P I expected actual)) in Hequal.
+ rewrite Hbinding in Hequal. contradiction.
+Qed.
+
+Theorem VWENC_248_MISMATCHED_FIBER_CANNOT_CONSTRUCT_A_HOT_TRAVERSAL_VIEW :
+ forall P I (expected actual : VocabularyFiber P I)
+ (snapshot : VocabularySnapshot P I actual) units,
+ expected <> actual ->
+ construct_bound_hot_traversal_view
+ P I expected actual snapshot units = None.
+Proof.
+ intros P I expected actual snapshot units Hdifferent.
+ unfold construct_bound_hot_traversal_view.
+ rewrite (VWENC_237_MISMATCHED_VOCABULARY_FIBERS_ARE_REJECTED_BEFORE_TRAVERSAL
+ P I expected actual Hdifferent).
+ reflexivity.
+Qed.
+
+Theorem VWENC_249_BOUND_HOT_VIEWS_CONTAIN_ONLY_EXACT_FIXED_WIDTH_UNITS :
+ (forall P I (expected actual : VocabularyFiber P I)
+ (snapshot : VocabularySnapshot P I actual)
+ (view : BoundHotTraversalView P I expected actual snapshot),
+ map (@length PhysicalByte)
+ (run_interned_hot_view P I expected actual snapshot view) =
+ repeat (carrier_width_bytes I)
+ (length (hot_view_units P I expected actual snapshot view)) /\
+ Forall
+ (fun bound =>
+ exists atom,
+ In (atom,
+ snapshot_bound_symbol_id P I actual snapshot bound)
+ (vocabulary_snapshot_live_entries P I actual snapshot))
+ (hot_view_units P I expected actual snapshot view)) /\
+ (forall domain (view : DirectHotTraversalView domain),
+ map (@length PhysicalByte) (run_direct_hot_view domain view) =
+ repeat (direct_byte_width (direct_codec_profile domain))
+ (length (direct_hot_view_units domain view))).
+Proof.
+ split.
+ - intros P I expected actual snapshot view. split.
+ + unfold run_interned_hot_view.
+ apply bound_kernel_widths_are_constant.
+ + induction (hot_view_units P I expected actual snapshot view)
+ as [|bound rest IH]; constructor.
+ * exact (snapshot_bound_live P I actual snapshot bound).
+ * exact IH.
+ - intros domain view. unfold run_direct_hot_view.
+ apply bound_kernel_widths_are_constant.
+Qed.
+
+End VariableWidthFamilyRefinementSpec.
diff --git a/formal-verification/rocq/Spec/VariableWidthInterningSpec.v b/formal-verification/rocq/Spec/VariableWidthInterningSpec.v
new file mode 100644
index 00000000..9b80bd71
--- /dev/null
+++ b/formal-verification/rocq/Spec/VariableWidthInterningSpec.v
@@ -0,0 +1,6553 @@
+(** * Certified variable-width atom interning and fixed-width ID views
+
+ This functional model is the second formal milestone of the
+ variable-width dictionary campaign. It consumes the certified profile
+ and codec laws from [VariableWidthCodecSpec]. In particular:
+
+ - an atom is indexed by one certified persistent profile and carries a
+ proof that its complete byte string is one canonical codeword;
+ - [SymbolId I] and [TermId T] are distinct nominal types parameterized by
+ open, positive-width fixed-width carrier profiles;
+ - a single interning state ties the live bijection, historical ownership,
+ packed bytes, reverse spans, sparse allocator frontier, dependent
+ sequences, and optional term-ID dictionary together;
+ - IDs which were published or burned as orphans are never rebound;
+ - sequence views are bound to an immutable backing identity and exact
+ vocabulary fiber, and index fixed-width IDs without decoding atoms;
+ - query-local IDs occupy a distinct, non-serializable namespace;
+ - model-to-Rust correspondence records exact paths, symbols, semantic
+ relationships, and obligations. Current conflicts are explicit.
+
+ Stateful object publication, crash recovery, immutable reader retention,
+ and repeated generations are modeled in
+ [VariableWidthVocabularyInterning.tla] and
+ [VariableWidthVocabularyPublication.tla].
+
+ Rocq lists model immutable mathematical observations. Allocation-free
+ borrowing, native slice layout, lifetimes, and hot-loop costs remain
+ explicit Rust refinement obligations; this file does not misdescribe a
+ Rocq list as a Rust borrow.
+
+ Stable theorem names beginning with [VWENC_] are machine-readable
+ invariant identifiers consumed by the conformance ledger.
+ *)
+
+From Coq Require Import Lists.List.
+From Coq Require Import Arith.Arith.
+From Coq Require Import Bool.Bool.
+From Coq Require Import micromega.Lia.
+From Coq Require Import Logic.ProofIrrelevance.
+From Coq Require Import Strings.String.
+From Coq Require Import Sorting.Permutation.
+Require Import ARTrie.Spec.VariableWidthCodecSpec.
+Import ListNotations.
+Import VariableWidthCodecSpec.
+
+Lemma skipn_length_local :
+ forall (A : Type) (n : nat) (xs : list A),
+ List.length (skipn n xs) = List.length xs - n.
+Proof.
+ intros A n. induction n as [| n IH]; intros xs; simpl; [lia|].
+ destruct xs as [| x xs]; simpl; [lia|].
+ rewrite IH. lia.
+Qed.
+
+Lemma firstn_length_local :
+ forall (A : Type) (n : nat) (xs : list A),
+ List.length (firstn n xs) = Nat.min n (List.length xs).
+Proof.
+ intros A n. induction n as [| n IH]; intros xs; simpl; [lia|].
+ destruct xs as [| x xs]; simpl; [lia|].
+ rewrite IH. reflexivity.
+Qed.
+
+Module VariableWidthInterning.
+
+(** ** Certified atom profiles and canonical atoms *)
+
+Definition descriptor_canonical_codeword
+ (descriptor : PersistentProfileDescriptor)
+ (bytes : list PhysicalByte) : Prop :=
+ match persistent_logical_profile descriptor with
+ | PersistedByte =>
+ List.length bytes = 1 /\ Forall valid_byte bytes
+ | PersistedUnicodeScalar =>
+ List.length bytes = 4 /\
+ Forall valid_byte bytes /\
+ unicode_scalar (decode_fixed_little_endian bytes)
+ | PersistedU64 =>
+ List.length bytes = 8 /\ Forall valid_byte bytes
+ | PersistedF64Bits =>
+ List.length bytes = 8 /\ Forall valid_byte bytes
+ | PersistedCanonicalUleb => canonical_uleb_codeword bytes
+ | PersistedCanonicalUtf8 =>
+ exists codepoint, canonical_utf8_codeword codepoint bytes
+ end.
+
+Lemma descriptor_canonical_codeword_nonempty :
+ forall descriptor bytes,
+ descriptor_canonical_codeword descriptor bytes -> bytes <> [].
+Proof.
+ intros [profile codec layout abi] bytes Hcodeword.
+ destruct profile; simpl in Hcodeword.
+ - destruct Hcodeword as [Hlength _].
+ intros Hequal. subst bytes. simpl in Hlength. discriminate.
+ - destruct Hcodeword as [Hlength _].
+ intros Hequal. subst bytes. simpl in Hlength. discriminate.
+ - destruct Hcodeword as [Hlength _].
+ intros Hequal. subst bytes. simpl in Hlength. discriminate.
+ - destruct Hcodeword as [Hlength _].
+ intros Hequal. subst bytes. simpl in Hlength. discriminate.
+ - now apply VWENC_03_ULEB_CODEWORDS_NONEMPTY.
+ - destruct Hcodeword as [codepoint [Hscalar Hbytes]].
+ subst bytes.
+ exact (proj1 (VWENC_12_UTF8_CODEWORDS_NONEMPTY_AND_AT_MOST_FOUR_BYTES
+ codepoint Hscalar)).
+Qed.
+
+Record CertifiedAtomProfile : Type := mkCertifiedAtomProfile {
+ atom_profile_descriptor : PersistentProfileDescriptor;
+ atom_profile_certificate :
+ certified_persistent_profile atom_profile_descriptor
+}.
+
+Definition atom_codeword
+ (profile : CertifiedAtomProfile) : list PhysicalByte -> Prop :=
+ descriptor_canonical_codeword (atom_profile_descriptor profile).
+
+Lemma atom_codeword_nonempty :
+ forall profile bytes, atom_codeword profile bytes -> bytes <> [].
+Proof.
+ intros profile bytes Hcodeword.
+ unfold atom_codeword in Hcodeword.
+ now apply descriptor_canonical_codeword_nonempty
+ with (descriptor := atom_profile_descriptor profile).
+Qed.
+
+Definition canonical_uleb_descriptor : PersistentProfileDescriptor :=
+ {| persistent_logical_profile := PersistedCanonicalUleb;
+ persistent_codec_identity := ProspectiveCanonicalUlebCodecV1;
+ persistent_layout_identity := ProspectiveLogicalUnitLayoutV1;
+ persistent_abi_version := 1 |}.
+
+Lemma canonical_uleb_descriptor_certified :
+ certified_persistent_profile canonical_uleb_descriptor.
+Proof.
+ exact VWENC_99_CERTIFICATION_ACCEPTS_VERSIONED_CANONICAL_ULEB_PROFILE.
+Qed.
+
+Definition canonical_uleb_profile : CertifiedAtomProfile :=
+ {| atom_profile_descriptor := canonical_uleb_descriptor;
+ atom_profile_certificate := canonical_uleb_descriptor_certified |}.
+
+Record CanonicalAtom (P : CertifiedAtomProfile) : Type := mkCanonicalAtom {
+ canonical_atom_bytes : list PhysicalByte;
+ canonical_atom_valid : atom_codeword P canonical_atom_bytes
+}.
+
+Definition canonical_atom_identity
+ {P : CertifiedAtomProfile} (atom : CanonicalAtom P) :=
+ (certified_profile_identity (atom_profile_descriptor P),
+ canonical_atom_bytes P atom).
+
+Definition canonical_atom_eq_dec
+ (P : CertifiedAtomProfile)
+ (left right : CanonicalAtom P) : {left = right} + {left <> right}.
+Proof.
+ destruct left as [left_bytes left_valid].
+ destruct right as [right_bytes right_valid].
+ destruct (list_eq_dec Nat.eq_dec left_bytes right_bytes)
+ as [Hbytes | Hbytes].
+ - subst right_bytes. left.
+ assert (left_valid = right_valid) by apply proof_irrelevance.
+ now subst right_valid.
+ - right. intros Hequal. inversion Hequal. contradiction.
+Defined.
+
+Theorem VWENC_101_CANONICAL_ATOM_IDENTITY_IS_CERTIFIED_PROFILE_AND_BYTES :
+ forall (P : CertifiedAtomProfile) (left right : CanonicalAtom P),
+ canonical_atom_identity left = canonical_atom_identity right ->
+ left = right.
+Proof.
+ intros P [left_bytes left_valid] [right_bytes right_valid] Hequal.
+ unfold canonical_atom_identity in Hequal. simpl in Hequal.
+ inversion Hequal. subst right_bytes.
+ assert (left_valid = right_valid) by apply proof_irrelevance.
+ now subst right_valid.
+Qed.
+
+Definition canonical_uleb_atom
+ (bytes : list PhysicalByte)
+ (Hcanonical : canonical_uleb_codeword bytes)
+ : CanonicalAtom canonical_uleb_profile.
+Proof.
+ refine (@mkCanonicalAtom canonical_uleb_profile bytes _).
+ change (canonical_uleb_codeword bytes).
+ exact Hcanonical.
+Defined.
+
+Theorem VWENC_102_ULEB_INTERNALIZATION_REQUIRES_CANONICAL_ARBITRARY_BYTES :
+ forall bytes (Hcanonical : canonical_uleb_codeword bytes),
+ canonical_atom_bytes
+ canonical_uleb_profile
+ (canonical_uleb_atom bytes Hcanonical) = bytes /\
+ bytes <> [] /\
+ certified_profile_identity
+ (atom_profile_descriptor canonical_uleb_profile) =
+ certified_profile_identity canonical_uleb_descriptor.
+Proof.
+ intros bytes Hcanonical.
+ split; [reflexivity |].
+ split.
+ - now apply VWENC_03_ULEB_CODEWORDS_NONEMPTY.
+ - reflexivity.
+Qed.
+
+Lemma one_byte_uleb_is_canonical :
+ forall byte, byte < 128 -> canonical_uleb_codeword [byte].
+Proof.
+ intros byte Hbyte.
+ split.
+ - constructor. exact Hbyte.
+ - unfold canonical_uleb_digits, decode_uleb_payloads.
+ simpl.
+ repeat split.
+ + discriminate.
+ + constructor.
+ * unfold valid_uleb_digit, uleb_payload.
+ apply Nat.mod_upper_bound. lia.
+ * constructor.
+ + simpl. lia.
+Qed.
+
+(** ** Open fixed-width ID carriers and nominal IDs *)
+
+Record FixedWidthCarrierProfile : Type := mkFixedWidthCarrierProfile {
+ carrier_format_identity : nat;
+ carrier_width_bytes : nat;
+ carrier_width_positive : 0 < carrier_width_bytes
+}.
+
+Definition carrier_capacity (I : FixedWidthCarrierProfile) : nat :=
+ 256 ^ carrier_width_bytes I.
+
+Lemma carrier_capacity_positive :
+ forall I, 0 < carrier_capacity I.
+Proof.
+ intros I.
+ unfold carrier_capacity.
+ assert (256 ^ carrier_width_bytes I <> 0).
+ { apply Nat.pow_nonzero. lia. }
+ lia.
+Qed.
+
+Record SymbolId (I : FixedWidthCarrierProfile) : Type := mkSymbolId {
+ symbol_id_value : nat;
+ symbol_id_in_range : symbol_id_value < carrier_capacity I
+}.
+
+Record TermId (T : FixedWidthCarrierProfile) : Type := mkTermId {
+ term_id_value : nat;
+ term_id_in_range : term_id_value < carrier_capacity T
+}.
+
+Definition symbol_id_eq_dec
+ (I : FixedWidthCarrierProfile)
+ (left right : SymbolId I) : {left = right} + {left <> right}.
+Proof.
+ destruct left as [left_value left_range].
+ destruct right as [right_value right_range].
+ destruct (Nat.eq_dec left_value right_value) as [Hequal | Hdifferent].
+ - subst right_value. left.
+ assert (left_range = right_range) by apply proof_irrelevance.
+ now subst right_range.
+ - right. intros Hequal. inversion Hequal. contradiction.
+Defined.
+
+Definition term_id_eq_dec
+ (T : FixedWidthCarrierProfile)
+ (left right : TermId T) : {left = right} + {left <> right}.
+Proof.
+ destruct left as [left_value left_range].
+ destruct right as [right_value right_range].
+ destruct (Nat.eq_dec left_value right_value) as [Hequal | Hdifferent].
+ - subst right_value. left.
+ assert (left_range = right_range) by apply proof_irrelevance.
+ now subst right_range.
+ - right. intros Hequal. inversion Hequal. contradiction.
+Defined.
+
+Definition symbol_id_of_nat
+ (I : FixedWidthCarrierProfile) (value : nat) : option (SymbolId I) :=
+ match lt_dec value (carrier_capacity I) with
+ | left Hfits =>
+ Some {| symbol_id_value := value; symbol_id_in_range := Hfits |}
+ | right _ => None
+ end.
+
+Definition term_id_of_nat
+ (T : FixedWidthCarrierProfile) (value : nat) : option (TermId T) :=
+ match lt_dec value (carrier_capacity T) with
+ | left Hfits =>
+ Some {| term_id_value := value; term_id_in_range := Hfits |}
+ | right _ => None
+ end.
+
+Definition encode_symbol_id
+ (I : FixedWidthCarrierProfile) (id : SymbolId I)
+ : list PhysicalByte :=
+ encode_fixed_little_endian
+ (carrier_width_bytes I) (symbol_id_value I id).
+
+Definition encode_term_id
+ (T : FixedWidthCarrierProfile) (id : TermId T)
+ : list PhysicalByte :=
+ encode_fixed_little_endian
+ (carrier_width_bytes T) (term_id_value T id).
+
+Definition decode_symbol_id
+ (I : FixedWidthCarrierProfile) (bytes : list PhysicalByte)
+ : option (SymbolId I) :=
+ if Nat.eq_dec (List.length bytes) (carrier_width_bytes I) then
+ if all_valid_bytesb bytes then
+ symbol_id_of_nat I (decode_fixed_little_endian bytes)
+ else None
+ else None.
+
+Definition decode_term_id
+ (T : FixedWidthCarrierProfile) (bytes : list PhysicalByte)
+ : option (TermId T) :=
+ if Nat.eq_dec (List.length bytes) (carrier_width_bytes T) then
+ if all_valid_bytesb bytes then
+ term_id_of_nat T (decode_fixed_little_endian bytes)
+ else None
+ else None.
+
+Lemma symbol_id_fixed_width_encoding_roundtrips :
+ forall (I : FixedWidthCarrierProfile) (id : SymbolId I),
+ List.length (encode_symbol_id I id) = carrier_width_bytes I /\
+ decode_symbol_id I (encode_symbol_id I id) = Some id.
+Proof.
+ intros I [value Hrange].
+ split.
+ - apply fixed_little_endian_length.
+ - unfold decode_symbol_id, encode_symbol_id. simpl.
+ rewrite fixed_little_endian_length.
+ destruct (Nat.eq_dec (carrier_width_bytes I) (carrier_width_bytes I))
+ as [_ | Himpossible].
+ 2: contradiction.
+ assert (Hvalid :
+ all_valid_bytesb
+ (encode_fixed_little_endian (carrier_width_bytes I) value) = true).
+ { apply (proj2 (all_valid_bytesb_reflects_validity _)).
+ apply fixed_little_endian_bytes_are_valid. }
+ rewrite Hvalid.
+ unfold symbol_id_of_nat.
+ rewrite fixed_little_endian_roundtrip by exact Hrange.
+ destruct (lt_dec value (carrier_capacity I)) as [Hfits | Hoverflow].
+ + f_equal. f_equal. apply proof_irrelevance.
+ + contradiction.
+Qed.
+
+Lemma term_id_fixed_width_encoding_roundtrips :
+ forall (T : FixedWidthCarrierProfile) (id : TermId T),
+ List.length (encode_term_id T id) = carrier_width_bytes T /\
+ decode_term_id T (encode_term_id T id) = Some id.
+Proof.
+ intros T [value Hrange].
+ split.
+ - apply fixed_little_endian_length.
+ - unfold decode_term_id, encode_term_id. simpl.
+ rewrite fixed_little_endian_length.
+ destruct (Nat.eq_dec (carrier_width_bytes T) (carrier_width_bytes T))
+ as [_ | Himpossible].
+ 2: contradiction.
+ assert (Hvalid :
+ all_valid_bytesb
+ (encode_fixed_little_endian (carrier_width_bytes T) value) = true).
+ { apply (proj2 (all_valid_bytesb_reflects_validity _)).
+ apply fixed_little_endian_bytes_are_valid. }
+ rewrite Hvalid.
+ unfold term_id_of_nat.
+ rewrite fixed_little_endian_roundtrip by exact Hrange.
+ destruct (lt_dec value (carrier_capacity T)) as [Hfits | Hoverflow].
+ + f_equal. f_equal. apply proof_irrelevance.
+ + contradiction.
+Qed.
+
+Theorem VWENC_109_SYMBOL_AND_TERM_ID_FIXED_WIDTH_ENCODINGS_ROUNDTRIP :
+ (forall (I : FixedWidthCarrierProfile) (id : SymbolId I),
+ List.length (encode_symbol_id I id) = carrier_width_bytes I /\
+ decode_symbol_id I (encode_symbol_id I id) = Some id) /\
+ (forall (T : FixedWidthCarrierProfile) (id : TermId T),
+ List.length (encode_term_id T id) = carrier_width_bytes T /\
+ decode_term_id T (encode_term_id T id) = Some id).
+Proof.
+ split.
+ - exact symbol_id_fixed_width_encoding_roundtrips.
+ - exact term_id_fixed_width_encoding_roundtrips.
+Qed.
+
+Lemma symbol_id_construction_rejects_overflow :
+ forall (I : FixedWidthCarrierProfile) value,
+ carrier_capacity I <= value ->
+ symbol_id_of_nat I value = None.
+Proof.
+ intros I value Hoverflow.
+ unfold symbol_id_of_nat.
+ destruct (lt_dec value (carrier_capacity I)); [lia | reflexivity].
+Qed.
+
+Lemma term_id_construction_rejects_overflow :
+ forall (T : FixedWidthCarrierProfile) value,
+ carrier_capacity T <= value ->
+ term_id_of_nat T value = None.
+Proof.
+ intros T value Hoverflow.
+ unfold term_id_of_nat.
+ destruct (lt_dec value (carrier_capacity T)); [lia | reflexivity].
+Qed.
+
+Theorem VWENC_110_SYMBOL_AND_TERM_ID_CONSTRUCTION_REJECTS_OVERFLOW :
+ (forall (I : FixedWidthCarrierProfile) value,
+ carrier_capacity I <= value ->
+ symbol_id_of_nat I value = None) /\
+ (forall (T : FixedWidthCarrierProfile) value,
+ carrier_capacity T <= value ->
+ term_id_of_nat T value = None).
+Proof.
+ split.
+ - exact symbol_id_construction_rejects_overflow.
+ - exact term_id_construction_rejects_overflow.
+Qed.
+
+Theorem VWENC_111_ID_CARRIER_INTERFACE_REMAINS_OPEN_TO_ANY_POSITIVE_WIDTH :
+ forall (I : FixedWidthCarrierProfile),
+ 0 < carrier_width_bytes I /\
+ 0 < carrier_capacity I /\
+ List.length
+ (encode_fixed_little_endian (carrier_width_bytes I) 0) =
+ carrier_width_bytes I.
+Proof.
+ intros I. repeat split.
+ - apply carrier_width_positive.
+ - apply carrier_capacity_positive.
+ - apply fixed_little_endian_length.
+Qed.
+
+Definition carrier_from_positive_width
+ (format_identity width : nat) (Hwidth : 0 < width)
+ : FixedWidthCarrierProfile :=
+ {| carrier_format_identity := format_identity;
+ carrier_width_bytes := width;
+ carrier_width_positive := Hwidth |}.
+
+Theorem VWENC_160_EVERY_POSITIVE_WIDTH_HAS_AN_EXACT_CARRIER_INSTANCE :
+ forall format_identity width,
+ 0 < width ->
+ exists carrier : FixedWidthCarrierProfile,
+ carrier_format_identity carrier = format_identity /\
+ carrier_width_bytes carrier = width.
+Proof.
+ intros format_identity width Hwidth.
+ exists (carrier_from_positive_width format_identity width Hwidth).
+ now split.
+Qed.
+
+(** ** Vocabulary fibers and exact atom/ID bijections *)
+
+Record VocabularyFiber
+ (P : CertifiedAtomProfile) (I : FixedWidthCarrierProfile) : Type :=
+ mkVocabularyFiber {
+ vocabulary_identity : nat;
+ vocabulary_generation : nat
+ }.
+
+Definition vocabulary_fiber_identity
+ {P : CertifiedAtomProfile} {I : FixedWidthCarrierProfile}
+ (fiber : VocabularyFiber P I) :=
+ (certified_profile_identity (atom_profile_descriptor P),
+ (carrier_format_identity I,
+ (carrier_width_bytes I,
+ (vocabulary_identity P I fiber,
+ vocabulary_generation P I fiber)))).
+
+Definition vocabulary_fiber_eq_dec
+ (P : CertifiedAtomProfile) (I : FixedWidthCarrierProfile)
+ (left right : VocabularyFiber P I)
+ : {left = right} + {left <> right}.
+Proof.
+ destruct left as [left_identity left_generation].
+ destruct right as [right_identity right_generation].
+ destruct (Nat.eq_dec left_identity right_identity)
+ as [Hidentity | Hidentity].
+ - subst right_identity.
+ destruct (Nat.eq_dec left_generation right_generation)
+ as [Hgeneration | Hgeneration].
+ + subst right_generation. left. reflexivity.
+ + right. intros Hequal. inversion Hequal. contradiction.
+ - right. intros Hequal. inversion Hequal. contradiction.
+Defined.
+
+Record FiberBoundSymbolId
+ (P : CertifiedAtomProfile) (I : FixedWidthCarrierProfile) : Type :=
+ mkFiberBoundSymbolId {
+ bound_symbol_fiber : VocabularyFiber P I;
+ bound_symbol_value : SymbolId I
+ }.
+
+Definition interpret_symbol_id
+ {P : CertifiedAtomProfile} {I : FixedWidthCarrierProfile}
+ (expected : VocabularyFiber P I)
+ (bound : FiberBoundSymbolId P I) : option (SymbolId I) :=
+ if vocabulary_fiber_eq_dec P I expected (bound_symbol_fiber P I bound)
+ then Some (bound_symbol_value P I bound)
+ else None.
+
+Theorem VWENC_112_CROSS_FIBER_ID_INTERPRETATION_IS_REJECTED :
+ forall (P : CertifiedAtomProfile) (I : FixedWidthCarrierProfile)
+ (expected actual : VocabularyFiber P I) (id : SymbolId I),
+ expected <> actual ->
+ interpret_symbol_id expected
+ (mkFiberBoundSymbolId P I actual id) = None.
+Proof.
+ intros P I expected actual id Hdifferent.
+ unfold interpret_symbol_id. simpl.
+ destruct (vocabulary_fiber_eq_dec P I expected actual)
+ as [Hequal | _].
+ - contradiction.
+ - reflexivity.
+Qed.
+
+Theorem VWENC_113_SAME_FIBER_ID_INTERPRETATION_IS_EXACT :
+ forall (P : CertifiedAtomProfile) (I : FixedWidthCarrierProfile)
+ (fiber : VocabularyFiber P I) (id : SymbolId I),
+ interpret_symbol_id fiber
+ (mkFiberBoundSymbolId P I fiber id) = Some id.
+Proof.
+ intros P I fiber id.
+ unfold interpret_symbol_id. simpl.
+ destruct (vocabulary_fiber_eq_dec P I fiber fiber)
+ as [_ | Himpossible].
+ - reflexivity.
+ - contradiction.
+Qed.
+
+Fixpoint assoc_lookup {Key Value : Type}
+ (key_eq_dec : forall left right : Key, {left = right} + {left <> right})
+ (entries : list (Key * Value))
+ (query : Key) : option Value :=
+ match entries with
+ | [] => None
+ | (key, value) :: rest =>
+ if key_eq_dec query key then Some value
+ else assoc_lookup key_eq_dec rest query
+ end.
+
+Lemma assoc_lookup_sound :
+ forall (Key Value : Type)
+ (key_eq_dec : forall left right : Key, {left = right} + {left <> right})
+ (entries : list (Key * Value)) query value,
+ assoc_lookup key_eq_dec entries query = Some value ->
+ In (query, value) entries.
+Proof.
+ intros Key Value key_eq_dec entries.
+ induction entries as [| [key current] rest IH];
+ intros query value Hlookup.
+ - discriminate.
+ - simpl in Hlookup.
+ destruct (key_eq_dec query key) as [Hequal | Hdifferent].
+ + inversion Hlookup. subst. now left.
+ + right. now apply IH.
+Qed.
+
+Lemma assoc_lookup_complete_unique :
+ forall (Key Value : Type)
+ (key_eq_dec : forall left right : Key, {left = right} + {left <> right})
+ (entries : list (Key * Value)) query value,
+ NoDup (map fst entries) ->
+ In (query, value) entries ->
+ assoc_lookup key_eq_dec entries query = Some value.
+Proof.
+ intros Key Value key_eq_dec entries.
+ induction entries as [| [key current] rest IH];
+ intros query value Hnodup Hin.
+ - contradiction.
+ - inversion Hnodup as [| head keys Hhead Hrest].
+ simpl in Hin.
+ destruct Hin as [Hequal | Hin].
+ + inversion Hequal. subst query value.
+ simpl. destruct (key_eq_dec key key); [reflexivity | contradiction].
+ + simpl.
+ destruct (key_eq_dec query key) as [Hequal | Hdifferent].
+ * subst query. exfalso. apply Hhead.
+ apply in_map with (f := fst) in Hin. exact Hin.
+ * now apply IH.
+Qed.
+
+Lemma assoc_lookup_none_key_absent :
+ forall (Key Value : Type)
+ (key_eq_dec : forall left right : Key, {left = right} + {left <> right})
+ (entries : list (Key * Value)) query,
+ assoc_lookup key_eq_dec entries query = None ->
+ ~ In query (map fst entries).
+Proof.
+ intros Key Value key_eq_dec entries.
+ induction entries as [| [key value] rest IH]; intros query Hlookup.
+ - simpl. tauto.
+ - simpl in Hlookup |- *.
+ destruct (key_eq_dec query key) as [Hequal | Hdifferent].
+ + discriminate.
+ + intros [Hequal | Hin].
+ * apply Hdifferent. symmetry. exact Hequal.
+ * now apply (IH query Hlookup).
+Qed.
+
+Definition VocabularyEntry
+ (P : CertifiedAtomProfile) (I : FixedWidthCarrierProfile) :=
+ (CanonicalAtom P * SymbolId I)%type.
+
+Definition reverse_vocabulary_entries
+ {P : CertifiedAtomProfile} {I : FixedWidthCarrierProfile}
+ (entries : list (VocabularyEntry P I))
+ : list (SymbolId I * CanonicalAtom P) :=
+ map (fun entry => (snd entry, fst entry)) entries.
+
+Lemma reverse_vocabulary_membership :
+ forall (P : CertifiedAtomProfile) (I : FixedWidthCarrierProfile)
+ (entries : list (VocabularyEntry P I)) atom id,
+ In (id, atom) (reverse_vocabulary_entries entries) <->
+ In (atom, id) entries.
+Proof.
+ intros P I entries atom id.
+ unfold reverse_vocabulary_entries. rewrite in_map_iff.
+ split.
+ - intros [[entry_atom entry_id] [Hequal Hin]].
+ simpl in Hequal. inversion Hequal. subst. exact Hin.
+ - intros Hin. exists (atom, id). split; [reflexivity | exact Hin].
+Qed.
+
+Lemma reverse_vocabulary_keys_are_ids :
+ forall (P : CertifiedAtomProfile) (I : FixedWidthCarrierProfile)
+ (entries : list (VocabularyEntry P I)),
+ map fst (reverse_vocabulary_entries entries) = map snd entries.
+Proof.
+ intros P I entries. unfold reverse_vocabulary_entries.
+ rewrite map_map. apply map_ext. intros [atom id]. reflexivity.
+Qed.
+
+Definition lookup_atom
+ {P : CertifiedAtomProfile} {I : FixedWidthCarrierProfile}
+ (entries : list (VocabularyEntry P I))
+ (atom : CanonicalAtom P) : option (SymbolId I) :=
+ assoc_lookup (canonical_atom_eq_dec P) entries atom.
+
+Definition lookup_symbol
+ {P : CertifiedAtomProfile} {I : FixedWidthCarrierProfile}
+ (entries : list (VocabularyEntry P I))
+ (id : SymbolId I) : option (CanonicalAtom P) :=
+ assoc_lookup (symbol_id_eq_dec I)
+ (reverse_vocabulary_entries entries) id.
+
+Definition vocabulary_relation_well_formed
+ {P : CertifiedAtomProfile} {I : FixedWidthCarrierProfile}
+ (entries : list (VocabularyEntry P I)) : Prop :=
+ NoDup (map fst entries) /\ NoDup (map snd entries).
+
+Theorem VWENC_103_PUBLISHED_VOCABULARY_IS_AN_EXACT_BIJECTION :
+ forall (P : CertifiedAtomProfile) (I : FixedWidthCarrierProfile)
+ (entries : list (VocabularyEntry P I)) atom id,
+ vocabulary_relation_well_formed entries ->
+ (lookup_atom entries atom = Some id <->
+ lookup_symbol entries id = Some atom).
+Proof.
+ intros P I entries atom id [Hatom_unique Hid_unique].
+ split; intros Hlookup.
+ - apply assoc_lookup_sound in Hlookup.
+ unfold lookup_symbol. apply assoc_lookup_complete_unique.
+ + rewrite reverse_vocabulary_keys_are_ids. exact Hid_unique.
+ + apply reverse_vocabulary_membership. exact Hlookup.
+ - unfold lookup_symbol in Hlookup.
+ apply assoc_lookup_sound in Hlookup.
+ apply reverse_vocabulary_membership in Hlookup.
+ unfold lookup_atom. now apply assoc_lookup_complete_unique.
+Qed.
+
+Definition fingerprint_candidate
+ {P : CertifiedAtomProfile} (_atom : CanonicalAtom P) : nat := 0.
+
+Definition collision_atom_left : CanonicalAtom canonical_uleb_profile :=
+ canonical_uleb_atom [1] (one_byte_uleb_is_canonical 1 ltac:(lia)).
+
+Definition collision_atom_right : CanonicalAtom canonical_uleb_profile :=
+ canonical_uleb_atom [2] (one_byte_uleb_is_canonical 2 ltac:(lia)).
+
+Definition u32_carrier : FixedWidthCarrierProfile :=
+ {| carrier_format_identity := 32;
+ carrier_width_bytes := 4;
+ carrier_width_positive := ltac:(lia) |}.
+
+Definition symbol_zero : SymbolId u32_carrier.
+Proof.
+ refine (@mkSymbolId u32_carrier 0 _).
+ apply carrier_capacity_positive.
+Defined.
+
+Definition symbol_one : SymbolId u32_carrier.
+Proof.
+ refine (@mkSymbolId u32_carrier 1 _).
+ unfold carrier_capacity, u32_carrier.
+ apply Nat.pow_gt_1.
+ - lia.
+ - discriminate.
+Defined.
+
+Definition symbol_two : SymbolId u32_carrier.
+Proof.
+ refine (@mkSymbolId u32_carrier 2 _).
+ change (2 < 256 ^ 4).
+ replace 4 with (S 3) by reflexivity.
+ rewrite Nat.pow_succ_r by lia.
+ set (power := 256 ^ 3).
+ assert (Hpower : power <> 0).
+ { unfold power. apply Nat.pow_nonzero. lia. }
+ nia.
+Defined.
+
+Lemma symbol_two_differs_from_symbol_zero :
+ symbol_two <> symbol_zero.
+Proof.
+ intros Hequal.
+ apply (f_equal (symbol_id_value u32_carrier)) in Hequal.
+ discriminate.
+Qed.
+
+Definition term_zero : TermId u32_carrier.
+Proof.
+ refine (@mkTermId u32_carrier 0 _).
+ apply carrier_capacity_positive.
+Defined.
+
+Definition witness_vocabulary_fiber :
+ VocabularyFiber canonical_uleb_profile u32_carrier :=
+ mkVocabularyFiber canonical_uleb_profile u32_carrier 700 1.
+
+Definition collision_vocabulary :
+ list (VocabularyEntry canonical_uleb_profile u32_carrier) :=
+ [(collision_atom_left, symbol_zero);
+ (collision_atom_right, symbol_one)].
+
+Theorem VWENC_104_FINGERPRINT_COLLISION_REQUIRES_FULL_CANONICAL_BYTES :
+ fingerprint_candidate collision_atom_left =
+ fingerprint_candidate collision_atom_right /\
+ collision_atom_left <> collision_atom_right /\
+ lookup_atom collision_vocabulary collision_atom_left = Some symbol_zero /\
+ lookup_atom collision_vocabulary collision_atom_right = Some symbol_one.
+Proof.
+ split; [reflexivity |].
+ split.
+ - intros Hequal.
+ apply (f_equal
+ (canonical_atom_bytes canonical_uleb_profile)) in Hequal.
+ discriminate.
+ - split.
+ + unfold lookup_atom, collision_vocabulary. simpl.
+ destruct (canonical_atom_eq_dec
+ canonical_uleb_profile collision_atom_left collision_atom_left);
+ [reflexivity | contradiction].
+ + unfold lookup_atom, collision_vocabulary. simpl.
+ destruct (canonical_atom_eq_dec
+ canonical_uleb_profile collision_atom_right collision_atom_left)
+ as [Hequal | _].
+ * exfalso. apply (f_equal
+ (canonical_atom_bytes canonical_uleb_profile)) in Hequal.
+ discriminate.
+ * destruct (canonical_atom_eq_dec
+ canonical_uleb_profile collision_atom_right collision_atom_right);
+ [reflexivity | contradiction].
+Qed.
+
+Inductive InternLookupDecision
+ (I : FixedWidthCarrierProfile) : Type :=
+| InternExisting : SymbolId I -> InternLookupDecision I
+| InternMissing : InternLookupDecision I.
+
+Definition inspect_interning
+ {P : CertifiedAtomProfile} {I : FixedWidthCarrierProfile}
+ (entries : list (VocabularyEntry P I))
+ (atom : CanonicalAtom P) : InternLookupDecision I :=
+ match lookup_atom entries atom with
+ | Some id => InternExisting I id
+ | None => InternMissing I
+ end.
+
+Theorem VWENC_105_EXISTING_ATOM_INTERNING_IS_IDEMPOTENT :
+ forall (P : CertifiedAtomProfile) (I : FixedWidthCarrierProfile)
+ (entries : list (VocabularyEntry P I)) atom id,
+ lookup_atom entries atom = Some id ->
+ inspect_interning entries atom = InternExisting I id.
+Proof.
+ intros P I entries atom id Hlookup.
+ unfold inspect_interning. now rewrite Hlookup.
+Qed.
+
+(** ** Packed canonical bytes and non-overwriting reverse spans *)
+
+Record ByteSpan : Type := mkByteSpan {
+ span_offset : nat;
+ span_length : nat
+}.
+
+Definition read_span (storage : list PhysicalByte) (span : ByteSpan)
+ : list PhysicalByte :=
+ firstn (span_length span) (skipn (span_offset span) storage).
+
+Definition span_in_bounds
+ (storage : list PhysicalByte) (span : ByteSpan) : Prop :=
+ span_offset span + span_length span <= List.length storage.
+
+Definition SpanEntry (I : FixedWidthCarrierProfile) :=
+ (SymbolId I * ByteSpan)%type.
+
+Record PackedAtomStorage (I : FixedWidthCarrierProfile) : Type :=
+ mkPackedAtomStorage {
+ packed_canonical_bytes : list PhysicalByte;
+ packed_reverse_spans : list (SpanEntry I)
+ }.
+
+Definition spans_disjoint (left right : ByteSpan) : Prop :=
+ span_offset left + span_length left <= span_offset right \/
+ span_offset right + span_length right <= span_offset left.
+
+Definition span_contains_offset (span : ByteSpan) (offset : nat) : Prop :=
+ span_offset span <= offset < span_offset span + span_length span.
+
+Definition packed_spans_pairwise_disjoint
+ {I : FixedWidthCarrierProfile}
+ (storage : PackedAtomStorage I) : Prop :=
+ forall left_id left_span right_id right_span,
+ In (left_id, left_span) (packed_reverse_spans I storage) ->
+ In (right_id, right_span) (packed_reverse_spans I storage) ->
+ left_id <> right_id ->
+ spans_disjoint left_span right_span.
+
+Definition packed_spans_cover_bytes
+ {I : FixedWidthCarrierProfile}
+ (storage : PackedAtomStorage I) : Prop :=
+ forall offset,
+ offset < List.length (packed_canonical_bytes I storage) <->
+ exists id span,
+ In (id, span) (packed_reverse_spans I storage) /\
+ span_contains_offset span offset.
+
+Definition lookup_span
+ {I : FixedWidthCarrierProfile}
+ (storage : PackedAtomStorage I) (id : SymbolId I)
+ : option ByteSpan :=
+ assoc_lookup (symbol_id_eq_dec I) (packed_reverse_spans I storage) id.
+
+Definition append_packed_atom
+ {P : CertifiedAtomProfile} {I : FixedWidthCarrierProfile}
+ (storage : PackedAtomStorage I)
+ (id : SymbolId I)
+ (atom : CanonicalAtom P) : option (PackedAtomStorage I) :=
+ match lookup_span storage id with
+ | Some _ => None
+ | None =>
+ let bytes := canonical_atom_bytes P atom in
+ let offset := List.length (packed_canonical_bytes I storage) in
+ Some
+ (mkPackedAtomStorage I
+ (packed_canonical_bytes I storage ++ bytes)
+ ((id, mkByteSpan offset (List.length bytes)) ::
+ packed_reverse_spans I storage))
+ end.
+
+Lemma read_appended_suffix_exact :
+ forall prefix suffix,
+ read_span (prefix ++ suffix)
+ (mkByteSpan (List.length prefix) (List.length suffix)) = suffix.
+Proof.
+ intros prefix suffix.
+ unfold read_span. simpl.
+ rewrite skipn_app, skipn_all, Nat.sub_diag. simpl.
+ apply firstn_all.
+Qed.
+
+Lemma read_span_append_preserved :
+ forall prefix suffix span,
+ span_in_bounds prefix span ->
+ read_span (prefix ++ suffix) span = read_span prefix span.
+Proof.
+ intros prefix suffix [offset count] Hbounds.
+ unfold span_in_bounds, read_span in *. simpl in *.
+ rewrite skipn_app.
+ replace (offset - List.length prefix) with 0 by lia.
+ simpl.
+ rewrite firstn_app.
+ replace (count - List.length (skipn offset prefix)) with 0.
+ 2: rewrite skipn_length_local; lia.
+ simpl. now rewrite app_nil_r.
+Qed.
+
+Theorem VWENC_114_SAFE_PACKED_APPEND_READS_EXACT_CANONICAL_BYTES :
+ forall (P : CertifiedAtomProfile) (I : FixedWidthCarrierProfile)
+ (storage updated : PackedAtomStorage I)
+ (id : SymbolId I) (atom : CanonicalAtom P),
+ append_packed_atom storage id atom = Some updated ->
+ exists span,
+ lookup_span updated id = Some span /\
+ read_span (packed_canonical_bytes I updated) span =
+ canonical_atom_bytes P atom /\
+ span_length span = List.length (canonical_atom_bytes P atom) /\
+ span_in_bounds (packed_canonical_bytes I updated) span.
+Proof.
+ intros P I storage updated id atom Happend.
+ unfold append_packed_atom in Happend.
+ destruct (lookup_span storage id) as [occupied |] eqn:Hlookup.
+ - discriminate.
+ - inversion Happend. subst updated. clear Happend.
+ exists
+ (mkByteSpan (List.length (packed_canonical_bytes I storage))
+ (List.length (canonical_atom_bytes P atom))).
+ split.
+ + unfold lookup_span. simpl.
+ destruct (symbol_id_eq_dec I id id); [reflexivity | contradiction].
+ + split.
+ * apply read_appended_suffix_exact.
+ * split; [reflexivity |].
+ unfold span_in_bounds. simpl. rewrite app_length. lia.
+Qed.
+
+Theorem VWENC_115_SAFE_PACKED_APPEND_PRESERVES_EXISTING_SPANS :
+ forall (P : CertifiedAtomProfile) (I : FixedWidthCarrierProfile)
+ (storage updated : PackedAtomStorage I)
+ (new_id existing_id : SymbolId I) (atom : CanonicalAtom P),
+ append_packed_atom storage new_id atom = Some updated ->
+ existing_id <> new_id ->
+ lookup_span updated existing_id = lookup_span storage existing_id.
+Proof.
+ intros P I storage updated new_id existing_id atom Happend Hdifferent.
+ unfold append_packed_atom in Happend.
+ destruct (lookup_span storage new_id); [discriminate |].
+ inversion Happend. subst updated. clear Happend.
+ unfold lookup_span. simpl.
+ destruct (symbol_id_eq_dec I existing_id new_id);
+ [contradiction | reflexivity].
+Qed.
+
+(** ** Term dictionaries and the combined interning state *)
+
+Record TermDictionaryFiber
+ (P : CertifiedAtomProfile)
+ (I T : FixedWidthCarrierProfile)
+ (vocabulary_fiber : VocabularyFiber P I) : Type :=
+ mkTermDictionaryFiber {
+ term_dictionary_identity : nat;
+ term_dictionary_generation : nat
+ }.
+
+Definition term_dictionary_fiber_identity
+ {P : CertifiedAtomProfile}
+ {I T : FixedWidthCarrierProfile}
+ {vocabulary_fiber : VocabularyFiber P I}
+ (fiber : TermDictionaryFiber P I T vocabulary_fiber) :=
+ (vocabulary_fiber_identity vocabulary_fiber,
+ (carrier_format_identity T,
+ (carrier_width_bytes T,
+ (term_dictionary_identity P I T vocabulary_fiber fiber,
+ term_dictionary_generation P I T vocabulary_fiber fiber)))).
+
+Definition term_dictionary_fiber_eq_dec
+ (P : CertifiedAtomProfile)
+ (I T : FixedWidthCarrierProfile)
+ (vocabulary_fiber : VocabularyFiber P I)
+ (left right : TermDictionaryFiber P I T vocabulary_fiber)
+ : {left = right} + {left <> right}.
+Proof.
+ destruct left as [left_identity left_generation].
+ destruct right as [right_identity right_generation].
+ destruct (Nat.eq_dec left_identity right_identity)
+ as [Hidentity | Hidentity].
+ - subst right_identity.
+ destruct (Nat.eq_dec left_generation right_generation)
+ as [Hgeneration | Hgeneration].
+ + subst right_generation. left. reflexivity.
+ + right. intros Hequal. inversion Hequal. contradiction.
+ - right. intros Hequal. inversion Hequal. contradiction.
+Defined.
+
+Record FiberBoundTermId
+ (P : CertifiedAtomProfile)
+ (I T : FixedWidthCarrierProfile)
+ (vocabulary_fiber : VocabularyFiber P I) : Type :=
+ mkFiberBoundTermId {
+ bound_term_fiber : TermDictionaryFiber P I T vocabulary_fiber;
+ bound_term_value : TermId T
+ }.
+
+Definition interpret_term_id
+ {P : CertifiedAtomProfile}
+ {I T : FixedWidthCarrierProfile}
+ {vocabulary_fiber : VocabularyFiber P I}
+ (expected : TermDictionaryFiber P I T vocabulary_fiber)
+ (bound : FiberBoundTermId P I T vocabulary_fiber)
+ : option (TermId T) :=
+ if term_dictionary_fiber_eq_dec P I T vocabulary_fiber
+ expected (bound_term_fiber P I T vocabulary_fiber bound)
+ then Some (bound_term_value P I T vocabulary_fiber bound)
+ else None.
+
+Theorem VWENC_169_CROSS_TERM_FIBER_ID_INTERPRETATION_IS_REJECTED :
+ forall (P : CertifiedAtomProfile) (I T : FixedWidthCarrierProfile)
+ (vocabulary_fiber : VocabularyFiber P I)
+ (expected actual : TermDictionaryFiber P I T vocabulary_fiber)
+ (id : TermId T),
+ expected <> actual ->
+ interpret_term_id expected
+ (mkFiberBoundTermId P I T vocabulary_fiber actual id) = None.
+Proof.
+ intros P I T vocabulary_fiber expected actual id Hdifferent.
+ unfold interpret_term_id. simpl.
+ destruct (term_dictionary_fiber_eq_dec
+ P I T vocabulary_fiber expected actual) as [Hequal | _].
+ - contradiction.
+ - reflexivity.
+Qed.
+
+Theorem VWENC_170_SAME_TERM_FIBER_ID_INTERPRETATION_IS_EXACT :
+ forall (P : CertifiedAtomProfile) (I T : FixedWidthCarrierProfile)
+ (vocabulary_fiber : VocabularyFiber P I)
+ (fiber : TermDictionaryFiber P I T vocabulary_fiber)
+ (id : TermId T),
+ interpret_term_id fiber
+ (mkFiberBoundTermId P I T vocabulary_fiber fiber id) = Some id.
+Proof.
+ intros P I T vocabulary_fiber fiber id.
+ unfold interpret_term_id. simpl.
+ destruct (term_dictionary_fiber_eq_dec
+ P I T vocabulary_fiber fiber fiber) as [_ | Himpossible].
+ - reflexivity.
+ - contradiction.
+Qed.
+
+Definition symbol_sequence_eq_dec
+ (I : FixedWidthCarrierProfile)
+ : forall left right : list (SymbolId I),
+ {left = right} + {left <> right} :=
+ list_eq_dec (symbol_id_eq_dec I).
+
+Definition TermEntry
+ (I T : FixedWidthCarrierProfile) :=
+ (list (SymbolId I) * TermId T)%type.
+
+Definition reverse_term_entries
+ {I T : FixedWidthCarrierProfile}
+ (entries : list (TermEntry I T))
+ : list (TermId T * list (SymbolId I)) :=
+ map (fun entry => (snd entry, fst entry)) entries.
+
+Definition lookup_term_sequence
+ {I T : FixedWidthCarrierProfile}
+ (entries : list (TermEntry I T))
+ (sequence : list (SymbolId I)) : option (TermId T) :=
+ assoc_lookup (symbol_sequence_eq_dec I) entries sequence.
+
+Definition lookup_term_id
+ {I T : FixedWidthCarrierProfile}
+ (entries : list (TermEntry I T))
+ (id : TermId T) : option (list (SymbolId I)) :=
+ assoc_lookup (term_id_eq_dec T) (reverse_term_entries entries) id.
+
+Lemma reverse_term_membership :
+ forall (I T : FixedWidthCarrierProfile)
+ (entries : list (TermEntry I T)) sequence id,
+ In (id, sequence) (reverse_term_entries entries) <->
+ In (sequence, id) entries.
+Proof.
+ intros I T entries sequence id.
+ unfold reverse_term_entries. rewrite in_map_iff.
+ split.
+ - intros [[entry_sequence entry_id] [Hequal Hin]].
+ simpl in Hequal. inversion Hequal. subst. exact Hin.
+ - intros Hin. exists (sequence, id). split; [reflexivity | exact Hin].
+Qed.
+
+Lemma reverse_term_keys_are_term_ids :
+ forall (I T : FixedWidthCarrierProfile)
+ (entries : list (TermEntry I T)),
+ map fst (reverse_term_entries entries) = map snd entries.
+Proof.
+ intros I T entries. unfold reverse_term_entries.
+ rewrite map_map. apply map_ext. intros [sequence id]. reflexivity.
+Qed.
+
+Definition term_relation_well_formed
+ {I T : FixedWidthCarrierProfile}
+ (entries : list (TermEntry I T)) : Prop :=
+ NoDup (map fst entries) /\ NoDup (map snd entries).
+
+Definition packed_entry_exact
+ {P : CertifiedAtomProfile} {I : FixedWidthCarrierProfile}
+ (storage : PackedAtomStorage I)
+ (atom : CanonicalAtom P) (id : SymbolId I) : Prop :=
+ exists span,
+ lookup_span storage id = Some span /\
+ read_span (packed_canonical_bytes I storage) span =
+ canonical_atom_bytes P atom /\
+ span_length span = List.length (canonical_atom_bytes P atom) /\
+ 0 < span_length span /\
+ span_in_bounds (packed_canonical_bytes I storage) span.
+
+Definition packed_storage_matches_allocations
+ {P : CertifiedAtomProfile} {I : FixedWidthCarrierProfile}
+ (allocations : list (VocabularyEntry P I))
+ (storage : PackedAtomStorage I) : Prop :=
+ NoDup (map fst (packed_reverse_spans I storage)) /\
+ packed_spans_pairwise_disjoint storage /\
+ packed_spans_cover_bytes storage /\
+ (forall atom id,
+ In (atom, id) allocations ->
+ packed_entry_exact storage atom id) /\
+ (forall id span,
+ In (id, span) (packed_reverse_spans I storage) ->
+ exists atom, In (atom, id) allocations).
+
+Lemma packed_reverse_span_in_bounds :
+ forall (P : CertifiedAtomProfile) (I : FixedWidthCarrierProfile)
+ (allocations : list (VocabularyEntry P I)) storage id span,
+ packed_storage_matches_allocations allocations storage ->
+ In (id, span) (packed_reverse_spans I storage) ->
+ span_in_bounds (packed_canonical_bytes I storage) span.
+Proof.
+ intros P I allocations storage id span
+ [Hunique [_ [_ [Hexact Hcomplete]]]] Hin.
+ destruct (Hcomplete id span Hin) as [atom Hallocation].
+ destruct (Hexact atom id Hallocation)
+ as [exact_span [Hlookup [_ [_ [_ Hbounds]]]]].
+ assert (Hmember_lookup : lookup_span storage id = Some span).
+ { unfold lookup_span.
+ eapply assoc_lookup_complete_unique; eassumption. }
+ rewrite Hmember_lookup in Hlookup. inversion Hlookup.
+ exact Hbounds.
+Qed.
+
+Lemma lookup_span_none_id_absent :
+ forall (I : FixedWidthCarrierProfile)
+ (storage : PackedAtomStorage I) id,
+ lookup_span storage id = None ->
+ ~ In id (map fst (packed_reverse_spans I storage)).
+Proof.
+ intros I storage id Hnone.
+ unfold lookup_span in Hnone.
+ now apply assoc_lookup_none_key_absent in Hnone.
+Qed.
+
+Lemma packed_storage_matches_allocations_after_append :
+ forall (P : CertifiedAtomProfile) (I : FixedWidthCarrierProfile)
+ (history : list (VocabularyEntry P I))
+ (storage updated : PackedAtomStorage I)
+ (atom : CanonicalAtom P) (id : SymbolId I),
+ packed_storage_matches_allocations history storage ->
+ ~ In id (map snd history) ->
+ append_packed_atom storage id atom = Some updated ->
+ packed_storage_matches_allocations ((atom, id) :: history) updated.
+Proof.
+ intros P I history storage updated atom id Hmatches
+ Hid_absent Happend.
+ pose proof Hmatches as Hmatches_for_bounds.
+ destruct Hmatches as
+ [Hspan_unique [Hspans_disjoint
+ [Hspans_cover [Hhistory_exact Hspan_complete]]]].
+ unfold append_packed_atom in Happend.
+ destruct (lookup_span storage id) as [occupied |] eqn:Hid_span.
+ - discriminate.
+ - inversion Happend. subst updated. clear Happend.
+ split.
+ + simpl. constructor.
+ * now apply lookup_span_none_id_absent.
+ * exact Hspan_unique.
+ + split.
+ * unfold packed_spans_pairwise_disjoint in *.
+ intros left_id left_span right_id right_span
+ Hleft Hright Hdifferent.
+ simpl in Hleft, Hright.
+ destruct Hleft as [Hleft_new | Hleft_old];
+ destruct Hright as [Hright_new | Hright_old].
+ { inversion Hleft_new. inversion Hright_new. subst.
+ contradiction. }
+ { inversion Hleft_new. subst left_id left_span.
+ right.
+ pose proof
+ (packed_reverse_span_in_bounds
+ P I history storage right_id right_span
+ Hmatches_for_bounds Hright_old) as Hbounds.
+ unfold span_in_bounds in Hbounds. simpl in Hbounds |- *.
+ exact Hbounds. }
+ { inversion Hright_new. subst right_id right_span.
+ left.
+ pose proof
+ (packed_reverse_span_in_bounds
+ P I history storage left_id left_span
+ Hmatches_for_bounds Hleft_old) as Hbounds.
+ unfold span_in_bounds in Hbounds. simpl in Hbounds |- *.
+ exact Hbounds. }
+ { now apply Hspans_disjoint with (left_id := left_id)
+ (right_id := right_id). }
+ * split.
+ { unfold packed_spans_cover_bytes in *.
+ simpl. intros offset. rewrite app_length. split.
+ - intros Hbelow.
+ destruct (Nat.lt_ge_cases offset
+ (List.length (packed_canonical_bytes I storage)))
+ as [Hold | Hnew].
+ + destruct (proj1 (Hspans_cover offset) Hold)
+ as [existing_id [span [Hin Hcontains]]].
+ exists existing_id, span. split; [now right | exact Hcontains].
+ + exists id,
+ (mkByteSpan
+ (List.length (packed_canonical_bytes I storage))
+ (List.length (canonical_atom_bytes P atom))).
+ split; [now left |].
+ unfold span_contains_offset. simpl. lia.
+ - intros [existing_id [span [Hin Hcontains]]].
+ simpl in Hin. destruct Hin as [Hnew | Hold].
+ + inversion Hnew. subst existing_id span.
+ unfold span_contains_offset in Hcontains. simpl in Hcontains.
+ lia.
+ + assert (Hbelow_old :
+ offset < List.length (packed_canonical_bytes I storage)).
+ { apply (proj2 (Hspans_cover offset)).
+ exists existing_id, span. now split. }
+ lia. }
+ { split.
+ - intros existing_atom existing_id Hin.
+ simpl in Hin. destruct Hin as [Hnew | Hold].
+ { inversion Hnew. subst existing_atom existing_id.
+ exists
+ (mkByteSpan
+ (List.length (packed_canonical_bytes I storage))
+ (List.length (canonical_atom_bytes P atom))).
+ split.
+ - unfold lookup_span. simpl.
+ destruct (symbol_id_eq_dec I id id);
+ [reflexivity | contradiction].
+ - split.
+ + apply read_appended_suffix_exact.
+ + split; [reflexivity |].
+ split.
+ * pose proof
+ (atom_codeword_nonempty P
+ (canonical_atom_bytes P atom)
+ (canonical_atom_valid P atom)) as Hnonempty.
+ destruct (canonical_atom_bytes P atom);
+ simpl; [contradiction | lia].
+ * unfold span_in_bounds. simpl. rewrite app_length. lia. }
+ { specialize (Hhistory_exact existing_atom existing_id Hold).
+ destruct Hhistory_exact as
+ [span [Hlookup [Hread [Hlength [Hpositive Hbounds]]]]].
+ assert (Hdifferent : existing_id <> id).
+ { intros Hequal. subst existing_id. apply Hid_absent.
+ apply in_map with (f := snd) in Hold. exact Hold. }
+ exists span. split.
+ - unfold lookup_span. simpl.
+ destruct (symbol_id_eq_dec I existing_id id);
+ [contradiction | exact Hlookup].
+ - split.
+ + simpl.
+ rewrite read_span_append_preserved by exact Hbounds.
+ exact Hread.
+ + split; [exact Hlength |].
+ split; [exact Hpositive |].
+ unfold span_in_bounds in Hbounds |- *. simpl.
+ rewrite app_length. lia. }
+ - intros existing_id span Hin.
+ simpl in Hin. destruct Hin as [Hnew | Hold].
+ { inversion Hnew. subst existing_id span.
+ exists atom. now left. }
+ { destruct (Hspan_complete existing_id span Hold)
+ as [existing_atom Hhistory].
+ exists existing_atom. now right. } }
+Qed.
+
+Lemma packed_storage_matches_allocations_permutation :
+ forall (P : CertifiedAtomProfile) (I : FixedWidthCarrierProfile)
+ (left right : list (VocabularyEntry P I)) storage,
+ Permutation left right ->
+ packed_storage_matches_allocations left storage ->
+ packed_storage_matches_allocations right storage.
+Proof.
+ intros P I left right storage Hpermutation
+ [Hspan_unique [Hdisjoint [Hcover [Hexact Hcomplete]]]].
+ split; [exact Hspan_unique |].
+ split; [exact Hdisjoint |].
+ split; [exact Hcover |].
+ split.
+ - intros atom id Hin.
+ apply Hexact.
+ eapply Permutation_in.
+ + exact (Permutation_sym Hpermutation).
+ + exact Hin.
+ - intros id span Hin.
+ destruct (Hcomplete id span Hin) as [atom Hleft].
+ exists atom.
+ eapply Permutation_in.
+ + exact Hpermutation.
+ + exact Hleft.
+Qed.
+
+Definition live_symbol
+ {P : CertifiedAtomProfile} {I : FixedWidthCarrierProfile}
+ (live : list (VocabularyEntry P I)) (id : SymbolId I) : Prop :=
+ exists atom, In (atom, id) live.
+
+Definition sequence_vocabulary_bound
+ {P : CertifiedAtomProfile} {I : FixedWidthCarrierProfile}
+ (live : list (VocabularyEntry P I))
+ (frontier : nat) (sequence : list (SymbolId I)) : Prop :=
+ Forall
+ (fun id =>
+ symbol_id_value I id < frontier /\ live_symbol live id)
+ sequence.
+
+Record InterningState
+ (P : CertifiedAtomProfile)
+ (I T : FixedWidthCarrierProfile) : Type :=
+ mkInterningState {
+ state_fiber : VocabularyFiber P I;
+ state_term_fiber : TermDictionaryFiber P I T state_fiber;
+ state_reserved_entries : list (VocabularyEntry P I);
+ state_claimed_entries : list (VocabularyEntry P I);
+ state_live_entries : list (VocabularyEntry P I);
+ state_ever_entries : list (VocabularyEntry P I);
+ state_orphan_entries : list (VocabularyEntry P I);
+ state_unmaterialized_orphan_entries : list (VocabularyEntry P I);
+ state_packed_storage : PackedAtomStorage I;
+ state_allocator_frontier : nat;
+ state_sequences : list (list (SymbolId I));
+ state_term_dictionary_enabled : bool;
+ state_term_entries : list (TermEntry I T)
+ }.
+
+Definition lookup_state_term_sequence
+ {P : CertifiedAtomProfile}
+ {I T : FixedWidthCarrierProfile}
+ (state : InterningState P I T)
+ (sequence : list (SymbolId I))
+ : option
+ (FiberBoundTermId
+ P I T (state_fiber P I T state)) :=
+ if state_term_dictionary_enabled P I T state then
+ match lookup_term_sequence
+ (state_term_entries P I T state) sequence with
+ | Some id =>
+ Some
+ (mkFiberBoundTermId
+ P I T (state_fiber P I T state)
+ (state_term_fiber P I T state) id)
+ | None => None
+ end
+ else None.
+
+Theorem VWENC_171_TERM_LOOKUP_RETURNS_EXACT_FIBER_BOUND_ID :
+ forall (P : CertifiedAtomProfile) (I T : FixedWidthCarrierProfile)
+ (state : InterningState P I T) sequence id,
+ state_term_dictionary_enabled P I T state = true ->
+ lookup_term_sequence
+ (state_term_entries P I T state) sequence = Some id ->
+ lookup_state_term_sequence state sequence =
+ Some
+ (mkFiberBoundTermId
+ P I T (state_fiber P I T state)
+ (state_term_fiber P I T state) id) /\
+ interpret_term_id
+ (state_term_fiber P I T state)
+ (mkFiberBoundTermId
+ P I T (state_fiber P I T state)
+ (state_term_fiber P I T state) id) = Some id.
+Proof.
+ intros P I T state sequence id Henabled Hlookup.
+ unfold lookup_state_term_sequence. rewrite Henabled, Hlookup.
+ split; [reflexivity |].
+ apply VWENC_170_SAME_TERM_FIBER_ID_INTERPRETATION_IS_EXACT.
+Qed.
+
+Definition state_allocation_entries
+ {P : CertifiedAtomProfile}
+ {I T : FixedWidthCarrierProfile}
+ (state : InterningState P I T) : list (VocabularyEntry P I) :=
+ state_ever_entries P I T state ++
+ state_reserved_entries P I T state ++
+ state_claimed_entries P I T state ++
+ state_orphan_entries P I T state ++
+ state_unmaterialized_orphan_entries P I T state.
+
+Definition state_materialized_entries
+ {P : CertifiedAtomProfile}
+ {I T : FixedWidthCarrierProfile}
+ (state : InterningState P I T) : list (VocabularyEntry P I) :=
+ state_ever_entries P I T state ++
+ state_claimed_entries P I T state ++
+ state_orphan_entries P I T state.
+
+Definition state_orphan_ids
+ {P : CertifiedAtomProfile}
+ {I T : FixedWidthCarrierProfile}
+ (state : InterningState P I T) : list (SymbolId I) :=
+ map snd
+ (state_orphan_entries P I T state ++
+ state_unmaterialized_orphan_entries P I T state).
+
+Inductive AllocationStatus :=
+| AllocationReserved
+| AllocationMaterializedClaimed
+| AllocationPublished
+| AllocationTombstoned
+| AllocationMaterializedOrphaned
+| AllocationUnmaterializedOrphaned.
+
+Definition vocabulary_entry_eq_dec
+ (P : CertifiedAtomProfile) (I : FixedWidthCarrierProfile)
+ : forall left right : VocabularyEntry P I,
+ {left = right} + {left <> right}.
+Proof.
+ intros [left_atom left_id] [right_atom right_id].
+ destruct (canonical_atom_eq_dec P left_atom right_atom)
+ as [Hatom | Hatom].
+ - subst right_atom.
+ destruct (symbol_id_eq_dec I left_id right_id) as [Hid | Hid].
+ + subst right_id. left. reflexivity.
+ + right. intros Hequal. inversion Hequal. contradiction.
+ - right. intros Hequal. inversion Hequal. contradiction.
+Defined.
+
+Definition allocation_status_of
+ {P : CertifiedAtomProfile}
+ {I T : FixedWidthCarrierProfile}
+ (state : InterningState P I T)
+ (atom : CanonicalAtom P)
+ (id : SymbolId I) : option AllocationStatus :=
+ let entry := (atom, id) in
+ if in_dec (vocabulary_entry_eq_dec P I) entry
+ (state_reserved_entries P I T state)
+ then Some AllocationReserved
+ else if in_dec (vocabulary_entry_eq_dec P I) entry
+ (state_claimed_entries P I T state)
+ then Some AllocationMaterializedClaimed
+ else if in_dec (vocabulary_entry_eq_dec P I) entry
+ (state_orphan_entries P I T state)
+ then Some AllocationMaterializedOrphaned
+ else if in_dec (vocabulary_entry_eq_dec P I) entry
+ (state_unmaterialized_orphan_entries P I T state)
+ then Some AllocationUnmaterializedOrphaned
+ else if in_dec (vocabulary_entry_eq_dec P I) entry
+ (state_ever_entries P I T state)
+ then
+ if in_dec (vocabulary_entry_eq_dec P I) entry
+ (state_live_entries P I T state)
+ then Some AllocationPublished
+ else Some AllocationTombstoned
+ else None.
+
+Definition allocation_has_status
+ {P : CertifiedAtomProfile}
+ {I T : FixedWidthCarrierProfile}
+ (state : InterningState P I T)
+ (atom : CanonicalAtom P)
+ (id : SymbolId I)
+ (status : AllocationStatus) : Prop :=
+ allocation_status_of state atom id = Some status.
+
+Definition allocation_status_category
+ {P : CertifiedAtomProfile}
+ {I T : FixedWidthCarrierProfile}
+ (state : InterningState P I T)
+ (atom : CanonicalAtom P)
+ (id : SymbolId I)
+ (status : AllocationStatus) : Prop :=
+ match status with
+ | AllocationReserved =>
+ In (atom, id) (state_reserved_entries P I T state)
+ | AllocationMaterializedClaimed =>
+ In (atom, id) (state_claimed_entries P I T state)
+ | AllocationPublished =>
+ In (atom, id) (state_live_entries P I T state) /\
+ In (atom, id) (state_ever_entries P I T state)
+ | AllocationTombstoned =>
+ In (atom, id) (state_ever_entries P I T state) /\
+ ~ In (atom, id) (state_live_entries P I T state)
+ | AllocationMaterializedOrphaned =>
+ In (atom, id) (state_orphan_entries P I T state)
+ | AllocationUnmaterializedOrphaned =>
+ In (atom, id)
+ (state_unmaterialized_orphan_entries P I T state)
+ end.
+
+Lemma allocation_status_reserved_from_membership :
+ forall (P : CertifiedAtomProfile) (I T : FixedWidthCarrierProfile)
+ (state : InterningState P I T) atom id,
+ In (atom, id) (state_reserved_entries P I T state) ->
+ allocation_has_status state atom id AllocationReserved.
+Proof.
+ intros P I T state atom id Hin.
+ unfold allocation_has_status, allocation_status_of.
+ destruct (in_dec (vocabulary_entry_eq_dec P I) (atom, id)
+ (state_reserved_entries P I T state)); [reflexivity | contradiction].
+Qed.
+
+Lemma allocation_status_materialized_claimed_from_membership :
+ forall (P : CertifiedAtomProfile) (I T : FixedWidthCarrierProfile)
+ (state : InterningState P I T) atom id,
+ ~ In (atom, id) (state_reserved_entries P I T state) ->
+ In (atom, id) (state_claimed_entries P I T state) ->
+ allocation_has_status state atom id AllocationMaterializedClaimed.
+Proof.
+ intros P I T state atom id Hreserved Hclaimed.
+ unfold allocation_has_status, allocation_status_of.
+ destruct (in_dec (vocabulary_entry_eq_dec P I) (atom, id)
+ (state_reserved_entries P I T state)); [contradiction |].
+ destruct (in_dec (vocabulary_entry_eq_dec P I) (atom, id)
+ (state_claimed_entries P I T state)); [reflexivity | contradiction].
+Qed.
+
+Lemma allocation_status_materialized_orphan_from_membership :
+ forall (P : CertifiedAtomProfile) (I T : FixedWidthCarrierProfile)
+ (state : InterningState P I T) atom id,
+ ~ In (atom, id) (state_reserved_entries P I T state) ->
+ ~ In (atom, id) (state_claimed_entries P I T state) ->
+ In (atom, id) (state_orphan_entries P I T state) ->
+ allocation_has_status state atom id AllocationMaterializedOrphaned.
+Proof.
+ intros P I T state atom id Hreserved Hclaimed Horphan.
+ unfold allocation_has_status, allocation_status_of.
+ destruct (in_dec (vocabulary_entry_eq_dec P I) (atom, id)
+ (state_reserved_entries P I T state)); [contradiction |].
+ destruct (in_dec (vocabulary_entry_eq_dec P I) (atom, id)
+ (state_claimed_entries P I T state)); [contradiction |].
+ destruct (in_dec (vocabulary_entry_eq_dec P I) (atom, id)
+ (state_orphan_entries P I T state)); [reflexivity | contradiction].
+Qed.
+
+Lemma allocation_status_unmaterialized_orphan_from_membership :
+ forall (P : CertifiedAtomProfile) (I T : FixedWidthCarrierProfile)
+ (state : InterningState P I T) atom id,
+ ~ In (atom, id) (state_reserved_entries P I T state) ->
+ ~ In (atom, id) (state_claimed_entries P I T state) ->
+ ~ In (atom, id) (state_orphan_entries P I T state) ->
+ In (atom, id)
+ (state_unmaterialized_orphan_entries P I T state) ->
+ allocation_has_status state atom id AllocationUnmaterializedOrphaned.
+Proof.
+ intros P I T state atom id Hreserved Hclaimed Horphan Hunmaterialized.
+ unfold allocation_has_status, allocation_status_of.
+ destruct (in_dec (vocabulary_entry_eq_dec P I) (atom, id)
+ (state_reserved_entries P I T state)); [contradiction |].
+ destruct (in_dec (vocabulary_entry_eq_dec P I) (atom, id)
+ (state_claimed_entries P I T state)); [contradiction |].
+ destruct (in_dec (vocabulary_entry_eq_dec P I) (atom, id)
+ (state_orphan_entries P I T state)); [contradiction |].
+ destruct (in_dec (vocabulary_entry_eq_dec P I) (atom, id)
+ (state_unmaterialized_orphan_entries P I T state));
+ [reflexivity | contradiction].
+Qed.
+
+Lemma allocation_status_published_from_membership :
+ forall (P : CertifiedAtomProfile) (I T : FixedWidthCarrierProfile)
+ (state : InterningState P I T) atom id,
+ ~ In (atom, id) (state_reserved_entries P I T state) ->
+ ~ In (atom, id) (state_claimed_entries P I T state) ->
+ ~ In (atom, id) (state_orphan_entries P I T state) ->
+ ~ In (atom, id)
+ (state_unmaterialized_orphan_entries P I T state) ->
+ In (atom, id) (state_ever_entries P I T state) ->
+ In (atom, id) (state_live_entries P I T state) ->
+ allocation_has_status state atom id AllocationPublished.
+Proof.
+ intros P I T state atom id
+ Hreserved Hclaimed Horphan Hunmaterialized Hever Hlive.
+ unfold allocation_has_status, allocation_status_of.
+ destruct (in_dec (vocabulary_entry_eq_dec P I) (atom, id)
+ (state_reserved_entries P I T state)); [contradiction |].
+ destruct (in_dec (vocabulary_entry_eq_dec P I) (atom, id)
+ (state_claimed_entries P I T state)); [contradiction |].
+ destruct (in_dec (vocabulary_entry_eq_dec P I) (atom, id)
+ (state_orphan_entries P I T state)); [contradiction |].
+ destruct (in_dec (vocabulary_entry_eq_dec P I) (atom, id)
+ (state_unmaterialized_orphan_entries P I T state));
+ [contradiction |].
+ destruct (in_dec (vocabulary_entry_eq_dec P I) (atom, id)
+ (state_ever_entries P I T state)); [| contradiction].
+ destruct (in_dec (vocabulary_entry_eq_dec P I) (atom, id)
+ (state_live_entries P I T state)); [reflexivity | contradiction].
+Qed.
+
+Lemma allocation_status_tombstoned_from_membership :
+ forall (P : CertifiedAtomProfile) (I T : FixedWidthCarrierProfile)
+ (state : InterningState P I T) atom id,
+ ~ In (atom, id) (state_reserved_entries P I T state) ->
+ ~ In (atom, id) (state_claimed_entries P I T state) ->
+ ~ In (atom, id) (state_orphan_entries P I T state) ->
+ ~ In (atom, id)
+ (state_unmaterialized_orphan_entries P I T state) ->
+ In (atom, id) (state_ever_entries P I T state) ->
+ ~ In (atom, id) (state_live_entries P I T state) ->
+ allocation_has_status state atom id AllocationTombstoned.
+Proof.
+ intros P I T state atom id
+ Hreserved Hclaimed Horphan Hunmaterialized Hever Hlive.
+ unfold allocation_has_status, allocation_status_of.
+ destruct (in_dec (vocabulary_entry_eq_dec P I) (atom, id)
+ (state_reserved_entries P I T state)); [contradiction |].
+ destruct (in_dec (vocabulary_entry_eq_dec P I) (atom, id)
+ (state_claimed_entries P I T state)); [contradiction |].
+ destruct (in_dec (vocabulary_entry_eq_dec P I) (atom, id)
+ (state_orphan_entries P I T state)); [contradiction |].
+ destruct (in_dec (vocabulary_entry_eq_dec P I) (atom, id)
+ (state_unmaterialized_orphan_entries P I T state));
+ [contradiction |].
+ destruct (in_dec (vocabulary_entry_eq_dec P I) (atom, id)
+ (state_ever_entries P I T state)); [| contradiction].
+ destruct (in_dec (vocabulary_entry_eq_dec P I) (atom, id)
+ (state_live_entries P I T state)); [contradiction | reflexivity].
+Qed.
+
+Theorem VWENC_161_ALLOCATION_STATUS_IS_FUNCTIONALLY_UNIQUE :
+ forall (P : CertifiedAtomProfile) (I T : FixedWidthCarrierProfile)
+ (state : InterningState P I T) atom id left right,
+ allocation_has_status state atom id left ->
+ allocation_has_status state atom id right ->
+ left = right.
+Proof.
+ intros P I T state atom id left right Hleft Hright.
+ unfold allocation_has_status in *. rewrite Hleft in Hright.
+ now inversion Hright.
+Qed.
+
+Lemma allocated_entry_has_computed_status :
+ forall (P : CertifiedAtomProfile) (I T : FixedWidthCarrierProfile)
+ (state : InterningState P I T) atom id,
+ In (atom, id) (state_allocation_entries state) ->
+ exists status, allocation_has_status state atom id status.
+Proof.
+ intros P I T state atom id Hallocated.
+ unfold allocation_has_status, allocation_status_of.
+ destruct (in_dec (vocabulary_entry_eq_dec P I) (atom, id)
+ (state_reserved_entries P I T state)) as [Hreserved | Hreserved].
+ - now exists AllocationReserved.
+ - destruct (in_dec (vocabulary_entry_eq_dec P I) (atom, id)
+ (state_claimed_entries P I T state)) as [Hclaimed | Hclaimed].
+ + now exists AllocationMaterializedClaimed.
+ + destruct (in_dec (vocabulary_entry_eq_dec P I) (atom, id)
+ (state_orphan_entries P I T state)) as [Horphan | Horphan].
+ * now exists AllocationMaterializedOrphaned.
+ * destruct (in_dec (vocabulary_entry_eq_dec P I) (atom, id)
+ (state_unmaterialized_orphan_entries P I T state))
+ as [Hunmaterialized | Hunmaterialized].
+ { now exists AllocationUnmaterializedOrphaned. }
+ { destruct (in_dec (vocabulary_entry_eq_dec P I) (atom, id)
+ (state_ever_entries P I T state)) as [Hever | Hever].
+ - destruct (in_dec (vocabulary_entry_eq_dec P I) (atom, id)
+ (state_live_entries P I T state)) as [Hlive | Hlive].
+ + now exists AllocationPublished.
+ + now exists AllocationTombstoned.
+ - exfalso. unfold state_allocation_entries in Hallocated.
+ repeat rewrite in_app_iff in Hallocated.
+ tauto. }
+Qed.
+
+Lemma allocation_status_reports_observable_membership :
+ forall (P : CertifiedAtomProfile) (I T : FixedWidthCarrierProfile)
+ (state : InterningState P I T) atom id status,
+ allocation_has_status state atom id status ->
+ match status with
+ | AllocationReserved =>
+ In (atom, id) (state_reserved_entries P I T state)
+ | AllocationMaterializedClaimed =>
+ In (atom, id) (state_claimed_entries P I T state)
+ | AllocationPublished =>
+ In (atom, id) (state_live_entries P I T state)
+ | AllocationTombstoned =>
+ In (atom, id) (state_ever_entries P I T state) /\
+ ~ In (atom, id) (state_live_entries P I T state)
+ | AllocationMaterializedOrphaned =>
+ In (atom, id) (state_orphan_entries P I T state)
+ | AllocationUnmaterializedOrphaned =>
+ In (atom, id)
+ (state_unmaterialized_orphan_entries P I T state)
+ end.
+Proof.
+ intros P I T state atom id status Hstatus.
+ unfold allocation_has_status, allocation_status_of in Hstatus.
+ destruct (in_dec (vocabulary_entry_eq_dec P I) (atom, id)
+ (state_reserved_entries P I T state)) as [Hreserved | Hreserved].
+ - inversion Hstatus. exact Hreserved.
+ - destruct (in_dec (vocabulary_entry_eq_dec P I) (atom, id)
+ (state_claimed_entries P I T state)) as [Hclaimed | Hclaimed].
+ + inversion Hstatus. exact Hclaimed.
+ + destruct (in_dec (vocabulary_entry_eq_dec P I) (atom, id)
+ (state_orphan_entries P I T state)) as [Horphan | Horphan].
+ * inversion Hstatus. exact Horphan.
+ * destruct (in_dec (vocabulary_entry_eq_dec P I) (atom, id)
+ (state_unmaterialized_orphan_entries P I T state))
+ as [Hunmaterialized | Hunmaterialized].
+ { inversion Hstatus. exact Hunmaterialized. }
+ { destruct (in_dec (vocabulary_entry_eq_dec P I) (atom, id)
+ (state_ever_entries P I T state)) as [Hever | Hever].
+ - destruct (in_dec (vocabulary_entry_eq_dec P I) (atom, id)
+ (state_live_entries P I T state)) as [Hlive | Hlive].
+ + inversion Hstatus. exact Hlive.
+ + inversion Hstatus. now split.
+ - discriminate. }
+Qed.
+
+Record InterningStateWellFormed
+ {P : CertifiedAtomProfile}
+ {I T : FixedWidthCarrierProfile}
+ (state : InterningState P I T) : Prop :=
+ mkInterningStateWellFormed {
+ state_live_bijection :
+ vocabulary_relation_well_formed (state_live_entries P I T state);
+ state_history_bijection :
+ vocabulary_relation_well_formed (state_ever_entries P I T state);
+ state_live_is_historical :
+ forall atom id,
+ In (atom, id) (state_live_entries P I T state) ->
+ In (atom, id) (state_ever_entries P I T state);
+ state_allocation_ids_unique :
+ NoDup (map snd (state_allocation_entries state));
+ state_packed_allocations_exact :
+ packed_storage_matches_allocations
+ (state_materialized_entries state)
+ (state_packed_storage P I T state);
+ state_allocations_below_sparse_frontier :
+ Forall
+ (fun entry =>
+ symbol_id_value I (snd entry) <
+ state_allocator_frontier P I T state)
+ (state_allocation_entries state);
+ state_frontier_representable :
+ state_allocator_frontier P I T state <= carrier_capacity I;
+ state_all_sequences_bound :
+ Forall
+ (sequence_vocabulary_bound
+ (state_live_entries P I T state)
+ (state_allocator_frontier P I T state))
+ (state_sequences P I T state);
+ state_term_relation_bijection :
+ term_relation_well_formed (state_term_entries P I T state);
+ state_term_sequences_bound :
+ Forall
+ (fun entry =>
+ sequence_vocabulary_bound
+ (state_live_entries P I T state)
+ (state_allocator_frontier P I T state)
+ (fst entry))
+ (state_term_entries P I T state);
+ state_disabled_term_dictionary_is_empty :
+ state_term_dictionary_enabled P I T state = false ->
+ state_term_entries P I T state = []
+ }.
+
+Lemma NoDup_in_separated_segments :
+ forall (Element : Type)
+ (prefix left middle right suffix : list Element) element,
+ NoDup (prefix ++ left ++ middle ++ right ++ suffix) ->
+ In element left ->
+ In element right ->
+ False.
+Proof.
+ intros Element prefix left middle right suffix element
+ Hunique Hleft Hright.
+ destruct (in_split element left Hleft)
+ as [before [after Hsplit]].
+ subst left.
+ assert (Hshape :
+ prefix ++ (before ++ element :: after) ++ middle ++ right ++ suffix =
+ (prefix ++ before) ++
+ element :: (after ++ middle ++ right ++ suffix)).
+ { repeat rewrite <- app_assoc. reflexivity. }
+ rewrite Hshape in Hunique.
+ pose proof
+ (NoDup_remove_2
+ (prefix ++ before)
+ (after ++ middle ++ right ++ suffix)
+ element Hunique) as Hnot_in_remainder.
+ apply Hnot_in_remainder.
+ apply in_or_app. right.
+ apply in_or_app. right.
+ apply in_or_app. right.
+ apply in_or_app. left. exact Hright.
+Qed.
+
+Inductive AllocationBucket :=
+| BucketHistorical
+| BucketReserved
+| BucketMaterializedClaimed
+| BucketMaterializedOrphaned
+| BucketUnmaterializedOrphaned.
+
+Definition allocation_bucket_entries
+ {P : CertifiedAtomProfile}
+ {I T : FixedWidthCarrierProfile}
+ (state : InterningState P I T)
+ (bucket : AllocationBucket) : list (VocabularyEntry P I) :=
+ match bucket with
+ | BucketHistorical => state_ever_entries P I T state
+ | BucketReserved => state_reserved_entries P I T state
+ | BucketMaterializedClaimed => state_claimed_entries P I T state
+ | BucketMaterializedOrphaned => state_orphan_entries P I T state
+ | BucketUnmaterializedOrphaned =>
+ state_unmaterialized_orphan_entries P I T state
+ end.
+
+Inductive AllocationBucketPrecedes :
+ AllocationBucket -> AllocationBucket -> Prop :=
+| HistoricalBeforeReserved :
+ AllocationBucketPrecedes BucketHistorical BucketReserved
+| HistoricalBeforeClaimed :
+ AllocationBucketPrecedes BucketHistorical BucketMaterializedClaimed
+| HistoricalBeforeMaterializedOrphan :
+ AllocationBucketPrecedes BucketHistorical BucketMaterializedOrphaned
+| HistoricalBeforeUnmaterializedOrphan :
+ AllocationBucketPrecedes BucketHistorical BucketUnmaterializedOrphaned
+| ReservedBeforeClaimed :
+ AllocationBucketPrecedes BucketReserved BucketMaterializedClaimed
+| ReservedBeforeMaterializedOrphan :
+ AllocationBucketPrecedes BucketReserved BucketMaterializedOrphaned
+| ReservedBeforeUnmaterializedOrphan :
+ AllocationBucketPrecedes BucketReserved BucketUnmaterializedOrphaned
+| ClaimedBeforeMaterializedOrphan :
+ AllocationBucketPrecedes
+ BucketMaterializedClaimed BucketMaterializedOrphaned
+| ClaimedBeforeUnmaterializedOrphan :
+ AllocationBucketPrecedes
+ BucketMaterializedClaimed BucketUnmaterializedOrphaned
+| MaterializedOrphanBeforeUnmaterializedOrphan :
+ AllocationBucketPrecedes
+ BucketMaterializedOrphaned BucketUnmaterializedOrphaned.
+
+Lemma allocation_bucket_precedence_makes_ids_disjoint :
+ forall (P : CertifiedAtomProfile) (I T : FixedWidthCarrierProfile)
+ (state : InterningState P I T) left right left_atom right_atom id,
+ InterningStateWellFormed state ->
+ AllocationBucketPrecedes left right ->
+ In (left_atom, id) (allocation_bucket_entries state left) ->
+ In (right_atom, id) (allocation_bucket_entries state right) ->
+ False.
+Proof.
+ intros P I T state left right left_atom right_atom id
+ Hwell Hprecedes Hleft Hright.
+ destruct Hwell as [_ _ _ Hunique].
+ unfold state_allocation_entries in Hunique.
+ repeat rewrite map_app in Hunique.
+ repeat rewrite <- app_assoc in Hunique.
+ assert (Hleft_id :
+ In id (map snd (allocation_bucket_entries state left))).
+ { now apply in_map with (f := snd) in Hleft. }
+ assert (Hright_id :
+ In id (map snd (allocation_bucket_entries state right))).
+ { now apply in_map with (f := snd) in Hright. }
+ destruct Hprecedes; simpl in Hleft_id, Hright_id.
+ - eapply NoDup_in_separated_segments
+ with
+ (prefix := [])
+ (left := map snd (state_ever_entries P I T state))
+ (middle := [])
+ (right := map snd (state_reserved_entries P I T state))
+ (suffix :=
+ map snd (state_claimed_entries P I T state) ++
+ map snd (state_orphan_entries P I T state) ++
+ map snd (state_unmaterialized_orphan_entries P I T state))
+ (element := id); simpl; repeat rewrite <- app_assoc; simpl;
+ try rewrite app_nil_r; eauto.
+ - eapply NoDup_in_separated_segments
+ with
+ (prefix := [])
+ (left := map snd (state_ever_entries P I T state))
+ (middle := map snd (state_reserved_entries P I T state))
+ (right := map snd (state_claimed_entries P I T state))
+ (suffix :=
+ map snd (state_orphan_entries P I T state) ++
+ map snd (state_unmaterialized_orphan_entries P I T state))
+ (element := id); simpl; repeat rewrite <- app_assoc; simpl;
+ try rewrite app_nil_r; eauto.
+ - eapply NoDup_in_separated_segments
+ with
+ (prefix := [])
+ (left := map snd (state_ever_entries P I T state))
+ (middle :=
+ map snd (state_reserved_entries P I T state) ++
+ map snd (state_claimed_entries P I T state))
+ (right := map snd (state_orphan_entries P I T state))
+ (suffix :=
+ map snd (state_unmaterialized_orphan_entries P I T state))
+ (element := id); simpl; repeat rewrite <- app_assoc; simpl;
+ try rewrite app_nil_r; eauto.
+ - eapply NoDup_in_separated_segments
+ with
+ (prefix := [])
+ (left := map snd (state_ever_entries P I T state))
+ (middle :=
+ map snd (state_reserved_entries P I T state) ++
+ map snd (state_claimed_entries P I T state) ++
+ map snd (state_orphan_entries P I T state))
+ (right :=
+ map snd (state_unmaterialized_orphan_entries P I T state))
+ (suffix := [])
+ (element := id); simpl; repeat rewrite <- app_assoc; simpl;
+ try rewrite app_nil_r; eauto.
+ - eapply NoDup_in_separated_segments
+ with
+ (prefix := map snd (state_ever_entries P I T state))
+ (left := map snd (state_reserved_entries P I T state))
+ (middle := [])
+ (right := map snd (state_claimed_entries P I T state))
+ (suffix :=
+ map snd (state_orphan_entries P I T state) ++
+ map snd (state_unmaterialized_orphan_entries P I T state))
+ (element := id); simpl; repeat rewrite <- app_assoc; simpl;
+ try rewrite app_nil_r; eauto.
+ - eapply NoDup_in_separated_segments
+ with
+ (prefix := map snd (state_ever_entries P I T state))
+ (left := map snd (state_reserved_entries P I T state))
+ (middle := map snd (state_claimed_entries P I T state))
+ (right := map snd (state_orphan_entries P I T state))
+ (suffix :=
+ map snd (state_unmaterialized_orphan_entries P I T state))
+ (element := id); simpl; repeat rewrite <- app_assoc; simpl;
+ try rewrite app_nil_r; eauto.
+ - eapply NoDup_in_separated_segments
+ with
+ (prefix := map snd (state_ever_entries P I T state))
+ (left := map snd (state_reserved_entries P I T state))
+ (middle :=
+ map snd (state_claimed_entries P I T state) ++
+ map snd (state_orphan_entries P I T state))
+ (right :=
+ map snd (state_unmaterialized_orphan_entries P I T state))
+ (suffix := [])
+ (element := id); simpl; repeat rewrite <- app_assoc; simpl;
+ try rewrite app_nil_r; eauto.
+ - eapply NoDup_in_separated_segments
+ with
+ (prefix :=
+ map snd (state_ever_entries P I T state) ++
+ map snd (state_reserved_entries P I T state))
+ (left := map snd (state_claimed_entries P I T state))
+ (middle := [])
+ (right := map snd (state_orphan_entries P I T state))
+ (suffix :=
+ map snd (state_unmaterialized_orphan_entries P I T state))
+ (element := id); simpl; repeat rewrite <- app_assoc; simpl;
+ try rewrite app_nil_r; eauto.
+ - eapply NoDup_in_separated_segments
+ with
+ (prefix :=
+ map snd (state_ever_entries P I T state) ++
+ map snd (state_reserved_entries P I T state))
+ (left := map snd (state_claimed_entries P I T state))
+ (middle := map snd (state_orphan_entries P I T state))
+ (right :=
+ map snd (state_unmaterialized_orphan_entries P I T state))
+ (suffix := [])
+ (element := id); simpl; repeat rewrite <- app_assoc; simpl;
+ try rewrite app_nil_r; eauto.
+ - eapply NoDup_in_separated_segments
+ with
+ (prefix :=
+ map snd (state_ever_entries P I T state) ++
+ map snd (state_reserved_entries P I T state) ++
+ map snd (state_claimed_entries P I T state))
+ (left := map snd (state_orphan_entries P I T state))
+ (middle := [])
+ (right :=
+ map snd (state_unmaterialized_orphan_entries P I T state))
+ (suffix := [])
+ (element := id); simpl; repeat rewrite <- app_assoc; simpl;
+ try rewrite app_nil_r; eauto.
+Qed.
+
+Theorem VWENC_163_ALLOCATION_STATUS_REPORTS_ITS_EXACT_STATE_CATEGORY :
+ forall (P : CertifiedAtomProfile) (I T : FixedWidthCarrierProfile)
+ (state : InterningState P I T) atom id status,
+ InterningStateWellFormed state ->
+ (allocation_has_status state atom id status <->
+ allocation_status_category state atom id status).
+Proof.
+ intros P I T state atom id status Hwell.
+ split.
+ - intros Hstatus.
+ pose proof (allocation_status_reports_observable_membership
+ P I T state atom id status Hstatus) as Hmembership.
+ destruct status; simpl in *; try exact Hmembership.
+ split; [exact Hmembership |].
+ now apply (state_live_is_historical state Hwell).
+ - intros Hcategory.
+ assert (Hdisjoint := allocation_bucket_precedence_makes_ids_disjoint
+ P I T state).
+ destruct status; simpl in Hcategory.
+ + now apply allocation_status_reserved_from_membership.
+ + apply allocation_status_materialized_claimed_from_membership.
+ * intros Hreserved.
+ eapply Hdisjoint with
+ (left := BucketReserved)
+ (right := BucketMaterializedClaimed); eauto using ReservedBeforeClaimed.
+ * exact Hcategory.
+ + destruct Hcategory as [Hlive Hever].
+ apply allocation_status_published_from_membership; try assumption.
+ * intros Hreserved.
+ eapply Hdisjoint with
+ (left := BucketHistorical) (right := BucketReserved);
+ eauto using HistoricalBeforeReserved.
+ * intros Hclaimed.
+ eapply Hdisjoint with
+ (left := BucketHistorical) (right := BucketMaterializedClaimed);
+ eauto using HistoricalBeforeClaimed.
+ * intros Horphan.
+ eapply Hdisjoint with
+ (left := BucketHistorical) (right := BucketMaterializedOrphaned);
+ eauto using HistoricalBeforeMaterializedOrphan.
+ * intros Hunmaterialized.
+ eapply Hdisjoint with
+ (left := BucketHistorical)
+ (right := BucketUnmaterializedOrphaned);
+ eauto using HistoricalBeforeUnmaterializedOrphan.
+ + destruct Hcategory as [Hever Hnot_live].
+ apply allocation_status_tombstoned_from_membership; try assumption.
+ * intros Hreserved.
+ eapply Hdisjoint with
+ (left := BucketHistorical) (right := BucketReserved);
+ eauto using HistoricalBeforeReserved.
+ * intros Hclaimed.
+ eapply Hdisjoint with
+ (left := BucketHistorical) (right := BucketMaterializedClaimed);
+ eauto using HistoricalBeforeClaimed.
+ * intros Horphan.
+ eapply Hdisjoint with
+ (left := BucketHistorical) (right := BucketMaterializedOrphaned);
+ eauto using HistoricalBeforeMaterializedOrphan.
+ * intros Hunmaterialized.
+ eapply Hdisjoint with
+ (left := BucketHistorical)
+ (right := BucketUnmaterializedOrphaned);
+ eauto using HistoricalBeforeUnmaterializedOrphan.
+ + apply allocation_status_materialized_orphan_from_membership.
+ * intros Hreserved.
+ eapply Hdisjoint with
+ (left := BucketReserved) (right := BucketMaterializedOrphaned);
+ eauto using ReservedBeforeMaterializedOrphan.
+ * intros Hclaimed.
+ eapply Hdisjoint with
+ (left := BucketMaterializedClaimed)
+ (right := BucketMaterializedOrphaned);
+ eauto using ClaimedBeforeMaterializedOrphan.
+ * exact Hcategory.
+ + apply allocation_status_unmaterialized_orphan_from_membership.
+ * intros Hreserved.
+ eapply Hdisjoint with
+ (left := BucketReserved)
+ (right := BucketUnmaterializedOrphaned);
+ eauto using ReservedBeforeUnmaterializedOrphan.
+ * intros Hclaimed.
+ eapply Hdisjoint with
+ (left := BucketMaterializedClaimed)
+ (right := BucketUnmaterializedOrphaned);
+ eauto using ClaimedBeforeUnmaterializedOrphan.
+ * intros Horphan.
+ eapply Hdisjoint with
+ (left := BucketMaterializedOrphaned)
+ (right := BucketUnmaterializedOrphaned);
+ eauto using MaterializedOrphanBeforeUnmaterializedOrphan.
+ * exact Hcategory.
+Qed.
+
+Theorem VWENC_162_EVERY_ALLOCATED_ENTRY_HAS_ONE_AUTHORITATIVE_STATUS :
+ forall (P : CertifiedAtomProfile) (I T : FixedWidthCarrierProfile)
+ (state : InterningState P I T) atom id,
+ InterningStateWellFormed state ->
+ In (atom, id) (state_allocation_entries state) ->
+ exists! status, allocation_status_category state atom id status.
+Proof.
+ intros P I T state atom id Hwell Hallocated.
+ destruct (allocated_entry_has_computed_status
+ P I T state atom id Hallocated) as [status Hstatus].
+ exists status.
+ split.
+ - now apply (proj1
+ (VWENC_163_ALLOCATION_STATUS_REPORTS_ITS_EXACT_STATE_CATEGORY
+ P I T state atom id status Hwell)).
+ - intros other Hother.
+ eapply VWENC_161_ALLOCATION_STATUS_IS_FUNCTIONALLY_UNIQUE.
+ + exact Hstatus.
+ + now apply (proj2
+ (VWENC_163_ALLOCATION_STATUS_REPORTS_ITS_EXACT_STATE_CATEGORY
+ P I T state atom id other Hwell)).
+Qed.
+
+Lemma NoDup_map_members_with_same_image_are_equal :
+ forall (Element Image : Type) (project : Element -> Image)
+ (values : list Element) left right,
+ NoDup (map project values) ->
+ In left values ->
+ In right values ->
+ project left = project right ->
+ left = right.
+Proof.
+ intros Element Image project values.
+ induction values as [| head tail IH]; intros left right
+ Hunique Hleft Hright Himage.
+ - contradiction.
+ - inversion Hunique as [| projected projected_tail
+ Hhead_absent Htail_unique]; subst.
+ simpl in Hleft, Hright.
+ destruct Hleft as [Hleft | Hleft];
+ destruct Hright as [Hright | Hright].
+ + now subst left; subst right.
+ + subst left. exfalso. apply Hhead_absent.
+ apply in_map_iff. exists right. split; [symmetry | assumption].
+ exact Himage.
+ + subst right. exfalso. apply Hhead_absent.
+ apply in_map_iff. exists left. now split.
+ + exact (IH left right Htail_unique Hleft Hright Himage).
+Qed.
+
+Lemma allocation_status_category_entry_is_allocated :
+ forall (P : CertifiedAtomProfile) (I T : FixedWidthCarrierProfile)
+ (state : InterningState P I T) atom id status,
+ allocation_status_category state atom id status ->
+ In (atom, id) (state_allocation_entries state).
+Proof.
+ intros P I T state atom id status Hcategory.
+ unfold state_allocation_entries.
+ repeat rewrite in_app_iff.
+ destruct status; simpl in Hcategory; tauto.
+Qed.
+
+Theorem VWENC_188_ALLOCATION_STATUS_CATEGORIES_ARE_PAIRWISE_DISJOINT_BY_ID :
+ forall (P : CertifiedAtomProfile) (I T : FixedWidthCarrierProfile)
+ (state : InterningState P I T)
+ left_atom right_atom id left_status right_status,
+ InterningStateWellFormed state ->
+ allocation_status_category state left_atom id left_status ->
+ allocation_status_category state right_atom id right_status ->
+ left_atom = right_atom /\ left_status = right_status.
+Proof.
+ intros P I T state left_atom right_atom id left_status right_status
+ Hwell Hleft_category Hright_category.
+ assert (Hleft_allocated :
+ In (left_atom, id) (state_allocation_entries state)).
+ { now apply allocation_status_category_entry_is_allocated
+ with (status := left_status). }
+ assert (Hright_allocated :
+ In (right_atom, id) (state_allocation_entries state)).
+ { now apply allocation_status_category_entry_is_allocated
+ with (status := right_status). }
+ assert (Hentry : (left_atom, id) = (right_atom, id)).
+ { eapply NoDup_map_members_with_same_image_are_equal
+ with (project := snd)
+ (values := state_allocation_entries state).
+ - exact (state_allocation_ids_unique state Hwell).
+ - exact Hleft_allocated.
+ - exact Hright_allocated.
+ - reflexivity. }
+ inversion Hentry. subst right_atom.
+ split; [reflexivity |].
+ eapply VWENC_161_ALLOCATION_STATUS_IS_FUNCTIONALLY_UNIQUE.
+ - now apply (proj2
+ (VWENC_163_ALLOCATION_STATUS_REPORTS_ITS_EXACT_STATE_CATEGORY
+ P I T state left_atom id left_status Hwell)).
+ - now apply (proj2
+ (VWENC_163_ALLOCATION_STATUS_REPORTS_ITS_EXACT_STATE_CATEGORY
+ P I T state left_atom id right_status Hwell)).
+Qed.
+
+Definition empty_packed_atom_storage
+ (I : FixedWidthCarrierProfile) : PackedAtomStorage I :=
+ mkPackedAtomStorage I [] [].
+
+Definition empty_interning_state
+ (P : CertifiedAtomProfile)
+ (I T : FixedWidthCarrierProfile)
+ (fiber : VocabularyFiber P I)
+ (term_identity term_generation : nat) : InterningState P I T :=
+ {| state_fiber := fiber;
+ state_term_fiber :=
+ mkTermDictionaryFiber P I T fiber term_identity term_generation;
+ state_reserved_entries := [];
+ state_claimed_entries := [];
+ state_live_entries := [];
+ state_ever_entries := [];
+ state_orphan_entries := [];
+ state_unmaterialized_orphan_entries := [];
+ state_packed_storage := empty_packed_atom_storage I;
+ state_allocator_frontier := 0;
+ state_sequences := [];
+ state_term_dictionary_enabled := false;
+ state_term_entries := [] |}.
+
+Theorem VWENC_157_EMPTY_INTERNING_STATE_IS_WELL_FORMED :
+ forall (P : CertifiedAtomProfile) (I T : FixedWidthCarrierProfile)
+ (fiber : VocabularyFiber P I) term_identity term_generation,
+ InterningStateWellFormed
+ (empty_interning_state
+ P I T fiber term_identity term_generation).
+Proof.
+ intros P I T fiber term_identity term_generation. constructor; simpl.
+ - split; constructor.
+ - split; constructor.
+ - intros atom id Hin. contradiction.
+ - constructor.
+ - split.
+ + constructor.
+ + split.
+ * unfold packed_spans_pairwise_disjoint. simpl.
+ intros left_id left_span right_id right_span Hleft.
+ contradiction.
+ * split.
+ { unfold packed_spans_cover_bytes. simpl. intros offset. split.
+ - lia.
+ - intros [id [span [Hin _]]]. contradiction. }
+ { split.
+ - intros atom id Hin. contradiction.
+ - intros id span Hin. contradiction. }
+ - constructor.
+ - pose proof (carrier_capacity_positive I). lia.
+ - constructor.
+ - split; constructor.
+ - constructor.
+ - intros _. reflexivity.
+Qed.
+
+Theorem VWENC_158_WELL_FORMED_PACKED_SPANS_ARE_DISJOINT_AND_COVER_EXACTLY :
+ forall (P : CertifiedAtomProfile) (I T : FixedWidthCarrierProfile)
+ (state : InterningState P I T),
+ InterningStateWellFormed state ->
+ packed_spans_pairwise_disjoint
+ (state_packed_storage P I T state) /\
+ packed_spans_cover_bytes
+ (state_packed_storage P I T state).
+Proof.
+ intros P I T state Hwell.
+ destruct Hwell as [_ _ _ _ Hpacked].
+ destruct Hpacked as [_ [Hdisjoint [Hcover _]]].
+ now split.
+Qed.
+
+Definition publish_fresh_atom
+ {P : CertifiedAtomProfile}
+ {I T : FixedWidthCarrierProfile}
+ (state : InterningState P I T)
+ (atom : CanonicalAtom P)
+ (id : SymbolId I) : option (InterningState P I T) :=
+ match lookup_atom (state_ever_entries P I T state) atom with
+ | Some _ => None
+ | None =>
+ match lookup_symbol (state_ever_entries P I T state) id with
+ | Some _ => None
+ | None =>
+ if Nat.leb
+ (state_allocator_frontier P I T state)
+ (symbol_id_value I id)
+ then
+ match append_packed_atom
+ (state_packed_storage P I T state) id atom with
+ | None => None
+ | Some packed =>
+ Some
+ {| state_fiber := state_fiber P I T state;
+ state_term_fiber := state_term_fiber P I T state;
+ state_reserved_entries :=
+ state_reserved_entries P I T state;
+ state_claimed_entries :=
+ state_claimed_entries P I T state;
+ state_live_entries :=
+ (atom, id) :: state_live_entries P I T state;
+ state_ever_entries :=
+ (atom, id) :: state_ever_entries P I T state;
+ state_orphan_entries :=
+ state_orphan_entries P I T state;
+ state_unmaterialized_orphan_entries :=
+ state_unmaterialized_orphan_entries P I T state;
+ state_packed_storage := packed;
+ state_allocator_frontier :=
+ S (symbol_id_value I id);
+ state_sequences := state_sequences P I T state;
+ state_term_dictionary_enabled :=
+ state_term_dictionary_enabled P I T state;
+ state_term_entries := state_term_entries P I T state |}
+ end
+ else None
+ end
+ end.
+
+Definition claim_atom_allocation
+ {P : CertifiedAtomProfile}
+ {I T : FixedWidthCarrierProfile}
+ (state : InterningState P I T)
+ (atom : CanonicalAtom P)
+ (id : SymbolId I) : option (InterningState P I T) :=
+ match lookup_atom (state_ever_entries P I T state) atom with
+ | Some _ => None
+ | None =>
+ if Nat.leb
+ (state_allocator_frontier P I T state)
+ (symbol_id_value I id)
+ then
+ Some
+ {| state_fiber := state_fiber P I T state;
+ state_term_fiber := state_term_fiber P I T state;
+ state_reserved_entries :=
+ (atom, id) :: state_reserved_entries P I T state;
+ state_claimed_entries := state_claimed_entries P I T state;
+ state_live_entries := state_live_entries P I T state;
+ state_ever_entries := state_ever_entries P I T state;
+ state_orphan_entries := state_orphan_entries P I T state;
+ state_unmaterialized_orphan_entries :=
+ state_unmaterialized_orphan_entries P I T state;
+ state_packed_storage := state_packed_storage P I T state;
+ state_allocator_frontier := S (symbol_id_value I id);
+ state_sequences := state_sequences P I T state;
+ state_term_dictionary_enabled :=
+ state_term_dictionary_enabled P I T state;
+ state_term_entries := state_term_entries P I T state |}
+ else None
+ end.
+
+Theorem VWENC_164_ALLOCATED_IDS_CANNOT_BE_RESERVED_OR_FRESHLY_PUBLISHED_AGAIN :
+ forall (P : CertifiedAtomProfile) (I T : FixedWidthCarrierProfile)
+ (state : InterningState P I T) existing_atom new_atom id,
+ InterningStateWellFormed state ->
+ In (existing_atom, id) (state_allocation_entries state) ->
+ claim_atom_allocation state new_atom id = None /\
+ publish_fresh_atom state new_atom id = None.
+Proof.
+ intros P I T state existing_atom new_atom id Hwell Hallocated.
+ destruct Hwell as [_ _ _ _ _ Hbelow].
+ apply Forall_forall with (x := (existing_atom, id)) in Hbelow;
+ [| exact Hallocated].
+ simpl in Hbelow. split.
+ - unfold claim_atom_allocation.
+ destruct (lookup_atom (state_ever_entries P I T state) new_atom);
+ [reflexivity |].
+ destruct (Nat.leb
+ (state_allocator_frontier P I T state)
+ (symbol_id_value I id)) eqn:Hfrontier; [| reflexivity].
+ apply Nat.leb_le in Hfrontier. lia.
+ - unfold publish_fresh_atom.
+ destruct (lookup_atom (state_ever_entries P I T state) new_atom);
+ [reflexivity |].
+ destruct (lookup_symbol (state_ever_entries P I T state) id);
+ [reflexivity |].
+ destruct (Nat.leb
+ (state_allocator_frontier P I T state)
+ (symbol_id_value I id)) eqn:Hfrontier; [| reflexivity].
+ apply Nat.leb_le in Hfrontier. lia.
+Qed.
+
+Theorem VWENC_106_FRESH_PUBLICATION_UPDATES_LIVE_HISTORY_AND_PACKED_BYTES :
+ forall (P : CertifiedAtomProfile) (I T : FixedWidthCarrierProfile)
+ (state updated : InterningState P I T)
+ (atom : CanonicalAtom P) (id : SymbolId I),
+ publish_fresh_atom state atom id = Some updated ->
+ In (atom, id) (state_live_entries P I T updated) /\
+ In (atom, id) (state_ever_entries P I T updated) /\
+ packed_entry_exact
+ (state_packed_storage P I T updated) atom id.
+Proof.
+ intros P I T state updated atom id Hpublish.
+ unfold publish_fresh_atom in Hpublish.
+ destruct (lookup_atom (state_ever_entries P I T state) atom);
+ [discriminate |].
+ destruct (lookup_symbol (state_ever_entries P I T state) id);
+ [discriminate |].
+ destruct (Nat.leb
+ (state_allocator_frontier P I T state)
+ (symbol_id_value I id)); [| discriminate].
+ destruct (append_packed_atom
+ (state_packed_storage P I T state) id atom)
+ as [packed |] eqn:Happend; [| discriminate].
+ inversion Hpublish. subst updated. clear Hpublish.
+ split; [now left |].
+ split; [now left |].
+ destruct (VWENC_114_SAFE_PACKED_APPEND_READS_EXACT_CANONICAL_BYTES
+ P I (state_packed_storage P I T state) packed id atom Happend)
+ as [span [Hlookup [Hread [Hlength Hbounds]]]].
+ exists span. split; [exact Hlookup |].
+ split; [exact Hread |].
+ split; [exact Hlength |].
+ split.
+ - pose proof
+ (atom_codeword_nonempty P
+ (canonical_atom_bytes P atom)
+ (canonical_atom_valid P atom)) as Hnonempty.
+ rewrite Hlength.
+ destruct (canonical_atom_bytes P atom); simpl; [contradiction | lia].
+ - exact Hbounds.
+Qed.
+
+Theorem VWENC_107_EVER_PUBLISHED_ID_CANNOT_BE_REBOUND_AFTER_TOMBSTONE :
+ forall (P : CertifiedAtomProfile) (I T : FixedWidthCarrierProfile)
+ (state : InterningState P I T)
+ (new_atom previous_atom : CanonicalAtom P) (id : SymbolId I),
+ lookup_symbol (state_ever_entries P I T state) id =
+ Some previous_atom ->
+ publish_fresh_atom state new_atom id = None.
+Proof.
+ intros P I T state new_atom previous_atom id Howned.
+ unfold publish_fresh_atom.
+ destruct (lookup_atom (state_ever_entries P I T state) new_atom);
+ [reflexivity |].
+ now rewrite Howned.
+Qed.
+
+Lemma referenced_ids_are_live_and_below_frontier :
+ forall (P : CertifiedAtomProfile) (I T : FixedWidthCarrierProfile)
+ (state : InterningState P I T) sequence id,
+ InterningStateWellFormed state ->
+ In sequence (state_sequences P I T state) ->
+ In id sequence ->
+ symbol_id_value I id < state_allocator_frontier P I T state /\
+ live_symbol (state_live_entries P I T state) id.
+Proof.
+ intros P I T state sequence id Hwell Hsequence Hid.
+ destruct Hwell as [_ _ _ _ _ _ _ Hsequences].
+ apply Forall_forall with (x := sequence) in Hsequences;
+ [| exact Hsequence].
+ now apply Forall_forall with (x := id) in Hsequences.
+Qed.
+
+Lemma vocabulary_insert_preserves_well_formedness :
+ forall (P : CertifiedAtomProfile) (I : FixedWidthCarrierProfile)
+ (entries : list (VocabularyEntry P I)) atom id,
+ vocabulary_relation_well_formed entries ->
+ lookup_atom entries atom = None ->
+ lookup_symbol entries id = None ->
+ vocabulary_relation_well_formed ((atom, id) :: entries).
+Proof.
+ intros P I entries atom id [Hatom_unique Hid_unique] Hatom Hid.
+ split; simpl; constructor.
+ - unfold lookup_atom in Hatom.
+ now apply assoc_lookup_none_key_absent in Hatom.
+ - exact Hatom_unique.
+ - unfold lookup_symbol in Hid.
+ apply assoc_lookup_none_key_absent in Hid.
+ rewrite reverse_vocabulary_keys_are_ids in Hid. exact Hid.
+ - exact Hid_unique.
+Qed.
+
+Lemma sequence_bound_monotone :
+ forall (P : CertifiedAtomProfile) (I : FixedWidthCarrierProfile)
+ (old_live new_live : list (VocabularyEntry P I))
+ old_frontier new_frontier sequence,
+ (forall atom id, In (atom, id) old_live ->
+ In (atom, id) new_live) ->
+ old_frontier <= new_frontier ->
+ sequence_vocabulary_bound old_live old_frontier sequence ->
+ sequence_vocabulary_bound new_live new_frontier sequence.
+Proof.
+ intros P I old_live new_live old_frontier new_frontier sequence
+ Hinclude Hfrontier Hbound.
+ apply Forall_forall. intros id Hin.
+ apply Forall_forall with (x := id) in Hbound; [| exact Hin].
+ destruct Hbound as [Hbelow [atom Hlive]].
+ split; [lia |].
+ exists atom. now apply Hinclude.
+Qed.
+
+Lemma NoDup_app_disjoint_right :
+ forall (Element : Type) (left right : list Element) element,
+ NoDup (left ++ right) ->
+ In element left ->
+ ~ In element right.
+Proof.
+ intros Element left right element Hunique Hin_left Hin_right.
+ destruct (in_split element left Hin_left)
+ as [prefix [suffix Hleft]].
+ subst left.
+ assert (Hshape :
+ (prefix ++ element :: suffix) ++ right =
+ prefix ++ element :: (suffix ++ right)).
+ { now rewrite <- app_assoc. }
+ rewrite Hshape in Hunique.
+ pose proof (NoDup_remove_2 prefix (suffix ++ right) element Hunique)
+ as Hnot_in_remainder.
+ apply Hnot_in_remainder.
+ apply in_or_app. right.
+ apply in_or_app. right. exact Hin_right.
+Qed.
+
+Lemma allocated_id_has_exact_span :
+ forall (P : CertifiedAtomProfile) (I : FixedWidthCarrierProfile)
+ (allocations : list (VocabularyEntry P I)) storage id,
+ packed_storage_matches_allocations allocations storage ->
+ In id (map snd allocations) ->
+ exists atom span,
+ In (atom, id) allocations /\
+ lookup_span storage id = Some span.
+Proof.
+ intros P I allocations storage id
+ [_ [_ [_ [Hexact _]]]] Hin.
+ apply in_map_iff in Hin.
+ destruct Hin as [[atom allocated_id] [Hequal Hin]].
+ simpl in Hequal. subst allocated_id.
+ destruct (Hexact atom id Hin)
+ as [span [Hlookup _]].
+ exists atom, span. now split.
+Qed.
+
+Lemma permutation_move_middle_entry_right :
+ forall (Element : Type)
+ (before prefix suffix after : list Element) (element : Element),
+ Permutation
+ (before ++ prefix ++ element :: suffix ++ after)
+ (before ++ prefix ++ suffix ++ element :: after).
+Proof.
+ intros Element before prefix suffix after element.
+ apply Permutation_app_head.
+ apply Permutation_app_head.
+ apply Permutation_middle.
+Qed.
+
+Lemma permutation_extract_after_three_prefixes :
+ forall (Element : Type)
+ (first second third fourth fifth : list Element) (element : Element),
+ Permutation
+ (first ++ second ++ third ++ element :: fourth ++ fifth)
+ (element :: first ++ second ++ third ++ fourth ++ fifth).
+Proof.
+ intros Element first second third fourth fifth element.
+ apply Permutation_sym.
+ eapply Permutation_trans.
+ - apply Permutation_middle.
+ - apply Permutation_app_head.
+ eapply Permutation_trans.
+ + apply Permutation_middle.
+ + apply Permutation_app_head.
+ apply Permutation_middle.
+Qed.
+
+Lemma permutation_move_after_three_prefixes :
+ forall (Element : Type)
+ (first second third fourth fifth : list Element) (element : Element),
+ Permutation
+ (first ++ second ++ third ++ element :: fourth ++ fifth)
+ (first ++ second ++ third ++ fourth ++ element :: fifth).
+Proof.
+ intros Element first second third fourth fifth element.
+ apply Permutation_app_head.
+ apply Permutation_app_head.
+ apply Permutation_app_head.
+ apply Permutation_middle.
+Qed.
+
+Lemma claim_atom_allocation_preserves_combined_state_well_formedness :
+ forall (P : CertifiedAtomProfile) (I T : FixedWidthCarrierProfile)
+ (state claimed : InterningState P I T)
+ (atom : CanonicalAtom P) (id : SymbolId I),
+ InterningStateWellFormed state ->
+ claim_atom_allocation state atom id = Some claimed ->
+ InterningStateWellFormed claimed.
+Proof.
+ intros P I T state claimed atom id Hwell Hclaim.
+ destruct Hwell as
+ [Hlive_bijection Hhistory_bijection Hlive_history
+ Hallocation_unique Hpacked Hallocations_below Hfrontier_capacity
+ Hsequences Hterm_bijection Hterm_bound Hdisabled].
+ unfold claim_atom_allocation in Hclaim.
+ destruct (lookup_atom (state_ever_entries P I T state) atom);
+ [discriminate |].
+ destruct (Nat.leb
+ (state_allocator_frontier P I T state)
+ (symbol_id_value I id)) eqn:Hfrontier; [| discriminate].
+ apply Nat.leb_le in Hfrontier.
+ inversion Hclaim. subst claimed. clear Hclaim.
+ assert (Hid_absent :
+ ~ In id (map snd (state_allocation_entries state))).
+ { intros Hin.
+ apply in_map_iff in Hin.
+ destruct Hin as [[allocated_atom allocated_id] [Hequal Hin]].
+ simpl in Hequal. subst allocated_id.
+ apply Forall_forall with
+ (x := (allocated_atom, id)) in Hallocations_below;
+ [simpl in Hallocations_below; lia | exact Hin]. }
+ assert (Hallocation_permutation :
+ Permutation
+ ((atom, id) :: state_allocation_entries state)
+ (state_allocation_entries
+ {| state_fiber := state_fiber P I T state;
+ state_term_fiber := state_term_fiber P I T state;
+ state_reserved_entries :=
+ (atom, id) :: state_reserved_entries P I T state;
+ state_claimed_entries := state_claimed_entries P I T state;
+ state_live_entries := state_live_entries P I T state;
+ state_ever_entries := state_ever_entries P I T state;
+ state_orphan_entries := state_orphan_entries P I T state;
+ state_unmaterialized_orphan_entries :=
+ state_unmaterialized_orphan_entries P I T state;
+ state_packed_storage := state_packed_storage P I T state;
+ state_allocator_frontier := S (symbol_id_value I id);
+ state_sequences := state_sequences P I T state;
+ state_term_dictionary_enabled :=
+ state_term_dictionary_enabled P I T state;
+ state_term_entries := state_term_entries P I T state |})).
+ { unfold state_allocation_entries. simpl.
+ apply Permutation_middle. }
+ constructor; simpl.
+ - exact Hlive_bijection.
+ - exact Hhistory_bijection.
+ - exact Hlive_history.
+ - apply (Permutation_NoDup (Permutation_map snd Hallocation_permutation)).
+ constructor; assumption.
+ - exact Hpacked.
+ - apply Forall_forall. intros entry Hin.
+ assert (Hordered :
+ In entry ((atom, id) :: state_allocation_entries state)).
+ { eapply Permutation_in.
+ - exact (Permutation_sym Hallocation_permutation).
+ - exact Hin. }
+ simpl in Hordered. destruct Hordered as [Hnew | Hold].
+ + inversion Hnew. simpl. lia.
+ + apply Forall_forall with (x := entry) in Hallocations_below;
+ [| exact Hold].
+ simpl in *. lia.
+ - pose proof (symbol_id_in_range I id). lia.
+ - apply Forall_forall. intros sequence Hin.
+ apply Forall_forall with (x := sequence) in Hsequences;
+ [| exact Hin].
+ eapply sequence_bound_monotone; [| | exact Hsequences].
+ + intros live_atom live_id Hlive. exact Hlive.
+ + lia.
+ - exact Hterm_bijection.
+ - apply Forall_forall. intros entry Hin.
+ apply Forall_forall with (x := entry) in Hterm_bound;
+ [| exact Hin].
+ eapply sequence_bound_monotone; [| | exact Hterm_bound].
+ + intros live_atom live_id Hlive. exact Hlive.
+ + lia.
+ - exact Hdisabled.
+Qed.
+
+Definition materialize_reserved_allocation
+ {P : CertifiedAtomProfile}
+ {I T : FixedWidthCarrierProfile}
+ (state : InterningState P I T)
+ (atom : CanonicalAtom P)
+ (id : SymbolId I)
+ (updated : InterningState P I T) : Prop :=
+ exists prefix suffix packed,
+ state_reserved_entries P I T state =
+ prefix ++ (atom, id) :: suffix /\
+ append_packed_atom
+ (state_packed_storage P I T state) id atom = Some packed /\
+ updated =
+ {| state_fiber := state_fiber P I T state;
+ state_term_fiber := state_term_fiber P I T state;
+ state_reserved_entries := prefix ++ suffix;
+ state_claimed_entries :=
+ (atom, id) :: state_claimed_entries P I T state;
+ state_live_entries := state_live_entries P I T state;
+ state_ever_entries := state_ever_entries P I T state;
+ state_orphan_entries := state_orphan_entries P I T state;
+ state_unmaterialized_orphan_entries :=
+ state_unmaterialized_orphan_entries P I T state;
+ state_packed_storage := packed;
+ state_allocator_frontier := state_allocator_frontier P I T state;
+ state_sequences := state_sequences P I T state;
+ state_term_dictionary_enabled :=
+ state_term_dictionary_enabled P I T state;
+ state_term_entries := state_term_entries P I T state |}.
+
+Lemma materialize_reserved_allocation_preserves_combined_state_well_formedness :
+ forall (P : CertifiedAtomProfile) (I T : FixedWidthCarrierProfile)
+ (state updated : InterningState P I T) atom id,
+ InterningStateWellFormed state ->
+ materialize_reserved_allocation state atom id updated ->
+ InterningStateWellFormed updated.
+Proof.
+ intros P I T state updated atom id Hwell Hmaterialize.
+ destruct Hwell as
+ [Hlive_bijection Hhistory_bijection Hlive_history
+ Hallocation_unique Hpacked Hallocations_below Hfrontier_capacity
+ Hsequences Hterm_bijection Hterm_bound Hdisabled].
+ destruct Hmaterialize as
+ [prefix [suffix [packed [Hreserved [Happend Hupdated]]]]].
+ subst updated.
+ assert (Hspan_none :
+ lookup_span (state_packed_storage P I T state) id = None).
+ { unfold append_packed_atom in Happend.
+ destruct (lookup_span (state_packed_storage P I T state) id);
+ [discriminate | reflexivity]. }
+ assert (Hid_materialized_absent :
+ ~ In id (map snd (state_materialized_entries state))).
+ { intros Hin.
+ destruct (allocated_id_has_exact_span
+ P I (state_materialized_entries state)
+ (state_packed_storage P I T state) id Hpacked Hin)
+ as [allocated_atom [span [_ Hlookup]]].
+ rewrite Hspan_none in Hlookup. discriminate. }
+ assert (Hallocation_permutation :
+ Permutation
+ (state_allocation_entries state)
+ (state_allocation_entries
+ {| state_fiber := state_fiber P I T state;
+ state_term_fiber := state_term_fiber P I T state;
+ state_reserved_entries := prefix ++ suffix;
+ state_claimed_entries :=
+ (atom, id) :: state_claimed_entries P I T state;
+ state_live_entries := state_live_entries P I T state;
+ state_ever_entries := state_ever_entries P I T state;
+ state_orphan_entries := state_orphan_entries P I T state;
+ state_unmaterialized_orphan_entries :=
+ state_unmaterialized_orphan_entries P I T state;
+ state_packed_storage := packed;
+ state_allocator_frontier := state_allocator_frontier P I T state;
+ state_sequences := state_sequences P I T state;
+ state_term_dictionary_enabled :=
+ state_term_dictionary_enabled P I T state;
+ state_term_entries := state_term_entries P I T state |})).
+ { unfold state_allocation_entries. simpl. rewrite Hreserved.
+ repeat rewrite <- app_assoc.
+ apply permutation_move_middle_entry_right. }
+ assert (Hmaterialized_permutation :
+ Permutation
+ ((atom, id) :: state_materialized_entries state)
+ (state_materialized_entries
+ {| state_fiber := state_fiber P I T state;
+ state_term_fiber := state_term_fiber P I T state;
+ state_reserved_entries := prefix ++ suffix;
+ state_claimed_entries :=
+ (atom, id) :: state_claimed_entries P I T state;
+ state_live_entries := state_live_entries P I T state;
+ state_ever_entries := state_ever_entries P I T state;
+ state_orphan_entries := state_orphan_entries P I T state;
+ state_unmaterialized_orphan_entries :=
+ state_unmaterialized_orphan_entries P I T state;
+ state_packed_storage := packed;
+ state_allocator_frontier := state_allocator_frontier P I T state;
+ state_sequences := state_sequences P I T state;
+ state_term_dictionary_enabled :=
+ state_term_dictionary_enabled P I T state;
+ state_term_entries := state_term_entries P I T state |})).
+ { unfold state_materialized_entries. simpl.
+ apply Permutation_middle. }
+ constructor; simpl.
+ - exact Hlive_bijection.
+ - exact Hhistory_bijection.
+ - exact Hlive_history.
+ - apply (Permutation_NoDup (Permutation_map snd Hallocation_permutation)).
+ exact Hallocation_unique.
+ - eapply packed_storage_matches_allocations_permutation.
+ + exact Hmaterialized_permutation.
+ + eapply packed_storage_matches_allocations_after_append;
+ eassumption.
+ - apply Forall_forall. intros entry Hin.
+ apply Forall_forall with (x := entry) in Hallocations_below.
+ + exact Hallocations_below.
+ + eapply Permutation_in.
+ * exact (Permutation_sym Hallocation_permutation).
+ * exact Hin.
+ - exact Hfrontier_capacity.
+ - exact Hsequences.
+ - exact Hterm_bijection.
+ - exact Hterm_bound.
+ - exact Hdisabled.
+Qed.
+
+Definition orphan_reserved_allocation
+ {P : CertifiedAtomProfile}
+ {I T : FixedWidthCarrierProfile}
+ (state : InterningState P I T)
+ (atom : CanonicalAtom P)
+ (id : SymbolId I)
+ (updated : InterningState P I T) : Prop :=
+ exists prefix suffix,
+ state_reserved_entries P I T state =
+ prefix ++ (atom, id) :: suffix /\
+ updated =
+ {| state_fiber := state_fiber P I T state;
+ state_term_fiber := state_term_fiber P I T state;
+ state_reserved_entries := prefix ++ suffix;
+ state_claimed_entries := state_claimed_entries P I T state;
+ state_live_entries := state_live_entries P I T state;
+ state_ever_entries := state_ever_entries P I T state;
+ state_orphan_entries := state_orphan_entries P I T state;
+ state_unmaterialized_orphan_entries :=
+ (atom, id) ::
+ state_unmaterialized_orphan_entries P I T state;
+ state_packed_storage := state_packed_storage P I T state;
+ state_allocator_frontier := state_allocator_frontier P I T state;
+ state_sequences := state_sequences P I T state;
+ state_term_dictionary_enabled :=
+ state_term_dictionary_enabled P I T state;
+ state_term_entries := state_term_entries P I T state |}.
+
+Lemma orphan_reserved_allocation_preserves_combined_state_well_formedness :
+ forall (P : CertifiedAtomProfile) (I T : FixedWidthCarrierProfile)
+ (state updated : InterningState P I T) atom id,
+ InterningStateWellFormed state ->
+ orphan_reserved_allocation state atom id updated ->
+ InterningStateWellFormed updated.
+Proof.
+ intros P I T state updated atom id Hwell Horphan.
+ destruct Hwell as
+ [Hlive_bijection Hhistory_bijection Hlive_history
+ Hallocation_unique Hpacked Hallocations_below Hfrontier_capacity
+ Hsequences Hterm_bijection Hterm_bound Hdisabled].
+ destruct Horphan as [prefix [suffix [Hreserved Hupdated]]].
+ subst updated.
+ assert (Hallocation_permutation :
+ Permutation
+ (state_allocation_entries state)
+ (state_allocation_entries
+ {| state_fiber := state_fiber P I T state;
+ state_term_fiber := state_term_fiber P I T state;
+ state_reserved_entries := prefix ++ suffix;
+ state_claimed_entries := state_claimed_entries P I T state;
+ state_live_entries := state_live_entries P I T state;
+ state_ever_entries := state_ever_entries P I T state;
+ state_orphan_entries := state_orphan_entries P I T state;
+ state_unmaterialized_orphan_entries :=
+ (atom, id) ::
+ state_unmaterialized_orphan_entries P I T state;
+ state_packed_storage := state_packed_storage P I T state;
+ state_allocator_frontier := state_allocator_frontier P I T state;
+ state_sequences := state_sequences P I T state;
+ state_term_dictionary_enabled :=
+ state_term_dictionary_enabled P I T state;
+ state_term_entries := state_term_entries P I T state |})).
+ { unfold state_allocation_entries. simpl. rewrite Hreserved.
+ repeat rewrite <- app_assoc.
+ simpl.
+ apply Permutation_app_head.
+ apply Permutation_app_head.
+ repeat rewrite app_assoc.
+ apply Permutation_middle. }
+ constructor; simpl.
+ - exact Hlive_bijection.
+ - exact Hhistory_bijection.
+ - exact Hlive_history.
+ - apply (Permutation_NoDup (Permutation_map snd Hallocation_permutation)).
+ exact Hallocation_unique.
+ - exact Hpacked.
+ - apply Forall_forall. intros entry Hin.
+ apply Forall_forall with (x := entry) in Hallocations_below.
+ + exact Hallocations_below.
+ + eapply Permutation_in.
+ * exact (Permutation_sym Hallocation_permutation).
+ * exact Hin.
+ - exact Hfrontier_capacity.
+ - exact Hsequences.
+ - exact Hterm_bijection.
+ - exact Hterm_bound.
+ - exact Hdisabled.
+Qed.
+
+Definition publish_claimed_allocation
+ {P : CertifiedAtomProfile}
+ {I T : FixedWidthCarrierProfile}
+ (state : InterningState P I T)
+ (atom : CanonicalAtom P)
+ (id : SymbolId I)
+ (updated : InterningState P I T) : Prop :=
+ exists prefix suffix,
+ state_claimed_entries P I T state =
+ prefix ++ (atom, id) :: suffix /\
+ lookup_atom (state_ever_entries P I T state) atom = None /\
+ lookup_symbol (state_ever_entries P I T state) id = None /\
+ lookup_atom (state_live_entries P I T state) atom = None /\
+ lookup_symbol (state_live_entries P I T state) id = None /\
+ updated =
+ {| state_fiber := state_fiber P I T state;
+ state_term_fiber := state_term_fiber P I T state;
+ state_reserved_entries := state_reserved_entries P I T state;
+ state_claimed_entries := prefix ++ suffix;
+ state_live_entries :=
+ (atom, id) :: state_live_entries P I T state;
+ state_ever_entries :=
+ (atom, id) :: state_ever_entries P I T state;
+ state_orphan_entries := state_orphan_entries P I T state;
+ state_unmaterialized_orphan_entries :=
+ state_unmaterialized_orphan_entries P I T state;
+ state_packed_storage := state_packed_storage P I T state;
+ state_allocator_frontier := state_allocator_frontier P I T state;
+ state_sequences := state_sequences P I T state;
+ state_term_dictionary_enabled :=
+ state_term_dictionary_enabled P I T state;
+ state_term_entries := state_term_entries P I T state |}.
+
+Lemma publish_claimed_allocation_preserves_combined_state_well_formedness :
+ forall (P : CertifiedAtomProfile) (I T : FixedWidthCarrierProfile)
+ (state updated : InterningState P I T) atom id,
+ InterningStateWellFormed state ->
+ publish_claimed_allocation state atom id updated ->
+ InterningStateWellFormed updated.
+Proof.
+ intros P I T state updated atom id Hwell Hpublish.
+ destruct Hwell as
+ [Hlive_bijection Hhistory_bijection Hlive_history
+ Hallocation_unique Hpacked Hallocations_below Hfrontier_capacity
+ Hsequences Hterm_bijection Hterm_bound Hdisabled].
+ destruct Hpublish as
+ [prefix [suffix
+ [Hclaimed [Hatom_history [Hid_history
+ [Hatom_live [Hid_live Hupdated]]]]]]].
+ subst updated.
+ assert (Hallocation_permutation :
+ Permutation
+ (state_allocation_entries state)
+ (state_allocation_entries
+ {| state_fiber := state_fiber P I T state;
+ state_term_fiber := state_term_fiber P I T state;
+ state_reserved_entries := state_reserved_entries P I T state;
+ state_claimed_entries := prefix ++ suffix;
+ state_live_entries :=
+ (atom, id) :: state_live_entries P I T state;
+ state_ever_entries :=
+ (atom, id) :: state_ever_entries P I T state;
+ state_orphan_entries := state_orphan_entries P I T state;
+ state_unmaterialized_orphan_entries :=
+ state_unmaterialized_orphan_entries P I T state;
+ state_packed_storage := state_packed_storage P I T state;
+ state_allocator_frontier := state_allocator_frontier P I T state;
+ state_sequences := state_sequences P I T state;
+ state_term_dictionary_enabled :=
+ state_term_dictionary_enabled P I T state;
+ state_term_entries := state_term_entries P I T state |})).
+ { unfold state_allocation_entries. simpl. rewrite Hclaimed.
+ repeat rewrite <- app_assoc.
+ apply permutation_extract_after_three_prefixes. }
+ assert (Hmaterialized_permutation :
+ Permutation
+ (state_materialized_entries state)
+ (state_materialized_entries
+ {| state_fiber := state_fiber P I T state;
+ state_term_fiber := state_term_fiber P I T state;
+ state_reserved_entries := state_reserved_entries P I T state;
+ state_claimed_entries := prefix ++ suffix;
+ state_live_entries :=
+ (atom, id) :: state_live_entries P I T state;
+ state_ever_entries :=
+ (atom, id) :: state_ever_entries P I T state;
+ state_orphan_entries := state_orphan_entries P I T state;
+ state_unmaterialized_orphan_entries :=
+ state_unmaterialized_orphan_entries P I T state;
+ state_packed_storage := state_packed_storage P I T state;
+ state_allocator_frontier := state_allocator_frontier P I T state;
+ state_sequences := state_sequences P I T state;
+ state_term_dictionary_enabled :=
+ state_term_dictionary_enabled P I T state;
+ state_term_entries := state_term_entries P I T state |})).
+ { unfold state_materialized_entries. simpl. rewrite Hclaimed.
+ repeat rewrite <- app_assoc.
+ exact
+ (permutation_extract_after_three_prefixes
+ (VocabularyEntry P I)
+ (state_ever_entries P I T state)
+ prefix [] suffix
+ (state_orphan_entries P I T state)
+ (atom, id)). }
+ constructor; simpl.
+ - now apply vocabulary_insert_preserves_well_formedness.
+ - now apply vocabulary_insert_preserves_well_formedness.
+ - intros live_atom live_id Hin.
+ simpl in Hin. destruct Hin as [Hnew | Hold].
+ + inversion Hnew. now left.
+ + right. now apply Hlive_history.
+ - apply (Permutation_NoDup (Permutation_map snd Hallocation_permutation)).
+ exact Hallocation_unique.
+ - eapply packed_storage_matches_allocations_permutation.
+ + exact Hmaterialized_permutation.
+ + exact Hpacked.
+ - apply Forall_forall. intros entry Hin.
+ apply Forall_forall with (x := entry) in Hallocations_below.
+ + exact Hallocations_below.
+ + eapply Permutation_in.
+ * exact (Permutation_sym Hallocation_permutation).
+ * exact Hin.
+ - exact Hfrontier_capacity.
+ - apply Forall_forall. intros sequence Hin.
+ apply Forall_forall with (x := sequence) in Hsequences;
+ [| exact Hin].
+ eapply (sequence_bound_monotone P I
+ (state_live_entries P I T state)
+ ((atom, id) :: state_live_entries P I T state)
+ (state_allocator_frontier P I T state)
+ (state_allocator_frontier P I T state)
+ sequence).
+ + intros live_atom live_id Hlive. now right.
+ + apply le_n.
+ + exact Hsequences.
+ - exact Hterm_bijection.
+ - apply Forall_forall. intros entry Hin.
+ apply Forall_forall with (x := entry) in Hterm_bound;
+ [| exact Hin].
+ eapply (sequence_bound_monotone P I
+ (state_live_entries P I T state)
+ ((atom, id) :: state_live_entries P I T state)
+ (state_allocator_frontier P I T state)
+ (state_allocator_frontier P I T state)
+ (fst entry)).
+ + intros live_atom live_id Hlive. now right.
+ + apply le_n.
+ + exact Hterm_bound.
+ - exact Hdisabled.
+Qed.
+
+Definition orphan_claimed_allocation
+ {P : CertifiedAtomProfile}
+ {I T : FixedWidthCarrierProfile}
+ (state : InterningState P I T)
+ (atom : CanonicalAtom P)
+ (id : SymbolId I)
+ (updated : InterningState P I T) : Prop :=
+ exists prefix suffix,
+ state_claimed_entries P I T state =
+ prefix ++ (atom, id) :: suffix /\
+ updated =
+ {| state_fiber := state_fiber P I T state;
+ state_term_fiber := state_term_fiber P I T state;
+ state_reserved_entries := state_reserved_entries P I T state;
+ state_claimed_entries := prefix ++ suffix;
+ state_live_entries := state_live_entries P I T state;
+ state_ever_entries := state_ever_entries P I T state;
+ state_orphan_entries :=
+ (atom, id) :: state_orphan_entries P I T state;
+ state_unmaterialized_orphan_entries :=
+ state_unmaterialized_orphan_entries P I T state;
+ state_packed_storage := state_packed_storage P I T state;
+ state_allocator_frontier := state_allocator_frontier P I T state;
+ state_sequences := state_sequences P I T state;
+ state_term_dictionary_enabled :=
+ state_term_dictionary_enabled P I T state;
+ state_term_entries := state_term_entries P I T state |}.
+
+Lemma orphan_claimed_allocation_preserves_combined_state_well_formedness :
+ forall (P : CertifiedAtomProfile) (I T : FixedWidthCarrierProfile)
+ (state updated : InterningState P I T) atom id,
+ InterningStateWellFormed state ->
+ orphan_claimed_allocation state atom id updated ->
+ InterningStateWellFormed updated.
+Proof.
+ intros P I T state updated atom id Hwell Horphan.
+ destruct Hwell as
+ [Hlive_bijection Hhistory_bijection Hlive_history
+ Hallocation_unique Hpacked Hallocations_below Hfrontier_capacity
+ Hsequences Hterm_bijection Hterm_bound Hdisabled].
+ destruct Horphan as
+ [prefix [suffix [Hclaimed Hupdated]]].
+ subst updated.
+ assert (Hallocation_permutation :
+ Permutation
+ (state_allocation_entries state)
+ (state_allocation_entries
+ {| state_fiber := state_fiber P I T state;
+ state_term_fiber := state_term_fiber P I T state;
+ state_reserved_entries := state_reserved_entries P I T state;
+ state_claimed_entries := prefix ++ suffix;
+ state_live_entries := state_live_entries P I T state;
+ state_ever_entries := state_ever_entries P I T state;
+ state_orphan_entries :=
+ (atom, id) :: state_orphan_entries P I T state;
+ state_unmaterialized_orphan_entries :=
+ state_unmaterialized_orphan_entries P I T state;
+ state_packed_storage := state_packed_storage P I T state;
+ state_allocator_frontier := state_allocator_frontier P I T state;
+ state_sequences := state_sequences P I T state;
+ state_term_dictionary_enabled :=
+ state_term_dictionary_enabled P I T state;
+ state_term_entries := state_term_entries P I T state |})).
+ { unfold state_allocation_entries. simpl. rewrite Hclaimed.
+ repeat rewrite <- app_assoc.
+ apply permutation_move_after_three_prefixes. }
+ assert (Hmaterialized_permutation :
+ Permutation
+ (state_materialized_entries state)
+ (state_materialized_entries
+ {| state_fiber := state_fiber P I T state;
+ state_term_fiber := state_term_fiber P I T state;
+ state_reserved_entries := state_reserved_entries P I T state;
+ state_claimed_entries := prefix ++ suffix;
+ state_live_entries := state_live_entries P I T state;
+ state_ever_entries := state_ever_entries P I T state;
+ state_orphan_entries :=
+ (atom, id) :: state_orphan_entries P I T state;
+ state_unmaterialized_orphan_entries :=
+ state_unmaterialized_orphan_entries P I T state;
+ state_packed_storage := state_packed_storage P I T state;
+ state_allocator_frontier := state_allocator_frontier P I T state;
+ state_sequences := state_sequences P I T state;
+ state_term_dictionary_enabled :=
+ state_term_dictionary_enabled P I T state;
+ state_term_entries := state_term_entries P I T state |})).
+ { unfold state_materialized_entries. simpl. rewrite Hclaimed.
+ repeat rewrite <- app_assoc.
+ exact
+ (permutation_move_after_three_prefixes
+ (VocabularyEntry P I)
+ (state_ever_entries P I T state)
+ prefix [] suffix
+ (state_orphan_entries P I T state)
+ (atom, id)). }
+ constructor; simpl.
+ - exact Hlive_bijection.
+ - exact Hhistory_bijection.
+ - exact Hlive_history.
+ - apply (Permutation_NoDup (Permutation_map snd Hallocation_permutation)).
+ exact Hallocation_unique.
+ - eapply packed_storage_matches_allocations_permutation.
+ + exact Hmaterialized_permutation.
+ + exact Hpacked.
+ - apply Forall_forall. intros entry Hin.
+ apply Forall_forall with (x := entry) in Hallocations_below.
+ + exact Hallocations_below.
+ + eapply Permutation_in.
+ * exact (Permutation_sym Hallocation_permutation).
+ * exact Hin.
+ - exact Hfrontier_capacity.
+ - exact Hsequences.
+ - exact Hterm_bijection.
+ - exact Hterm_bound.
+ - exact Hdisabled.
+Qed.
+
+Lemma different_id_survives_middle_entry_removal :
+ forall (P : CertifiedAtomProfile) (I : FixedWidthCarrierProfile)
+ (prefix suffix : list (VocabularyEntry P I))
+ atom id removed_atom removed_id,
+ In (atom, id) (prefix ++ (removed_atom, removed_id) :: suffix) ->
+ id <> removed_id ->
+ In (atom, id) (prefix ++ suffix).
+Proof.
+ intros P I prefix suffix atom id removed_atom removed_id Hin Hdifferent.
+ apply in_app_or in Hin. apply in_or_app.
+ destruct Hin as [Hprefix | Htail].
+ - now left.
+ - simpl in Htail. destruct Htail as [Hremoved | Hsuffix].
+ + exfalso. apply Hdifferent.
+ apply (f_equal snd) in Hremoved. now symmetry.
+ + now right.
+Qed.
+
+Lemma different_id_middle_entry_membership_iff :
+ forall (P : CertifiedAtomProfile) (I : FixedWidthCarrierProfile)
+ (prefix suffix : list (VocabularyEntry P I))
+ atom id removed_atom removed_id,
+ id <> removed_id ->
+ (In (atom, id) (prefix ++ (removed_atom, removed_id) :: suffix) <->
+ In (atom, id) (prefix ++ suffix)).
+Proof.
+ intros P I prefix suffix atom id removed_atom removed_id Hdifferent.
+ split.
+ - intros Hin.
+ exact (different_id_survives_middle_entry_removal
+ P I prefix suffix atom id removed_atom removed_id Hin Hdifferent).
+ - intros Hin.
+ apply in_app_or in Hin. apply in_or_app.
+ destruct Hin as [Hprefix | Hsuffix].
+ + now left.
+ + right. simpl. now right.
+Qed.
+
+Lemma different_id_cons_entry_membership_iff :
+ forall (P : CertifiedAtomProfile) (I : FixedWidthCarrierProfile)
+ (entries : list (VocabularyEntry P I))
+ atom id inserted_atom inserted_id,
+ id <> inserted_id ->
+ (In (atom, id) ((inserted_atom, inserted_id) :: entries) <->
+ In (atom, id) entries).
+Proof.
+ intros P I entries atom id inserted_atom inserted_id Hdifferent.
+ simpl. split.
+ - intros [Hequal | Hin].
+ + exfalso. apply Hdifferent.
+ apply (f_equal snd) in Hequal. now symmetry.
+ + exact Hin.
+ - now right.
+Qed.
+
+Definition tombstone_published_allocation
+ {P : CertifiedAtomProfile}
+ {I T : FixedWidthCarrierProfile}
+ (state : InterningState P I T)
+ (atom : CanonicalAtom P)
+ (id : SymbolId I)
+ (updated : InterningState P I T) : Prop :=
+ exists prefix suffix,
+ state_live_entries P I T state =
+ prefix ++ (atom, id) :: suffix /\
+ Forall (fun sequence => ~ In id sequence)
+ (state_sequences P I T state) /\
+ Forall (fun entry => ~ In id (fst entry))
+ (state_term_entries P I T state) /\
+ updated =
+ {| state_fiber := state_fiber P I T state;
+ state_term_fiber := state_term_fiber P I T state;
+ state_reserved_entries := state_reserved_entries P I T state;
+ state_claimed_entries := state_claimed_entries P I T state;
+ state_live_entries := prefix ++ suffix;
+ state_ever_entries := state_ever_entries P I T state;
+ state_orphan_entries := state_orphan_entries P I T state;
+ state_unmaterialized_orphan_entries :=
+ state_unmaterialized_orphan_entries P I T state;
+ state_packed_storage := state_packed_storage P I T state;
+ state_allocator_frontier := state_allocator_frontier P I T state;
+ state_sequences := state_sequences P I T state;
+ state_term_dictionary_enabled :=
+ state_term_dictionary_enabled P I T state;
+ state_term_entries := state_term_entries P I T state |}.
+
+Lemma tombstone_published_allocation_preserves_combined_state_well_formedness :
+ forall (P : CertifiedAtomProfile) (I T : FixedWidthCarrierProfile)
+ (state updated : InterningState P I T) atom id,
+ InterningStateWellFormed state ->
+ tombstone_published_allocation state atom id updated ->
+ InterningStateWellFormed updated.
+Proof.
+ intros P I T state updated atom id Hwell Htombstone.
+ destruct Hwell as
+ [[Hlive_atoms Hlive_ids] Hhistory_bijection Hlive_history
+ Hallocation_unique Hpacked Hallocations_below Hfrontier_capacity
+ Hsequences Hterm_bijection Hterm_bound Hdisabled].
+ destruct Htombstone as
+ [prefix [suffix
+ [Hlive [Hsequence_excludes [Hterm_excludes Hupdated]]]]].
+ subst updated.
+ constructor; simpl.
+ - split.
+ + rewrite Hlive in Hlive_atoms.
+ rewrite map_app in Hlive_atoms. simpl in Hlive_atoms.
+ rewrite map_app.
+ apply NoDup_remove_1 with (a := atom). exact Hlive_atoms.
+ + rewrite Hlive in Hlive_ids.
+ rewrite map_app in Hlive_ids. simpl in Hlive_ids.
+ rewrite map_app.
+ apply NoDup_remove_1 with (a := id). exact Hlive_ids.
+ - exact Hhistory_bijection.
+ - intros live_atom live_id Hin.
+ apply Hlive_history. rewrite Hlive.
+ apply in_or_app. apply in_app_or in Hin.
+ destruct Hin as [Hprefix | Hsuffix].
+ + now left.
+ + right. simpl. now right.
+ - exact Hallocation_unique.
+ - exact Hpacked.
+ - exact Hallocations_below.
+ - exact Hfrontier_capacity.
+ - apply Forall_forall. intros sequence Hin_sequence.
+ apply Forall_forall with (x := sequence) in Hsequences;
+ [| exact Hin_sequence].
+ apply Forall_forall with (x := sequence) in Hsequence_excludes;
+ [| exact Hin_sequence].
+ apply Forall_forall. intros sequence_id Hin_id.
+ apply Forall_forall with (x := sequence_id) in Hsequences;
+ [| exact Hin_id].
+ destruct Hsequences as [Hbelow [live_atom Hlive_entry]].
+ split; [exact Hbelow |]. exists live_atom.
+ eapply different_id_survives_middle_entry_removal.
+ + rewrite Hlive in Hlive_entry. exact Hlive_entry.
+ + intros Hequal. subst sequence_id. contradiction.
+ - exact Hterm_bijection.
+ - apply Forall_forall. intros entry Hin_entry.
+ apply Forall_forall with (x := entry) in Hterm_bound;
+ [| exact Hin_entry].
+ apply Forall_forall with (x := entry) in Hterm_excludes;
+ [| exact Hin_entry].
+ apply Forall_forall. intros term_id Hin_id.
+ apply Forall_forall with (x := term_id) in Hterm_bound;
+ [| exact Hin_id].
+ destruct Hterm_bound as [Hbelow [live_atom Hlive_entry]].
+ split; [exact Hbelow |]. exists live_atom.
+ eapply different_id_survives_middle_entry_removal.
+ + rewrite Hlive in Hlive_entry. exact Hlive_entry.
+ + intros Hequal. subst term_id. contradiction.
+ - exact Hdisabled.
+Qed.
+
+Definition add_dependent_sequence
+ {P : CertifiedAtomProfile}
+ {I T : FixedWidthCarrierProfile}
+ (state : InterningState P I T)
+ (sequence : list (SymbolId I))
+ (updated : InterningState P I T) : Prop :=
+ sequence_vocabulary_bound
+ (state_live_entries P I T state)
+ (state_allocator_frontier P I T state)
+ sequence /\
+ updated =
+ {| state_fiber := state_fiber P I T state;
+ state_term_fiber := state_term_fiber P I T state;
+ state_reserved_entries := state_reserved_entries P I T state;
+ state_claimed_entries := state_claimed_entries P I T state;
+ state_live_entries := state_live_entries P I T state;
+ state_ever_entries := state_ever_entries P I T state;
+ state_orphan_entries := state_orphan_entries P I T state;
+ state_unmaterialized_orphan_entries :=
+ state_unmaterialized_orphan_entries P I T state;
+ state_packed_storage := state_packed_storage P I T state;
+ state_allocator_frontier := state_allocator_frontier P I T state;
+ state_sequences := sequence :: state_sequences P I T state;
+ state_term_dictionary_enabled :=
+ state_term_dictionary_enabled P I T state;
+ state_term_entries := state_term_entries P I T state |}.
+
+Lemma add_dependent_sequence_preserves_combined_state_well_formedness :
+ forall (P : CertifiedAtomProfile) (I T : FixedWidthCarrierProfile)
+ (state updated : InterningState P I T) sequence,
+ InterningStateWellFormed state ->
+ add_dependent_sequence state sequence updated ->
+ InterningStateWellFormed updated.
+Proof.
+ intros P I T state updated sequence Hwell [Hbound Hupdated].
+ subst updated. destruct Hwell.
+ constructor; simpl; try assumption.
+ now constructor.
+Qed.
+
+Definition enable_term_dictionary
+ {P : CertifiedAtomProfile}
+ {I T : FixedWidthCarrierProfile}
+ (state updated : InterningState P I T) : Prop :=
+ updated =
+ {| state_fiber := state_fiber P I T state;
+ state_term_fiber := state_term_fiber P I T state;
+ state_reserved_entries := state_reserved_entries P I T state;
+ state_claimed_entries := state_claimed_entries P I T state;
+ state_live_entries := state_live_entries P I T state;
+ state_ever_entries := state_ever_entries P I T state;
+ state_orphan_entries := state_orphan_entries P I T state;
+ state_unmaterialized_orphan_entries :=
+ state_unmaterialized_orphan_entries P I T state;
+ state_packed_storage := state_packed_storage P I T state;
+ state_allocator_frontier := state_allocator_frontier P I T state;
+ state_sequences := state_sequences P I T state;
+ state_term_dictionary_enabled := true;
+ state_term_entries := state_term_entries P I T state |}.
+
+Lemma enable_term_dictionary_preserves_combined_state_well_formedness :
+ forall (P : CertifiedAtomProfile) (I T : FixedWidthCarrierProfile)
+ (state updated : InterningState P I T),
+ InterningStateWellFormed state ->
+ enable_term_dictionary state updated ->
+ InterningStateWellFormed updated.
+Proof.
+ intros P I T state updated Hwell Hupdated.
+ unfold enable_term_dictionary in Hupdated.
+ subst updated. destruct Hwell.
+ constructor; simpl; try assumption.
+ discriminate.
+Qed.
+
+Definition disable_empty_term_dictionary
+ {P : CertifiedAtomProfile}
+ {I T : FixedWidthCarrierProfile}
+ (state updated : InterningState P I T) : Prop :=
+ state_term_entries P I T state = [] /\
+ updated =
+ {| state_fiber := state_fiber P I T state;
+ state_term_fiber := state_term_fiber P I T state;
+ state_reserved_entries := state_reserved_entries P I T state;
+ state_claimed_entries := state_claimed_entries P I T state;
+ state_live_entries := state_live_entries P I T state;
+ state_ever_entries := state_ever_entries P I T state;
+ state_orphan_entries := state_orphan_entries P I T state;
+ state_unmaterialized_orphan_entries :=
+ state_unmaterialized_orphan_entries P I T state;
+ state_packed_storage := state_packed_storage P I T state;
+ state_allocator_frontier := state_allocator_frontier P I T state;
+ state_sequences := state_sequences P I T state;
+ state_term_dictionary_enabled := false;
+ state_term_entries := state_term_entries P I T state |}.
+
+Lemma disable_empty_term_dictionary_preserves_combined_state_well_formedness :
+ forall (P : CertifiedAtomProfile) (I T : FixedWidthCarrierProfile)
+ (state updated : InterningState P I T),
+ InterningStateWellFormed state ->
+ disable_empty_term_dictionary state updated ->
+ InterningStateWellFormed updated.
+Proof.
+ intros P I T state updated Hwell [Hempty Hupdated].
+ subst updated. destruct Hwell.
+ constructor; simpl; try assumption.
+ intros _. exact Hempty.
+Qed.
+
+Lemma term_insert_preserves_well_formedness :
+ forall (I T : FixedWidthCarrierProfile)
+ (entries : list (TermEntry I T)) sequence term_id,
+ term_relation_well_formed entries ->
+ lookup_term_sequence entries sequence = None ->
+ lookup_term_id entries term_id = None ->
+ term_relation_well_formed ((sequence, term_id) :: entries).
+Proof.
+ intros I T entries sequence term_id
+ [Hsequence_unique Hid_unique] Hsequence Hid.
+ split; simpl; constructor.
+ - unfold lookup_term_sequence in Hsequence.
+ now apply assoc_lookup_none_key_absent in Hsequence.
+ - exact Hsequence_unique.
+ - unfold lookup_term_id in Hid.
+ apply assoc_lookup_none_key_absent in Hid.
+ rewrite reverse_term_keys_are_term_ids in Hid. exact Hid.
+ - exact Hid_unique.
+Qed.
+
+Definition insert_term_dictionary_entry
+ {P : CertifiedAtomProfile}
+ {I T : FixedWidthCarrierProfile}
+ (state : InterningState P I T)
+ (sequence : list (SymbolId I))
+ (term_id : TermId T)
+ (updated : InterningState P I T) : Prop :=
+ state_term_dictionary_enabled P I T state = true /\
+ sequence_vocabulary_bound
+ (state_live_entries P I T state)
+ (state_allocator_frontier P I T state)
+ sequence /\
+ lookup_term_sequence (state_term_entries P I T state) sequence = None /\
+ lookup_term_id (state_term_entries P I T state) term_id = None /\
+ updated =
+ {| state_fiber := state_fiber P I T state;
+ state_term_fiber := state_term_fiber P I T state;
+ state_reserved_entries := state_reserved_entries P I T state;
+ state_claimed_entries := state_claimed_entries P I T state;
+ state_live_entries := state_live_entries P I T state;
+ state_ever_entries := state_ever_entries P I T state;
+ state_orphan_entries := state_orphan_entries P I T state;
+ state_unmaterialized_orphan_entries :=
+ state_unmaterialized_orphan_entries P I T state;
+ state_packed_storage := state_packed_storage P I T state;
+ state_allocator_frontier := state_allocator_frontier P I T state;
+ state_sequences := state_sequences P I T state;
+ state_term_dictionary_enabled := true;
+ state_term_entries :=
+ (sequence, term_id) :: state_term_entries P I T state |}.
+
+Lemma insert_term_dictionary_entry_preserves_combined_state_well_formedness :
+ forall (P : CertifiedAtomProfile) (I T : FixedWidthCarrierProfile)
+ (state updated : InterningState P I T) sequence term_id,
+ InterningStateWellFormed state ->
+ insert_term_dictionary_entry state sequence term_id updated ->
+ InterningStateWellFormed updated.
+Proof.
+ intros P I T state updated sequence term_id Hwell
+ [Henabled [Hbound [Hsequence [Hid Hupdated]]]].
+ subst updated.
+ destruct Hwell as
+ [Hlive_bijection Hhistory_bijection Hlive_history
+ Hallocation_unique Hpacked Hallocations_below Hfrontier_capacity
+ Hsequences Hterm_bijection Hterm_bound Hdisabled].
+ constructor; simpl; try assumption.
+ - now apply term_insert_preserves_well_formedness.
+ - now constructor.
+ - discriminate.
+Qed.
+
+Lemma fresh_publication_preserves_combined_state_well_formedness :
+ forall (P : CertifiedAtomProfile) (I T : FixedWidthCarrierProfile)
+ (state updated : InterningState P I T)
+ (atom : CanonicalAtom P) (id : SymbolId I),
+ InterningStateWellFormed state ->
+ publish_fresh_atom state atom id = Some updated ->
+ InterningStateWellFormed updated.
+Proof.
+ intros P I T state updated atom id Hwell Hpublish.
+ destruct Hwell as
+ [Hlive_bijection Hhistory_bijection Hlive_history
+ Halloc_unique Hpacked Halloc_below Hfrontier_capacity
+ Hsequences Hterm_bijection Hterm_bound Hdisabled].
+ unfold publish_fresh_atom in Hpublish.
+ destruct (lookup_atom (state_ever_entries P I T state) atom)
+ as [existing_atom_id |] eqn:Hatom; [discriminate |].
+ destruct (lookup_symbol (state_ever_entries P I T state) id)
+ as [existing_atom |] eqn:Hid; [discriminate |].
+ destruct (Nat.leb
+ (state_allocator_frontier P I T state)
+ (symbol_id_value I id)) eqn:Hfrontier; [| discriminate].
+ apply Nat.leb_le in Hfrontier.
+ destruct (append_packed_atom
+ (state_packed_storage P I T state) id atom)
+ as [packed |] eqn:Happend; [| discriminate].
+ inversion Hpublish. subst updated. clear Hpublish.
+ assert (Hid_history_absent :
+ ~ In id (map snd (state_ever_entries P I T state))).
+ { unfold lookup_symbol in Hid.
+ apply assoc_lookup_none_key_absent in Hid.
+ rewrite reverse_vocabulary_keys_are_ids in Hid. exact Hid. }
+ assert (Hatom_history_absent :
+ ~ In atom (map fst (state_ever_entries P I T state))).
+ { unfold lookup_atom in Hatom.
+ now apply assoc_lookup_none_key_absent in Hatom. }
+ assert (Hid_allocation_absent :
+ ~ In id (map snd (state_allocation_entries state))).
+ { intros Hin.
+ apply in_map_iff in Hin.
+ destruct Hin as [[allocated_atom allocated_id] [Hequal Hin]].
+ simpl in Hequal. subst allocated_id.
+ apply Forall_forall with
+ (x := (allocated_atom, id)) in Halloc_below; [| exact Hin].
+ simpl in Halloc_below. lia. }
+ assert (Hspan_none :
+ lookup_span (state_packed_storage P I T state) id = None).
+ { unfold append_packed_atom in Happend.
+ destruct (lookup_span (state_packed_storage P I T state) id);
+ [discriminate | reflexivity]. }
+ assert (Hid_materialized_absent :
+ ~ In id (map snd (state_materialized_entries state))).
+ { intros Hin.
+ destruct (allocated_id_has_exact_span
+ P I (state_materialized_entries state)
+ (state_packed_storage P I T state) id Hpacked Hin)
+ as [allocated_atom [span [_ Hlookup]]].
+ rewrite Hspan_none in Hlookup. discriminate. }
+ assert (Hatom_live_none :
+ lookup_atom (state_live_entries P I T state) atom = None).
+ { destruct (lookup_atom (state_live_entries P I T state) atom)
+ as [live_id |] eqn:Hlive_lookup; [| reflexivity].
+ exfalso. apply Hatom_history_absent.
+ unfold lookup_atom in Hlive_lookup.
+ apply assoc_lookup_sound in Hlive_lookup.
+ apply in_map_iff.
+ exists (atom, live_id). split; [reflexivity |].
+ now apply Hlive_history. }
+ assert (Hid_live_none :
+ lookup_symbol (state_live_entries P I T state) id = None).
+ { destruct (lookup_symbol (state_live_entries P I T state) id)
+ as [live_atom |] eqn:Hlive_lookup; [| reflexivity].
+ exfalso. apply Hid_history_absent.
+ unfold lookup_symbol in Hlive_lookup.
+ apply assoc_lookup_sound in Hlive_lookup.
+ apply reverse_vocabulary_membership in Hlive_lookup.
+ apply in_map_iff.
+ exists (live_atom, id). split; [reflexivity |].
+ now apply Hlive_history. }
+ constructor; simpl.
+ - apply vocabulary_insert_preserves_well_formedness.
+ + exact Hlive_bijection.
+ + exact Hatom_live_none.
+ + exact Hid_live_none.
+ - now apply vocabulary_insert_preserves_well_formedness.
+ - intros live_atom live_id Hin.
+ simpl in Hin. destruct Hin as [Hnew | Hold].
+ + inversion Hnew. now left.
+ + right. now apply Hlive_history.
+ - constructor.
+ + exact Hid_allocation_absent.
+ + exact Halloc_unique.
+ - eapply (packed_storage_matches_allocations_after_append
+ P I
+ (state_materialized_entries state)
+ (state_packed_storage P I T state)
+ packed atom id).
+ + exact Hpacked.
+ + exact Hid_materialized_absent.
+ + exact Happend.
+ - constructor.
+ + simpl. lia.
+ + apply Forall_forall. intros entry Hin.
+ apply Forall_forall with (x := entry) in Halloc_below;
+ [| exact Hin].
+ lia.
+ - pose proof (symbol_id_in_range I id). lia.
+ - apply Forall_forall. intros sequence Hin.
+ apply Forall_forall with (x := sequence) in Hsequences;
+ [| exact Hin].
+ eapply sequence_bound_monotone; [| | exact Hsequences].
+ + intros live_atom live_id Hlive. now right.
+ + lia.
+ - exact Hterm_bijection.
+ - apply Forall_forall. intros entry Hin.
+ apply Forall_forall with (x := entry) in Hterm_bound;
+ [| exact Hin].
+ eapply sequence_bound_monotone; [| | exact Hterm_bound].
+ + intros live_atom live_id Hlive. now right.
+ + lia.
+ - exact Hdisabled.
+Qed.
+
+Inductive InterningTransition
+ {P : CertifiedAtomProfile}
+ {I T : FixedWidthCarrierProfile}
+ : InterningState P I T -> InterningState P I T -> Prop :=
+| TransitionFreshPublication :
+ forall state updated atom id,
+ publish_fresh_atom state atom id = Some updated ->
+ InterningTransition state updated
+| TransitionClaimAllocation :
+ forall state updated atom id,
+ claim_atom_allocation state atom id = Some updated ->
+ InterningTransition state updated
+| TransitionMaterializeReservation :
+ forall state updated atom id,
+ materialize_reserved_allocation state atom id updated ->
+ InterningTransition state updated
+| TransitionPublishClaim :
+ forall state updated atom id,
+ publish_claimed_allocation state atom id updated ->
+ InterningTransition state updated
+| TransitionOrphanClaim :
+ forall state updated atom id,
+ orphan_claimed_allocation state atom id updated ->
+ InterningTransition state updated
+| TransitionOrphanReservation :
+ forall state updated atom id,
+ orphan_reserved_allocation state atom id updated ->
+ InterningTransition state updated
+| TransitionTombstonePublished :
+ forall state updated atom id,
+ tombstone_published_allocation state atom id updated ->
+ InterningTransition state updated
+| TransitionAddDependentSequence :
+ forall state updated sequence,
+ add_dependent_sequence state sequence updated ->
+ InterningTransition state updated
+| TransitionEnableTermDictionary :
+ forall state updated,
+ enable_term_dictionary state updated ->
+ InterningTransition state updated
+| TransitionDisableEmptyTermDictionary :
+ forall state updated,
+ disable_empty_term_dictionary state updated ->
+ InterningTransition state updated
+| TransitionInsertTermEntry :
+ forall state updated sequence term_id,
+ insert_term_dictionary_entry state sequence term_id updated ->
+ InterningTransition state updated.
+
+Theorem VWENC_132_EVERY_INTERNING_TRANSITION_PRESERVES_COMBINED_STATE_WELL_FORMEDNESS :
+ forall (P : CertifiedAtomProfile) (I T : FixedWidthCarrierProfile)
+ (state updated : InterningState P I T),
+ InterningStateWellFormed state ->
+ InterningTransition state updated ->
+ InterningStateWellFormed updated.
+Proof.
+ intros P I T state updated Hwell Htransition.
+ inversion Htransition; subst;
+ eauto using
+ fresh_publication_preserves_combined_state_well_formedness,
+ claim_atom_allocation_preserves_combined_state_well_formedness,
+ materialize_reserved_allocation_preserves_combined_state_well_formedness,
+ publish_claimed_allocation_preserves_combined_state_well_formedness,
+ orphan_claimed_allocation_preserves_combined_state_well_formedness,
+ orphan_reserved_allocation_preserves_combined_state_well_formedness,
+ tombstone_published_allocation_preserves_combined_state_well_formedness,
+ add_dependent_sequence_preserves_combined_state_well_formedness,
+ enable_term_dictionary_preserves_combined_state_well_formedness,
+ disable_empty_term_dictionary_preserves_combined_state_well_formedness,
+ insert_term_dictionary_entry_preserves_combined_state_well_formedness.
+Qed.
+
+(** ** Exact allocation transition algebra *)
+
+Inductive AllocationPhase (P : CertifiedAtomProfile) : Type :=
+| PhaseUnallocated
+| PhaseAllocated : CanonicalAtom P -> AllocationStatus -> AllocationPhase P.
+
+Definition allocation_phase_matches
+ {P : CertifiedAtomProfile}
+ {I T : FixedWidthCarrierProfile}
+ (state : InterningState P I T)
+ (id : SymbolId I)
+ (phase : AllocationPhase P) : Prop :=
+ match phase with
+ | PhaseUnallocated _ =>
+ forall atom status,
+ ~ allocation_status_category state atom id status
+ | PhaseAllocated _ atom status =>
+ allocation_status_category state atom id status
+ end.
+
+Inductive LegalAllocationEdge (P : CertifiedAtomProfile)
+ : AllocationPhase P -> AllocationPhase P -> Prop :=
+| EdgeFreshToReserved :
+ forall atom,
+ LegalAllocationEdge P
+ (PhaseUnallocated P)
+ (PhaseAllocated P atom AllocationReserved)
+| EdgeFreshToPublished :
+ forall atom,
+ LegalAllocationEdge P
+ (PhaseUnallocated P)
+ (PhaseAllocated P atom AllocationPublished)
+| EdgeReservedToMaterializedClaimed :
+ forall atom,
+ LegalAllocationEdge P
+ (PhaseAllocated P atom AllocationReserved)
+ (PhaseAllocated P atom AllocationMaterializedClaimed)
+| EdgeReservedToUnmaterializedOrphan :
+ forall atom,
+ LegalAllocationEdge P
+ (PhaseAllocated P atom AllocationReserved)
+ (PhaseAllocated P atom AllocationUnmaterializedOrphaned)
+| EdgeMaterializedClaimedToPublished :
+ forall atom,
+ LegalAllocationEdge P
+ (PhaseAllocated P atom AllocationMaterializedClaimed)
+ (PhaseAllocated P atom AllocationPublished)
+| EdgeMaterializedClaimedToMaterializedOrphan :
+ forall atom,
+ LegalAllocationEdge P
+ (PhaseAllocated P atom AllocationMaterializedClaimed)
+ (PhaseAllocated P atom AllocationMaterializedOrphaned)
+| EdgePublishedToTombstoned :
+ forall atom,
+ LegalAllocationEdge P
+ (PhaseAllocated P atom AllocationPublished)
+ (PhaseAllocated P atom AllocationTombstoned).
+
+Inductive AllocationDelta
+ {P : CertifiedAtomProfile}
+ {I T : FixedWidthCarrierProfile}
+ (state updated : InterningState P I T) : Prop :=
+| AllocationDeltaNone :
+ (forall atom id status,
+ allocation_status_category state atom id status <->
+ allocation_status_category updated atom id status) ->
+ AllocationDelta state updated
+| AllocationDeltaOne :
+ forall id before after,
+ LegalAllocationEdge P before after ->
+ allocation_phase_matches state id before ->
+ allocation_phase_matches updated id after ->
+ (forall other_atom other_id status,
+ other_id <> id ->
+ (allocation_status_category state other_atom other_id status <->
+ allocation_status_category updated other_atom other_id status)) ->
+ AllocationDelta state updated.
+
+Lemma allocation_category_preserved_by_exact_components :
+ forall (P : CertifiedAtomProfile) (I T : FixedWidthCarrierProfile)
+ (state updated : InterningState P I T) atom id,
+ (In (atom, id) (state_reserved_entries P I T state) <->
+ In (atom, id) (state_reserved_entries P I T updated)) ->
+ (In (atom, id) (state_claimed_entries P I T state) <->
+ In (atom, id) (state_claimed_entries P I T updated)) ->
+ (In (atom, id) (state_live_entries P I T state) <->
+ In (atom, id) (state_live_entries P I T updated)) ->
+ (In (atom, id) (state_ever_entries P I T state) <->
+ In (atom, id) (state_ever_entries P I T updated)) ->
+ (In (atom, id) (state_orphan_entries P I T state) <->
+ In (atom, id) (state_orphan_entries P I T updated)) ->
+ (In (atom, id)
+ (state_unmaterialized_orphan_entries P I T state) <->
+ In (atom, id)
+ (state_unmaterialized_orphan_entries P I T updated)) ->
+ forall status,
+ allocation_status_category state atom id status <->
+ allocation_status_category updated atom id status.
+Proof.
+ intros P I T state updated atom id
+ Hreserved Hclaimed Hlive Hever Horphan Hunmaterialized status.
+ destruct status; simpl in *; tauto.
+Qed.
+
+Lemma allocation_above_frontier_is_unallocated :
+ forall (P : CertifiedAtomProfile) (I T : FixedWidthCarrierProfile)
+ (state : InterningState P I T) id,
+ InterningStateWellFormed state ->
+ state_allocator_frontier P I T state <= symbol_id_value I id ->
+ allocation_phase_matches state id (PhaseUnallocated P).
+Proof.
+ intros P I T state id Hwell Habove atom status Hcategory.
+ apply allocation_status_category_entry_is_allocated in Hcategory.
+ pose proof (state_allocations_below_sparse_frontier state Hwell)
+ as Hbelow.
+ apply Forall_forall with (x := (atom, id)) in Hbelow;
+ [simpl in Hbelow; lia | exact Hcategory].
+Qed.
+
+Theorem VWENC_191_TERMINAL_ALLOCATION_PHASES_HAVE_NO_LEGAL_OUTBOUND_EDGE :
+ forall (P : CertifiedAtomProfile) atom after,
+ (~ LegalAllocationEdge P
+ (PhaseAllocated P atom AllocationTombstoned) after) /\
+ (~ LegalAllocationEdge P
+ (PhaseAllocated P atom AllocationMaterializedOrphaned) after) /\
+ (~ LegalAllocationEdge P
+ (PhaseAllocated P atom AllocationUnmaterializedOrphaned) after).
+Proof.
+ intros P atom after. repeat split; intros Hedge; inversion Hedge.
+Qed.
+
+Lemma fresh_publication_has_exact_allocation_delta :
+ forall (P : CertifiedAtomProfile) (I T : FixedWidthCarrierProfile)
+ (state updated : InterningState P I T) atom id,
+ InterningStateWellFormed state ->
+ publish_fresh_atom state atom id = Some updated ->
+ AllocationDelta state updated.
+Proof.
+ intros P I T state updated atom id Hwell Hpublish.
+ unfold publish_fresh_atom in Hpublish.
+ destruct (lookup_atom (state_ever_entries P I T state) atom);
+ [discriminate |].
+ destruct (lookup_symbol (state_ever_entries P I T state) id);
+ [discriminate |].
+ destruct (Nat.leb
+ (state_allocator_frontier P I T state)
+ (symbol_id_value I id)) eqn:Hfrontier; [| discriminate].
+ destruct (append_packed_atom
+ (state_packed_storage P I T state) id atom)
+ as [packed |] eqn:Happend; [| discriminate].
+ inversion Hpublish. subst updated. clear Hpublish.
+ eapply AllocationDeltaOne
+ with
+ (id := id)
+ (before := PhaseUnallocated P)
+ (after := PhaseAllocated P atom AllocationPublished).
+ - apply EdgeFreshToPublished.
+ - apply allocation_above_frontier_is_unallocated; [exact Hwell |].
+ now apply Nat.leb_le.
+ - simpl. split; now left.
+ - intros other_atom other_id status Hother.
+ eapply allocation_category_preserved_by_exact_components;
+ simpl; try tauto.
+ + symmetry. now apply different_id_cons_entry_membership_iff.
+ + symmetry. now apply different_id_cons_entry_membership_iff.
+Qed.
+
+Lemma claim_allocation_has_exact_allocation_delta :
+ forall (P : CertifiedAtomProfile) (I T : FixedWidthCarrierProfile)
+ (state updated : InterningState P I T) atom id,
+ InterningStateWellFormed state ->
+ claim_atom_allocation state atom id = Some updated ->
+ AllocationDelta state updated.
+Proof.
+ intros P I T state updated atom id Hwell Hclaim.
+ unfold claim_atom_allocation in Hclaim.
+ destruct (lookup_atom (state_ever_entries P I T state) atom);
+ [discriminate |].
+ destruct (Nat.leb
+ (state_allocator_frontier P I T state)
+ (symbol_id_value I id)) eqn:Hfrontier; [| discriminate].
+ inversion Hclaim. subst updated. clear Hclaim.
+ eapply AllocationDeltaOne
+ with
+ (id := id)
+ (before := PhaseUnallocated P)
+ (after := PhaseAllocated P atom AllocationReserved).
+ - apply EdgeFreshToReserved.
+ - apply allocation_above_frontier_is_unallocated; [exact Hwell |].
+ now apply Nat.leb_le.
+ - simpl. now left.
+ - intros other_atom other_id status Hother.
+ eapply allocation_category_preserved_by_exact_components;
+ simpl; try tauto.
+ symmetry. now apply different_id_cons_entry_membership_iff.
+Qed.
+
+Lemma materialize_reservation_has_exact_allocation_delta :
+ forall (P : CertifiedAtomProfile) (I T : FixedWidthCarrierProfile)
+ (state updated : InterningState P I T) atom id,
+ InterningStateWellFormed state ->
+ materialize_reserved_allocation state atom id updated ->
+ AllocationDelta state updated.
+Proof.
+ intros P I T state updated atom id Hwell Hmaterialize.
+ destruct Hmaterialize as
+ [prefix [suffix [packed [Hreserved [Happend Hupdated]]]]].
+ subst updated.
+ eapply AllocationDeltaOne
+ with
+ (id := id)
+ (before := PhaseAllocated P atom AllocationReserved)
+ (after := PhaseAllocated P atom AllocationMaterializedClaimed).
+ - apply EdgeReservedToMaterializedClaimed.
+ - simpl. rewrite Hreserved. apply in_or_app. right. now left.
+ - simpl. now left.
+ - intros other_atom other_id status Hother.
+ eapply allocation_category_preserved_by_exact_components; simpl; try tauto.
+ + rewrite Hreserved.
+ now apply different_id_middle_entry_membership_iff.
+ + symmetry. now apply different_id_cons_entry_membership_iff.
+Qed.
+
+Lemma orphan_reservation_has_exact_allocation_delta :
+ forall (P : CertifiedAtomProfile) (I T : FixedWidthCarrierProfile)
+ (state updated : InterningState P I T) atom id,
+ InterningStateWellFormed state ->
+ orphan_reserved_allocation state atom id updated ->
+ AllocationDelta state updated.
+Proof.
+ intros P I T state updated atom id Hwell Horphan.
+ destruct Horphan as [prefix [suffix [Hreserved Hupdated]]].
+ subst updated.
+ eapply AllocationDeltaOne
+ with
+ (id := id)
+ (before := PhaseAllocated P atom AllocationReserved)
+ (after :=
+ PhaseAllocated P atom AllocationUnmaterializedOrphaned).
+ - apply EdgeReservedToUnmaterializedOrphan.
+ - simpl. rewrite Hreserved. apply in_or_app. right. now left.
+ - simpl. now left.
+ - intros other_atom other_id status Hother.
+ eapply allocation_category_preserved_by_exact_components; simpl; try tauto.
+ + rewrite Hreserved.
+ now apply different_id_middle_entry_membership_iff.
+ + symmetry. now apply different_id_cons_entry_membership_iff.
+Qed.
+
+Lemma publish_claim_has_exact_allocation_delta :
+ forall (P : CertifiedAtomProfile) (I T : FixedWidthCarrierProfile)
+ (state updated : InterningState P I T) atom id,
+ InterningStateWellFormed state ->
+ publish_claimed_allocation state atom id updated ->
+ AllocationDelta state updated.
+Proof.
+ intros P I T state updated atom id Hwell Hpublish.
+ destruct Hpublish as
+ [prefix [suffix
+ [Hclaimed [_ [_ [_ [_ Hupdated]]]]]]].
+ subst updated.
+ eapply AllocationDeltaOne
+ with
+ (id := id)
+ (before := PhaseAllocated P atom AllocationMaterializedClaimed)
+ (after := PhaseAllocated P atom AllocationPublished).
+ - apply EdgeMaterializedClaimedToPublished.
+ - simpl. rewrite Hclaimed. apply in_or_app. right. now left.
+ - simpl. split; now left.
+ - intros other_atom other_id status Hother.
+ eapply allocation_category_preserved_by_exact_components; simpl; try tauto.
+ + rewrite Hclaimed.
+ now apply different_id_middle_entry_membership_iff.
+ + symmetry. now apply different_id_cons_entry_membership_iff.
+ + symmetry. now apply different_id_cons_entry_membership_iff.
+Qed.
+
+Lemma orphan_claim_has_exact_allocation_delta :
+ forall (P : CertifiedAtomProfile) (I T : FixedWidthCarrierProfile)
+ (state updated : InterningState P I T) atom id,
+ InterningStateWellFormed state ->
+ orphan_claimed_allocation state atom id updated ->
+ AllocationDelta state updated.
+Proof.
+ intros P I T state updated atom id Hwell Horphan.
+ destruct Horphan as [prefix [suffix [Hclaimed Hupdated]]].
+ subst updated.
+ eapply AllocationDeltaOne
+ with
+ (id := id)
+ (before := PhaseAllocated P atom AllocationMaterializedClaimed)
+ (after := PhaseAllocated P atom AllocationMaterializedOrphaned).
+ - apply EdgeMaterializedClaimedToMaterializedOrphan.
+ - simpl. rewrite Hclaimed. apply in_or_app. right. now left.
+ - simpl. now left.
+ - intros other_atom other_id status Hother.
+ eapply allocation_category_preserved_by_exact_components; simpl; try tauto.
+ + rewrite Hclaimed.
+ now apply different_id_middle_entry_membership_iff.
+ + symmetry. now apply different_id_cons_entry_membership_iff.
+Qed.
+
+Lemma tombstone_publication_has_exact_allocation_delta :
+ forall (P : CertifiedAtomProfile) (I T : FixedWidthCarrierProfile)
+ (state updated : InterningState P I T) atom id,
+ InterningStateWellFormed state ->
+ tombstone_published_allocation state atom id updated ->
+ AllocationDelta state updated.
+Proof.
+ intros P I T state updated atom id Hwell Htombstone.
+ destruct Htombstone as
+ [prefix [suffix
+ [Hlive [_ [_ Hupdated]]]]].
+ assert (Hever : In (atom, id) (state_ever_entries P I T state)).
+ { apply (state_live_is_historical state Hwell).
+ rewrite Hlive. apply in_or_app. right. now left. }
+ assert (Hnot_remaining : ~ In (atom, id) (prefix ++ suffix)).
+ { pose proof (state_live_bijection state Hwell) as [_ Hlive_ids].
+ rewrite Hlive in Hlive_ids.
+ rewrite map_app in Hlive_ids. simpl in Hlive_ids.
+ intros Hin.
+ assert (Hin_id : In id (map snd prefix ++ map snd suffix)).
+ { rewrite <- map_app. now apply in_map with (f := snd) in Hin. }
+ eapply (NoDup_remove_2
+ (map snd prefix) (map snd suffix) id Hlive_ids).
+ exact Hin_id. }
+ subst updated.
+ eapply AllocationDeltaOne
+ with
+ (id := id)
+ (before := PhaseAllocated P atom AllocationPublished)
+ (after := PhaseAllocated P atom AllocationTombstoned).
+ - apply EdgePublishedToTombstoned.
+ - simpl. split; [| exact Hever].
+ rewrite Hlive. apply in_or_app. right. now left.
+ - simpl. now split; [exact Hever | exact Hnot_remaining].
+ - intros other_atom other_id status Hother.
+ eapply allocation_category_preserved_by_exact_components; simpl; try tauto.
+ rewrite Hlive.
+ now apply different_id_middle_entry_membership_iff.
+Qed.
+
+Lemma add_sequence_has_no_allocation_delta :
+ forall (P : CertifiedAtomProfile) (I T : FixedWidthCarrierProfile)
+ (state updated : InterningState P I T) sequence,
+ add_dependent_sequence state sequence updated ->
+ AllocationDelta state updated.
+Proof.
+ intros P I T state updated sequence [_ Hupdated].
+ subst updated. apply AllocationDeltaNone.
+ intros atom id status. destruct status; reflexivity.
+Qed.
+
+Lemma enable_term_dictionary_has_no_allocation_delta :
+ forall (P : CertifiedAtomProfile) (I T : FixedWidthCarrierProfile)
+ (state updated : InterningState P I T),
+ enable_term_dictionary state updated ->
+ AllocationDelta state updated.
+Proof.
+ intros P I T state updated Hupdated.
+ unfold enable_term_dictionary in Hupdated. subst updated.
+ apply AllocationDeltaNone.
+ intros atom id status. destruct status; reflexivity.
+Qed.
+
+Lemma disable_term_dictionary_has_no_allocation_delta :
+ forall (P : CertifiedAtomProfile) (I T : FixedWidthCarrierProfile)
+ (state updated : InterningState P I T),
+ disable_empty_term_dictionary state updated ->
+ AllocationDelta state updated.
+Proof.
+ intros P I T state updated [_ Hupdated]. subst updated.
+ apply AllocationDeltaNone.
+ intros atom id status. destruct status; reflexivity.
+Qed.
+
+Lemma insert_term_entry_has_no_allocation_delta :
+ forall (P : CertifiedAtomProfile) (I T : FixedWidthCarrierProfile)
+ (state updated : InterningState P I T) sequence term_id,
+ insert_term_dictionary_entry state sequence term_id updated ->
+ AllocationDelta state updated.
+Proof.
+ intros P I T state updated sequence term_id
+ [_ [_ [_ [_ Hupdated]]]].
+ subst updated. apply AllocationDeltaNone.
+ intros atom id status. destruct status; reflexivity.
+Qed.
+
+Theorem VWENC_189_EVERY_INTERNING_TRANSITION_HAS_ONE_EXACT_LEGAL_ALLOCATION_DELTA :
+ forall (P : CertifiedAtomProfile) (I T : FixedWidthCarrierProfile)
+ (state updated : InterningState P I T),
+ InterningStateWellFormed state ->
+ InterningTransition state updated ->
+ AllocationDelta state updated.
+Proof.
+ intros P I T state updated Hwell Htransition.
+ inversion Htransition; subst;
+ eauto using
+ fresh_publication_has_exact_allocation_delta,
+ claim_allocation_has_exact_allocation_delta,
+ materialize_reservation_has_exact_allocation_delta,
+ publish_claim_has_exact_allocation_delta,
+ orphan_claim_has_exact_allocation_delta,
+ orphan_reservation_has_exact_allocation_delta,
+ tombstone_publication_has_exact_allocation_delta,
+ add_sequence_has_no_allocation_delta,
+ enable_term_dictionary_has_no_allocation_delta,
+ disable_term_dictionary_has_no_allocation_delta,
+ insert_term_entry_has_no_allocation_delta.
+Qed.
+
+Theorem VWENC_190_INTERNING_TRANSITIONS_PRESERVE_EVERY_UNAFFECTED_ID_STATUS :
+ forall (P : CertifiedAtomProfile) (I T : FixedWidthCarrierProfile)
+ (state updated : InterningState P I T),
+ InterningStateWellFormed state ->
+ InterningTransition state updated ->
+ (forall atom id status,
+ allocation_status_category state atom id status <->
+ allocation_status_category updated atom id status) \/
+ exists changed_id,
+ forall atom id status,
+ id <> changed_id ->
+ (allocation_status_category state atom id status <->
+ allocation_status_category updated atom id status).
+Proof.
+ intros P I T state updated Hwell Htransition.
+ pose proof
+ (VWENC_189_EVERY_INTERNING_TRANSITION_HAS_ONE_EXACT_LEGAL_ALLOCATION_DELTA
+ P I T state updated Hwell Htransition) as Hdelta.
+ inversion Hdelta as [Hnone | id before after Hedge Hbefore Hafter Hothers];
+ subst.
+ - now left.
+ - right. exists id. exact Hothers.
+Qed.
+
+Inductive InterningReachable
+ (P : CertifiedAtomProfile)
+ (I T : FixedWidthCarrierProfile)
+ (fiber : VocabularyFiber P I)
+ (term_identity term_generation : nat)
+ : InterningState P I T -> Prop :=
+| ReachableInitial :
+ InterningReachable P I T fiber term_identity term_generation
+ (empty_interning_state
+ P I T fiber term_identity term_generation)
+| ReachableStep :
+ forall state updated,
+ InterningReachable
+ P I T fiber term_identity term_generation state ->
+ InterningTransition state updated ->
+ InterningReachable
+ P I T fiber term_identity term_generation updated.
+
+Theorem VWENC_159_EVERY_REACHABLE_INTERNING_STATE_IS_WELL_FORMED :
+ forall (P : CertifiedAtomProfile) (I T : FixedWidthCarrierProfile)
+ (fiber : VocabularyFiber P I) term_identity term_generation state,
+ InterningReachable
+ P I T fiber term_identity term_generation state ->
+ InterningStateWellFormed state.
+Proof.
+ intros P I T fiber term_identity term_generation state Hreachable.
+ induction Hreachable.
+ - apply VWENC_157_EMPTY_INTERNING_STATE_IS_WELL_FORMED.
+ - eapply VWENC_132_EVERY_INTERNING_TRANSITION_PRESERVES_COMBINED_STATE_WELL_FORMEDNESS;
+ eassumption.
+Qed.
+
+Definition WitnessInterningState : Type :=
+ InterningState canonical_uleb_profile u32_carrier u32_carrier.
+
+Definition witness_initial_state : WitnessInterningState :=
+ empty_interning_state
+ canonical_uleb_profile u32_carrier u32_carrier
+ witness_vocabulary_fiber 900 1.
+
+Definition witness_term_fiber :
+ TermDictionaryFiber
+ canonical_uleb_profile u32_carrier u32_carrier
+ witness_vocabulary_fiber :=
+ mkTermDictionaryFiber
+ canonical_uleb_profile u32_carrier u32_carrier
+ witness_vocabulary_fiber 900 1.
+
+Definition witness_packed_zero : PackedAtomStorage u32_carrier :=
+ mkPackedAtomStorage u32_carrier
+ [1]
+ [(symbol_zero, mkByteSpan 0 1)].
+
+Definition witness_reserved_zero : WitnessInterningState :=
+ {| state_fiber := witness_vocabulary_fiber;
+ state_term_fiber := witness_term_fiber;
+ state_reserved_entries := [(collision_atom_left, symbol_zero)];
+ state_claimed_entries := [];
+ state_live_entries := [];
+ state_ever_entries := [];
+ state_orphan_entries := [];
+ state_unmaterialized_orphan_entries := [];
+ state_packed_storage := empty_packed_atom_storage u32_carrier;
+ state_allocator_frontier := 1;
+ state_sequences := [];
+ state_term_dictionary_enabled := false;
+ state_term_entries := [] |}.
+
+Definition witness_materialized_zero : WitnessInterningState :=
+ {| state_fiber := witness_vocabulary_fiber;
+ state_term_fiber := witness_term_fiber;
+ state_reserved_entries := [];
+ state_claimed_entries := [(collision_atom_left, symbol_zero)];
+ state_live_entries := [];
+ state_ever_entries := [];
+ state_orphan_entries := [];
+ state_unmaterialized_orphan_entries := [];
+ state_packed_storage := witness_packed_zero;
+ state_allocator_frontier := 1;
+ state_sequences := [];
+ state_term_dictionary_enabled := false;
+ state_term_entries := [] |}.
+
+Definition witness_live_zero : WitnessInterningState :=
+ {| state_fiber := witness_vocabulary_fiber;
+ state_term_fiber := witness_term_fiber;
+ state_reserved_entries := [];
+ state_claimed_entries := [];
+ state_live_entries := [(collision_atom_left, symbol_zero)];
+ state_ever_entries := [(collision_atom_left, symbol_zero)];
+ state_orphan_entries := [];
+ state_unmaterialized_orphan_entries := [];
+ state_packed_storage := witness_packed_zero;
+ state_allocator_frontier := 1;
+ state_sequences := [];
+ state_term_dictionary_enabled := false;
+ state_term_entries := [] |}.
+
+Definition witness_tombstoned_zero : WitnessInterningState :=
+ {| state_fiber := witness_vocabulary_fiber;
+ state_term_fiber := witness_term_fiber;
+ state_reserved_entries := [];
+ state_claimed_entries := [];
+ state_live_entries := [];
+ state_ever_entries := [(collision_atom_left, symbol_zero)];
+ state_orphan_entries := [];
+ state_unmaterialized_orphan_entries := [];
+ state_packed_storage := witness_packed_zero;
+ state_allocator_frontier := 1;
+ state_sequences := [];
+ state_term_dictionary_enabled := false;
+ state_term_entries := [] |}.
+
+Definition witness_materialized_orphan_zero : WitnessInterningState :=
+ {| state_fiber := witness_vocabulary_fiber;
+ state_term_fiber := witness_term_fiber;
+ state_reserved_entries := [];
+ state_claimed_entries := [];
+ state_live_entries := [];
+ state_ever_entries := [];
+ state_orphan_entries := [(collision_atom_left, symbol_zero)];
+ state_unmaterialized_orphan_entries := [];
+ state_packed_storage := witness_packed_zero;
+ state_allocator_frontier := 1;
+ state_sequences := [];
+ state_term_dictionary_enabled := false;
+ state_term_entries := [] |}.
+
+Definition witness_reserved_two_after_orphan : WitnessInterningState :=
+ {| state_fiber := witness_vocabulary_fiber;
+ state_term_fiber := witness_term_fiber;
+ state_reserved_entries := [(collision_atom_right, symbol_two)];
+ state_claimed_entries := [];
+ state_live_entries := [];
+ state_ever_entries := [];
+ state_orphan_entries := [(collision_atom_left, symbol_zero)];
+ state_unmaterialized_orphan_entries := [];
+ state_packed_storage := witness_packed_zero;
+ state_allocator_frontier := 3;
+ state_sequences := [];
+ state_term_dictionary_enabled := false;
+ state_term_entries := [] |}.
+
+Definition witness_sparse_orphan_state : WitnessInterningState :=
+ {| state_fiber := witness_vocabulary_fiber;
+ state_term_fiber := witness_term_fiber;
+ state_reserved_entries := [];
+ state_claimed_entries := [];
+ state_live_entries := [];
+ state_ever_entries := [];
+ state_orphan_entries := [(collision_atom_left, symbol_zero)];
+ state_unmaterialized_orphan_entries :=
+ [(collision_atom_right, symbol_two)];
+ state_packed_storage := witness_packed_zero;
+ state_allocator_frontier := 3;
+ state_sequences := [];
+ state_term_dictionary_enabled := false;
+ state_term_entries := [] |}.
+
+Definition witness_live_sequence_zero : WitnessInterningState :=
+ {| state_fiber := witness_vocabulary_fiber;
+ state_term_fiber := witness_term_fiber;
+ state_reserved_entries := [];
+ state_claimed_entries := [];
+ state_live_entries := [(collision_atom_left, symbol_zero)];
+ state_ever_entries := [(collision_atom_left, symbol_zero)];
+ state_orphan_entries := [];
+ state_unmaterialized_orphan_entries := [];
+ state_packed_storage := witness_packed_zero;
+ state_allocator_frontier := 1;
+ state_sequences := [[symbol_zero]];
+ state_term_dictionary_enabled := false;
+ state_term_entries := [] |}.
+
+Definition witness_live_term_enabled : WitnessInterningState :=
+ {| state_fiber := witness_vocabulary_fiber;
+ state_term_fiber := witness_term_fiber;
+ state_reserved_entries := [];
+ state_claimed_entries := [];
+ state_live_entries := [(collision_atom_left, symbol_zero)];
+ state_ever_entries := [(collision_atom_left, symbol_zero)];
+ state_orphan_entries := [];
+ state_unmaterialized_orphan_entries := [];
+ state_packed_storage := witness_packed_zero;
+ state_allocator_frontier := 1;
+ state_sequences := [];
+ state_term_dictionary_enabled := true;
+ state_term_entries := [] |}.
+
+Definition witness_live_term_entry : WitnessInterningState :=
+ {| state_fiber := witness_vocabulary_fiber;
+ state_term_fiber := witness_term_fiber;
+ state_reserved_entries := [];
+ state_claimed_entries := [];
+ state_live_entries := [(collision_atom_left, symbol_zero)];
+ state_ever_entries := [(collision_atom_left, symbol_zero)];
+ state_orphan_entries := [];
+ state_unmaterialized_orphan_entries := [];
+ state_packed_storage := witness_packed_zero;
+ state_allocator_frontier := 1;
+ state_sequences := [];
+ state_term_dictionary_enabled := true;
+ state_term_entries := [([symbol_zero], term_zero)] |}.
+
+Lemma witness_reserve_zero :
+ claim_atom_allocation
+ witness_initial_state collision_atom_left symbol_zero =
+ Some witness_reserved_zero.
+Proof. reflexivity. Qed.
+
+Lemma witness_materialize_zero :
+ materialize_reserved_allocation
+ witness_reserved_zero collision_atom_left symbol_zero
+ witness_materialized_zero.
+Proof.
+ unfold materialize_reserved_allocation.
+ exists [], [], witness_packed_zero. repeat split; reflexivity.
+Qed.
+
+Lemma witness_publish_zero :
+ publish_claimed_allocation
+ witness_materialized_zero collision_atom_left symbol_zero
+ witness_live_zero.
+Proof.
+ unfold publish_claimed_allocation.
+ exists [], []. repeat split; reflexivity.
+Qed.
+
+Lemma witness_orphan_materialized_zero :
+ orphan_claimed_allocation
+ witness_materialized_zero collision_atom_left symbol_zero
+ witness_materialized_orphan_zero.
+Proof.
+ unfold orphan_claimed_allocation.
+ exists [], []. now split.
+Qed.
+
+Lemma witness_reserve_two_after_orphan :
+ claim_atom_allocation
+ witness_materialized_orphan_zero collision_atom_right symbol_two =
+ Some witness_reserved_two_after_orphan.
+Proof. reflexivity. Qed.
+
+Lemma witness_orphan_unmaterialized_two :
+ orphan_reserved_allocation
+ witness_reserved_two_after_orphan collision_atom_right symbol_two
+ witness_sparse_orphan_state.
+Proof.
+ unfold orphan_reserved_allocation.
+ exists [], []. now split.
+Qed.
+
+Lemma witness_fresh_publish_zero :
+ publish_fresh_atom
+ witness_initial_state collision_atom_left symbol_zero =
+ Some witness_live_zero.
+Proof. reflexivity. Qed.
+
+Lemma witness_tombstone_zero :
+ tombstone_published_allocation
+ witness_live_zero collision_atom_left symbol_zero
+ witness_tombstoned_zero.
+Proof.
+ unfold tombstone_published_allocation.
+ exists [], []. repeat split; constructor.
+Qed.
+
+Lemma witness_add_live_sequence :
+ add_dependent_sequence
+ witness_live_zero [symbol_zero] witness_live_sequence_zero.
+Proof.
+ unfold add_dependent_sequence. split.
+ - constructor.
+ + split; [simpl; lia |].
+ exists collision_atom_left. now left.
+ + constructor.
+ - reflexivity.
+Qed.
+
+Lemma witness_enable_term_dictionary :
+ enable_term_dictionary witness_live_zero witness_live_term_enabled.
+Proof. reflexivity. Qed.
+
+Lemma witness_disable_empty_term_dictionary :
+ disable_empty_term_dictionary witness_live_term_enabled witness_live_zero.
+Proof. now split. Qed.
+
+Lemma witness_insert_term_entry :
+ insert_term_dictionary_entry
+ witness_live_term_enabled [symbol_zero] term_zero
+ witness_live_term_entry.
+Proof.
+ unfold insert_term_dictionary_entry. repeat split.
+ - constructor.
+ + split; [simpl; lia |].
+ exists collision_atom_left. now left.
+ + constructor.
+Qed.
+
+Lemma witness_sparse_state_is_reachable :
+ InterningReachable
+ canonical_uleb_profile u32_carrier u32_carrier
+ witness_vocabulary_fiber 900 1 witness_sparse_orphan_state.
+Proof.
+ eapply ReachableStep.
+ - eapply ReachableStep.
+ + eapply ReachableStep.
+ * eapply ReachableStep.
+ { eapply ReachableStep.
+ - apply ReachableInitial.
+ - eapply TransitionClaimAllocation
+ with (atom := collision_atom_left) (id := symbol_zero).
+ exact witness_reserve_zero. }
+ { eapply TransitionMaterializeReservation
+ with (atom := collision_atom_left) (id := symbol_zero).
+ exact witness_materialize_zero. }
+ * eapply TransitionOrphanClaim
+ with (atom := collision_atom_left) (id := symbol_zero).
+ exact witness_orphan_materialized_zero.
+ + eapply TransitionClaimAllocation
+ with (atom := collision_atom_right) (id := symbol_two).
+ exact witness_reserve_two_after_orphan.
+ - eapply TransitionOrphanReservation
+ with (atom := collision_atom_right) (id := symbol_two).
+ exact witness_orphan_unmaterialized_two.
+Qed.
+
+Theorem VWENC_166_EVERY_TRANSITION_FAMILY_HAS_A_CONCRETE_WITNESS :
+ InterningTransition witness_initial_state witness_live_zero /\
+ InterningTransition witness_initial_state witness_reserved_zero /\
+ InterningTransition witness_reserved_zero witness_materialized_zero /\
+ InterningTransition witness_materialized_zero witness_live_zero /\
+ InterningTransition witness_materialized_zero
+ witness_materialized_orphan_zero /\
+ InterningTransition witness_reserved_two_after_orphan
+ witness_sparse_orphan_state /\
+ InterningTransition witness_live_zero witness_tombstoned_zero /\
+ InterningTransition witness_live_zero witness_live_sequence_zero /\
+ InterningTransition witness_live_zero witness_live_term_enabled /\
+ InterningTransition witness_live_term_enabled witness_live_zero /\
+ InterningTransition witness_live_term_enabled witness_live_term_entry.
+Proof.
+ repeat split.
+ - eapply TransitionFreshPublication
+ with (atom := collision_atom_left) (id := symbol_zero).
+ exact witness_fresh_publish_zero.
+ - eapply TransitionClaimAllocation
+ with (atom := collision_atom_left) (id := symbol_zero).
+ exact witness_reserve_zero.
+ - eapply TransitionMaterializeReservation
+ with (atom := collision_atom_left) (id := symbol_zero).
+ exact witness_materialize_zero.
+ - eapply TransitionPublishClaim
+ with (atom := collision_atom_left) (id := symbol_zero).
+ exact witness_publish_zero.
+ - eapply TransitionOrphanClaim
+ with (atom := collision_atom_left) (id := symbol_zero).
+ exact witness_orphan_materialized_zero.
+ - eapply TransitionOrphanReservation
+ with (atom := collision_atom_right) (id := symbol_two).
+ exact witness_orphan_unmaterialized_two.
+ - eapply TransitionTombstonePublished
+ with (atom := collision_atom_left) (id := symbol_zero).
+ exact witness_tombstone_zero.
+ - eapply TransitionAddDependentSequence with (sequence := [symbol_zero]).
+ exact witness_add_live_sequence.
+ - apply TransitionEnableTermDictionary. exact witness_enable_term_dictionary.
+ - apply TransitionDisableEmptyTermDictionary.
+ exact witness_disable_empty_term_dictionary.
+ - eapply TransitionInsertTermEntry
+ with (sequence := [symbol_zero]) (term_id := term_zero).
+ exact witness_insert_term_entry.
+Qed.
+
+Theorem VWENC_167_EVERY_ALLOCATION_STATUS_HAS_A_CONCRETE_WITNESS :
+ allocation_has_status witness_reserved_zero
+ collision_atom_left symbol_zero AllocationReserved /\
+ allocation_has_status witness_materialized_zero
+ collision_atom_left symbol_zero AllocationMaterializedClaimed /\
+ allocation_has_status witness_live_zero
+ collision_atom_left symbol_zero AllocationPublished /\
+ allocation_has_status witness_tombstoned_zero
+ collision_atom_left symbol_zero AllocationTombstoned /\
+ allocation_has_status witness_materialized_orphan_zero
+ collision_atom_left symbol_zero AllocationMaterializedOrphaned /\
+ allocation_has_status witness_sparse_orphan_state
+ collision_atom_right symbol_two AllocationUnmaterializedOrphaned.
+Proof.
+ repeat split.
+ - apply allocation_status_reserved_from_membership.
+ simpl. now left.
+ - apply allocation_status_materialized_claimed_from_membership.
+ + simpl. tauto.
+ + simpl. now left.
+ - apply allocation_status_published_from_membership.
+ + simpl. tauto.
+ + simpl. tauto.
+ + simpl. tauto.
+ + simpl. tauto.
+ + simpl. now left.
+ + simpl. now left.
+ - apply allocation_status_tombstoned_from_membership.
+ + simpl. tauto.
+ + simpl. tauto.
+ + simpl. tauto.
+ + simpl. tauto.
+ + simpl. now left.
+ + simpl. tauto.
+ - apply allocation_status_materialized_orphan_from_membership.
+ + simpl. tauto.
+ + simpl. tauto.
+ + simpl. now left.
+ - apply allocation_status_unmaterialized_orphan_from_membership.
+ + simpl. tauto.
+ + simpl. tauto.
+ + simpl. intros [Hequal | []].
+ apply (f_equal snd) in Hequal. simpl in Hequal.
+ now apply symbol_two_differs_from_symbol_zero.
+ + simpl. now left.
+Qed.
+
+Theorem VWENC_108_SPARSE_FRONTIER_HAS_A_GAP_AND_BOTH_ORPHAN_CLASSES :
+ exists state : WitnessInterningState,
+ InterningStateWellFormed state /\
+ symbol_id_value u32_carrier symbol_one <
+ state_allocator_frontier
+ canonical_uleb_profile u32_carrier u32_carrier state /\
+ ~ In symbol_one (map snd (state_allocation_entries state)) /\
+ allocation_has_status state
+ collision_atom_left symbol_zero AllocationMaterializedOrphaned /\
+ allocation_has_status state
+ collision_atom_right symbol_two AllocationUnmaterializedOrphaned /\
+ state_live_entries
+ canonical_uleb_profile u32_carrier u32_carrier state = [] /\
+ state_sequences
+ canonical_uleb_profile u32_carrier u32_carrier state = [] /\
+ state_term_entries
+ canonical_uleb_profile u32_carrier u32_carrier state = [].
+Proof.
+ exists witness_sparse_orphan_state.
+ split.
+ - eapply VWENC_159_EVERY_REACHABLE_INTERNING_STATE_IS_WELL_FORMED.
+ exact witness_sparse_state_is_reachable.
+ - split.
+ + unfold witness_sparse_orphan_state, symbol_one.
+ simpl. lia.
+ + split.
+ * simpl. intros [Hequal | [Hequal | []]].
+ { apply (f_equal (symbol_id_value u32_carrier)) in Hequal.
+ discriminate. }
+ { apply (f_equal (symbol_id_value u32_carrier)) in Hequal.
+ discriminate. }
+ * split.
+ { apply allocation_status_materialized_orphan_from_membership.
+ - simpl. tauto.
+ - simpl. tauto.
+ - simpl. now left. }
+ { split.
+ - apply allocation_status_unmaterialized_orphan_from_membership.
+ + simpl. tauto.
+ + simpl. tauto.
+ + simpl. intros [Hequal | []].
+ apply (f_equal snd) in Hequal. simpl in Hequal.
+ now apply symbol_two_differs_from_symbol_zero.
+ + simpl. now left.
+ - split; [reflexivity |].
+ split; reflexivity. }
+Qed.
+
+Theorem VWENC_130_FRESH_INSERT_PRESERVES_EXISTING_ATOM_LOOKUPS :
+ forall (P : CertifiedAtomProfile) (I : FixedWidthCarrierProfile)
+ (entries : list (VocabularyEntry P I))
+ new_atom existing_atom new_id existing_id,
+ existing_atom <> new_atom ->
+ lookup_atom entries existing_atom = Some existing_id ->
+ lookup_atom ((new_atom, new_id) :: entries) existing_atom =
+ Some existing_id.
+Proof.
+ intros P I entries new_atom existing_atom new_id existing_id
+ Hdifferent Hlookup.
+ unfold lookup_atom. simpl.
+ destruct (canonical_atom_eq_dec P existing_atom new_atom);
+ [contradiction | exact Hlookup].
+Qed.
+
+Theorem VWENC_131_FRESH_INSERT_PRESERVES_EXISTING_REVERSE_LOOKUPS :
+ forall (P : CertifiedAtomProfile) (I : FixedWidthCarrierProfile)
+ (entries : list (VocabularyEntry P I))
+ new_atom existing_atom new_id existing_id,
+ existing_id <> new_id ->
+ lookup_symbol entries existing_id = Some existing_atom ->
+ lookup_symbol ((new_atom, new_id) :: entries) existing_id =
+ Some existing_atom.
+Proof.
+ intros P I entries new_atom existing_atom new_id existing_id
+ Hdifferent Hlookup.
+ unfold lookup_symbol, reverse_vocabulary_entries in *. simpl.
+ destruct (symbol_id_eq_dec I existing_id new_id);
+ [contradiction | exact Hlookup].
+Qed.
+
+Theorem VWENC_133_EVERY_LIVE_ID_HAS_EXACT_NONEMPTY_BOUNDED_CANONICAL_SPAN :
+ forall (P : CertifiedAtomProfile) (I T : FixedWidthCarrierProfile)
+ (state : InterningState P I T) atom id,
+ InterningStateWellFormed state ->
+ In (atom, id) (state_live_entries P I T state) ->
+ packed_entry_exact (state_packed_storage P I T state) atom id.
+Proof.
+ intros P I T state atom id Hwell Hlive.
+ destruct Hwell as
+ [_ _ Hlive_history _ Hpacked].
+ destruct Hpacked as [_ [_ [_ [Hexact _]]]].
+ apply Hexact.
+ unfold state_materialized_entries.
+ apply in_or_app. left.
+ now apply Hlive_history.
+Qed.
+
+(** ** Certified vocabulary snapshots and sequence descriptors *)
+
+Record VocabularySnapshot
+ (P : CertifiedAtomProfile)
+ (I : FixedWidthCarrierProfile)
+ (fiber : VocabularyFiber P I) : Type :=
+ mkVocabularySnapshot {
+ vocabulary_snapshot_live_entries : list (VocabularyEntry P I);
+ vocabulary_snapshot_available_frontier : nat;
+ vocabulary_snapshot_packed_storage : PackedAtomStorage I;
+ vocabulary_snapshot_live_bijection :
+ vocabulary_relation_well_formed vocabulary_snapshot_live_entries;
+ vocabulary_snapshot_frontier_representable :
+ vocabulary_snapshot_available_frontier <= carrier_capacity I;
+ vocabulary_snapshot_live_ids_below_frontier :
+ Forall
+ (fun entry =>
+ symbol_id_value I (snd entry) <
+ vocabulary_snapshot_available_frontier)
+ vocabulary_snapshot_live_entries;
+ vocabulary_snapshot_live_metadata_exact :
+ forall atom id,
+ In (atom, id) vocabulary_snapshot_live_entries ->
+ packed_entry_exact vocabulary_snapshot_packed_storage atom id
+ }.
+
+Definition capture_vocabulary_snapshot
+ {P : CertifiedAtomProfile}
+ {I T : FixedWidthCarrierProfile}
+ (state : InterningState P I T)
+ (Hwell : InterningStateWellFormed state)
+ : VocabularySnapshot P I (state_fiber P I T state).
+Proof.
+ pose proof Hwell as Hwhole.
+ destruct Hwell as
+ [Hlive_bijection _ Hlive_history _ _ Halloc_below Hfrontier].
+ refine (mkVocabularySnapshot
+ P I (state_fiber P I T state)
+ (state_live_entries P I T state)
+ (state_allocator_frontier P I T state)
+ (state_packed_storage P I T state)
+ Hlive_bijection Hfrontier _ _).
+ - apply Forall_forall. intros entry Hlive.
+ apply Forall_forall with (x := entry) in Halloc_below.
+ + exact Halloc_below.
+ + unfold state_allocation_entries.
+ apply in_or_app. left.
+ destruct entry as [atom id].
+ now apply Hlive_history.
+ - intros atom id Hlive.
+ now apply VWENC_133_EVERY_LIVE_ID_HAS_EXACT_NONEMPTY_BOUNDED_CANONICAL_SPAN.
+Defined.
+
+Theorem VWENC_181_CAPTURED_VOCABULARY_SNAPSHOT_IS_ONE_EXACT_STATE_FIBER :
+ forall (P : CertifiedAtomProfile) (I T : FixedWidthCarrierProfile)
+ (state : InterningState P I T)
+ (Hwell : InterningStateWellFormed state),
+ vocabulary_fiber_identity (state_fiber P I T state) =
+ vocabulary_fiber_identity (state_fiber P I T state) /\
+ vocabulary_snapshot_live_entries
+ P I (state_fiber P I T state)
+ (capture_vocabulary_snapshot state Hwell) =
+ state_live_entries P I T state /\
+ vocabulary_snapshot_available_frontier
+ P I (state_fiber P I T state)
+ (capture_vocabulary_snapshot state Hwell) =
+ state_allocator_frontier P I T state /\
+ vocabulary_snapshot_packed_storage
+ P I (state_fiber P I T state)
+ (capture_vocabulary_snapshot state Hwell) =
+ state_packed_storage P I T state.
+Proof.
+ intros P I T state Hwell.
+ destruct Hwell. repeat split.
+Qed.
+
+Record SequenceDescriptor
+ (P : CertifiedAtomProfile) (I : FixedWidthCarrierProfile) : Type :=
+ mkSequenceDescriptor {
+ descriptor_fiber : VocabularyFiber P I;
+ descriptor_required_frontier : nat;
+ descriptor_ids : list (SymbolId I)
+ }.
+
+Definition descriptor_accepts_snapshot
+ {P : CertifiedAtomProfile} {I : FixedWidthCarrierProfile}
+ (expected_fiber : VocabularyFiber P I)
+ (live : list (VocabularyEntry P I))
+ (available_frontier : nat)
+ (descriptor : SequenceDescriptor P I) : Prop :=
+ descriptor_fiber P I descriptor = expected_fiber /\
+ descriptor_required_frontier P I descriptor <= available_frontier /\
+ Forall
+ (fun id =>
+ symbol_id_value I id <
+ descriptor_required_frontier P I descriptor /\
+ live_symbol live id)
+ (descriptor_ids P I descriptor).
+
+Definition descriptor_accepts_vocabulary_snapshot
+ {P : CertifiedAtomProfile} {I : FixedWidthCarrierProfile}
+ {fiber : VocabularyFiber P I}
+ (snapshot : VocabularySnapshot P I fiber)
+ (descriptor : SequenceDescriptor P I) : Prop :=
+ descriptor_accepts_snapshot
+ fiber
+ (vocabulary_snapshot_live_entries P I fiber snapshot)
+ (vocabulary_snapshot_available_frontier P I fiber snapshot)
+ descriptor.
+
+Definition encode_symbol_sequence
+ (I : FixedWidthCarrierProfile) (ids : list (SymbolId I))
+ : list PhysicalByte :=
+ flat_map (encode_symbol_id I) ids.
+
+(** ** Fiber-bound fixed-width ID sequence views *)
+
+Record IdSequenceBacking
+ (P : CertifiedAtomProfile) (I : FixedWidthCarrierProfile) : Type :=
+ mkIdSequenceBacking {
+ backing_identity : nat;
+ backing_fiber : VocabularyFiber P I;
+ backing_snapshot : VocabularySnapshot P I backing_fiber;
+ backing_descriptor : SequenceDescriptor P I;
+ backing_descriptor_accepted :
+ descriptor_accepts_vocabulary_snapshot
+ backing_snapshot backing_descriptor;
+ backing_bytes : list PhysicalByte;
+ backing_bytes_encode_exact_descriptor :
+ backing_bytes =
+ encode_symbol_sequence I (descriptor_ids P I backing_descriptor);
+ backing_bytes_are_valid : Forall valid_byte backing_bytes;
+ backing_bytes_have_exact_descriptor_length :
+ List.length backing_bytes =
+ List.length (descriptor_ids P I backing_descriptor) *
+ carrier_width_bytes I
+ }.
+
+Definition valid_id_sequence_backing
+ {P : CertifiedAtomProfile} {I : FixedWidthCarrierProfile}
+ (backing : IdSequenceBacking P I) : Prop :=
+ Forall valid_byte (backing_bytes P I backing) /\
+ List.length (backing_bytes P I backing) =
+ List.length
+ (descriptor_ids P I (backing_descriptor P I backing)) *
+ carrier_width_bytes I /\
+ descriptor_accepts_vocabulary_snapshot
+ (backing_snapshot P I backing)
+ (backing_descriptor P I backing) /\
+ backing_bytes P I backing =
+ encode_symbol_sequence I
+ (descriptor_ids P I (backing_descriptor P I backing)).
+
+Theorem VWENC_182_EVERY_ID_SEQUENCE_BACKING_IS_CERTIFIED_BY_ONE_EXACT_SNAPSHOT :
+ forall (P : CertifiedAtomProfile) (I : FixedWidthCarrierProfile)
+ (backing : IdSequenceBacking P I),
+ valid_id_sequence_backing backing.
+Proof.
+ intros P I backing.
+ split; [exact (backing_bytes_are_valid P I backing) |].
+ split; [exact (backing_bytes_have_exact_descriptor_length P I backing) |].
+ split.
+ - exact (backing_descriptor_accepted P I backing).
+ - exact (backing_bytes_encode_exact_descriptor P I backing).
+Qed.
+
+Record IdSequenceView
+ (P : CertifiedAtomProfile) (I : FixedWidthCarrierProfile) : Type :=
+ mkIdSequenceView {
+ view_backing : IdSequenceBacking P I;
+ view_start : nat;
+ view_count : nat
+ }.
+
+Definition valid_id_sequence_view
+ {P : CertifiedAtomProfile} {I : FixedWidthCarrierProfile}
+ (view : IdSequenceView P I) : Prop :=
+ valid_id_sequence_backing (view_backing P I view) /\
+ view_start P I view + view_count P I view <=
+ List.length
+ (descriptor_ids P I
+ (backing_descriptor P I (view_backing P I view))).
+
+Definition id_sequence_view_byte_offset
+ {P : CertifiedAtomProfile} {I : FixedWidthCarrierProfile}
+ (view : IdSequenceView P I) (index : nat) : nat :=
+ (view_start P I view + index) * carrier_width_bytes I.
+
+Definition id_sequence_view_byte_window
+ {P : CertifiedAtomProfile} {I : FixedWidthCarrierProfile}
+ (view : IdSequenceView P I) (index : nat)
+ : list PhysicalByte :=
+ firstn
+ (carrier_width_bytes I)
+ (skipn
+ (id_sequence_view_byte_offset view index)
+ (backing_bytes P I (view_backing P I view))).
+
+Definition id_sequence_view_bytes
+ {P : CertifiedAtomProfile} {I : FixedWidthCarrierProfile}
+ (view : IdSequenceView P I) (index : nat)
+ : option (list PhysicalByte) :=
+ if index view_count P I view
+ then Some (id_sequence_view_byte_window view index)
+ else None.
+
+Definition id_sequence_view_index
+ {P : CertifiedAtomProfile} {I : FixedWidthCarrierProfile}
+ (view : IdSequenceView P I) (index : nat)
+ : option (FiberBoundSymbolId P I) :=
+ match id_sequence_view_bytes view index with
+ | Some bytes =>
+ match decode_symbol_id I bytes with
+ | Some id =>
+ Some
+ (mkFiberBoundSymbolId P I
+ (backing_fiber P I (view_backing P I view)) id)
+ | None => None
+ end
+ | None => None
+ end.
+
+Definition id_sequence_subview
+ {P : CertifiedAtomProfile} {I : FixedWidthCarrierProfile}
+ (view : IdSequenceView P I) (offset count : nat)
+ : option (IdSequenceView P I) :=
+ if offset + count <=? view_count P I view
+ then Some
+ (mkIdSequenceView P I
+ (view_backing P I view)
+ (view_start P I view + offset)
+ count)
+ else None.
+
+Lemma Forall_firstn_preserved :
+ forall (A : Type) (predicate : A -> Prop) count values,
+ Forall predicate values ->
+ Forall predicate (firstn count values).
+Proof.
+ intros A predicate count.
+ induction count as [| count IH]; intros values Hforall.
+ - simpl. constructor.
+ - destruct values as [| value rest].
+ + simpl. constructor.
+ + inversion Hforall; subst. simpl. constructor; [assumption |].
+ now apply IH.
+Qed.
+
+Lemma Forall_skipn_preserved :
+ forall (A : Type) (predicate : A -> Prop) count values,
+ Forall predicate values ->
+ Forall predicate (skipn count values).
+Proof.
+ intros A predicate count.
+ induction count as [| count IH]; intros values Hforall.
+ - exact Hforall.
+ - destruct values as [| value rest].
+ + simpl. constructor.
+ + inversion Hforall; subst. simpl. now apply IH.
+Qed.
+
+Lemma decode_fixed_little_endian_bounded_by_width :
+ forall bytes,
+ Forall valid_byte bytes ->
+ decode_fixed_little_endian bytes < 256 ^ List.length bytes.
+Proof.
+ induction bytes as [| byte rest IH]; intros Hvalid.
+ - simpl. lia.
+ - inversion Hvalid as [| current tail Hbyte Hrest]; subst.
+ specialize (IH Hrest).
+ cbn [decode_fixed_little_endian List.length].
+ rewrite Nat.pow_succ_r by lia.
+ unfold valid_byte in Hbyte.
+ nia.
+Qed.
+
+Lemma decode_symbol_id_accepts_every_exact_width_byte_window :
+ forall (I : FixedWidthCarrierProfile) bytes,
+ List.length bytes = carrier_width_bytes I ->
+ Forall valid_byte bytes ->
+ exists id, decode_symbol_id I bytes = Some id.
+Proof.
+ intros I bytes Hlength Hvalid.
+ assert (Hbounded :
+ decode_fixed_little_endian bytes < carrier_capacity I).
+ { unfold carrier_capacity. rewrite <- Hlength.
+ now apply decode_fixed_little_endian_bounded_by_width. }
+ unfold decode_symbol_id.
+ rewrite Hlength.
+ destruct (Nat.eq_dec (carrier_width_bytes I) (carrier_width_bytes I))
+ as [_ | Himpossible]; [| contradiction].
+ assert (Hvalidb : all_valid_bytesb bytes = true).
+ { now apply (proj2 (all_valid_bytesb_reflects_validity bytes)). }
+ rewrite Hvalidb. unfold symbol_id_of_nat.
+ destruct (lt_dec (decode_fixed_little_endian bytes)
+ (carrier_capacity I)) as [Hfits | Hoverflow].
+ - eexists. reflexivity.
+ - contradiction.
+Qed.
+
+Lemma firstn_exact_left_append :
+ forall (A : Type) (left right : list A),
+ firstn (List.length left) (left ++ right) = left.
+Proof.
+ intros A left.
+ induction left as [| value tail IH]; intros right.
+ - reflexivity.
+ - simpl. now rewrite IH.
+Qed.
+
+Lemma skipn_exact_left_append :
+ forall (A : Type) (left right : list A) count,
+ skipn (List.length left + count) (left ++ right) =
+ skipn count right.
+Proof.
+ intros A left.
+ induction left as [| value tail IH]; intros right count.
+ - reflexivity.
+ - simpl. now rewrite IH.
+Qed.
+
+Lemma encoded_symbol_sequence_window_at :
+ forall (I : FixedWidthCarrierProfile) ids index id,
+ nth_error ids index = Some id ->
+ firstn
+ (carrier_width_bytes I)
+ (skipn
+ (index * carrier_width_bytes I)
+ (encode_symbol_sequence I ids)) =
+ encode_symbol_id I id.
+Proof.
+ intros I ids.
+ induction ids as [| head tail IH]; intros index id Hnth.
+ - destruct index; discriminate.
+ - destruct index as [| index].
+ + simpl in Hnth. inversion Hnth. subst id.
+ change
+ (firstn (carrier_width_bytes I)
+ (encode_symbol_id I head ++ encode_symbol_sequence I tail) =
+ encode_symbol_id I head).
+ rewrite <- (proj1 (symbol_id_fixed_width_encoding_roundtrips I head)).
+ apply firstn_exact_left_append.
+ + simpl in Hnth.
+ change
+ (firstn (carrier_width_bytes I)
+ (skipn (S index * carrier_width_bytes I)
+ (encode_symbol_id I head ++ encode_symbol_sequence I tail)) =
+ encode_symbol_id I id).
+ assert (Hhead_length :
+ List.length (encode_symbol_id I head) = carrier_width_bytes I).
+ { apply symbol_id_fixed_width_encoding_roundtrips. }
+ replace (S index * carrier_width_bytes I) with
+ (List.length (encode_symbol_id I head) +
+ index * carrier_width_bytes I) by
+ (rewrite Hhead_length; lia).
+ rewrite skipn_exact_left_append.
+ now apply IH.
+Qed.
+
+Lemma valid_id_sequence_view_window_is_descriptor_encoding :
+ forall (P : CertifiedAtomProfile) (I : FixedWidthCarrierProfile)
+ (view : IdSequenceView P I) index,
+ valid_id_sequence_view view ->
+ index < view_count P I view ->
+ exists id,
+ nth_error
+ (descriptor_ids P I
+ (backing_descriptor P I (view_backing P I view)))
+ (view_start P I view + index) = Some id /\
+ id_sequence_view_byte_window view index = encode_symbol_id I id.
+Proof.
+ intros P I view index [Hbacking Hrange] Hindex.
+ destruct Hbacking as [_ [_ [_ Hbytes_exact]]].
+ assert (Hposition :
+ view_start P I view + index <
+ List.length
+ (descriptor_ids P I
+ (backing_descriptor P I (view_backing P I view)))) by lia.
+ destruct (nth_error
+ (descriptor_ids P I
+ (backing_descriptor P I (view_backing P I view)))
+ (view_start P I view + index)) as [id |] eqn:Hnth.
+ - exists id. split; [reflexivity |].
+ unfold id_sequence_view_byte_window,
+ id_sequence_view_byte_offset.
+ rewrite Hbytes_exact.
+ now apply encoded_symbol_sequence_window_at.
+ - apply nth_error_None in Hnth. lia.
+Qed.
+
+Lemma valid_id_sequence_view_has_exact_byte_window :
+ forall (P : CertifiedAtomProfile) (I : FixedWidthCarrierProfile)
+ (view : IdSequenceView P I) index,
+ valid_id_sequence_view view ->
+ index < view_count P I view ->
+ List.length (id_sequence_view_byte_window view index) =
+ carrier_width_bytes I /\
+ Forall valid_byte (id_sequence_view_byte_window view index).
+Proof.
+ intros P I view index
+ [[Hbytes [Hbacking_length [_ _]]] Hrange] Hindex.
+ pose proof (carrier_width_positive I) as Hwidth.
+ assert (Hwindow_end :
+ id_sequence_view_byte_offset view index + carrier_width_bytes I <=
+ List.length (backing_bytes P I (view_backing P I view))).
+ { unfold id_sequence_view_byte_offset. nia. }
+ unfold id_sequence_view_byte_window.
+ split.
+ - rewrite firstn_length_local, skipn_length_local.
+ rewrite Nat.min_l; lia.
+ - apply Forall_firstn_preserved.
+ now apply Forall_skipn_preserved.
+Qed.
+
+Theorem VWENC_116_VALID_ID_VIEW_INDEXES_BOUND_BACKING_DIRECTLY :
+ forall (P : CertifiedAtomProfile) (I : FixedWidthCarrierProfile)
+ (view : IdSequenceView P I) index,
+ valid_id_sequence_view view ->
+ index < view_count P I view ->
+ exists bytes id,
+ nth_error
+ (descriptor_ids P I
+ (backing_descriptor P I (view_backing P I view)))
+ (view_start P I view + index) = Some id /\
+ id_sequence_view_bytes view index = Some bytes /\
+ bytes = id_sequence_view_byte_window view index /\
+ bytes = encode_symbol_id I id /\
+ List.length bytes = carrier_width_bytes I /\
+ Forall valid_byte bytes /\
+ decode_symbol_id I bytes = Some id /\
+ live_symbol
+ (vocabulary_snapshot_live_entries
+ P I
+ (backing_fiber P I (view_backing P I view))
+ (backing_snapshot P I (view_backing P I view))) id /\
+ id_sequence_view_index view index =
+ Some
+ (mkFiberBoundSymbolId P I
+ (backing_fiber P I (view_backing P I view)) id).
+Proof.
+ intros P I view index Hvalid Hindex.
+ destruct (valid_id_sequence_view_window_is_descriptor_encoding
+ P I view index Hvalid Hindex) as [id [Hnth Hencoded]].
+ destruct (valid_id_sequence_view_has_exact_byte_window
+ P I view index Hvalid Hindex) as [Hlength Hbytes].
+ assert (Hdecode :
+ decode_symbol_id I (id_sequence_view_byte_window view index) = Some id).
+ { rewrite Hencoded.
+ apply symbol_id_fixed_width_encoding_roundtrips. }
+ assert (Hlive :
+ live_symbol
+ (vocabulary_snapshot_live_entries
+ P I
+ (backing_fiber P I (view_backing P I view))
+ (backing_snapshot P I (view_backing P I view))) id).
+ { destruct Hvalid as [[_ [_ [Haccepted _]]] _].
+ unfold descriptor_accepts_vocabulary_snapshot,
+ descriptor_accepts_snapshot in Haccepted.
+ destruct Haccepted as [_ [_ Hids]].
+ apply Forall_forall with (x := id) in Hids.
+ - exact (proj2 Hids).
+ - now apply nth_error_In in Hnth. }
+ exists (id_sequence_view_byte_window view index), id.
+ split; [exact Hnth |]. split.
+ - unfold id_sequence_view_bytes.
+ apply Nat.ltb_lt in Hindex. now rewrite Hindex.
+ - split; [reflexivity |].
+ split; [exact Hencoded |].
+ split; [exact Hlength |].
+ split; [exact Hbytes |].
+ split; [exact Hdecode |].
+ split; [exact Hlive |].
+ unfold id_sequence_view_index, id_sequence_view_bytes.
+ apply Nat.ltb_lt in Hindex. now rewrite Hindex, Hdecode.
+Qed.
+
+Theorem VWENC_117_SUBVIEW_PRESERVES_BACKING_FIBER_AND_VALID_RANGE :
+ forall (P : CertifiedAtomProfile) (I : FixedWidthCarrierProfile)
+ (view subview : IdSequenceView P I) offset count,
+ valid_id_sequence_view view ->
+ id_sequence_subview view offset count = Some subview ->
+ view_backing P I subview = view_backing P I view /\
+ backing_fiber P I (view_backing P I subview) =
+ backing_fiber P I (view_backing P I view) /\
+ valid_id_sequence_view subview.
+Proof.
+ intros P I view subview offset count Hvalid Hsubview.
+ unfold id_sequence_subview in Hsubview.
+ destruct (offset + count <=? view_count P I view)
+ eqn:Hrange; [| discriminate].
+ apply Nat.leb_le in Hrange.
+ inversion Hsubview. subst subview. clear Hsubview.
+ split; [reflexivity |].
+ split; [reflexivity |].
+ destruct Hvalid as [Hbacking Hvalid].
+ split; [exact Hbacking |].
+ simpl in *. pose proof (carrier_width_positive I). nia.
+Qed.
+
+Theorem VWENC_134_ID_SEQUENCE_VIEW_REJECTS_OUT_OF_RANGE_INDEX :
+ forall (P : CertifiedAtomProfile) (I : FixedWidthCarrierProfile)
+ (view : IdSequenceView P I) index,
+ view_count P I view <= index ->
+ id_sequence_view_index view index = None.
+Proof.
+ intros P I view index Hrange.
+ unfold id_sequence_view_index, id_sequence_view_bytes.
+ destruct (index view_count P I view) eqn:Hless.
+ - apply Nat.ltb_lt in Hless. lia.
+ - reflexivity.
+Qed.
+
+Theorem VWENC_135_ID_VIEW_ELEMENTS_HAVE_EXACT_CARRIER_STRIDE :
+ forall (P : CertifiedAtomProfile) (I : FixedWidthCarrierProfile)
+ (view : IdSequenceView P I) index bound_id,
+ valid_id_sequence_view view ->
+ id_sequence_view_index view index = Some bound_id ->
+ index < view_count P I view /\
+ exists bytes id,
+ bound_id =
+ mkFiberBoundSymbolId P I
+ (backing_fiber P I (view_backing P I view)) id /\
+ nth_error
+ (descriptor_ids P I
+ (backing_descriptor P I (view_backing P I view)))
+ (view_start P I view + index) = Some id /\
+ id_sequence_view_bytes view index = Some bytes /\
+ bytes = id_sequence_view_byte_window view index /\
+ bytes = encode_symbol_id I id /\
+ live_symbol
+ (vocabulary_snapshot_live_entries
+ P I
+ (backing_fiber P I (view_backing P I view))
+ (backing_snapshot P I (view_backing P I view))) id /\
+ id_sequence_view_byte_offset view index =
+ (view_start P I view + index) * carrier_width_bytes I /\
+ List.length bytes = carrier_width_bytes I /\
+ Forall valid_byte bytes /\
+ decode_symbol_id I bytes = Some id /\
+ List.length (encode_symbol_id I id) = carrier_width_bytes I /\
+ decode_symbol_id I (encode_symbol_id I id) = Some id.
+Proof.
+ intros P I view index bound_id Hvalid Hindex.
+ assert (Hwithin : index < view_count P I view).
+ { destruct (index view_count P I view) eqn:Hless.
+ - now apply Nat.ltb_lt.
+ - exfalso. apply Nat.ltb_ge in Hless.
+ now rewrite (VWENC_134_ID_SEQUENCE_VIEW_REJECTS_OUT_OF_RANGE_INDEX
+ P I view index Hless) in Hindex. }
+ destruct (VWENC_116_VALID_ID_VIEW_INDEXES_BOUND_BACKING_DIRECTLY
+ P I view index Hvalid Hwithin)
+ as [bytes [id
+ [Hnth [Hwindow [Hexact [Hencoded [Hlength [Hbytes
+ [Hdecode [Hlive Hbound]]]]]]]]]].
+ rewrite Hindex in Hbound. inversion Hbound. subst bound_id.
+ split; [exact Hwithin |]. exists bytes, id.
+ split; [reflexivity |].
+ split; [exact Hnth |].
+ split; [exact Hwindow |].
+ split; [exact Hexact |].
+ split; [exact Hencoded |].
+ split; [exact Hlive |].
+ split; [reflexivity |].
+ split; [exact Hlength |].
+ split; [exact Hbytes |].
+ split; [exact Hdecode |].
+ apply symbol_id_fixed_width_encoding_roundtrips.
+Qed.
+
+Theorem VWENC_187_ID_VIEW_RESULT_REJECTS_EVERY_DIFFERENT_FIBER :
+ forall (P : CertifiedAtomProfile) (I : FixedWidthCarrierProfile)
+ (view : IdSequenceView P I) index bound_id expected,
+ valid_id_sequence_view view ->
+ id_sequence_view_index view index = Some bound_id ->
+ expected <> backing_fiber P I (view_backing P I view) ->
+ interpret_symbol_id expected bound_id = None.
+Proof.
+ intros P I view index bound_id expected Hvalid Hindex Hdifferent.
+ destruct (VWENC_135_ID_VIEW_ELEMENTS_HAVE_EXACT_CARRIER_STRIDE
+ P I view index bound_id Hvalid Hindex)
+ as [_ [bytes [id [Hbound _]]]].
+ subst bound_id.
+ now apply VWENC_112_CROSS_FIBER_ID_INTERPRETATION_IS_REJECTED.
+Qed.
+
+(** ** Two-level term IDs and exact vocabulary binding *)
+
+Fixpoint interpret_bound_symbol_sequence
+ {P : CertifiedAtomProfile}
+ {I : FixedWidthCarrierProfile}
+ (expected : VocabularyFiber P I)
+ (sequence : list (FiberBoundSymbolId P I))
+ : option (list (SymbolId I)) :=
+ match sequence with
+ | [] => Some []
+ | bound :: tail =>
+ match interpret_symbol_id expected bound,
+ interpret_bound_symbol_sequence expected tail with
+ | Some id, Some ids => Some (id :: ids)
+ | _, _ => None
+ end
+ end.
+
+Definition resolve_atom_then_term
+ {P : CertifiedAtomProfile}
+ {I T : FixedWidthCarrierProfile}
+ (state : InterningState P I T)
+ (atom : CanonicalAtom P)
+ (tail : list (FiberBoundSymbolId P I))
+ : option
+ (FiberBoundTermId P I T (state_fiber P I T state)) :=
+ match lookup_atom (state_live_entries P I T state) atom,
+ interpret_bound_symbol_sequence (state_fiber P I T state) tail with
+ | Some id, Some ids => lookup_state_term_sequence state (id :: ids)
+ | _, _ => None
+ end.
+
+Theorem VWENC_118_ATOM_ID_AND_TERM_ID_LOOKUP_LAYERS_ARE_EXPLICIT :
+ forall (P : CertifiedAtomProfile) (I T : FixedWidthCarrierProfile)
+ (state : InterningState P I T)
+ atom id tail interpreted_tail term_id,
+ lookup_atom (state_live_entries P I T state) atom = Some id ->
+ interpret_bound_symbol_sequence
+ (state_fiber P I T state) tail = Some interpreted_tail ->
+ state_term_dictionary_enabled P I T state = true ->
+ lookup_term_sequence
+ (state_term_entries P I T state)
+ (id :: interpreted_tail) = Some term_id ->
+ resolve_atom_then_term state atom tail =
+ Some
+ (mkFiberBoundTermId
+ P I T (state_fiber P I T state)
+ (state_term_fiber P I T state) term_id).
+Proof.
+ intros P I T state atom id tail interpreted_tail term_id
+ Hatom Htail Henabled Hterm.
+ unfold resolve_atom_then_term.
+ rewrite Hatom, Htail.
+ unfold lookup_state_term_sequence. now rewrite Henabled, Hterm.
+Qed.
+
+Theorem VWENC_183_TWO_LEVEL_RESOLUTION_REJECTS_A_FOREIGN_FIBER_TAIL :
+ forall (P : CertifiedAtomProfile) (I T : FixedWidthCarrierProfile)
+ (state : InterningState P I T)
+ (actual : VocabularyFiber P I)
+ (atom : CanonicalAtom P) (id : SymbolId I) tail,
+ state_fiber P I T state <> actual ->
+ interpret_bound_symbol_sequence (state_fiber P I T state)
+ (mkFiberBoundSymbolId P I actual id :: tail) = None /\
+ resolve_atom_then_term state atom
+ (mkFiberBoundSymbolId P I actual id :: tail) = None.
+Proof.
+ intros P I T state actual atom id tail Hdifferent.
+ assert (Hreject :
+ interpret_bound_symbol_sequence (state_fiber P I T state)
+ (mkFiberBoundSymbolId P I actual id :: tail) = None).
+ { simpl. now rewrite
+ (VWENC_112_CROSS_FIBER_ID_INTERPRETATION_IS_REJECTED
+ P I (state_fiber P I T state) actual id Hdifferent). }
+ split; [exact Hreject |].
+ unfold resolve_atom_then_term. rewrite Hreject.
+ now destruct (lookup_atom (state_live_entries P I T state) atom).
+Qed.
+
+Theorem VWENC_119_OPTIONAL_TERM_DICTIONARY_SEQUENCES_USE_LIVE_VOCABULARY_IDS :
+ forall (P : CertifiedAtomProfile) (I T : FixedWidthCarrierProfile)
+ (state : InterningState P I T) sequence term_id,
+ InterningStateWellFormed state ->
+ In (sequence, term_id) (state_term_entries P I T state) ->
+ sequence_vocabulary_bound
+ (state_live_entries P I T state)
+ (state_allocator_frontier P I T state)
+ sequence.
+Proof.
+ intros P I T state sequence term_id Hwell Hin.
+ destruct Hwell as
+ [_ _ _ _ _ _ _ _ _ Hterm_bound _].
+ apply Forall_forall with (x := (sequence, term_id))
+ in Hterm_bound; [exact Hterm_bound | exact Hin].
+Qed.
+
+Lemma orphan_id_has_no_live_binding :
+ forall (P : CertifiedAtomProfile) (I T : FixedWidthCarrierProfile)
+ (state : InterningState P I T) id,
+ InterningStateWellFormed state ->
+ In id (state_orphan_ids state) ->
+ ~ live_symbol (state_live_entries P I T state) id.
+Proof.
+ intros P I T state id Hwell Horphan.
+ destruct Hwell as
+ [_ _ Hlive_history Hallocation_unique].
+ intros [atom Hlive].
+ assert (Hever : In id (map snd (state_ever_entries P I T state))).
+ { apply in_map_iff. exists (atom, id). split; [reflexivity |].
+ now apply Hlive_history. }
+ unfold state_allocation_entries in Hallocation_unique.
+ rewrite !map_app in Hallocation_unique.
+ eapply NoDup_app_disjoint_right;
+ [exact Hallocation_unique | exact Hever |].
+ unfold state_orphan_ids in Horphan.
+ rewrite map_app in Horphan.
+ apply in_or_app. right.
+ apply in_or_app. right.
+ exact Horphan.
+Qed.
+
+Theorem VWENC_120_ORPHAN_IDS_HAVE_NO_LIVE_OR_SEQUENCE_BINDING :
+ forall (P : CertifiedAtomProfile) (I T : FixedWidthCarrierProfile)
+ (state : InterningState P I T) id sequence,
+ InterningStateWellFormed state ->
+ In id (state_orphan_ids state) ->
+ In sequence (state_sequences P I T state) ->
+ ~ live_symbol (state_live_entries P I T state) id /\
+ ~ In id sequence.
+Proof.
+ intros P I T state id sequence Hwell Horphan Hsequence.
+ pose proof (orphan_id_has_no_live_binding
+ P I T state id Hwell Horphan) as Hnot_live.
+ destruct Hwell as [_ _ _ _ _ _ _ Hsequences].
+ split; [exact Hnot_live |].
+ intros Hin.
+ apply Forall_forall with (x := sequence) in Hsequences;
+ [| exact Hsequence].
+ apply Forall_forall with (x := id) in Hsequences; [| exact Hin].
+ destruct Hsequences as [_ Hlive]. contradiction.
+Qed.
+
+Theorem VWENC_165_ORPHAN_IDS_HAVE_NO_TERM_SEQUENCE_BINDING :
+ forall (P : CertifiedAtomProfile) (I T : FixedWidthCarrierProfile)
+ (state : InterningState P I T) id sequence term_id,
+ InterningStateWellFormed state ->
+ In id (state_orphan_ids state) ->
+ In (sequence, term_id) (state_term_entries P I T state) ->
+ ~ In id sequence.
+Proof.
+ intros P I T state id sequence term_id Hwell Horphan Hterm Hin.
+ pose proof (orphan_id_has_no_live_binding
+ P I T state id Hwell Horphan) as Hnot_live.
+ pose proof Hwell as Hwell_for_terms.
+ destruct Hwell_for_terms as [_ _ _ _ _ _ _ _ _ Hterm_bound].
+ apply Forall_forall with (x := (sequence, term_id)) in Hterm_bound;
+ [| exact Hterm].
+ apply Forall_forall with (x := id) in Hterm_bound; [| exact Hin].
+ destruct Hterm_bound as [_ Hlive]. contradiction.
+Qed.
+
+Inductive AnyLocalId
+ (I T : FixedWidthCarrierProfile) : Type :=
+| AnySymbolId : SymbolId I -> AnyLocalId I T
+| AnyTermId : TermId T -> AnyLocalId I T.
+
+Theorem VWENC_136_SYMBOL_AND_TERM_IDS_ARE_NOMINALLY_DISJOINT :
+ forall (I T : FixedWidthCarrierProfile)
+ (symbol : SymbolId I) (term : TermId T),
+ AnySymbolId I T symbol <> AnyTermId I T term.
+Proof. discriminate. Qed.
+
+Theorem VWENC_137_TERM_ID_DICTIONARY_IS_A_SECOND_EXACT_BIJECTION :
+ forall (I T : FixedWidthCarrierProfile)
+ (entries : list (TermEntry I T)) sequence term_id,
+ term_relation_well_formed entries ->
+ (lookup_term_sequence entries sequence = Some term_id <->
+ lookup_term_id entries term_id = Some sequence).
+Proof.
+ intros I T entries sequence term_id [Hsequence_unique Hterm_unique].
+ split; intros Hlookup.
+ - unfold lookup_term_sequence in Hlookup.
+ apply assoc_lookup_sound in Hlookup.
+ unfold lookup_term_id. apply assoc_lookup_complete_unique.
+ + rewrite reverse_term_keys_are_term_ids. exact Hterm_unique.
+ + apply reverse_term_membership. exact Hlookup.
+ - unfold lookup_term_id in Hlookup.
+ apply assoc_lookup_sound in Hlookup.
+ apply reverse_term_membership in Hlookup.
+ unfold lookup_term_sequence.
+ now apply assoc_lookup_complete_unique.
+Qed.
+
+(** ** Query-local overlay: fiber-bound, namespaced, and non-serializable *)
+
+Record QueryOverlayNamespace
+ (P : CertifiedAtomProfile)
+ (I : FixedWidthCarrierProfile)
+ (fiber : VocabularyFiber P I) : Type :=
+ mkQueryOverlayNamespace {
+ query_overlay_namespace_identity : nat
+ }.
+
+Definition query_overlay_namespace_full_identity
+ {P : CertifiedAtomProfile}
+ {I : FixedWidthCarrierProfile}
+ {fiber : VocabularyFiber P I}
+ (namespace : QueryOverlayNamespace P I fiber) :=
+ (vocabulary_fiber_identity fiber,
+ query_overlay_namespace_identity P I fiber namespace).
+
+Definition query_overlay_namespace_eq_dec
+ (P : CertifiedAtomProfile)
+ (I : FixedWidthCarrierProfile)
+ (fiber : VocabularyFiber P I)
+ (left right : QueryOverlayNamespace P I fiber)
+ : {left = right} + {left <> right}.
+Proof.
+ destruct left as [left_identity].
+ destruct right as [right_identity].
+ destruct (Nat.eq_dec left_identity right_identity)
+ as [Hequal | Hdifferent].
+ - subst right_identity. left. reflexivity.
+ - right. intros Hequal. inversion Hequal. contradiction.
+Defined.
+
+Record QueryLocalId
+ (P : CertifiedAtomProfile)
+ (I : FixedWidthCarrierProfile)
+ (fiber : VocabularyFiber P I) : Type :=
+ mkQueryLocalId {
+ query_local_namespace : QueryOverlayNamespace P I fiber;
+ query_local_id_value : nat
+ }.
+
+Definition interpret_query_local_id
+ {P : CertifiedAtomProfile}
+ {I : FixedWidthCarrierProfile}
+ {fiber : VocabularyFiber P I}
+ (expected : QueryOverlayNamespace P I fiber)
+ (id : QueryLocalId P I fiber) : option nat :=
+ if query_overlay_namespace_eq_dec
+ P I fiber expected (query_local_namespace P I fiber id)
+ then Some (query_local_id_value P I fiber id)
+ else None.
+
+Theorem VWENC_172_CROSS_OVERLAY_QUERY_LOCAL_ID_IS_REJECTED :
+ forall (P : CertifiedAtomProfile) (I : FixedWidthCarrierProfile)
+ (fiber : VocabularyFiber P I)
+ (expected actual : QueryOverlayNamespace P I fiber) value,
+ expected <> actual ->
+ interpret_query_local_id expected
+ (mkQueryLocalId P I fiber actual value) = None.
+Proof.
+ intros P I fiber expected actual value Hdifferent.
+ unfold interpret_query_local_id. simpl.
+ destruct (query_overlay_namespace_eq_dec
+ P I fiber expected actual) as [Hequal | _].
+ - contradiction.
+ - reflexivity.
+Qed.
+
+Definition QueryOverlayEntry
+ (P : CertifiedAtomProfile)
+ (I : FixedWidthCarrierProfile)
+ (fiber : VocabularyFiber P I) :=
+ (CanonicalAtom P * QueryLocalId P I fiber)%type.
+
+Record QueryOverlay
+ (P : CertifiedAtomProfile)
+ (I : FixedWidthCarrierProfile)
+ (fiber : VocabularyFiber P I) : Type :=
+ mkQueryOverlay {
+ query_overlay_namespace : QueryOverlayNamespace P I fiber;
+ query_overlay_entries : list (QueryOverlayEntry P I fiber);
+ query_overlay_next : nat
+ }.
+
+Definition PackedQueryOverlay
+ (P : CertifiedAtomProfile)
+ (I : FixedWidthCarrierProfile) : Type :=
+ { fiber : VocabularyFiber P I & QueryOverlay P I fiber }.
+
+Definition transport_query_overlay
+ {P : CertifiedAtomProfile}
+ {I : FixedWidthCarrierProfile}
+ {actual expected : VocabularyFiber P I}
+ (Hequal : actual = expected)
+ (overlay : QueryOverlay P I actual)
+ : QueryOverlay P I expected :=
+ eq_rect
+ actual (fun fiber => QueryOverlay P I fiber)
+ overlay expected Hequal.
+
+Definition align_query_overlay
+ {P : CertifiedAtomProfile}
+ {I : FixedWidthCarrierProfile}
+ (expected : VocabularyFiber P I)
+ (packed : PackedQueryOverlay P I)
+ : option (QueryOverlay P I expected).
+Proof.
+ destruct packed as [actual overlay].
+ destruct (vocabulary_fiber_eq_dec P I actual expected)
+ as [Hequal | Hdifferent].
+ - exact (Some (transport_query_overlay Hequal overlay)).
+ - exact None.
+Defined.
+
+Theorem VWENC_186_QUERY_OVERLAY_FROM_ANOTHER_VOCABULARY_FIBER_IS_REJECTED :
+ forall (P : CertifiedAtomProfile) (I : FixedWidthCarrierProfile)
+ (expected actual : VocabularyFiber P I)
+ (overlay : QueryOverlay P I actual),
+ expected <> actual ->
+ align_query_overlay expected
+ (existT (fun fiber => QueryOverlay P I fiber) actual overlay) = None.
+Proof.
+ intros P I expected actual overlay Hdifferent.
+ unfold align_query_overlay.
+ destruct (vocabulary_fiber_eq_dec P I actual expected)
+ as [Hequal | _].
+ - exfalso. apply Hdifferent. symmetry. exact Hequal.
+ - reflexivity.
+Qed.
+
+Definition query_overlay_id_values
+ {P : CertifiedAtomProfile}
+ {I : FixedWidthCarrierProfile}
+ {fiber : VocabularyFiber P I}
+ (overlay : QueryOverlay P I fiber) : list nat :=
+ map
+ (fun entry =>
+ query_local_id_value P I fiber (snd entry))
+ (query_overlay_entries P I fiber overlay).
+
+Definition query_overlay_well_formed
+ {P : CertifiedAtomProfile}
+ {I : FixedWidthCarrierProfile}
+ {fiber : VocabularyFiber P I}
+ (overlay : QueryOverlay P I fiber) : Prop :=
+ NoDup (map fst (query_overlay_entries P I fiber overlay)) /\
+ NoDup (query_overlay_id_values overlay) /\
+ Forall
+ (fun entry =>
+ query_local_namespace P I fiber (snd entry) =
+ query_overlay_namespace P I fiber overlay /\
+ query_local_id_value P I fiber (snd entry) <
+ query_overlay_next P I fiber overlay)
+ (query_overlay_entries P I fiber overlay).
+
+Definition lookup_query_local
+ {P : CertifiedAtomProfile}
+ {I : FixedWidthCarrierProfile}
+ {fiber : VocabularyFiber P I}
+ (overlay : QueryOverlay P I fiber)
+ (atom : CanonicalAtom P) : option (QueryLocalId P I fiber) :=
+ assoc_lookup (canonical_atom_eq_dec P)
+ (query_overlay_entries P I fiber overlay) atom.
+
+Inductive QueryAtomResolution
+ (P : CertifiedAtomProfile)
+ (I : FixedWidthCarrierProfile)
+ (fiber : VocabularyFiber P I) : Type :=
+| QueryDurableSymbol :
+ FiberBoundSymbolId P I -> QueryAtomResolution P I fiber
+| QueryLocalSymbol : QueryLocalId P I fiber -> QueryAtomResolution P I fiber.
+
+Record QueryResolutionResult
+ (P : CertifiedAtomProfile)
+ (I : FixedWidthCarrierProfile)
+ (fiber : VocabularyFiber P I) : Type :=
+ mkQueryResolutionResult {
+ query_resolution : QueryAtomResolution P I fiber;
+ query_overlay_after : QueryOverlay P I fiber
+ }.
+
+Definition resolve_query_atom
+ {P : CertifiedAtomProfile}
+ {I : FixedWidthCarrierProfile}
+ {fiber : VocabularyFiber P I}
+ (snapshot : VocabularySnapshot P I fiber)
+ (overlay : QueryOverlay P I fiber)
+ (atom : CanonicalAtom P) : QueryResolutionResult P I fiber :=
+ match lookup_atom
+ (vocabulary_snapshot_live_entries P I fiber snapshot) atom with
+ | Some id =>
+ mkQueryResolutionResult P I fiber
+ (QueryDurableSymbol P I fiber
+ (mkFiberBoundSymbolId P I fiber id)) overlay
+ | None =>
+ match lookup_query_local overlay atom with
+ | Some id =>
+ mkQueryResolutionResult P I fiber
+ (QueryLocalSymbol P I fiber id) overlay
+ | None =>
+ let id :=
+ mkQueryLocalId P I fiber
+ (query_overlay_namespace P I fiber overlay)
+ (query_overlay_next P I fiber overlay) in
+ let updated :=
+ mkQueryOverlay P I fiber
+ (query_overlay_namespace P I fiber overlay)
+ ((atom, id) :: query_overlay_entries P I fiber overlay)
+ (S (query_overlay_next P I fiber overlay)) in
+ mkQueryResolutionResult P I fiber
+ (QueryLocalSymbol P I fiber id) updated
+ end
+ end.
+
+Lemma query_overlay_fresh_insert_preserves_well_formedness :
+ forall (P : CertifiedAtomProfile) (I : FixedWidthCarrierProfile)
+ (fiber : VocabularyFiber P I)
+ (overlay : QueryOverlay P I fiber) atom,
+ query_overlay_well_formed overlay ->
+ lookup_query_local overlay atom = None ->
+ let fresh :=
+ mkQueryLocalId P I fiber
+ (query_overlay_namespace P I fiber overlay)
+ (query_overlay_next P I fiber overlay) in
+ query_overlay_well_formed
+ (mkQueryOverlay P I fiber
+ (query_overlay_namespace P I fiber overlay)
+ ((atom, fresh) :: query_overlay_entries P I fiber overlay)
+ (S (query_overlay_next P I fiber overlay))) /\
+ ~ In (query_overlay_next P I fiber overlay)
+ (query_overlay_id_values overlay).
+Proof.
+ intros P I fiber overlay atom
+ [Hatom_unique [Hid_unique Hbelow]] Hlookup.
+ simpl.
+ assert (Hatom_absent :
+ ~ In atom (map fst (query_overlay_entries P I fiber overlay))).
+ { unfold lookup_query_local in Hlookup.
+ now apply assoc_lookup_none_key_absent in Hlookup. }
+ assert (Hid_absent :
+ ~ In (query_overlay_next P I fiber overlay)
+ (query_overlay_id_values overlay)).
+ { intros Hin.
+ unfold query_overlay_id_values in Hin.
+ apply in_map_iff in Hin.
+ destruct Hin as [[existing_atom existing_id] [Hequal Hin]].
+ simpl in Hequal.
+ apply Forall_forall with
+ (x := (existing_atom, existing_id)) in Hbelow; [| exact Hin].
+ destruct Hbelow as [_ Hlt]. simpl in Hlt. lia. }
+ split.
+ - split.
+ + simpl. constructor; assumption.
+ + split.
+ * unfold query_overlay_id_values. simpl.
+ constructor; assumption.
+ * simpl. constructor.
+ { split; [reflexivity |].
+ apply Nat.lt_succ_diag_r. }
+ { apply Forall_forall. intros entry Hin.
+ apply Forall_forall with (x := entry) in Hbelow; [| exact Hin].
+ destruct Hbelow as [Hnamespace Hlt].
+ now split; [exact Hnamespace | lia]. }
+ - exact Hid_absent.
+Qed.
+
+Theorem VWENC_121_UNKNOWN_QUERY_ATOM_RECEIVES_STABLE_QUERY_LOCAL_ID :
+ forall (P : CertifiedAtomProfile) (I : FixedWidthCarrierProfile)
+ (fiber : VocabularyFiber P I)
+ (snapshot : VocabularySnapshot P I fiber)
+ (overlay : QueryOverlay P I fiber) atom,
+ query_overlay_well_formed overlay ->
+ lookup_atom
+ (vocabulary_snapshot_live_entries P I fiber snapshot) atom = None ->
+ lookup_query_local overlay atom = None ->
+ let fresh :=
+ mkQueryLocalId P I fiber
+ (query_overlay_namespace P I fiber overlay)
+ (query_overlay_next P I fiber overlay) in
+ let result := resolve_query_atom snapshot overlay atom in
+ query_resolution P I fiber result =
+ QueryLocalSymbol P I fiber fresh /\
+ lookup_query_local (query_overlay_after P I fiber result) atom =
+ Some fresh /\
+ query_overlay_well_formed
+ (query_overlay_after P I fiber result) /\
+ interpret_query_local_id
+ (query_overlay_namespace P I fiber overlay) fresh =
+ Some (query_overlay_next P I fiber overlay) /\
+ ~ In (query_overlay_next P I fiber overlay)
+ (query_overlay_id_values overlay).
+Proof.
+ intros P I fiber snapshot overlay atom Hwell Hdurable Hoverlay.
+ unfold resolve_query_atom. rewrite Hdurable, Hoverlay. simpl.
+ split; [reflexivity |]. split.
+ - unfold lookup_query_local. simpl.
+ destruct (canonical_atom_eq_dec P atom atom);
+ [reflexivity | contradiction].
+ - split.
+ + apply (proj1
+ (query_overlay_fresh_insert_preserves_well_formedness
+ P I fiber overlay atom Hwell Hoverlay)).
+ + split.
+ * unfold interpret_query_local_id. simpl.
+ destruct (query_overlay_namespace_eq_dec P I fiber
+ (query_overlay_namespace P I fiber overlay)
+ (query_overlay_namespace P I fiber overlay));
+ [reflexivity | contradiction].
+ * apply (proj2
+ (query_overlay_fresh_insert_preserves_well_formedness
+ P I fiber overlay atom Hwell Hoverlay)).
+Qed.
+
+Theorem VWENC_122_REPEATED_QUERY_REUSES_OVERLAY_WITHOUT_DURABLE_MUTATION :
+ forall (P : CertifiedAtomProfile) (I : FixedWidthCarrierProfile)
+ (fiber : VocabularyFiber P I)
+ (snapshot : VocabularySnapshot P I fiber)
+ (overlay : QueryOverlay P I fiber) atom first,
+ query_overlay_well_formed overlay ->
+ lookup_atom
+ (vocabulary_snapshot_live_entries P I fiber snapshot) atom = None ->
+ resolve_query_atom snapshot overlay atom = first ->
+ resolve_query_atom snapshot
+ (query_overlay_after P I fiber first) atom =
+ mkQueryResolutionResult P I fiber
+ (query_resolution P I fiber first)
+ (query_overlay_after P I fiber first) /\
+ snapshot = snapshot /\
+ query_overlay_well_formed
+ (query_overlay_after P I fiber first).
+Proof.
+ intros P I fiber snapshot overlay atom first Hwell Hdurable Hfirst.
+ unfold resolve_query_atom in Hfirst.
+ rewrite Hdurable in Hfirst.
+ destruct (lookup_query_local overlay atom)
+ as [existing |] eqn:Hoverlay.
+ - inversion Hfirst. subst first.
+ split.
+ + change
+ ((match lookup_atom
+ (vocabulary_snapshot_live_entries P I fiber snapshot) atom with
+ | Some durable_id =>
+ mkQueryResolutionResult P I fiber
+ (QueryDurableSymbol P I fiber
+ (mkFiberBoundSymbolId P I fiber durable_id)) overlay
+ | None =>
+ match lookup_query_local overlay atom with
+ | Some local_id =>
+ mkQueryResolutionResult P I fiber
+ (QueryLocalSymbol P I fiber local_id) overlay
+ | None =>
+ let local_id :=
+ mkQueryLocalId P I fiber
+ (query_overlay_namespace P I fiber overlay)
+ (query_overlay_next P I fiber overlay) in
+ mkQueryResolutionResult P I fiber
+ (QueryLocalSymbol P I fiber local_id)
+ (mkQueryOverlay P I fiber
+ (query_overlay_namespace P I fiber overlay)
+ ((atom, local_id) ::
+ query_overlay_entries P I fiber overlay)
+ (S (query_overlay_next P I fiber overlay)))
+ end
+ end) =
+ mkQueryResolutionResult P I fiber
+ (QueryLocalSymbol P I fiber existing) overlay).
+ now rewrite Hdurable, Hoverlay.
+ + now split.
+ - inversion Hfirst. subst first. simpl.
+ unfold resolve_query_atom. rewrite Hdurable. simpl.
+ unfold lookup_query_local. simpl.
+ destruct (canonical_atom_eq_dec P atom atom);
+ [| contradiction].
+ split; [reflexivity |]. split; [reflexivity |].
+ apply (proj1
+ (query_overlay_fresh_insert_preserves_well_formedness
+ P I fiber overlay atom Hwell Hoverlay)).
+Qed.
+
+Definition serialize_query_resolution
+ {P : CertifiedAtomProfile}
+ {I : FixedWidthCarrierProfile}
+ {fiber : VocabularyFiber P I}
+ (resolution : QueryAtomResolution P I fiber)
+ : option (FiberBoundSymbolId P I) :=
+ match resolution with
+ | QueryDurableSymbol _ _ _ id => Some id
+ | QueryLocalSymbol _ _ _ _ => None
+ end.
+
+Theorem VWENC_184_DURABLE_QUERY_RESOLUTION_BINDS_THE_EXACT_SNAPSHOT_FIBER :
+ forall (P : CertifiedAtomProfile) (I : FixedWidthCarrierProfile)
+ (fiber : VocabularyFiber P I)
+ (snapshot : VocabularySnapshot P I fiber)
+ (overlay : QueryOverlay P I fiber) atom id,
+ lookup_atom
+ (vocabulary_snapshot_live_entries P I fiber snapshot) atom = Some id ->
+ query_resolution P I fiber
+ (resolve_query_atom snapshot overlay atom) =
+ QueryDurableSymbol P I fiber
+ (mkFiberBoundSymbolId P I fiber id) /\
+ serialize_query_resolution
+ (query_resolution P I fiber
+ (resolve_query_atom snapshot overlay atom)) =
+ Some (mkFiberBoundSymbolId P I fiber id).
+Proof.
+ intros P I fiber snapshot overlay atom id Hlookup.
+ unfold resolve_query_atom. rewrite Hlookup. now split.
+Qed.
+
+Theorem VWENC_185_SERIALIZED_DURABLE_QUERY_ID_RETAINS_ITS_FIBER :
+ forall (P : CertifiedAtomProfile) (I : FixedWidthCarrierProfile)
+ (fiber actual : VocabularyFiber P I) id,
+ serialize_query_resolution
+ (QueryDurableSymbol P I fiber
+ (mkFiberBoundSymbolId P I actual id)) =
+ Some (mkFiberBoundSymbolId P I actual id) /\
+ (fiber <> actual ->
+ interpret_symbol_id fiber
+ (mkFiberBoundSymbolId P I actual id) = None).
+Proof.
+ intros P I fiber actual id.
+ split; [reflexivity |].
+ apply VWENC_112_CROSS_FIBER_ID_INTERPRETATION_IS_REJECTED.
+Qed.
+
+Theorem VWENC_139_QUERY_LOCAL_IDS_CANNOT_ENTER_DURABLE_ID_SEQUENCES :
+ forall (P : CertifiedAtomProfile) (I : FixedWidthCarrierProfile)
+ (fiber : VocabularyFiber P I) local_id,
+ serialize_query_resolution
+ (QueryLocalSymbol P I fiber local_id) = None.
+Proof. reflexivity. Qed.
+(** ** Exact dependent sequence descriptors *)
+
+Theorem VWENC_123_SEQUENCE_DESCRIPTOR_REQUIRES_EXACT_VOCABULARY_FIBER :
+ forall (P : CertifiedAtomProfile) (I : FixedWidthCarrierProfile)
+ (fiber : VocabularyFiber P I)
+ (snapshot : VocabularySnapshot P I fiber) descriptor,
+ descriptor_accepts_vocabulary_snapshot snapshot descriptor ->
+ descriptor_fiber P I descriptor = fiber.
+Proof. intros P I fiber snapshot descriptor [Hexact _]. exact Hexact. Qed.
+
+Theorem VWENC_124_DESCRIPTOR_VALIDATES_EACH_LIVE_ID_NOT_DENSE_FRONTIER :
+ forall (P : CertifiedAtomProfile) (I : FixedWidthCarrierProfile)
+ (fiber : VocabularyFiber P I)
+ (snapshot : VocabularySnapshot P I fiber) descriptor id,
+ descriptor_accepts_vocabulary_snapshot snapshot descriptor ->
+ In id (descriptor_ids P I descriptor) ->
+ symbol_id_value I id <
+ descriptor_required_frontier P I descriptor /\
+ live_symbol
+ (vocabulary_snapshot_live_entries P I fiber snapshot) id.
+Proof.
+ intros P I fiber snapshot descriptor id
+ [_ [_ Hids]] Hin.
+ now apply Forall_forall with (x := id) in Hids.
+Qed.
+
+(** ** Immutable exact-state snapshot observations *)
+
+Definition observed_vocabulary_entry
+ {P : CertifiedAtomProfile} {I : FixedWidthCarrierProfile}
+ (entry : VocabularyEntry P I) :=
+ (canonical_atom_identity (fst entry),
+ symbol_id_value I (snd entry)).
+
+Definition observed_symbol_sequence
+ {I : FixedWidthCarrierProfile} (sequence : list (SymbolId I)) :=
+ map (symbol_id_value I) sequence.
+
+Definition observed_term_entry
+ {I T : FixedWidthCarrierProfile} (entry : TermEntry I T) :=
+ (observed_symbol_sequence (fst entry),
+ term_id_value T (snd entry)).
+
+Definition observed_reverse_span
+ {I : FixedWidthCarrierProfile}
+ (entry : SymbolId I * ByteSpan) :=
+ (symbol_id_value I (fst entry),
+ (span_offset (snd entry), span_length (snd entry))).
+
+Definition observed_allocation_classes
+ {P : CertifiedAtomProfile}
+ {I T : FixedWidthCarrierProfile}
+ (state : InterningState P I T) :=
+ (map observed_vocabulary_entry
+ (state_reserved_entries P I T state),
+ (map observed_vocabulary_entry
+ (state_claimed_entries P I T state),
+ (map observed_vocabulary_entry
+ (state_live_entries P I T state),
+ (map observed_vocabulary_entry
+ (state_ever_entries P I T state),
+ (map observed_vocabulary_entry
+ (state_orphan_entries P I T state),
+ map observed_vocabulary_entry
+ (state_unmaterialized_orphan_entries P I T state)))))).
+
+Definition observed_packed_storage
+ {P : CertifiedAtomProfile}
+ {I T : FixedWidthCarrierProfile}
+ (state : InterningState P I T) :=
+ (packed_canonical_bytes I (state_packed_storage P I T state),
+ map observed_reverse_span
+ (packed_reverse_spans I (state_packed_storage P I T state))).
+
+Definition observed_dependent_state
+ {P : CertifiedAtomProfile}
+ {I T : FixedWidthCarrierProfile}
+ (state : InterningState P I T) :=
+ (state_allocator_frontier P I T state,
+ (map observed_symbol_sequence (state_sequences P I T state),
+ (state_term_dictionary_enabled P I T state,
+ map observed_term_entry (state_term_entries P I T state)))).
+
+Definition interning_state_observation
+ {P : CertifiedAtomProfile}
+ {I T : FixedWidthCarrierProfile}
+ (state : InterningState P I T) :=
+ (vocabulary_fiber_identity (state_fiber P I T state),
+ (term_dictionary_fiber_identity (state_term_fiber P I T state),
+ (observed_allocation_classes state,
+ (observed_packed_storage state,
+ observed_dependent_state state)))).
+
+Record InternedDictionarySnapshot
+ (P : CertifiedAtomProfile)
+ (I T : FixedWidthCarrierProfile) : Type :=
+ mkInternedDictionarySnapshot {
+ snapshot_exact_state : InterningState P I T
+ }.
+
+Definition capture_snapshot
+ {P : CertifiedAtomProfile}
+ {I T : FixedWidthCarrierProfile}
+ (state : InterningState P I T)
+ : InternedDictionarySnapshot P I T :=
+ mkInternedDictionarySnapshot P I T state.
+
+Definition snapshot_observation
+ {P : CertifiedAtomProfile}
+ {I T : FixedWidthCarrierProfile}
+ (snapshot : InternedDictionarySnapshot P I T) :=
+ interning_state_observation
+ (snapshot_exact_state P I T snapshot).
+
+Record SnapshotSession
+ (P : CertifiedAtomProfile)
+ (I T : FixedWidthCarrierProfile) : Type :=
+ mkSnapshotSession {
+ session_captured : InternedDictionarySnapshot P I T;
+ session_current : InterningState P I T
+ }.
+
+Definition begin_snapshot_session
+ {P : CertifiedAtomProfile}
+ {I T : FixedWidthCarrierProfile}
+ (state : InterningState P I T) : SnapshotSession P I T :=
+ mkSnapshotSession P I T (capture_snapshot state) state.
+
+Inductive SnapshotSessionTransition
+ {P : CertifiedAtomProfile}
+ {I T : FixedWidthCarrierProfile}
+ : SnapshotSession P I T -> SnapshotSession P I T -> Prop :=
+| AdvanceSnapshotSession :
+ forall captured current later,
+ InterningTransition current later ->
+ SnapshotSessionTransition
+ (mkSnapshotSession P I T captured current)
+ (mkSnapshotSession P I T captured later).
+
+Theorem VWENC_125_CAPTURED_SNAPSHOT_OBSERVATIONS_SURVIVE_LATER_PUBLICATION :
+ forall (P : CertifiedAtomProfile) (I T : FixedWidthCarrierProfile)
+ (before later : SnapshotSession P I T),
+ SnapshotSessionTransition before later ->
+ session_captured P I T later = session_captured P I T before /\
+ snapshot_observation (session_captured P I T later) =
+ snapshot_observation (session_captured P I T before).
+Proof.
+ intros P I T before later Htransition.
+ inversion Htransition. now split.
+Qed.
+
+Theorem VWENC_173_CAPTURED_SNAPSHOT_IS_THE_EXACT_INITIAL_STATE :
+ forall (P : CertifiedAtomProfile) (I T : FixedWidthCarrierProfile)
+ (state : InterningState P I T),
+ snapshot_exact_state P I T
+ (session_captured P I T (begin_snapshot_session state)) = state /\
+ snapshot_observation
+ (session_captured P I T (begin_snapshot_session state)) =
+ interning_state_observation state.
+Proof. intros. now split. Qed.
+
+Inductive SnapshotSessionReachable
+ {P : CertifiedAtomProfile}
+ {I T : FixedWidthCarrierProfile}
+ (initial : SnapshotSession P I T)
+ : SnapshotSession P I T -> Prop :=
+| SnapshotSessionReachableInitial :
+ SnapshotSessionReachable initial initial
+| SnapshotSessionReachableStep :
+ forall current later,
+ SnapshotSessionReachable initial current ->
+ SnapshotSessionTransition current later ->
+ SnapshotSessionReachable initial later.
+
+Theorem VWENC_174_EXACT_CAPTURE_SURVIVES_ARBITRARY_LATER_TRANSITIONS :
+ forall (P : CertifiedAtomProfile) (I T : FixedWidthCarrierProfile)
+ (initial later : SnapshotSession P I T),
+ SnapshotSessionReachable initial later ->
+ session_captured P I T later = session_captured P I T initial /\
+ snapshot_observation (session_captured P I T later) =
+ snapshot_observation (session_captured P I T initial).
+Proof.
+ intros P I T initial later Hreachable.
+ induction Hreachable as
+ [| current later Hcurrent IH Htransition].
+ - now split.
+ - destruct (VWENC_125_CAPTURED_SNAPSHOT_OBSERVATIONS_SURVIVE_LATER_PUBLICATION
+ P I T current later Htransition) as [Hcaptured Hobservation].
+ split.
+ + now rewrite Hcaptured.
+ + now rewrite Hobservation.
+Qed.
+(** ** Exact, machine-readable model-to-Rust correspondence *)
+
+Inductive CorrespondenceRelationship : Type :=
+| Refines
+| CommonSubstrateOnly
+| Conflicts
+| Prospective.
+
+Inductive InterningFormalPoint : Type :=
+| PointCertifiedAtomProfile
+| PointSymbolIdCarrierCodec
+| PointTermIdCarrierCodec
+| PointForwardAtomToId
+| PointReverseIdToAtom
+| PointForwardReverseBijection
+| PointAllocationStatus
+| PointClaimAllocation
+| PointOrphanAllocation
+| PointTombstoneNoReuse
+| PointPackedCanonicalStorage
+| PointSparseAllocatorFrontierStorage
+| PointSparseAllocatorFrontierAccess
+| PointVocabularyFiberHeader
+| PointIdSequenceView
+| PointSequenceDescriptorLiveMembership
+| PointOptionalTermDictionary
+| PointCoordinatedSequenceOwner
+| PointQueryLocalOverlay
+| PointImmutableSnapshot
+| PointBeginGeneration
+| PointDurabilizeLiveId
+| PointSealDurableVocabulary
+| PointPublishVocabularyEligibility
+| PointStageDependentSequence
+| PointPublishSequenceVisibility
+| PointDurabilizeDependentSequence
+| PointWriteVocabularyObject
+| PointSyncVocabularyObject
+| PointWriteSequenceObject
+| PointSyncSequenceObject
+| PointAtomicCheckpointHeadPublication
+| PointCaptureReader
+| PointSaveReaderContinuation
+| PointResumeReaderContinuation
+| PointLoseVocabularyArtifact
+| PointLoseSequenceArtifact
+| PointCorruptVocabularyArtifact
+| PointCorruptSequenceArtifact
+| PointCrashTransition
+| PointStrictPairRecovery
+| PointCommitSequenceSubstrate
+| PointCommittedWatermarkSubstrate
+| PointDurableOverlayInsertionSubstrate
+| PointCheckpointLockSubstrate
+| PointHeaderCheckpointPublicationSubstrate.
+
+Inductive ImplementationObligation : Type :=
+| ObligationAddCertifiedProfileSurface
+| ObligationAddSymbolIdCarrierCodec
+| ObligationAddTermIdCarrierCodec
+| ObligationGeneralizeForwardVocabulary
+| ObligationGeneralizeReverseVocabulary
+| ObligationCoordinateBijectionVisibility
+| ObligationAddAllocationLedger
+| ObligationReuseSparseAllocationClaim
+| ObligationRetainOrphanedIds
+| ObligationAddNoReuseTombstones
+| ObligationAddPackedStorage
+| ObligationPreserveSparseFrontierStorage
+| ObligationExposeSparseFrontier
+| ObligationAddProfileGenerationHeader
+| ObligationAddBorrowedFiberBoundView
+| ObligationAddSequenceDescriptorValidation
+| ObligationAddOptionalTermDictionary
+| ObligationAddCoordinatedOwner
+| ObligationAddEphemeralOverlay
+| ObligationAuditSnapshotRefinement
+| ObligationAddGenerationStaging
+| ObligationAddDurablePackedPublication
+| ObligationAddVocabularySeal
+| ObligationAddVocabularyEligibilityPublication
+| ObligationAddSequenceStaging
+| ObligationAddSequenceVisibilityPublication
+| ObligationAddSequenceDurabilityPublication
+| ObligationReuseVocabularyObjectWrite
+| ObligationReuseVocabularyObjectSync
+| ObligationReuseSequenceObjectWrite
+| ObligationReuseSequenceObjectSync
+| ObligationAddAtomicCheckpointHead
+| ObligationAddReaderCapture
+| ObligationAddContinuationCapture
+| ObligationAddContinuationResume
+| ObligationAddVocabularyLossRecoveryCase
+| ObligationAddSequenceLossRecoveryCase
+| ObligationAddVocabularyCorruptionRecoveryCase
+| ObligationAddSequenceCorruptionRecoveryCase
+| ObligationAddCrashStateTransition
+| ObligationAddExactOldNewRecovery
+| ObligationReuseCommitSequence
+| ObligationReuseCommittedWatermark
+| ObligationReuseDurableOverlayInsertion
+| ObligationReuseCheckpointLock
+| ObligationExtendHeaderCheckpointPublication.
+
+Record CorrespondenceRow : Type := mkCorrespondenceRow {
+ correspondence_formal_point : InterningFormalPoint;
+ correspondence_source_path : string;
+ correspondence_rust_symbol : string;
+ correspondence_relationship : CorrespondenceRelationship;
+ correspondence_obligation : ImplementationObligation
+}.
+
+Definition declared_correspondence_row
+ (point : InterningFormalPoint) : CorrespondenceRow :=
+ match point with
+ | PointCertifiedAtomProfile =>
+ mkCorrespondenceRow point
+ ("src/profile/mod.rs")%string
+ ("DictionaryProfile")%string
+ Prospective ObligationAddCertifiedProfileSurface
+ | PointSymbolIdCarrierCodec =>
+ mkCorrespondenceRow point
+ ("src/profile/interned/id.rs")%string
+ ("SymbolId::{try_from_nat,encode,decode}")%string
+ Prospective ObligationAddSymbolIdCarrierCodec
+ | PointTermIdCarrierCodec =>
+ mkCorrespondenceRow point
+ ("src/profile/interned/id.rs")%string
+ ("TermId::{try_from_nat,encode,decode}")%string
+ Prospective ObligationAddTermIdCarrierCodec
+ | PointForwardAtomToId =>
+ mkCorrespondenceRow point
+ ("src/persistent_artrie/vocab/mutation_api.rs")%string
+ ("PersistentVocabARTrie::insert")%string
+ CommonSubstrateOnly ObligationGeneralizeForwardVocabulary
+ | PointReverseIdToAtom =>
+ mkCorrespondenceRow point
+ ("src/persistent_artrie/vocab/query_api.rs")%string
+ ("PersistentVocabARTrie::get_term")%string
+ CommonSubstrateOnly ObligationGeneralizeReverseVocabulary
+ | PointForwardReverseBijection =>
+ mkCorrespondenceRow point
+ ("src/persistent_artrie/vocab/dict_impl.rs")%string
+ ("PersistentVocabARTrie::reverse_term_map")%string
+ Conflicts ObligationCoordinateBijectionVisibility
+ | PointAllocationStatus =>
+ mkCorrespondenceRow point
+ ("src/profile/interned/allocation.rs")%string
+ ("AllocationStatus")%string
+ Prospective ObligationAddAllocationLedger
+ | PointClaimAllocation =>
+ mkCorrespondenceRow point
+ ("src/persistent_artrie/vocab/mutation_api.rs")%string
+ ("PersistentVocabARTrie::insert_overlay")%string
+ CommonSubstrateOnly ObligationReuseSparseAllocationClaim
+ | PointOrphanAllocation =>
+ mkCorrespondenceRow point
+ ("src/persistent_artrie/vocab/mutation_api.rs")%string
+ ("PersistentVocabARTrie::insert_overlay")%string
+ CommonSubstrateOnly ObligationRetainOrphanedIds
+ | PointTombstoneNoReuse =>
+ mkCorrespondenceRow point
+ ("src/profile/interned/allocation.rs")%string
+ ("AllocationLedger::tombstone")%string
+ Prospective ObligationAddNoReuseTombstones
+ | PointPackedCanonicalStorage =>
+ mkCorrespondenceRow point
+ ("src/profile/interned/storage.rs")%string
+ ("PackedAtomStorage")%string
+ Prospective ObligationAddPackedStorage
+ | PointSparseAllocatorFrontierStorage =>
+ mkCorrespondenceRow point
+ ("src/persistent_artrie/vocab/dict_impl.rs")%string
+ ("PersistentVocabARTrie::next_index")%string
+ CommonSubstrateOnly ObligationPreserveSparseFrontierStorage
+ | PointSparseAllocatorFrontierAccess =>
+ mkCorrespondenceRow point
+ ("src/persistent_artrie/vocab/query_api.rs")%string
+ ("PersistentVocabARTrie::next_index")%string
+ CommonSubstrateOnly ObligationExposeSparseFrontier
+ | PointVocabularyFiberHeader =>
+ mkCorrespondenceRow point
+ ("src/persistent_artrie/vocab/types.rs")%string
+ ("VocabTrieFileHeader")%string
+ Conflicts ObligationAddProfileGenerationHeader
+ | PointIdSequenceView =>
+ mkCorrespondenceRow point
+ ("src/profile/interned/view.rs")%string
+ ("IdSequenceView")%string
+ Prospective ObligationAddBorrowedFiberBoundView
+ | PointSequenceDescriptorLiveMembership =>
+ mkCorrespondenceRow point
+ ("src/profile/interned/descriptor.rs")%string
+ ("SequenceDescriptor::validate_live_ids")%string
+ Prospective ObligationAddSequenceDescriptorValidation
+ | PointOptionalTermDictionary =>
+ mkCorrespondenceRow point
+ ("src/profile/interned/term_dictionary.rs")%string
+ ("TermSequenceDictionary")%string
+ Prospective ObligationAddOptionalTermDictionary
+ | PointCoordinatedSequenceOwner =>
+ mkCorrespondenceRow point
+ ("src/profile/interned/coordinator.rs")%string
+ ("InternedSequenceDictionary (entries: I) -> Self
+ where
+ P: crate::AtomProfile (&self, sequence: &crate::AtomSequence ) -> Option (entries: I) -> Self
+ where
+ P: AtomProfile (sequences: I) -> Self
+ where
+ P: crate::AtomProfile (entries: I) -> Self
+ where
+ P: crate::AtomProfile (&self, sequence: &crate::AtomSequence ) -> Option (sequences: I) -> Self
+ where
+ P: crate::AtomProfile (entries: I) -> Self
+ where
+ P: crate::AtomProfile (&self, sequence: &crate::AtomSequence ) -> Option \{$'
+}
+
+require_vocab_struct() {
+ local point="$1"
+ local source_path="$2"
+ local rust_symbol="$3"
+ require_regex "$point" "$source_path" "$rust_symbol" \
+ 'PersistentVocabARTrie type owner' \
+ '^pub struct PersistentVocabARTrie