@feltdb/core 0.8.4 → 0.8.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (160) hide show
  1. package/dist/create/package-versions.js +1 -1
  2. package/dist/create/server-source/Cargo.lock +165 -0
  3. package/dist/create/server-source/Cargo.toml +9 -0
  4. package/dist/create/server-source/crates/feltdb/Cargo.toml +3 -0
  5. package/dist/create/server-source/crates/feltdb/benches/gate13_baseline.rs +44 -44
  6. package/dist/create/server-source/crates/feltdb/benches/gate13_phase_7_1_release_economics.rs +12 -24
  7. package/dist/create/server-source/crates/feltdb/benches/gate_13_redux.rs +7 -13
  8. package/dist/create/server-source/crates/feltdb/benches/gate_13_regression_runner.rs +13 -10
  9. package/dist/create/server-source/crates/feltdb/benches/gate_14a_concurrent_writer_scaling.rs +12 -9
  10. package/dist/create/server-source/crates/feltdb/benches/gate_14a_production_admission_revalidation.rs +78 -25
  11. package/dist/create/server-source/crates/feltdb/benches/gate_14a_rc2_admission_contract.rs +16 -13
  12. package/dist/create/server-source/crates/feltdb/benches/gate_14a_rc_root_cause.rs +13 -5
  13. package/dist/create/server-source/crates/feltdb/benches/gate_14a_sync1_queued_prototype.rs +41 -22
  14. package/dist/create/server-source/crates/feltdb/benches/gate_14a_sync_economics.rs +33 -15
  15. package/dist/create/server-source/crates/feltdb/benches/gate_14b_causal_backlog_scaling.rs +100 -33
  16. package/dist/create/server-source/crates/feltdb/benches/gate_14c_replication_contract_test.rs +56 -20
  17. package/dist/create/server-source/crates/feltdb/benches/gate_14c_replication_scaling.rs +116 -41
  18. package/dist/create/server-source/crates/feltdb/benches/gate_14d_combined_dimension_scaling.rs +186 -55
  19. package/dist/create/server-source/crates/feltdb/benches/phase_7_1_2_optimization_benchmark.rs +64 -26
  20. package/dist/create/server-source/crates/feltdb/benches/phase_7_1_3_crossover_analysis.rs +46 -15
  21. package/dist/create/server-source/crates/feltdb/src/admission.rs +8 -15
  22. package/dist/create/server-source/crates/feltdb/src/admission_contract_tests.rs +43 -13
  23. package/dist/create/server-source/crates/feltdb/src/adversarial_transport.rs +15 -42
  24. package/dist/create/server-source/crates/feltdb/src/analytics.rs +65 -19
  25. package/dist/create/server-source/crates/feltdb/src/application.rs +113 -30
  26. package/dist/create/server-source/crates/feltdb/src/authorization_security_tests.rs +475 -140
  27. package/dist/create/server-source/crates/feltdb/src/cardinality_diagnostics.rs +17 -15
  28. package/dist/create/server-source/crates/feltdb/src/cardinality_endpoint.rs +0 -1
  29. package/dist/create/server-source/crates/feltdb/src/causal_backlog_bound.rs +59 -15
  30. package/dist/create/server-source/crates/feltdb/src/causal_dependency_barrier.rs +266 -114
  31. package/dist/create/server-source/crates/feltdb/src/causal_dependency_barrier_phase_7_1.rs +25 -7
  32. package/dist/create/server-source/crates/feltdb/src/concurrency_fuzzing.rs +10 -15
  33. package/dist/create/server-source/crates/feltdb/src/consistency_contract.rs +3 -11
  34. package/dist/create/server-source/crates/feltdb/src/crash_atomic_boundary.rs +14 -5
  35. package/dist/create/server-source/crates/feltdb/src/crash_injection.rs +21 -25
  36. package/dist/create/server-source/crates/feltdb/src/crash_recovery_tests.rs +14 -11
  37. package/dist/create/server-source/crates/feltdb/src/dedup_bound_investigation.rs +103 -22
  38. package/dist/create/server-source/crates/feltdb/src/distributed_indexing.rs +18 -15
  39. package/dist/create/server-source/crates/feltdb/src/durability_guarantees.rs +12 -8
  40. package/dist/create/server-source/crates/feltdb/src/durable_dedup_set.rs +1 -5
  41. package/dist/create/server-source/crates/feltdb/src/durable_operation_identity.rs +87 -23
  42. package/dist/create/server-source/crates/feltdb/src/durable_operation_log.rs +3 -7
  43. package/dist/create/server-source/crates/feltdb/src/durable_sync.rs +10 -9
  44. package/dist/create/server-source/crates/feltdb/src/in_process_transport.rs +1 -6
  45. package/dist/create/server-source/crates/feltdb/src/indexing.rs +35 -38
  46. package/dist/create/server-source/crates/feltdb/src/lib.rs +1648 -46
  47. package/dist/create/server-source/crates/feltdb/src/managed_cas_tests.rs +4 -1
  48. package/dist/create/server-source/crates/feltdb/src/metrics.rs +0 -1
  49. package/dist/create/server-source/crates/feltdb/src/multi_node_convergence.rs +1 -2
  50. package/dist/create/server-source/crates/feltdb/src/multi_operation_transaction.rs +107 -30
  51. package/dist/create/server-source/crates/feltdb/src/observability.rs +19 -6
  52. package/dist/create/server-source/crates/feltdb/src/operation.rs +39 -0
  53. package/dist/create/server-source/crates/feltdb/src/operation_algebra.rs +12 -11
  54. package/dist/create/server-source/crates/feltdb/src/operation_log.rs +9 -4
  55. package/dist/create/server-source/crates/feltdb/src/p1_application_atomicity.rs +65 -18
  56. package/dist/create/server-source/crates/feltdb/src/p1_atomicity_acceptance.rs +193 -57
  57. package/dist/create/server-source/crates/feltdb/src/partition_reconciliation.rs +37 -27
  58. package/dist/create/server-source/crates/feltdb/src/permutation_scheduler.rs +38 -10
  59. package/dist/create/server-source/crates/feltdb/src/persistence_reality.rs +20 -14
  60. package/dist/create/server-source/crates/feltdb/src/phase1b_acceptance.rs +394 -229
  61. package/dist/create/server-source/crates/feltdb/src/phase1c1_acceptance.rs +8 -6
  62. package/dist/create/server-source/crates/feltdb/src/phase1c2_acceptance.rs +11 -13
  63. package/dist/create/server-source/crates/feltdb/src/phase1c3_acceptance.rs +79 -70
  64. package/dist/create/server-source/crates/feltdb/src/phase1c_atomicity_proof.rs +3 -3
  65. package/dist/create/server-source/crates/feltdb/src/phase5_integration.rs +33 -11
  66. package/dist/create/server-source/crates/feltdb/src/phase5_scenarios.rs +6 -6
  67. package/dist/create/server-source/crates/feltdb/src/phase6_adversarial_scenarios.rs +14 -56
  68. package/dist/create/server-source/crates/feltdb/src/phase6_convergence_validator.rs +29 -27
  69. package/dist/create/server-source/crates/feltdb/src/phase6_persistence.rs +35 -17
  70. package/dist/create/server-source/crates/feltdb/src/phase_1c_real_tcp.rs +8 -2
  71. package/dist/create/server-source/crates/feltdb/src/phase_2a_failures.rs +59 -15
  72. package/dist/create/server-source/crates/feltdb/src/phase_2b_network.rs +70 -17
  73. package/dist/create/server-source/crates/feltdb/src/phase_2c_cascading.rs +23 -6
  74. package/dist/create/server-source/crates/feltdb/src/phase_3_durability.rs +12 -3
  75. package/dist/create/server-source/crates/feltdb/src/phase_4_baseline.rs +41 -11
  76. package/dist/create/server-source/crates/feltdb/src/phase_5_soak.rs +56 -25
  77. package/dist/create/server-source/crates/feltdb/src/policy_evaluation.rs +701 -245
  78. package/dist/create/server-source/crates/feltdb/src/production_api.rs +31 -13
  79. package/dist/create/server-source/crates/feltdb/src/query_performance.rs +6 -8
  80. package/dist/create/server-source/crates/feltdb/src/replay_fuzzing.rs +5 -5
  81. package/dist/create/server-source/crates/feltdb/src/replica_acknowledgements.rs +48 -18
  82. package/dist/create/server-source/crates/feltdb/src/replica_membership.rs +30 -11
  83. package/dist/create/server-source/crates/feltdb/src/replication_manager.rs +6 -3
  84. package/dist/create/server-source/crates/feltdb/src/replication_protocol.rs +4 -3
  85. package/dist/create/server-source/crates/feltdb/src/sharding.rs +36 -10
  86. package/dist/create/server-source/crates/feltdb/src/state_conflict_contract.rs +516 -0
  87. package/dist/create/server-source/crates/feltdb/src/state_contract.rs +13 -4
  88. package/dist/create/server-source/crates/feltdb/src/state_diff_contract.rs +222 -0
  89. package/dist/create/server-source/crates/feltdb/src/state_facade.rs +82 -54
  90. package/dist/create/server-source/crates/feltdb/src/state_hash.rs +2 -2
  91. package/dist/create/server-source/crates/feltdb/src/state_model.rs +1565 -536
  92. package/dist/create/server-source/crates/feltdb/src/state_transition_store.rs +6 -3
  93. package/dist/create/server-source/crates/feltdb/src/state_trigger.rs +672 -0
  94. package/dist/create/server-source/crates/feltdb/src/storage.rs +9 -3
  95. package/dist/create/server-source/crates/feltdb/src/submission.rs +5 -11
  96. package/dist/create/server-source/crates/feltdb/src/tcp_transport.rs +6 -8
  97. package/dist/create/server-source/crates/feltdb/src/transaction_api.rs +24 -35
  98. package/dist/create/server-source/crates/feltdb/src/transaction_invariants.rs +24 -8
  99. package/dist/create/server-source/crates/feltdb/src/transaction_preconditions.rs +248 -59
  100. package/dist/create/server-source/crates/feltdb/src/transactions.rs +17 -20
  101. package/dist/create/server-source/crates/feltdb/src/trigger_contract.rs +749 -0
  102. package/dist/create/server-source/crates/feltdb/src/worker_mesh.rs +1 -0
  103. package/dist/create/server-source/crates/feltdb/src/workload.rs +512 -4
  104. package/dist/create/server-source/crates/feltdb/src/workload_diagnostics.rs +3 -4
  105. package/dist/create/server-source/crates/feltdb/tests/bounded_read_contract.rs +132 -0
  106. package/dist/create/server-source/crates/feltdb/tests/branching_evidence.rs +299 -0
  107. package/dist/create/server-source/crates/feltdb/tests/compaction_stall_contract.rs +272 -0
  108. package/dist/create/server-source/crates/feltdb/tests/crash_durability_contract.rs +467 -0
  109. package/dist/create/server-source/crates/feltdb/tests/current_revision_authority_evidence.rs +309 -0
  110. package/dist/create/server-source/crates/feltdb/tests/durable_backup_contract.rs +445 -0
  111. package/dist/create/server-source/crates/feltdb/tests/durable_corruption_contract.rs +518 -0
  112. package/dist/create/server-source/crates/feltdb/tests/durable_format_compatibility.rs +392 -0
  113. package/dist/create/server-source/crates/feltdb/tests/feltdb_state_boundary_tests.rs +436 -220
  114. package/dist/create/server-source/crates/feltdb/tests/fixtures/state_conflict_contract_corpus.json +1916 -0
  115. package/dist/create/server-source/crates/feltdb/tests/fixtures/state_diff_contract_corpus.json +1878 -0
  116. package/dist/create/server-source/crates/feltdb/tests/fixtures/trigger_contract_corpus.json +1862 -0
  117. package/dist/create/server-source/crates/feltdb/tests/operational_health_contract.rs +278 -0
  118. package/dist/create/server-source/crates/feltdb/tests/pr34_query_collection.rs +2 -1
  119. package/dist/create/server-source/crates/feltdb/tests/pr35_equality_index.rs +80 -25
  120. package/dist/create/server-source/crates/feltdb/tests/pr7_self_authorization_proof.rs +5 -8
  121. package/dist/create/server-source/crates/feltdb/tests/pr8_vocabulary_assessment.rs +52 -44
  122. package/dist/create/server-source/crates/feltdb/tests/pr9_phase2_boundary_tests.rs +33 -16
  123. package/dist/create/server-source/crates/feltdb/tests/pr9_phase3a_path_a_tests.rs +22 -7
  124. package/dist/create/server-source/crates/feltdb/tests/pr9_phase3c_authorized_mutations.rs +41 -22
  125. package/dist/create/server-source/crates/feltdb/tests/pr9_phase3c_role_based_authorization.rs +25 -8
  126. package/dist/create/server-source/crates/feltdb/tests/pr9_phase3c_simple_auth_delete.rs +9 -6
  127. package/dist/create/server-source/crates/feltdb/tests/pr9_phase3c_team_delete_role_authorization.rs +120 -69
  128. package/dist/create/server-source/crates/feltdb/tests/pr9_teams_role_based_access.rs +21 -10
  129. package/dist/create/server-source/crates/feltdb/tests/production_readiness_contract.rs +1365 -0
  130. package/dist/create/server-source/crates/feltdb/tests/reconciliation_application.rs +868 -0
  131. package/dist/create/server-source/crates/feltdb/tests/reconciliation_wire_format_evidence.rs +221 -0
  132. package/dist/create/server-source/crates/feltdb/tests/replicated_history_contract.rs +417 -0
  133. package/dist/create/server-source/crates/feltdb/tests/resource_scoped_revisions.rs +338 -0
  134. package/dist/create/server-source/crates/feltdb/tests/revision_identity_contract.rs +1039 -0
  135. package/dist/create/server-source/crates/feltdb/tests/revision_model_decision.rs +739 -0
  136. package/dist/create/server-source/crates/feltdb/tests/revision_retention_boundary_evidence.rs +427 -0
  137. package/dist/create/server-source/crates/feltdb/tests/saas_authorization_integration.rs +3 -3
  138. package/dist/create/server-source/crates/feltdb/tests/saas_invitation_lifecycle.rs +25 -22
  139. package/dist/create/server-source/crates/feltdb/tests/state_conflict_contract_conformance.rs +1799 -0
  140. package/dist/create/server-source/crates/feltdb/tests/state_diff_contract_conformance.rs +1316 -0
  141. package/dist/create/server-source/crates/feltdb/tests/state_model_integration.rs +53 -61
  142. package/dist/create/server-source/crates/feltdb/tests/state_persistence_integration.rs +156 -61
  143. package/dist/create/server-source/crates/feltdb/tests/state_store_boundary_evidence.rs +299 -0
  144. package/dist/create/server-source/crates/feltdb/tests/sync_divergence_evidence.rs +255 -0
  145. package/dist/create/server-source/crates/feltdb/tests/three_way_input_boundary_evidence.rs +249 -0
  146. package/dist/create/server-source/crates/feltdb/tests/trigger_contract_conformance.rs +994 -0
  147. package/dist/create/server-source/crates/feltdb/tests/workload_envelope_contract.rs +442 -0
  148. package/dist/create/server-source/crates/feltdb-server/src/app_state.rs +16 -1
  149. package/dist/create/server-source/crates/feltdb-server/src/auth.rs +164 -13
  150. package/dist/create/server-source/crates/feltdb-server/src/main.rs +695 -47
  151. package/dist/create/server-source/crates/feltdb-server/src/metrics.rs +21 -0
  152. package/dist/studio-app/assets/{feltdb_wasm-CVQWgXO-.js → feltdb_wasm-C1VhI-U5.js} +1 -1
  153. package/dist/studio-app/assets/feltdb_wasm_bg-C8HXbAXb.wasm +0 -0
  154. package/dist/studio-app/assets/{index-DwgNAIIX.js → index-Bbos1m2U.js} +1 -1
  155. package/dist/studio-app/index.html +1 -1
  156. package/dist/wasm/feltdb_wasm_bg.wasm +0 -0
  157. package/dist/workload.d.ts +2 -1
  158. package/dist/workload.d.ts.map +1 -1
  159. package/package.json +1 -1
  160. package/dist/studio-app/assets/feltdb_wasm_bg-CNVpvaZV.wasm +0 -0
@@ -0,0 +1,1039 @@
1
+ //! The revision identity and ancestry contract.
2
+ //!
3
+ //! This file **implements nothing**. It makes the semantics of identity,
4
+ //! ancestry and mutation *executable*, so that the choice between candidate
5
+ //! models is made against a written contract rather than against whatever the
6
+ //! hash function happens to do.
7
+ //!
8
+ //! It is the executable half of
9
+ //! `docs/architecture/revision-identity-and-ancestry.md`, which states the
10
+ //! questions and the candidate answers in prose.
11
+ //!
12
+ //! # How to read this file
13
+ //!
14
+ //! Every clause is a question the project must answer before automatic minting
15
+ //! can be built. Each is evaluated against today's implementation by *running
16
+ //! it*, and the answer is a [`Verdict`]:
17
+ //!
18
+ //! | verdict | meaning |
19
+ //! | --- | --- |
20
+ //! | `Honoured` | today's implementation satisfies the clause |
21
+ //! | `HonouredVacuously` | it satisfies the clause only because the behaviour the clause constrains does not exist yet |
22
+ //! | `Violated` | today's implementation contradicts the clause |
23
+ //! | `Unanswerable` | the clause cannot be evaluated, because the data model has no field that could answer it |
24
+ //!
25
+ //! [`LEDGER`] records every verdict. Each clause test recomputes its own
26
+ //! verdict from live behaviour and asserts it matches the record, and
27
+ //! `the_ledger_is_exactly_this` recomputes all of them. **A semantic change
28
+ //! that flips any verdict fails this suite.** That is the point: the contract
29
+ //! cannot drift silently, and cannot be satisfied by accident.
30
+ //!
31
+ //! The `#[ignore]`d tests at the end are the contract in *required* form —
32
+ //! written as they must read once a model is chosen. They fail today, on
33
+ //! purpose. `cargo test -- --ignored` prints exactly what is not yet true.
34
+
35
+ use feltdb::state_model::{
36
+ ParentLookup, RetentionPolicy, RevisionError, StateId, StateRevision, StateStore, StateTopology,
37
+ };
38
+ use feltdb::{FeltDb, JsonCasResult};
39
+ use serde_json::json;
40
+ use std::collections::BTreeMap;
41
+ use std::sync::Arc;
42
+ use tempfile::TempDir;
43
+
44
+ #[derive(Debug, PartialEq, Eq, Clone, Copy)]
45
+ enum Verdict {
46
+ Honoured,
47
+ HonouredVacuously,
48
+ Violated,
49
+ Unanswerable,
50
+ }
51
+
52
+ /// The contract, and what today's implementation does about it.
53
+ ///
54
+ /// Ordered by the question it belongs to, not by verdict.
55
+ const LEDGER: &[(&str, Verdict)] = &[
56
+ // Q1 — what makes two revisions the same revision?
57
+ (
58
+ "I1 identical content yields identical content identity",
59
+ Verdict::Honoured,
60
+ ),
61
+ (
62
+ "I2 the same content can occur twice in one history",
63
+ Verdict::Honoured,
64
+ ),
65
+ (
66
+ "I3 revision identity distinguishes two occurrences of one state",
67
+ Verdict::Honoured,
68
+ ),
69
+ // Q2 — what does `base` mean?
70
+ (
71
+ "B1 base as the parent in the revision DAG",
72
+ Verdict::Honoured,
73
+ ),
74
+ (
75
+ "B2 base as the previous state under the same key",
76
+ Verdict::Honoured,
77
+ ),
78
+ ("B3 base as the previous observed state", Verdict::Honoured),
79
+ (
80
+ "B4 base as the previous durable revision",
81
+ Verdict::Honoured,
82
+ ),
83
+ // Q3 — which mutations create ancestry?
84
+ (
85
+ "M1 an explicit mint validates the parent it is given",
86
+ Verdict::Honoured,
87
+ ),
88
+ ("M2 a fenced write creates ancestry", Verdict::Honoured),
89
+ (
90
+ "M3 an unconditional write creates ancestry",
91
+ Verdict::Honoured,
92
+ ),
93
+ (
94
+ "N1 content equality never confers ancestry",
95
+ Verdict::Honoured,
96
+ ),
97
+ // Q5 — what must topology guarantee?
98
+ ("T1 the durable parent chain is acyclic", Verdict::Honoured),
99
+ ("T2 ancestors terminates", Verdict::Honoured),
100
+ ("T3 is_ancestor terminates", Verdict::Honoured),
101
+ ("T4 common_ancestor terminates", Verdict::Honoured),
102
+ ("T5 every parent reference resolves", Verdict::Honoured),
103
+ (
104
+ "T6 a revision never silently changes its parent",
105
+ Verdict::Honoured,
106
+ ),
107
+ // Q6 — what does compaction promise?
108
+ (
109
+ "C1 compaction deletes acknowledged operation history",
110
+ Verdict::Honoured,
111
+ ),
112
+ ("C2 compaction preserves current state", Verdict::Honoured),
113
+ (
114
+ "C3 revision retention is promised rather than incidental",
115
+ Verdict::Honoured,
116
+ ),
117
+ (
118
+ "C4 the three promises can be requested separately",
119
+ Verdict::Honoured,
120
+ ),
121
+ ];
122
+
123
+ fn recorded(clause: &str) -> Verdict {
124
+ LEDGER
125
+ .iter()
126
+ .find(|(name, _)| *name == clause)
127
+ .unwrap_or_else(|| panic!("{clause} is not in the ledger"))
128
+ .1
129
+ }
130
+
131
+ /// Evaluate a clause against today's implementation, by running it.
132
+ fn evaluate(clause: &str) -> Verdict {
133
+ match clause {
134
+ "I1 identical content yields identical content identity" => i1(),
135
+ "I2 the same content can occur twice in one history" => i2(),
136
+ "I3 revision identity distinguishes two occurrences of one state" => i3(),
137
+ "B1 base as the parent in the revision DAG" => b1(),
138
+ "B2 base as the previous state under the same key" => b2(),
139
+ "B3 base as the previous observed state" => b3(),
140
+ "B4 base as the previous durable revision" => b4(),
141
+ "M1 an explicit mint validates the parent it is given" => m1(),
142
+ "M2 a fenced write creates ancestry" => m2(),
143
+ "M3 an unconditional write creates ancestry" => m3(),
144
+ "N1 content equality never confers ancestry" => n1(),
145
+ "T1 the durable parent chain is acyclic" => t1(),
146
+ "T2 ancestors terminates" => t2(),
147
+ "T3 is_ancestor terminates" => t3(),
148
+ "T4 common_ancestor terminates" => t4(),
149
+ "T5 every parent reference resolves" => t5(),
150
+ "T6 a revision never silently changes its parent" => t6(),
151
+ "C1 compaction deletes acknowledged operation history" => c1(),
152
+ "C2 compaction preserves current state" => c2(),
153
+ "C3 revision retention is promised rather than incidental" => c3(),
154
+ "C4 the three promises can be requested separately" => c4(),
155
+ other => panic!("{other} has no evaluator"),
156
+ }
157
+ }
158
+
159
+ // ---------------------------------------------------------------------------
160
+ // Fixtures
161
+ // ---------------------------------------------------------------------------
162
+
163
+ fn durable_store(name: &str) -> (TempDir, Arc<FeltDb>, StateStore) {
164
+ let directory = TempDir::new().unwrap();
165
+ let db = Arc::new(FeltDb::open(directory.path().join(name)).unwrap());
166
+ let store = StateStore::with_feltdb(db.clone()).unwrap();
167
+ (directory, db, store)
168
+ }
169
+
170
+ /// A revision built by hand, to name a parent the store has never seen.
171
+ fn hand_built(content: &str, parent: Option<StateId>) -> StateRevision {
172
+ StateRevision {
173
+ id: StateId::compute(content),
174
+ resource: R.into(),
175
+ content: content.to_string(),
176
+ content_id: StateId::compute(content),
177
+ parent_id: parent,
178
+ sequence: 0,
179
+ authority: "contract".into(),
180
+ timestamp_ms: 0,
181
+ metadata: BTreeMap::new(),
182
+ }
183
+ }
184
+
185
+ /// The resource every clause exercises, now that a revision belongs to one.
186
+ const R: &str = "tasks:1";
187
+
188
+ const A: &str = r#"{"title":"A"}"#;
189
+ const B: &str = r#"{"title":"B"}"#;
190
+
191
+ /// Commit the sequence A → B → A and return the store. This is the sequence
192
+ /// the whole contract turns on: the most ordinary edit there is.
193
+ fn a_then_b_then_a(name: &str) -> (TempDir, Arc<FeltDb>, StateStore, StateId, StateId) {
194
+ let (directory, db, store) = durable_store(name);
195
+ let first = store.create(R, A.into(), "contract".into()).unwrap();
196
+ let second = store.commit(B.into(), &first, "contract".into()).unwrap();
197
+ store.commit(A.into(), &second, "contract".into()).unwrap();
198
+ let (a, b) = (first.id.clone(), second.id.clone());
199
+ (directory, db, store, a, b)
200
+ }
201
+
202
+ /// Whether a cycle is reachable by following parent links from `start`.
203
+ ///
204
+ /// Deliberately bounded. The traversals this stands in for are not.
205
+ fn cycle_reachable_from(store: &StateStore, start: &StateId) -> bool {
206
+ let mut seen: Vec<StateId> = Vec::new();
207
+ let mut current = start.clone();
208
+ for _ in 0..64 {
209
+ if seen.contains(&current) {
210
+ return true;
211
+ }
212
+ seen.push(current.clone());
213
+ match store.get(&current).and_then(|revision| revision.parent_id) {
214
+ Some(parent) => current = parent,
215
+ None => return false,
216
+ }
217
+ }
218
+ true
219
+ }
220
+
221
+ // ---------------------------------------------------------------------------
222
+ // Q1 — What makes two revisions the same revision?
223
+ // ---------------------------------------------------------------------------
224
+
225
+ /// **Identical content yields identical identity.**
226
+ ///
227
+ /// `StateId::compute` is SHA-256 over the canonical content and nothing else.
228
+ /// This is a property worth keeping — it is what makes a revision verifiable
229
+ /// against its own id, and what deduplicates repeated state.
230
+ fn i1() -> Verdict {
231
+ if StateId::compute(A) == StateId::compute(A) && StateId::compute(A) != StateId::compute(B) {
232
+ Verdict::Honoured
233
+ } else {
234
+ Verdict::Violated
235
+ }
236
+ }
237
+
238
+ /// **The same content can occur at two points in one history.**
239
+ ///
240
+ /// Not an edge case. A field set, changed, and changed back is the second most
241
+ /// common edit there is.
242
+ fn i2() -> Verdict {
243
+ let (_directory, _db, store, a, b) = a_then_b_then_a("i2.log");
244
+ // Both A-states are in one history, and B lies between them.
245
+ if store.exists(&a) && store.exists(&b) {
246
+ Verdict::Honoured
247
+ } else {
248
+ Verdict::Violated
249
+ }
250
+ }
251
+
252
+ /// **Content alone is a complete revision identity.**
253
+ ///
254
+ /// This is the clause the project must reject or accept explicitly, because I1
255
+ /// and I2 together make it false: if identity is content, and content recurs,
256
+ /// then two distinct points in history are one revision. The third commit does
257
+ /// not create a revision — it overwrites the first.
258
+ fn i3() -> Verdict {
259
+ let (_directory, _db, store, a, b) = a_then_b_then_a("i3.log");
260
+ let history = store.history_of(R);
261
+ let distinct = history.len() == 3
262
+ && history[0].id != history[2].id
263
+ && history[0].content_id == history[2].content_id;
264
+ let first_intact = store.get(&a).unwrap().parent_id.is_none();
265
+ let third_descends = history[2].parent_id.as_ref() == Some(&b);
266
+ if distinct && first_intact && third_descends {
267
+ Verdict::Honoured
268
+ } else {
269
+ Verdict::Violated
270
+ }
271
+ }
272
+
273
+ // ---------------------------------------------------------------------------
274
+ // Q2 — What does `base` mean?
275
+ // ---------------------------------------------------------------------------
276
+
277
+ /// **`base` as the parent in the revision DAG.**
278
+ ///
279
+ /// Sound as a definition, and unusable while T1, T5 and T6 hold: the parent
280
+ /// link can point at a revision that was never stored, can be rewritten by a
281
+ /// later commit, and can close a cycle.
282
+ fn b1() -> Verdict {
283
+ let (_directory, _db, store, a, _b) = a_then_b_then_a("b1.log");
284
+ if cycle_reachable_from(&store, &a) {
285
+ Verdict::Violated
286
+ } else {
287
+ Verdict::Honoured
288
+ }
289
+ }
290
+
291
+ /// **`base` as the previous state under the same key.**
292
+ ///
293
+ /// Cannot be evaluated at all. A `StateRevision` has six fields — `authority`,
294
+ /// `content`, `id`, `metadata`, `parent_id`, `timestamp_ms` — and none of them
295
+ /// says which resource the revision is a state *of*. The revision store is
296
+ /// keyed by content hash alone, so "the previous state of `tasks:1`" is not a
297
+ /// question it can be asked.
298
+ ///
299
+ /// `metadata` could carry a key. Nothing puts one there, and if something did,
300
+ /// the key would not participate in the identity.
301
+ fn b2() -> Verdict {
302
+ let revision = hand_built(A, None);
303
+ let encoded = serde_json::to_value(&revision).unwrap();
304
+ let fields: Vec<&String> = encoded.as_object().unwrap().keys().collect();
305
+ let names_a_resource = fields
306
+ .iter()
307
+ .any(|field| matches!(field.as_str(), "key" | "resource" | "capability"));
308
+ if names_a_resource {
309
+ Verdict::Honoured
310
+ } else {
311
+ Verdict::Unanswerable
312
+ }
313
+ }
314
+
315
+ /// **`base` as the previous observed state.**
316
+ ///
317
+ /// Available, and only at the fenced boundary, which reads the whole prior
318
+ /// document before deciding. Established by the three-way input boundary audit;
319
+ /// re-checked here because the contract depends on it.
320
+ fn b3() -> Verdict {
321
+ let directory = TempDir::new().unwrap();
322
+ let db = FeltDb::open(directory.path().join("b3.log")).unwrap();
323
+ db.insert(
324
+ "tasks:1",
325
+ json!({"title": "A", "__version": 1, "authority": {"epoch": 7}}),
326
+ )
327
+ .unwrap();
328
+ let refused = db
329
+ .compare_and_set_json("tasks:1", 1, Some(6), None, false, json!({"title": "B"}))
330
+ .unwrap();
331
+ if matches!(refused, JsonCasResult::AuthorityConflict { .. }) {
332
+ Verdict::Honoured
333
+ } else {
334
+ Verdict::Violated
335
+ }
336
+ }
337
+
338
+ /// **`base` as the previous durable revision.**
339
+ ///
340
+ /// Vacuous. No write path mints a revision, so no revision is ever the previous
341
+ /// one. The definition is not wrong; there is simply nothing for it to denote.
342
+ fn b4() -> Verdict {
343
+ let directory = TempDir::new().unwrap();
344
+ let db = Arc::new(FeltDb::open(directory.path().join("b4.log")).unwrap());
345
+ let store = StateStore::with_feltdb(db.clone()).unwrap();
346
+ db.insert("tasks:1", json!({"title": "A"})).unwrap();
347
+ db.update("tasks:1", json!({"title": "B"})).unwrap();
348
+
349
+ // The head is the state just written; its parent is the state before it,
350
+ // which is exactly `base`.
351
+ let head = store
352
+ .head_of("tasks:1")
353
+ .expect("the write minted a revision");
354
+ let Some(ParentLookup::Revision(previous)) = store.parent_of(&head.id) else {
355
+ return Verdict::Violated;
356
+ };
357
+ if previous.content == r#"{"title":"A"}"# {
358
+ Verdict::Honoured
359
+ } else {
360
+ Verdict::Violated
361
+ }
362
+ }
363
+
364
+ // ---------------------------------------------------------------------------
365
+ // Q3 — Which mutations create ancestry?
366
+ // ---------------------------------------------------------------------------
367
+
368
+ /// **An explicit mint validates the parent it is given.**
369
+ ///
370
+ /// It does not. `commit` takes a `&StateRevision` the caller holds, and nothing
371
+ /// requires that revision to be in the store. A child of a revision that was
372
+ /// never stored is accepted, and its `parent_id` points at nothing.
373
+ fn m1() -> Verdict {
374
+ let (_directory, _db, store) = durable_store("m1.log");
375
+ let never_stored = hand_built(r#"{"never":"stored"}"#, None);
376
+ match store.commit(A.into(), &never_stored, "contract".into()) {
377
+ Err(RevisionError::UnknownParent(id)) if id == never_stored.id => Verdict::Honoured,
378
+ _ => Verdict::Violated,
379
+ }
380
+ }
381
+
382
+ /// **A fenced write creates ancestry.**
383
+ ///
384
+ /// Vacuous: it creates none, because nothing mints. Recorded separately from
385
+ /// M3 because the two paths differ in what they *could* do — the fence already
386
+ /// holds the prior document, and the unconditional paths do not.
387
+ fn m2() -> Verdict {
388
+ let directory = TempDir::new().unwrap();
389
+ let db = Arc::new(FeltDb::open(directory.path().join("m2.log")).unwrap());
390
+ let store = StateStore::with_feltdb(db.clone()).unwrap();
391
+ db.insert("tasks:1", json!({"title": "A", "__version": 1}))
392
+ .unwrap();
393
+ db.compare_and_set_json("tasks:1", 1, None, None, false, json!({"title": "B"}))
394
+ .unwrap();
395
+ let history = store.history_of("tasks:1");
396
+ if history.len() == 2 && history[1].parent_id.as_ref() == Some(&history[0].id) {
397
+ Verdict::Honoured
398
+ } else {
399
+ Verdict::Violated
400
+ }
401
+ }
402
+
403
+ /// **An unconditional write creates ancestry.**
404
+ ///
405
+ /// Vacuous, and doubly so: nothing mints, and `insert_internal` and
406
+ /// `update_internal` never read the prior row, so there would be no parent to
407
+ /// record even if something did.
408
+ fn m3() -> Verdict {
409
+ let directory = TempDir::new().unwrap();
410
+ let db = Arc::new(FeltDb::open(directory.path().join("m3.log")).unwrap());
411
+ let store = StateStore::with_feltdb(db.clone()).unwrap();
412
+ db.insert("tasks:1", json!({"title": "A"})).unwrap();
413
+ db.update("tasks:1", json!({"title": "B"})).unwrap();
414
+ let history = store.history_of("tasks:1");
415
+ if history.len() == 2 && history[1].parent_id.as_ref() == Some(&history[0].id) {
416
+ Verdict::Honoured
417
+ } else {
418
+ Verdict::Violated
419
+ }
420
+ }
421
+
422
+ /// **Content equality never confers ancestry.** *(negative control)*
423
+ ///
424
+ /// The distinction this protects is the one the whole contract turns on: a
425
+ /// write whose result happens to equal an existing revision's content must not
426
+ /// thereby inherit that revision's history. Arriving at the same value is not
427
+ /// the same as descending from it.
428
+ ///
429
+ /// Today this holds vacuously — no write mints anything, so no write can
430
+ /// inherit anything. It is recorded now so that whatever model is chosen has to
431
+ /// keep holding it, and the required-form version at the end of this file is
432
+ /// the one that will matter.
433
+ fn n1() -> Verdict {
434
+ let directory = TempDir::new().unwrap();
435
+ let db = Arc::new(FeltDb::open(directory.path().join("n1.log")).unwrap());
436
+ let store = StateStore::with_feltdb(db.clone()).unwrap();
437
+
438
+ // An unrelated resource whose history contains exactly the content the
439
+ // write is about to produce.
440
+ let unrelated_root = store
441
+ .create("other:1", r#"{"unrelated":true}"#.into(), "other".into())
442
+ .unwrap();
443
+ let planted = store
444
+ .commit(r#"{"title":"B"}"#.into(), &unrelated_root, "other".into())
445
+ .unwrap();
446
+
447
+ db.insert("tasks:1", json!({"title": "A"})).unwrap();
448
+ db.update("tasks:1", json!({"title": "B"})).unwrap();
449
+
450
+ let history = store.history_of("tasks:1");
451
+ if history.len() != 2 {
452
+ return Verdict::Violated;
453
+ }
454
+ let minted = &history[1];
455
+
456
+ // Same state, different revision, and the ancestry followed the resource
457
+ // rather than the content.
458
+ let reached_the_same_value = minted.content_id == planted.content_id;
459
+ let distinct_revision = minted.id != planted.id;
460
+ let descends_from_this_resource = minted.parent_id.as_ref() == Some(&history[0].id);
461
+ let planted_untouched = store.get(&planted.id).unwrap().parent_id == Some(unrelated_root.id);
462
+
463
+ if reached_the_same_value
464
+ && distinct_revision
465
+ && descends_from_this_resource
466
+ && planted_untouched
467
+ {
468
+ Verdict::Honoured
469
+ } else {
470
+ Verdict::Violated
471
+ }
472
+ }
473
+
474
+ // ---------------------------------------------------------------------------
475
+ // Q5 — What must topology guarantee?
476
+ // ---------------------------------------------------------------------------
477
+
478
+ /// **The durable parent chain is acyclic.**
479
+ fn t1() -> Verdict {
480
+ let (_directory, _db, store, a, _b) = a_then_b_then_a("t1.log");
481
+ if cycle_reachable_from(&store, &a) {
482
+ Verdict::Violated
483
+ } else {
484
+ Verdict::Honoured
485
+ }
486
+ }
487
+
488
+ /// Whether the topology walkers can terminate on the graph A → B → A builds.
489
+ ///
490
+ /// `ancestors`, `is_ancestor` and `common_ancestor`
491
+ /// (`crates/feltdb/src/state_model.rs:186-230`) follow parent links in a
492
+ /// `while let` loop with **no visited set**. A cycle reachable from their start
493
+ /// node is therefore sufficient for non-termination.
494
+ ///
495
+ /// This is established by demonstrating the cycle and reading the loop, not by
496
+ /// calling the traversal. Calling it would not return.
497
+ fn walkers_can_terminate() -> Verdict {
498
+ // Build the graph that used to hang: two revisions sharing an identity
499
+ // because they share content, closing a loop through their parents. The
500
+ // resource-scoped model no longer produces this, so it is assembled by hand
501
+ // — which is the point. The walkers must terminate on a graph they did not
502
+ // create, read from an older log or built by a careless caller.
503
+ let mut topology = StateTopology::new();
504
+ let first = hand_built(A, None);
505
+ let second = hand_built(B, Some(first.id.clone()));
506
+ let third = hand_built(A, Some(second.id.clone()));
507
+ assert_eq!(first.id, third.id, "the hand-built graph is cyclic");
508
+ topology.add_revision(first.clone());
509
+ topology.add_revision(second.clone());
510
+ topology.add_revision(third);
511
+
512
+ // These calls did not return before the visited sets were added. Reaching
513
+ // the line below is the whole claim; the answers themselves are whatever a
514
+ // cyclic graph deserves, and are not what this clause is about.
515
+ let ancestors = topology.ancestors(&first.id);
516
+ let is_ancestor = topology.is_ancestor(&hand_built(r#"{"unrelated":1}"#, None).id, &first.id);
517
+ let _common = topology.common_ancestor(&first.id, &second.id);
518
+
519
+ if ancestors.len() <= 4 && !is_ancestor {
520
+ Verdict::Honoured
521
+ } else {
522
+ Verdict::Violated
523
+ }
524
+ }
525
+
526
+ /// **`ancestors` terminates.**
527
+ fn t2() -> Verdict {
528
+ walkers_can_terminate()
529
+ }
530
+
531
+ /// **`is_ancestor` terminates.**
532
+ fn t3() -> Verdict {
533
+ walkers_can_terminate()
534
+ }
535
+
536
+ /// **`common_ancestor` terminates.**
537
+ fn t4() -> Verdict {
538
+ walkers_can_terminate()
539
+ }
540
+
541
+ /// **Every parent reference resolves.**
542
+ ///
543
+ /// Same mechanism as M1, stated as a graph invariant rather than as a property
544
+ /// of the mint: a stored revision can name a parent that is not stored.
545
+ fn t5() -> Verdict {
546
+ let (_directory, _db, store) = durable_store("t5.log");
547
+ let never_stored = hand_built(r#"{"never":"stored"}"#, None);
548
+ if store
549
+ .commit(A.into(), &never_stored, "contract".into())
550
+ .is_ok()
551
+ {
552
+ return Verdict::Violated;
553
+ }
554
+
555
+ // And every parent a real history names does resolve.
556
+ let first = store.create(R, A.into(), "contract".into()).unwrap();
557
+ let second = store.commit(B.into(), &first, "contract".into()).unwrap();
558
+ match store.parent_of(&second.id) {
559
+ Some(ParentLookup::Revision(parent)) if parent.id == first.id => Verdict::Honoured,
560
+ _ => Verdict::Violated,
561
+ }
562
+ }
563
+
564
+ /// **A revision never silently changes its parent.**
565
+ ///
566
+ /// It changes in both directions, and neither is reported.
567
+ ///
568
+ /// *Gains one it never had:* A → B → A gives the first revision B as a parent.
569
+ ///
570
+ /// *Loses the one it had:* committing B as a child of A, then `create`-ing the
571
+ /// same content as a parentless initial revision, sets B's parent back to
572
+ /// `None` — erasing the fact that B ever descended from anything.
573
+ fn t6() -> Verdict {
574
+ let (_directory, _db, store) = durable_store("t6.log");
575
+ let first = store.create(R, A.into(), "contract".into()).unwrap();
576
+ let second = store.commit(B.into(), &first, "contract".into()).unwrap();
577
+ assert_eq!(
578
+ store.get(&second.id).unwrap().parent_id,
579
+ Some(first.id.clone())
580
+ );
581
+
582
+ // Beginning the resource again is refused, so the parent cannot be erased
583
+ // that way.
584
+ let begun_again = store.create(R, B.into(), "contract".into());
585
+ let refused = matches!(begun_again, Err(RevisionError::ResourceAlreadyBegun { .. }));
586
+
587
+ // And a further commit of the same content is a new revision, not a
588
+ // rewrite of the existing one.
589
+ let third = store.commit(B.into(), &second, "contract".into()).unwrap();
590
+ let untouched = store.get(&second.id).unwrap().parent_id == Some(first.id);
591
+
592
+ if refused && untouched && third.id != second.id {
593
+ Verdict::Honoured
594
+ } else {
595
+ Verdict::Violated
596
+ }
597
+ }
598
+
599
+ // ---------------------------------------------------------------------------
600
+ // Q6 — What does compaction promise?
601
+ // ---------------------------------------------------------------------------
602
+
603
+ /// Compact a store holding both plain rows and revisions, and report what
604
+ /// happened to each of the three things compaction touches.
605
+ struct CompactionOutcome {
606
+ operations_pruned: bool,
607
+ current_state_survived: bool,
608
+ revisions_survived: bool,
609
+ revisions_rewritten: usize,
610
+ }
611
+
612
+ fn compact_and_observe(name: &str) -> CompactionOutcome {
613
+ let directory = TempDir::new().unwrap();
614
+ let path = directory.path().join(name);
615
+ let db = Arc::new(FeltDb::open(&path).unwrap());
616
+ let store = StateStore::with_feltdb(db.clone()).unwrap();
617
+
618
+ db.insert("tasks:1", json!({"title": "A"})).unwrap();
619
+ db.update("tasks:1", json!({"title": "B"})).unwrap();
620
+ let mut ids = Vec::new();
621
+ let mut revision = store
622
+ .create("history:1", r#"{"n":0}"#.into(), "contract".into())
623
+ .unwrap();
624
+ ids.push(revision.id.clone());
625
+ for n in 1..5 {
626
+ revision = store
627
+ .commit(format!(r#"{{"n":{n}}}"#), &revision, "contract".into())
628
+ .unwrap();
629
+ ids.push(revision.id.clone());
630
+ }
631
+
632
+ let versions = db.operation_versions().unwrap();
633
+ db.acknowledge_peer_versions("peer-1".to_string(), versions)
634
+ .unwrap();
635
+ let removed = db.compact_operation_log(&["peer-1".to_string()]).unwrap();
636
+ let log = std::fs::read_to_string(&path).unwrap();
637
+
638
+ let current: Option<serde_json::Value> = db.get("tasks:1").unwrap();
639
+ CompactionOutcome {
640
+ operations_pruned: removed > 0,
641
+ current_state_survived: current.map(|v| v["title"] == json!("B")).unwrap_or(false),
642
+ revisions_survived: ids.iter().all(|id| store.exists(id)),
643
+ revisions_rewritten: log
644
+ .lines()
645
+ .filter(|line| line.contains("state:revision:"))
646
+ .count(),
647
+ }
648
+ }
649
+
650
+ /// **Compaction deletes acknowledged operation history.** Its stated purpose.
651
+ fn c1() -> Verdict {
652
+ if compact_and_observe("c1.log").operations_pruned {
653
+ Verdict::Honoured
654
+ } else {
655
+ Verdict::Violated
656
+ }
657
+ }
658
+
659
+ /// **Compaction preserves current state.** Also its stated purpose.
660
+ fn c2() -> Verdict {
661
+ if compact_and_observe("c2.log").current_state_survived {
662
+ Verdict::Honoured
663
+ } else {
664
+ Verdict::Violated
665
+ }
666
+ }
667
+
668
+ /// **Revision retention is promised rather than incidental.**
669
+ ///
670
+ /// It is now a policy a resource carries, applied at the moment history is
671
+ /// created. Revisions survive because the policy retains them, not because the
672
+ /// rule that protects current state happens to sweep them up.
673
+ fn c3() -> Verdict {
674
+ let directory = TempDir::new().unwrap();
675
+ let path = directory.path().join("c3.log");
676
+ let db = Arc::new(FeltDb::open(&path).unwrap());
677
+ let store = StateStore::with_feltdb(db.clone()).unwrap();
678
+
679
+ store
680
+ .set_retention_policy("tasks:1", RetentionPolicy::keep_last(2))
681
+ .unwrap();
682
+ db.insert("tasks:1", json!({"n": 0})).unwrap();
683
+ for n in 1..6 {
684
+ db.update("tasks:1", json!({ "n": n })).unwrap();
685
+ }
686
+
687
+ let history = store.history_of("tasks:1");
688
+ let bounded = history.len() == 2;
689
+ let current_survived = history
690
+ .last()
691
+ .map(|revision| revision.content.contains("\"n\":5"))
692
+ .unwrap_or(false);
693
+ let horizon_recorded = store.retention_horizon("tasks:1") > 0;
694
+
695
+ if bounded && current_survived && horizon_recorded {
696
+ Verdict::Honoured
697
+ } else {
698
+ Verdict::Violated
699
+ }
700
+ }
701
+
702
+ /// **The three promises can be requested separately.**
703
+ ///
704
+ /// Compaction bounds the operation log and preserves current state. Retention
705
+ /// bounds revision history. Neither does the other's job, and each can be asked
706
+ /// for on its own.
707
+ fn c4() -> Verdict {
708
+ let directory = TempDir::new().unwrap();
709
+ let path = directory.path().join("c4.log");
710
+ let db = Arc::new(FeltDb::open(&path).unwrap());
711
+ let store = StateStore::with_feltdb(db.clone()).unwrap();
712
+
713
+ db.insert("tasks:1", json!({"n": 0})).unwrap();
714
+ for n in 1..6 {
715
+ db.update("tasks:1", json!({ "n": n })).unwrap();
716
+ }
717
+
718
+ // Compaction alone: operations pruned, revisions untouched.
719
+ let before = store.history_of("tasks:1").len();
720
+ let versions = db.operation_versions().unwrap();
721
+ db.acknowledge_peer_versions("peer-1".to_string(), versions)
722
+ .unwrap();
723
+ let pruned = db.compact_operation_log(&["peer-1".to_string()]).unwrap();
724
+ let compaction_left_history_alone = store.history_of("tasks:1").len() == before;
725
+
726
+ // Retention alone: revisions expired, current state untouched.
727
+ let expired = store
728
+ .set_retention_policy("tasks:1", RetentionPolicy::keep_last(2))
729
+ .unwrap();
730
+ let current: Option<serde_json::Value> = db.get("tasks:1").unwrap();
731
+ let retention_left_state_alone = current.map(|v| v["n"] == json!(5)).unwrap_or(false);
732
+
733
+ if pruned > 0 && compaction_left_history_alone && expired > 0 && retention_left_state_alone {
734
+ Verdict::Honoured
735
+ } else {
736
+ Verdict::Violated
737
+ }
738
+ }
739
+
740
+ // ---------------------------------------------------------------------------
741
+ // The clauses, as tests
742
+ // ---------------------------------------------------------------------------
743
+
744
+ macro_rules! clause {
745
+ ($test:ident, $clause:expr) => {
746
+ #[test]
747
+ fn $test() {
748
+ assert_eq!(
749
+ evaluate($clause),
750
+ recorded($clause),
751
+ "the behaviour of `{}` no longer matches the recorded contract verdict; \
752
+ update docs/architecture/revision-identity-and-ancestry.md deliberately",
753
+ $clause
754
+ );
755
+ }
756
+ };
757
+ }
758
+
759
+ clause!(
760
+ i1_identical_content_yields_identical_content_identity,
761
+ "I1 identical content yields identical content identity"
762
+ );
763
+ clause!(
764
+ i2_the_same_content_can_occur_twice,
765
+ "I2 the same content can occur twice in one history"
766
+ );
767
+ clause!(
768
+ i3_revision_identity_distinguishes_occurrences,
769
+ "I3 revision identity distinguishes two occurrences of one state"
770
+ );
771
+ clause!(
772
+ b1_base_as_the_parent_in_the_dag,
773
+ "B1 base as the parent in the revision DAG"
774
+ );
775
+ clause!(
776
+ b2_base_as_the_previous_state_for_a_key,
777
+ "B2 base as the previous state under the same key"
778
+ );
779
+ clause!(
780
+ b3_base_as_the_previous_observed_state,
781
+ "B3 base as the previous observed state"
782
+ );
783
+ clause!(
784
+ b4_base_as_the_previous_durable_revision,
785
+ "B4 base as the previous durable revision"
786
+ );
787
+ clause!(
788
+ m1_explicit_mint_validates_its_parent,
789
+ "M1 an explicit mint validates the parent it is given"
790
+ );
791
+ clause!(
792
+ m2_a_fenced_write_creates_ancestry,
793
+ "M2 a fenced write creates ancestry"
794
+ );
795
+ clause!(
796
+ m3_an_unconditional_write_creates_ancestry,
797
+ "M3 an unconditional write creates ancestry"
798
+ );
799
+ clause!(
800
+ n1_content_equality_confers_no_ancestry,
801
+ "N1 content equality never confers ancestry"
802
+ );
803
+ clause!(
804
+ t1_the_parent_chain_is_acyclic,
805
+ "T1 the durable parent chain is acyclic"
806
+ );
807
+ clause!(t2_ancestors_terminates, "T2 ancestors terminates");
808
+ clause!(t3_is_ancestor_terminates, "T3 is_ancestor terminates");
809
+ clause!(
810
+ t4_common_ancestor_terminates,
811
+ "T4 common_ancestor terminates"
812
+ );
813
+ clause!(
814
+ t5_every_parent_reference_resolves,
815
+ "T5 every parent reference resolves"
816
+ );
817
+ clause!(
818
+ t6_a_revision_never_silently_changes_its_parent,
819
+ "T6 a revision never silently changes its parent"
820
+ );
821
+ clause!(
822
+ c1_compaction_deletes_operation_history,
823
+ "C1 compaction deletes acknowledged operation history"
824
+ );
825
+ clause!(
826
+ c2_compaction_preserves_current_state,
827
+ "C2 compaction preserves current state"
828
+ );
829
+ clause!(
830
+ c3_revision_retention_is_promised,
831
+ "C3 revision retention is promised rather than incidental"
832
+ );
833
+ clause!(
834
+ c4_the_promises_are_separable,
835
+ "C4 the three promises can be requested separately"
836
+ );
837
+
838
+ /// **The tripwire.**
839
+ ///
840
+ /// Every clause, recomputed from live behaviour and checked against the record.
841
+ /// A change to identity, ancestry or compaction semantics that flips any
842
+ /// verdict fails here — including a change that *fixes* one. That is intended:
843
+ /// the contract is a decision, and it should not be possible to satisfy it by
844
+ /// accident and leave the document saying otherwise.
845
+ #[test]
846
+ fn the_ledger_is_exactly_this() {
847
+ let mut drifted = Vec::new();
848
+ for (clause, expected) in LEDGER {
849
+ let actual = evaluate(clause);
850
+ if actual != *expected {
851
+ drifted.push(format!(
852
+ " {clause}: recorded {expected:?}, observed {actual:?}"
853
+ ));
854
+ }
855
+ }
856
+ assert!(
857
+ drifted.is_empty(),
858
+ "the contract ledger has drifted from the implementation:\n{}\n\n\
859
+ Update docs/architecture/revision-identity-and-ancestry.md and this ledger together.",
860
+ drifted.join("\n")
861
+ );
862
+ }
863
+
864
+ /// Every clause has an evaluator, and no evaluator is orphaned.
865
+ #[test]
866
+ fn the_ledger_is_complete() {
867
+ assert_eq!(
868
+ LEDGER.len(),
869
+ 21,
870
+ "clauses were added or removed without updating the count"
871
+ );
872
+ for (clause, _) in LEDGER {
873
+ let _ = evaluate(clause);
874
+ }
875
+ }
876
+
877
+ // ---------------------------------------------------------------------------
878
+ // The contract in required form
879
+ // ---------------------------------------------------------------------------
880
+ //
881
+ // These were written before a model was chosen, and were `#[ignore]`d because
882
+ // they could not pass. They pass now, under the resource-scoped model.
883
+ //
884
+ // **Two of them were rewritten to get here, and it matters which.** The
885
+ // centrepiece is unchanged apart from naming the resource a revision now
886
+ // belongs to. But the fenced and unconditional path tests, and the negative
887
+ // control, looked a minted revision up by `StateId::compute(content)` — they
888
+ // assumed content *was* revision identity, which is the assumption the adopted
889
+ // model rejects. Their assertions are preserved; the lookups are not, because
890
+ // under model C there is no revision at a content hash. That is a deliberate
891
+ // contract update, not a test bent to fit the code.
892
+
893
+ /// **The centrepiece.** A → B → A, with the expected graph stated rather than
894
+ /// left to the hash function.
895
+ #[test]
896
+ fn a_then_b_then_a_produces_three_revisions() {
897
+ let (_directory, _db, store) = durable_store("required-mint.log");
898
+
899
+ let first = store.create(R, A.into(), "contract".into()).unwrap();
900
+ let second = store.commit(B.into(), &first, "contract".into()).unwrap();
901
+ let third = store.commit(A.into(), &second, "contract".into()).unwrap();
902
+
903
+ assert_ne!(first.id, third.id, "arriving at A twice is two revisions");
904
+ assert_eq!(
905
+ first.content_id, third.content_id,
906
+ "and it is the same state both times"
907
+ );
908
+ assert_eq!(store.get(&first.id).unwrap().parent_id, None);
909
+ assert_eq!(
910
+ store.get(&second.id).unwrap().parent_id,
911
+ Some(first.id.clone())
912
+ );
913
+ assert_eq!(
914
+ store.get(&third.id).unwrap().parent_id,
915
+ Some(second.id.clone())
916
+ );
917
+ assert!(
918
+ !cycle_reachable_from(&store, &third.id),
919
+ "the graph is acyclic"
920
+ );
921
+ assert!(
922
+ store.parent(&third.id).is_some(),
923
+ "parent references resolve"
924
+ );
925
+ assert!(
926
+ store.parent(&second.id).is_some(),
927
+ "parent references resolve"
928
+ );
929
+ }
930
+
931
+ /// **Two resources at the same value are two revisions.**
932
+ ///
933
+ /// The row the model was adopted for: a revision belongs to a resource, so
934
+ /// identical content on two resources is never one historical object.
935
+ #[test]
936
+ fn two_resources_at_the_same_value_are_distinct_revisions() {
937
+ let (_directory, _db, store) = durable_store("required-resources.log");
938
+
939
+ let one = store
940
+ .create("tasks:1", A.into(), "contract".into())
941
+ .unwrap();
942
+ let two = store
943
+ .create("tasks:2", A.into(), "contract".into())
944
+ .unwrap();
945
+
946
+ assert_ne!(one.id, two.id, "same state, different resources");
947
+ assert_eq!(one.content_id, two.content_id, "and it is the same state");
948
+ assert_eq!(store.history_of("tasks:1").len(), 1);
949
+ assert_eq!(store.history_of("tasks:2").len(), 1);
950
+ }
951
+
952
+ /// The same sequence driven through the fenced write path.
953
+ #[test]
954
+ fn a_then_b_then_a_through_the_fenced_path() {
955
+ let directory = TempDir::new().unwrap();
956
+ let db = Arc::new(FeltDb::open(directory.path().join("required-cas.log")).unwrap());
957
+ let store = StateStore::with_feltdb(db.clone()).unwrap();
958
+
959
+ db.insert("tasks:1", json!({"title": "A", "__version": 1}))
960
+ .unwrap();
961
+ db.compare_and_set_json("tasks:1", 1, None, None, false, json!({"title": "B"}))
962
+ .unwrap();
963
+ db.compare_and_set_json("tasks:1", 2, None, None, false, json!({"title": "A"}))
964
+ .unwrap();
965
+
966
+ let history = store.history_of("tasks:1");
967
+ assert_eq!(history.len(), 3, "each fenced write minted a revision");
968
+ assert_ne!(
969
+ history[0].id, history[2].id,
970
+ "returning to A is a new revision"
971
+ );
972
+ assert_eq!(history[1].parent_id.as_ref(), Some(&history[0].id));
973
+ assert_eq!(history[2].parent_id.as_ref(), Some(&history[1].id));
974
+ }
975
+
976
+ /// The same sequence driven through the unconditional write path.
977
+ #[test]
978
+ fn a_then_b_then_a_through_the_unconditional_path() {
979
+ let directory = TempDir::new().unwrap();
980
+ let db = Arc::new(FeltDb::open(directory.path().join("required-uncond.log")).unwrap());
981
+ let store = StateStore::with_feltdb(db.clone()).unwrap();
982
+
983
+ db.insert("tasks:1", json!({"title": "A"})).unwrap();
984
+ db.update("tasks:1", json!({"title": "B"})).unwrap();
985
+ db.update("tasks:1", json!({"title": "A"})).unwrap();
986
+
987
+ let history = store.history_of("tasks:1");
988
+ assert_eq!(history.len(), 3, "each write minted a revision");
989
+ assert_ne!(history[0].id, history[2].id);
990
+ assert_eq!(
991
+ history[0].content_id, history[2].content_id,
992
+ "the same state, twice"
993
+ );
994
+ assert_eq!(history[2].parent_id.as_ref(), Some(&history[1].id));
995
+ }
996
+
997
+ /// **The negative control, in the form that matters.**
998
+ ///
999
+ /// A write that lands on content equal to an existing revision produces a *new*
1000
+ /// revision descending from what this resource held — it does not adopt the
1001
+ /// existing revision's ancestry. Content equality is not descent.
1002
+ #[test]
1003
+ fn a_write_that_matches_existing_content_does_not_inherit_its_ancestry() {
1004
+ let directory = TempDir::new().unwrap();
1005
+ let db = Arc::new(FeltDb::open(directory.path().join("required-control.log")).unwrap());
1006
+ let store = StateStore::with_feltdb(db.clone()).unwrap();
1007
+
1008
+ // An unrelated history that happens to contain the content {"title":"B"}.
1009
+ let unrelated_root = store
1010
+ .create("other:1", r#"{"unrelated":true}"#.into(), "other".into())
1011
+ .unwrap();
1012
+ let planted = store
1013
+ .commit(r#"{"title":"B"}"#.into(), &unrelated_root, "other".into())
1014
+ .unwrap();
1015
+
1016
+ // A resource written to A, then to the same content as `planted`.
1017
+ db.insert("tasks:1", json!({"title": "A"})).unwrap();
1018
+ db.update("tasks:1", json!({"title": "B"})).unwrap();
1019
+
1020
+ let history = store.history_of("tasks:1");
1021
+ assert_eq!(history.len(), 2, "both writes minted");
1022
+ let minted = &history[1];
1023
+
1024
+ assert_eq!(
1025
+ minted.content_id, planted.content_id,
1026
+ "the write reached the same value"
1027
+ );
1028
+ assert_ne!(minted.id, planted.id, "and is still a different revision");
1029
+ assert_eq!(
1030
+ minted.parent_id.as_ref(),
1031
+ Some(&history[0].id),
1032
+ "it descends from what this resource held"
1033
+ );
1034
+ assert_eq!(
1035
+ store.get(&planted.id).unwrap().parent_id,
1036
+ Some(unrelated_root.id),
1037
+ "the unrelated history was not touched"
1038
+ );
1039
+ }