@feltdb/core 0.8.3 → 0.8.5

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 (193) hide show
  1. package/dist/cli/commands.js +4 -1
  2. package/dist/cli/provisioning-neutrality.js +79 -0
  3. package/dist/collection.d.ts +43 -1
  4. package/dist/collection.d.ts.map +1 -1
  5. package/dist/collection.js +192 -22
  6. package/dist/create/create.js +25 -21
  7. package/dist/create/managed-account.js +11 -0
  8. package/dist/create/package-versions.js +1 -1
  9. package/dist/create/server-source/Cargo.lock +165 -0
  10. package/dist/create/server-source/Cargo.toml +9 -0
  11. package/dist/create/server-source/crates/feltdb/Cargo.toml +3 -0
  12. package/dist/create/server-source/crates/feltdb/benches/gate13_baseline.rs +44 -44
  13. package/dist/create/server-source/crates/feltdb/benches/gate13_phase_7_1_release_economics.rs +12 -24
  14. package/dist/create/server-source/crates/feltdb/benches/gate_13_redux.rs +7 -13
  15. package/dist/create/server-source/crates/feltdb/benches/gate_13_regression_runner.rs +13 -10
  16. package/dist/create/server-source/crates/feltdb/benches/gate_14a_concurrent_writer_scaling.rs +12 -9
  17. package/dist/create/server-source/crates/feltdb/benches/gate_14a_production_admission_revalidation.rs +78 -25
  18. package/dist/create/server-source/crates/feltdb/benches/gate_14a_rc2_admission_contract.rs +16 -13
  19. package/dist/create/server-source/crates/feltdb/benches/gate_14a_rc_root_cause.rs +13 -5
  20. package/dist/create/server-source/crates/feltdb/benches/gate_14a_sync1_queued_prototype.rs +41 -22
  21. package/dist/create/server-source/crates/feltdb/benches/gate_14a_sync_economics.rs +33 -15
  22. package/dist/create/server-source/crates/feltdb/benches/gate_14b_causal_backlog_scaling.rs +100 -33
  23. package/dist/create/server-source/crates/feltdb/benches/gate_14c_replication_contract_test.rs +56 -20
  24. package/dist/create/server-source/crates/feltdb/benches/gate_14c_replication_scaling.rs +116 -41
  25. package/dist/create/server-source/crates/feltdb/benches/gate_14d_combined_dimension_scaling.rs +186 -55
  26. package/dist/create/server-source/crates/feltdb/benches/phase_7_1_2_optimization_benchmark.rs +64 -26
  27. package/dist/create/server-source/crates/feltdb/benches/phase_7_1_3_crossover_analysis.rs +46 -15
  28. package/dist/create/server-source/crates/feltdb/src/admission.rs +8 -15
  29. package/dist/create/server-source/crates/feltdb/src/admission_contract_tests.rs +43 -13
  30. package/dist/create/server-source/crates/feltdb/src/adversarial_transport.rs +15 -42
  31. package/dist/create/server-source/crates/feltdb/src/analytics.rs +65 -19
  32. package/dist/create/server-source/crates/feltdb/src/application.rs +113 -30
  33. package/dist/create/server-source/crates/feltdb/src/authorization_security_tests.rs +475 -140
  34. package/dist/create/server-source/crates/feltdb/src/cardinality_diagnostics.rs +17 -15
  35. package/dist/create/server-source/crates/feltdb/src/cardinality_endpoint.rs +0 -1
  36. package/dist/create/server-source/crates/feltdb/src/causal_backlog_bound.rs +59 -15
  37. package/dist/create/server-source/crates/feltdb/src/causal_dependency_barrier.rs +266 -114
  38. package/dist/create/server-source/crates/feltdb/src/causal_dependency_barrier_phase_7_1.rs +25 -7
  39. package/dist/create/server-source/crates/feltdb/src/concurrency_fuzzing.rs +10 -15
  40. package/dist/create/server-source/crates/feltdb/src/consistency_contract.rs +3 -11
  41. package/dist/create/server-source/crates/feltdb/src/crash_atomic_boundary.rs +14 -5
  42. package/dist/create/server-source/crates/feltdb/src/crash_injection.rs +21 -25
  43. package/dist/create/server-source/crates/feltdb/src/crash_recovery_tests.rs +14 -11
  44. package/dist/create/server-source/crates/feltdb/src/dedup_bound_investigation.rs +103 -22
  45. package/dist/create/server-source/crates/feltdb/src/distributed_indexing.rs +18 -15
  46. package/dist/create/server-source/crates/feltdb/src/durability_guarantees.rs +12 -8
  47. package/dist/create/server-source/crates/feltdb/src/durable_dedup_set.rs +1 -5
  48. package/dist/create/server-source/crates/feltdb/src/durable_operation_identity.rs +87 -23
  49. package/dist/create/server-source/crates/feltdb/src/durable_operation_log.rs +3 -7
  50. package/dist/create/server-source/crates/feltdb/src/durable_sync.rs +10 -9
  51. package/dist/create/server-source/crates/feltdb/src/equality_index.rs +595 -0
  52. package/dist/create/server-source/crates/feltdb/src/in_process_transport.rs +1 -6
  53. package/dist/create/server-source/crates/feltdb/src/indexing.rs +35 -38
  54. package/dist/create/server-source/crates/feltdb/src/lib.rs +1050 -117
  55. package/dist/create/server-source/crates/feltdb/src/managed_cas_tests.rs +4 -1
  56. package/dist/create/server-source/crates/feltdb/src/metrics.rs +0 -1
  57. package/dist/create/server-source/crates/feltdb/src/multi_node_convergence.rs +1 -2
  58. package/dist/create/server-source/crates/feltdb/src/multi_operation_transaction.rs +107 -30
  59. package/dist/create/server-source/crates/feltdb/src/observability.rs +19 -6
  60. package/dist/create/server-source/crates/feltdb/src/operation_algebra.rs +12 -11
  61. package/dist/create/server-source/crates/feltdb/src/operation_log.rs +9 -4
  62. package/dist/create/server-source/crates/feltdb/src/p1_application_atomicity.rs +65 -18
  63. package/dist/create/server-source/crates/feltdb/src/p1_atomicity_acceptance.rs +193 -57
  64. package/dist/create/server-source/crates/feltdb/src/partition_reconciliation.rs +37 -27
  65. package/dist/create/server-source/crates/feltdb/src/permutation_scheduler.rs +38 -10
  66. package/dist/create/server-source/crates/feltdb/src/persistence_reality.rs +20 -14
  67. package/dist/create/server-source/crates/feltdb/src/phase1b_acceptance.rs +394 -229
  68. package/dist/create/server-source/crates/feltdb/src/phase1c1_acceptance.rs +8 -6
  69. package/dist/create/server-source/crates/feltdb/src/phase1c2_acceptance.rs +11 -13
  70. package/dist/create/server-source/crates/feltdb/src/phase1c3_acceptance.rs +90 -72
  71. package/dist/create/server-source/crates/feltdb/src/phase1c_atomicity_proof.rs +3 -3
  72. package/dist/create/server-source/crates/feltdb/src/phase5_integration.rs +33 -11
  73. package/dist/create/server-source/crates/feltdb/src/phase5_scenarios.rs +6 -6
  74. package/dist/create/server-source/crates/feltdb/src/phase6_adversarial_scenarios.rs +14 -56
  75. package/dist/create/server-source/crates/feltdb/src/phase6_convergence_validator.rs +29 -27
  76. package/dist/create/server-source/crates/feltdb/src/phase6_persistence.rs +35 -17
  77. package/dist/create/server-source/crates/feltdb/src/phase_1c_real_tcp.rs +8 -2
  78. package/dist/create/server-source/crates/feltdb/src/phase_2a_failures.rs +59 -15
  79. package/dist/create/server-source/crates/feltdb/src/phase_2b_network.rs +70 -17
  80. package/dist/create/server-source/crates/feltdb/src/phase_2c_cascading.rs +23 -6
  81. package/dist/create/server-source/crates/feltdb/src/phase_3_durability.rs +12 -3
  82. package/dist/create/server-source/crates/feltdb/src/phase_4_baseline.rs +41 -11
  83. package/dist/create/server-source/crates/feltdb/src/phase_5_soak.rs +56 -25
  84. package/dist/create/server-source/crates/feltdb/src/policy_evaluation.rs +701 -245
  85. package/dist/create/server-source/crates/feltdb/src/production_api.rs +31 -13
  86. package/dist/create/server-source/crates/feltdb/src/query_execution_diagnostics.rs +126 -0
  87. package/dist/create/server-source/crates/feltdb/src/query_performance.rs +6 -8
  88. package/dist/create/server-source/crates/feltdb/src/replay_fuzzing.rs +5 -5
  89. package/dist/create/server-source/crates/feltdb/src/replica_acknowledgements.rs +48 -18
  90. package/dist/create/server-source/crates/feltdb/src/replica_membership.rs +30 -11
  91. package/dist/create/server-source/crates/feltdb/src/replication_manager.rs +6 -3
  92. package/dist/create/server-source/crates/feltdb/src/replication_protocol.rs +4 -3
  93. package/dist/create/server-source/crates/feltdb/src/sharding.rs +36 -10
  94. package/dist/create/server-source/crates/feltdb/src/state_conflict_contract.rs +516 -0
  95. package/dist/create/server-source/crates/feltdb/src/state_contract.rs +305 -6
  96. package/dist/create/server-source/crates/feltdb/src/state_diff_contract.rs +222 -0
  97. package/dist/create/server-source/crates/feltdb/src/state_facade.rs +82 -54
  98. package/dist/create/server-source/crates/feltdb/src/state_hash.rs +2 -2
  99. package/dist/create/server-source/crates/feltdb/src/state_model.rs +1514 -537
  100. package/dist/create/server-source/crates/feltdb/src/state_transition_store.rs +6 -3
  101. package/dist/create/server-source/crates/feltdb/src/state_trigger.rs +672 -0
  102. package/dist/create/server-source/crates/feltdb/src/submission.rs +5 -11
  103. package/dist/create/server-source/crates/feltdb/src/sync.rs +12 -0
  104. package/dist/create/server-source/crates/feltdb/src/tcp_transport.rs +6 -8
  105. package/dist/create/server-source/crates/feltdb/src/transaction_api.rs +24 -35
  106. package/dist/create/server-source/crates/feltdb/src/transaction_invariants.rs +24 -8
  107. package/dist/create/server-source/crates/feltdb/src/transaction_preconditions.rs +248 -59
  108. package/dist/create/server-source/crates/feltdb/src/transactions.rs +17 -20
  109. package/dist/create/server-source/crates/feltdb/src/trigger_contract.rs +749 -0
  110. package/dist/create/server-source/crates/feltdb/src/worker_mesh.rs +1 -0
  111. package/dist/create/server-source/crates/feltdb/src/workload.rs +512 -4
  112. package/dist/create/server-source/crates/feltdb/src/workload_diagnostics.rs +442 -0
  113. package/dist/create/server-source/crates/feltdb/tests/branching_evidence.rs +299 -0
  114. package/dist/create/server-source/crates/feltdb/tests/current_revision_authority_evidence.rs +288 -0
  115. package/dist/create/server-source/crates/feltdb/tests/durable_format_compatibility.rs +392 -0
  116. package/dist/create/server-source/crates/feltdb/tests/feltdb_state_boundary_tests.rs +436 -220
  117. package/dist/create/server-source/crates/feltdb/tests/fixtures/state_conflict_contract_corpus.json +1916 -0
  118. package/dist/create/server-source/crates/feltdb/tests/fixtures/state_diff_contract_corpus.json +1878 -0
  119. package/dist/create/server-source/crates/feltdb/tests/fixtures/trigger_contract_corpus.json +1862 -0
  120. package/dist/create/server-source/crates/feltdb/tests/pr34_query_collection.rs +234 -0
  121. package/dist/create/server-source/crates/feltdb/tests/pr35_equality_index.rs +947 -0
  122. package/dist/create/server-source/crates/feltdb/tests/pr7_self_authorization_proof.rs +5 -8
  123. package/dist/create/server-source/crates/feltdb/tests/pr8_vocabulary_assessment.rs +52 -44
  124. package/dist/create/server-source/crates/feltdb/tests/pr9_phase2_boundary_tests.rs +33 -16
  125. package/dist/create/server-source/crates/feltdb/tests/pr9_phase3a_path_a_tests.rs +22 -7
  126. package/dist/create/server-source/crates/feltdb/tests/pr9_phase3c_authorized_mutations.rs +41 -22
  127. package/dist/create/server-source/crates/feltdb/tests/pr9_phase3c_role_based_authorization.rs +25 -8
  128. package/dist/create/server-source/crates/feltdb/tests/pr9_phase3c_simple_auth_delete.rs +9 -6
  129. package/dist/create/server-source/crates/feltdb/tests/pr9_phase3c_team_delete_role_authorization.rs +120 -69
  130. package/dist/create/server-source/crates/feltdb/tests/pr9_teams_role_based_access.rs +21 -10
  131. package/dist/create/server-source/crates/feltdb/tests/production_readiness_contract.rs +1032 -0
  132. package/dist/create/server-source/crates/feltdb/tests/reconciliation_application.rs +868 -0
  133. package/dist/create/server-source/crates/feltdb/tests/reconciliation_wire_format_evidence.rs +221 -0
  134. package/dist/create/server-source/crates/feltdb/tests/resource_scoped_revisions.rs +338 -0
  135. package/dist/create/server-source/crates/feltdb/tests/revision_identity_contract.rs +1039 -0
  136. package/dist/create/server-source/crates/feltdb/tests/revision_model_decision.rs +739 -0
  137. package/dist/create/server-source/crates/feltdb/tests/revision_retention_boundary_evidence.rs +427 -0
  138. package/dist/create/server-source/crates/feltdb/tests/saas_authorization_integration.rs +3 -3
  139. package/dist/create/server-source/crates/feltdb/tests/saas_invitation_lifecycle.rs +25 -22
  140. package/dist/create/server-source/crates/feltdb/tests/state_conflict_contract_conformance.rs +1799 -0
  141. package/dist/create/server-source/crates/feltdb/tests/state_diff_contract_conformance.rs +1316 -0
  142. package/dist/create/server-source/crates/feltdb/tests/state_model_integration.rs +53 -61
  143. package/dist/create/server-source/crates/feltdb/tests/state_persistence_integration.rs +156 -61
  144. package/dist/create/server-source/crates/feltdb/tests/state_store_boundary_evidence.rs +299 -0
  145. package/dist/create/server-source/crates/feltdb/tests/sync_divergence_evidence.rs +255 -0
  146. package/dist/create/server-source/crates/feltdb/tests/three_way_input_boundary_evidence.rs +249 -0
  147. package/dist/create/server-source/crates/feltdb/tests/trigger_contract_conformance.rs +994 -0
  148. package/dist/create/server-source/crates/feltdb-server/src/app_state.rs +2 -1
  149. package/dist/create/server-source/crates/feltdb-server/src/audit.rs +1137 -29
  150. package/dist/create/server-source/crates/feltdb-server/src/auth.rs +164 -13
  151. package/dist/create/server-source/crates/feltdb-server/src/main.rs +800 -34
  152. package/dist/db.d.ts +33 -34
  153. package/dist/db.d.ts.map +1 -1
  154. package/dist/db.js +74 -20
  155. package/dist/deployment.d.ts +30 -0
  156. package/dist/deployment.d.ts.map +1 -0
  157. package/dist/deployment.js +130 -0
  158. package/dist/embedded-transaction.d.ts +22 -4
  159. package/dist/embedded-transaction.d.ts.map +1 -1
  160. package/dist/embedded-transaction.js +51 -5
  161. package/dist/feltdb.d.ts +14 -2
  162. package/dist/feltdb.d.ts.map +1 -1
  163. package/dist/file-db.js +1 -1
  164. package/dist/http-client.d.ts +14 -0
  165. package/dist/http-client.d.ts.map +1 -1
  166. package/dist/http-client.js +23 -5
  167. package/dist/http-db.d.ts +119 -1
  168. package/dist/http-db.d.ts.map +1 -1
  169. package/dist/http-db.js +346 -31
  170. package/dist/index-core.d.ts +2 -0
  171. package/dist/index-core.d.ts.map +1 -1
  172. package/dist/index-core.js +2 -0
  173. package/dist/index.d.ts.map +1 -1
  174. package/dist/index.js +9 -0
  175. package/dist/indexeddb-db.d.ts.map +1 -1
  176. package/dist/indexeddb-db.js +35 -21
  177. package/dist/managed-recovery.d.ts +192 -0
  178. package/dist/managed-recovery.d.ts.map +1 -0
  179. package/dist/managed-recovery.js +242 -0
  180. package/dist/memory-db.js +1 -1
  181. package/dist/studio-app/assets/{feltdb_wasm-DB8cX151.js → feltdb_wasm-DaNwCLRX.js} +1 -1
  182. package/dist/studio-app/assets/feltdb_wasm_bg-DnsHNv6g.wasm +0 -0
  183. package/dist/studio-app/assets/index-j8IlhNqJ.js +29 -0
  184. package/dist/studio-app/index.html +1 -1
  185. package/dist/transaction.d.ts +30 -0
  186. package/dist/transaction.d.ts.map +1 -1
  187. package/dist/transaction.js +41 -0
  188. package/dist/wasm/feltdb_wasm_bg.wasm +0 -0
  189. package/dist/workload.d.ts +2 -1
  190. package/dist/workload.d.ts.map +1 -1
  191. package/package.json +1 -1
  192. package/dist/studio-app/assets/feltdb_wasm_bg-ClhDHp0S.wasm +0 -0
  193. package/dist/studio-app/assets/index-B0k4UAlI.js +0 -29
@@ -8,7 +8,6 @@
8
8
  * - Query routing to appropriate shards
9
9
  * - Data migration between shards
10
10
  */
11
-
12
11
  use serde::{Deserialize, Serialize};
13
12
  use std::collections::{BTreeMap, HashMap, HashSet};
14
13
 
@@ -189,7 +188,9 @@ impl ShardManager {
189
188
  }
190
189
  "delete" => {
191
190
  metrics.entry_count = metrics.entry_count.saturating_sub(records_affected);
192
- metrics.size_bytes = metrics.size_bytes.saturating_sub(size_bytes.min(metrics.size_bytes));
191
+ metrics.size_bytes = metrics
192
+ .size_bytes
193
+ .saturating_sub(size_bytes.min(metrics.size_bytes));
193
194
  }
194
195
  _ => {}
195
196
  }
@@ -253,7 +254,9 @@ impl ShardManager {
253
254
  }
254
255
 
255
256
  // High write load
256
- if write_std_dev > 0.0 && (metrics.writes as f64 - avg_writes).abs() > write_std_dev * 2.0 {
257
+ if write_std_dev > 0.0
258
+ && (metrics.writes as f64 - avg_writes).abs() > write_std_dev * 2.0
259
+ {
257
260
  alerts.push(HotspotAlert {
258
261
  shard_id: metrics.shard_id.clone(),
259
262
  reason: "High write load".to_string(),
@@ -269,7 +272,9 @@ impl ShardManager {
269
272
  }
270
273
 
271
274
  // Data imbalance
272
- if entry_std_dev > 0.0 && (metrics.entry_count as f64 - avg_entries).abs() > entry_std_dev * 3.0 {
275
+ if entry_std_dev > 0.0
276
+ && (metrics.entry_count as f64 - avg_entries).abs() > entry_std_dev * 3.0
277
+ {
273
278
  alerts.push(HotspotAlert {
274
279
  shard_id: metrics.shard_id.clone(),
275
280
  reason: "Data imbalance".to_string(),
@@ -297,13 +302,22 @@ impl ShardManager {
297
302
  for hotspot in hotspots {
298
303
  if hotspot.severity == "high" {
299
304
  // Find the overloaded shard
300
- if let Some(shard_range) = self.shard_ranges.iter().find(|r| r.shard_id == hotspot.shard_id) {
305
+ if let Some(shard_range) = self
306
+ .shard_ranges
307
+ .iter()
308
+ .find(|r| r.shard_id == hotspot.shard_id)
309
+ {
301
310
  // Split the hash range in half
302
- let mid_hash = (shard_range.start_hash as u128 + shard_range.end_hash as u128) / 2;
311
+ let mid_hash =
312
+ (shard_range.start_hash as u128 + shard_range.end_hash as u128) / 2;
303
313
  let mid_hash = mid_hash as u64;
304
314
 
305
315
  // Create a new shard ID for the split
306
- let new_shard_id = ShardId(format!("{}-split-{}", hotspot.shard_id.0, current_time_ms()));
316
+ let new_shard_id = ShardId(format!(
317
+ "{}-split-{}",
318
+ hotspot.shard_id.0,
319
+ current_time_ms()
320
+ ));
307
321
 
308
322
  operations.push(RebalanceOperation {
309
323
  source_shard: hotspot.shard_id.clone(),
@@ -415,7 +429,10 @@ mod tests {
415
429
  ShardingStrategy::ConsistentHash,
416
430
  );
417
431
 
418
- let shards = vec![ShardId("shard-0".to_string()), ShardId("shard-1".to_string())];
432
+ let shards = vec![
433
+ ShardId("shard-0".to_string()),
434
+ ShardId("shard-1".to_string()),
435
+ ];
419
436
  let mut replicas = HashMap::new();
420
437
  replicas.insert("shard-0".to_string(), vec!["node-1".to_string()]);
421
438
  replicas.insert("shard-1".to_string(), vec!["node-2".to_string()]);
@@ -435,7 +452,10 @@ mod tests {
435
452
  ShardingStrategy::ConsistentHash,
436
453
  );
437
454
 
438
- let shards = vec![ShardId("shard-0".to_string()), ShardId("shard-1".to_string())];
455
+ let shards = vec![
456
+ ShardId("shard-0".to_string()),
457
+ ShardId("shard-1".to_string()),
458
+ ];
439
459
  manager.initialize_shards(shards, HashMap::new());
440
460
 
441
461
  let shard = manager.get_shard_for_key("user123");
@@ -510,7 +530,13 @@ mod tests {
510
530
  manager.initialize_shards(shards, HashMap::new());
511
531
 
512
532
  // Create severe imbalanced load across 3 shards
513
- manager.record_shard_operation(&ShardId("shard-0".to_string()), "write", 5.0, 100000, 50000000);
533
+ manager.record_shard_operation(
534
+ &ShardId("shard-0".to_string()),
535
+ "write",
536
+ 5.0,
537
+ 100000,
538
+ 50000000,
539
+ );
514
540
  manager.record_shard_operation(&ShardId("shard-1".to_string()), "write", 5.0, 1000, 500000);
515
541
  manager.record_shard_operation(&ShardId("shard-2".to_string()), "write", 5.0, 100, 50000);
516
542
 
@@ -0,0 +1,516 @@
1
+ //! The deterministic contract behind FeltDB's conflict classification.
2
+ //!
3
+ //! The third specimen of the pattern established by [`crate::trigger_contract`]
4
+ //! and [`crate::state_diff_contract`], and the first that reasons over
5
+ //! *competing* changes rather than deciding or computing over one input.
6
+ //!
7
+ //! ```text
8
+ //! base + left + right, as canonical content
9
+ //! │
10
+ //! ┌──────────────┴──────────────┐
11
+ //! │ │
12
+ //! native evaluation WASM evaluation
13
+ //! │ │
14
+ //! └──────────────┬──────────────┘
15
+ //! │
16
+ //! canonical classification bytes
17
+ //! ```
18
+ //!
19
+ //! # This module adds no classification semantics
20
+ //!
21
+ //! [`ConflictClassification::classify`] is untouched and remains authoritative.
22
+ //! Everything here is envelope: identity, version, canonical encoding, and the
23
+ //! decision to report an unusable input rather than fail. If this module and
24
+ //! `classify` ever disagree, `classify` is right.
25
+ //!
26
+ //! # Why the input is three strings and not three revisions
27
+ //!
28
+ //! `classify` takes three [`StateRevision`]s and reads exactly one field of
29
+ //! each: `content`. It never looks at `id`, `parent_id`, `authority`,
30
+ //! `timestamp_ms` or `metadata`, and a unit test in this module proves it.
31
+ //!
32
+ //! Taking revisions into the contract would therefore drag a clock reading into
33
+ //! it for nothing — `StateRevision::initial` calls `SystemTime::now()` — along
34
+ //! with an authority identity that has no bearing on the answer. The contract
35
+ //! takes the three content strings instead, which is the real semantic
36
+ //! boundary.
37
+ //!
38
+ //! It is a *string* rather than parsed JSON on purpose: `classify` parses with
39
+ //! `unwrap_or(Value::Null)`, so content that is not JSON classifies as JSON
40
+ //! null instead of failing. That tolerance is part of the semantics, and a
41
+ //! contract taking parsed values could not express it.
42
+ //!
43
+ //! # Determinism budget
44
+ //!
45
+ //! Evaluation reads nothing but its three strings. No clock, filesystem,
46
+ //! network, random source, process identity, authentication context, authority
47
+ //! metadata, revision identity, timestamp, operation provenance or
48
+ //! process-global mutable state participates, and the audit found none in the
49
+ //! implementation either.
50
+ //!
51
+ //! # What the audit established about the semantics
52
+ //!
53
+ //! Recorded here because the contract is defined against the implementation's
54
+ //! actual behaviour rather than against an idea of what a three-way merge
55
+ //! should do. Several of these will surprise a reader who expects a merge tool.
56
+ //!
57
+ //! - **There are three classes and no fourth.** `Independent`, `Convergent`,
58
+ //! `Conflict`. There is no "no change" class: `classify(a, a, a)` returns an
59
+ //! empty conflict list whose `overall` is `Independent`.
60
+ //! - **Classification is per overlapping path.** Two changes interact when
61
+ //! their paths are equal *or* when one contains the other. A branch replacing
62
+ //! `o` and a branch editing `o.a` cannot both be applied, so both paths are
63
+ //! `Conflict`. Overlap is structural, over whole path components, so `a.b`
64
+ //! and `a.bc` are disjoint. Version 1 of this contract collided on equal
65
+ //! paths only and reported that case as `Independent`; see
66
+ //! [state model](../../../docs/architecture/state-conflict-semantics.md).
67
+ //! - **Convergence ignores `old_value`.** Two sides agree when their change
68
+ //! kind and their new value are equal, so both removing a member is
69
+ //! `Convergent`, and both adding the same value is `Convergent`.
70
+ //! - **Differing kinds always conflict**, even when the outcome would agree —
71
+ //! removing on one side and changing on the other is a `Conflict`. The kind
72
+ //! half of the convergence test cannot actually decide anything, though:
73
+ //! both diffs share a base, so whether a path resolves in it is a property of
74
+ //! the base alone, and the one kind pair that can differ — `Removed` against
75
+ //! `Changed` — always disagrees on the new value too, because a removal has
76
+ //! none. The conformance suite asserts that redundancy rather than assuming
77
+ //! it, and it is why relabelling a change kind is invisible to this
78
+ //! contract while the diff contract catches it.
79
+ //! - **`base_value` is the common ancestor's value at the path**, read from the
80
+ //! base state. Version 1 read it from the left branch's change, which
81
+ //! reported `null` for a path only the right branch touched even when the
82
+ //! base held a value there. Correcting it makes the whole result symmetric
83
+ //! under a branch swap apart from the two branch values exchanging.
84
+ //! - **Absent and null collapse in the recorded values.** All three value
85
+ //! fields are `Option<Value>` flattened from an optional change, so "no
86
+ //! change here" and "the value is JSON null" both encode as `null`. The
87
+ //! `classification` field is what carries the meaning.
88
+ //! - **`overall` is the maximum severity present**: `Conflict` if any path
89
+ //! conflicts, else `Convergent` if any path converges, else `Independent`.
90
+ //! - **Ordering is total.** Paths are unique — they are the union of two
91
+ //! path-keyed maps — and the result is sorted by path.
92
+ //! - **Diff semantics are inherited**, including positional arrays, so the same
93
+ //! index changed on both sides conflicts while different indexes remain
94
+ //! independent — under positional semantics both index changes survive a
95
+ //! merge. Removing an array element while the other branch edits inside it
96
+ //! *is* an overlap, and conflicts.
97
+
98
+ use crate::state_model::{ConflictClassification, StateId, StateRevision};
99
+ use serde::{Deserialize, Serialize};
100
+ use sha2::{Digest, Sha256};
101
+ use std::collections::BTreeMap;
102
+
103
+ /// Stable identity of this contract.
104
+ pub const STATE_CONFLICT_CONTRACT_ID: &str = "feltdb.state.conflict";
105
+
106
+ /// Version of this contract's input shape, output shape and semantics.
107
+ ///
108
+ /// The output shape is [`ConflictClassification`]'s own serialization, so a
109
+ /// change to that type is a change to this contract and must bump this.
110
+ pub const STATE_CONFLICT_CONTRACT_VERSION: u32 = 2;
111
+
112
+ /// The complete deterministic input: three state contents, and the contract's
113
+ /// identity.
114
+ ///
115
+ /// Members are declared alphabetically so the canonical struct encoding matches
116
+ /// the sorted-key encoding `serde_json` gives every JSON object.
117
+ #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
118
+ #[serde(deny_unknown_fields)]
119
+ pub struct StateConflictInput {
120
+ /// The common ancestor's content.
121
+ pub base: String,
122
+ pub contract: String,
123
+ /// The first branch's content.
124
+ pub left: String,
125
+ /// The second branch's content.
126
+ pub right: String,
127
+ pub version: u32,
128
+ }
129
+
130
+ impl StateConflictInput {
131
+ /// Builds an input stamped with this contract's identity and version.
132
+ pub fn new(base: String, left: String, right: String) -> Self {
133
+ Self {
134
+ base,
135
+ contract: STATE_CONFLICT_CONTRACT_ID.to_string(),
136
+ left,
137
+ right,
138
+ version: STATE_CONFLICT_CONTRACT_VERSION,
139
+ }
140
+ }
141
+ }
142
+
143
+ /// Why an input could not be evaluated.
144
+ ///
145
+ /// The same three codes the other two contracts use. Note that unparseable
146
+ /// *state content* is not one of them: that is a classification, not an error.
147
+ #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
148
+ #[serde(rename_all = "SCREAMING_SNAKE_CASE")]
149
+ pub enum ContractErrorCode {
150
+ /// The bytes are not a well-formed instance of this contract's input.
151
+ ContractInputInvalid,
152
+ /// The input declares a different contract.
153
+ ContractIdMismatch,
154
+ /// The input declares a version this implementation does not implement.
155
+ ContractVersionUnsupported,
156
+ }
157
+
158
+ /// The error body of a contract output.
159
+ #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
160
+ #[serde(deny_unknown_fields)]
161
+ pub struct ContractErrorBody {
162
+ pub code: ContractErrorCode,
163
+ }
164
+
165
+ /// The complete deterministic output.
166
+ ///
167
+ /// Exactly one of `classification` and `error` is present. `classification` is
168
+ /// [`ConflictClassification`] serialized exactly as it already serializes —
169
+ /// this contract does not reshape it, because the existing result is the
170
+ /// contract.
171
+ #[derive(Debug, Clone, Serialize, Deserialize)]
172
+ #[serde(deny_unknown_fields)]
173
+ pub struct StateConflictOutput {
174
+ #[serde(default, skip_serializing_if = "Option::is_none")]
175
+ pub classification: Option<ConflictClassification>,
176
+ pub contract: String,
177
+ #[serde(default, skip_serializing_if = "Option::is_none")]
178
+ pub error: Option<ContractErrorBody>,
179
+ pub version: u32,
180
+ }
181
+
182
+ impl StateConflictOutput {
183
+ fn classified(classification: ConflictClassification) -> Self {
184
+ Self {
185
+ classification: Some(classification),
186
+ contract: STATE_CONFLICT_CONTRACT_ID.to_string(),
187
+ error: None,
188
+ version: STATE_CONFLICT_CONTRACT_VERSION,
189
+ }
190
+ }
191
+
192
+ fn failure(code: ContractErrorCode) -> Self {
193
+ Self {
194
+ classification: None,
195
+ contract: STATE_CONFLICT_CONTRACT_ID.to_string(),
196
+ error: Some(ContractErrorBody { code }),
197
+ version: STATE_CONFLICT_CONTRACT_VERSION,
198
+ }
199
+ }
200
+ }
201
+
202
+ /// The runtime that executed a contract, recorded in evidence.
203
+ ///
204
+ /// Only [`ContractRuntime::Native`] is wired anywhere.
205
+ #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
206
+ #[serde(rename_all = "snake_case")]
207
+ pub enum ContractRuntime {
208
+ Native,
209
+ Wasm,
210
+ }
211
+
212
+ impl ContractRuntime {
213
+ pub fn as_str(self) -> &'static str {
214
+ match self {
215
+ Self::Native => "native",
216
+ Self::Wasm => "wasm",
217
+ }
218
+ }
219
+ }
220
+
221
+ /// Wraps state content in the revision shape `classify` expects.
222
+ ///
223
+ /// Every field but `content` is fixed, because `classify` reads no other field
224
+ /// and the contract must not acquire an input the decision does not use. In
225
+ /// particular nothing here reads a clock, unlike `StateRevision::initial`.
226
+ fn revision(content: &str) -> StateRevision {
227
+ StateRevision {
228
+ id: StateId::compute(content),
229
+ resource: String::new(),
230
+ content: content.to_string(),
231
+ content_id: StateId::compute(content),
232
+ parent_id: None,
233
+ sequence: 0,
234
+ authority: String::new(),
235
+ timestamp_ms: 0,
236
+ metadata: BTreeMap::new(),
237
+ }
238
+ }
239
+
240
+ /// The deterministic contract, natively implemented.
241
+ ///
242
+ /// A thin adapter over the existing implementation, deliberately holding no
243
+ /// classification logic of its own.
244
+ pub fn classify_states(base: &str, left: &str, right: &str) -> ConflictClassification {
245
+ ConflictClassification::classify(&revision(base), &revision(left), &revision(right))
246
+ }
247
+
248
+ /// The canonical byte encoding of a contract input.
249
+ pub fn canonical_input_bytes(input: &StateConflictInput) -> Vec<u8> {
250
+ serde_json::to_vec(input).expect("contract input is always serializable")
251
+ }
252
+
253
+ /// The canonical byte encoding of a contract output.
254
+ pub fn canonical_output_bytes(output: &StateConflictOutput) -> Vec<u8> {
255
+ serde_json::to_vec(output).expect("contract output is always serializable")
256
+ }
257
+
258
+ /// Content identity of a contract input, for provenance.
259
+ pub fn input_digest(input: &StateConflictInput) -> String {
260
+ format!("sha256:{:x}", Sha256::digest(canonical_input_bytes(input)))
261
+ }
262
+
263
+ /// The runtime-independent entry point: canonical bytes in, canonical bytes out.
264
+ ///
265
+ /// Never panics and never returns anything but a canonical output encoding, so
266
+ /// an unusable input is a contract decision rather than a host-specific failure
267
+ /// mode. Unparseable *state content* is not an unusable input: it classifies as
268
+ /// JSON null, which is what the existing implementation does.
269
+ pub fn evaluate_canonical(input: &[u8]) -> Vec<u8> {
270
+ canonical_output_bytes(&evaluate_canonical_output(input))
271
+ }
272
+
273
+ /// [`evaluate_canonical`] before encoding, for callers that want the value.
274
+ pub fn evaluate_canonical_output(input: &[u8]) -> StateConflictOutput {
275
+ let Ok(parsed) = serde_json::from_slice::<StateConflictInput>(input) else {
276
+ return StateConflictOutput::failure(ContractErrorCode::ContractInputInvalid);
277
+ };
278
+ if parsed.contract != STATE_CONFLICT_CONTRACT_ID {
279
+ return StateConflictOutput::failure(ContractErrorCode::ContractIdMismatch);
280
+ }
281
+ if parsed.version != STATE_CONFLICT_CONTRACT_VERSION {
282
+ return StateConflictOutput::failure(ContractErrorCode::ContractVersionUnsupported);
283
+ }
284
+ StateConflictOutput::classified(classify_states(&parsed.base, &parsed.left, &parsed.right))
285
+ }
286
+
287
+ #[cfg(test)]
288
+ mod tests {
289
+ use super::*;
290
+ use crate::state_model::ConflictClass;
291
+
292
+ fn classify(base: &str, left: &str, right: &str) -> String {
293
+ String::from_utf8(canonical_output_bytes(&StateConflictOutput::classified(
294
+ classify_states(base, left, right),
295
+ )))
296
+ .unwrap()
297
+ }
298
+
299
+ fn overall(base: &str, left: &str, right: &str) -> ConflictClass {
300
+ classify_states(base, left, right).overall
301
+ }
302
+
303
+ #[test]
304
+ fn the_contract_reads_only_revision_content() {
305
+ // Two revisions differing in every field the decision does not use must
306
+ // classify identically. If revision identity, authority, a timestamp or
307
+ // metadata ever reached the classifier, the contract would stop being
308
+ // reproducible anywhere and this would fail.
309
+ let plain = revision(r#"{"x":1}"#);
310
+ let decorated = StateRevision {
311
+ id: StateId::compute("something else entirely"),
312
+ resource: "some:other:resource".into(),
313
+ content: r#"{"x":1}"#.to_string(),
314
+ content_id: StateId::compute("not even the content"),
315
+ parent_id: Some(StateId::compute("a parent")),
316
+ sequence: 41,
317
+ authority: "someone-else".into(),
318
+ timestamp_ms: 1_700_000_000_000,
319
+ metadata: [("k".to_string(), serde_json::json!("v"))]
320
+ .into_iter()
321
+ .collect(),
322
+ };
323
+ let base = revision(r#"{"x":0}"#);
324
+ assert_eq!(
325
+ serde_json::to_string(&ConflictClassification::classify(&base, &plain, &plain))
326
+ .unwrap(),
327
+ serde_json::to_string(&ConflictClassification::classify(
328
+ &base, &decorated, &decorated
329
+ ))
330
+ .unwrap()
331
+ );
332
+ }
333
+
334
+ #[test]
335
+ fn identical_states_classify_as_independent_with_no_paths() {
336
+ // There is no "no change" class; this is what the absence of change
337
+ // looks like.
338
+ assert_eq!(
339
+ classify(r#"{"x":1}"#, r#"{"x":1}"#, r#"{"x":1}"#),
340
+ r#"{"classification":{"path_conflicts":[],"overall":"Independent"},"contract":"feltdb.state.conflict","version":2}"#
341
+ );
342
+ }
343
+
344
+ #[test]
345
+ fn one_sided_changes_are_independent() {
346
+ assert_eq!(
347
+ overall(r#"{"x":1}"#, r#"{"x":2}"#, r#"{"x":1}"#),
348
+ ConflictClass::Independent
349
+ );
350
+ assert_eq!(
351
+ overall(r#"{"x":1}"#, r#"{"x":1}"#, r#"{"x":2}"#),
352
+ ConflictClass::Independent
353
+ );
354
+ }
355
+
356
+ #[test]
357
+ fn agreeing_changes_converge_and_disagreeing_ones_conflict() {
358
+ assert_eq!(
359
+ overall(r#"{"x":1}"#, r#"{"x":2}"#, r#"{"x":2}"#),
360
+ ConflictClass::Convergent
361
+ );
362
+ assert_eq!(
363
+ overall(r#"{"x":1}"#, r#"{"x":2}"#, r#"{"x":3}"#),
364
+ ConflictClass::Conflict
365
+ );
366
+ // Both removing the member agree, because convergence compares the
367
+ // change kind and the new value, and both are absent.
368
+ assert_eq!(overall(r#"{"x":1}"#, "{}", "{}"), ConflictClass::Convergent);
369
+ // Removing on one side and changing on the other does not, because the
370
+ // kinds differ even though a merge tool might reconcile it.
371
+ assert_eq!(
372
+ overall(r#"{"x":1}"#, "{}", r#"{"x":2}"#),
373
+ ConflictClass::Conflict
374
+ );
375
+ }
376
+
377
+ #[test]
378
+ fn an_ancestor_descendant_overlap_conflicts() {
379
+ // Left replaces the whole of `o` while right edits `o.a`. The paths are
380
+ // not equal, but one contains the other, and the two changes cannot
381
+ // both be applied: left decides the value of `o` that right was editing
382
+ // inside. Version 1 of this contract reported both paths as
383
+ // `Independent`, which was unsafe as a basis for reconciliation.
384
+ let output = classify_states(
385
+ r#"{"o":{"a":1}}"#,
386
+ r#"{"o":"replaced"}"#,
387
+ r#"{"o":{"a":2}}"#,
388
+ );
389
+ assert_eq!(output.overall, ConflictClass::Conflict);
390
+ assert_eq!(output.path_conflicts.len(), 2);
391
+ assert!(output
392
+ .path_conflicts
393
+ .iter()
394
+ .all(|entry| entry.classification == ConflictClass::Conflict));
395
+
396
+ // Removing the parent is the same overlap.
397
+ assert_eq!(
398
+ overall(r#"{"o":{"a":1}}"#, "{}", r#"{"o":{"a":2}}"#),
399
+ ConflictClass::Conflict
400
+ );
401
+
402
+ // Sibling paths under an untouched parent still do not overlap.
403
+ assert_eq!(
404
+ overall(
405
+ r#"{"o":{"a":1,"b":1}}"#,
406
+ r#"{"o":{"a":2,"b":1}}"#,
407
+ r#"{"o":{"a":1,"b":2}}"#
408
+ ),
409
+ ConflictClass::Independent
410
+ );
411
+ // Nor do keys that merely share a string prefix.
412
+ assert_eq!(
413
+ overall(
414
+ r#"{"a":{"b":1,"bc":1}}"#,
415
+ r#"{"a":{"b":2,"bc":1}}"#,
416
+ r#"{"a":{"b":1,"bc":2}}"#
417
+ ),
418
+ ConflictClass::Independent
419
+ );
420
+ }
421
+
422
+ #[test]
423
+ fn base_value_is_the_base_states_value_at_the_path() {
424
+ // The base holds 1 at `x` and only the right branch changed it.
425
+ // Version 1 read `base_value` from the left branch's change and so
426
+ // reported `null` here, losing the ancestor's value exactly where a
427
+ // reconciler would need it.
428
+ let output = classify_states(r#"{"x":1}"#, r#"{"x":1}"#, r#"{"x":2}"#);
429
+ let entry = &output.path_conflicts[0];
430
+ assert_eq!(entry.base_value, Some(serde_json::json!(1)));
431
+ assert_eq!(entry.left_value, None, "the left branch changed nothing");
432
+ assert_eq!(entry.right_value, Some(serde_json::json!(2)));
433
+
434
+ // A path the base does not hold has no base value.
435
+ let added = classify_states("{}", r#"{"x":1}"#, "{}");
436
+ assert_eq!(added.path_conflicts[0].base_value, None);
437
+
438
+ // And it does not depend on which branch is called left.
439
+ let forward = classify_states(r#"{"x":1}"#, r#"{"x":1}"#, r#"{"x":2}"#);
440
+ let reversed = classify_states(r#"{"x":1}"#, r#"{"x":2}"#, r#"{"x":1}"#);
441
+ assert_eq!(
442
+ forward.path_conflicts[0].base_value,
443
+ reversed.path_conflicts[0].base_value
444
+ );
445
+ }
446
+
447
+ #[test]
448
+ fn unparseable_content_classifies_as_json_null_rather_than_failing() {
449
+ // `classify` parses with `unwrap_or(Value::Null)`. Both sides moving
450
+ // from unparseable base to the same state therefore converge.
451
+ let output = classify_states("not json at all", r#"{"x":1}"#, r#"{"x":1}"#);
452
+ assert_eq!(output.overall, ConflictClass::Convergent);
453
+ assert_eq!(output.path_conflicts[0].path, vec![]);
454
+
455
+ // And it is a classification, not a contract error.
456
+ let bytes =
457
+ canonical_input_bytes(&StateConflictInput::new("{".into(), "}".into(), "]".into()));
458
+ let parsed = evaluate_canonical_output(&bytes);
459
+ assert!(parsed.error.is_none());
460
+ assert!(parsed.classification.is_some());
461
+ }
462
+
463
+ #[test]
464
+ fn unevaluatable_inputs_are_decisions_rather_than_failures() {
465
+ for (bytes, code) in [
466
+ (&b"not json"[..], ContractErrorCode::ContractInputInvalid),
467
+ (
468
+ br#"{"base":"{}","contract":"other","left":"{}","right":"{}","version":2}"#,
469
+ ContractErrorCode::ContractIdMismatch,
470
+ ),
471
+ (
472
+ br#"{"base":"{}","contract":"feltdb.state.conflict","left":"{}","right":"{}","version":9}"#,
473
+ ContractErrorCode::ContractVersionUnsupported,
474
+ ),
475
+ ] {
476
+ let output = evaluate_canonical_output(bytes);
477
+ assert_eq!(output.error.map(|error| error.code), Some(code));
478
+ assert!(output.classification.is_none());
479
+ }
480
+ }
481
+
482
+ #[test]
483
+ fn canonical_round_trip_is_stable() {
484
+ let input = StateConflictInput::new(
485
+ r#"{"x":1}"#.into(),
486
+ r#"{"x":2}"#.into(),
487
+ r#"{"x":3}"#.into(),
488
+ );
489
+ let once = canonical_input_bytes(&input);
490
+ let parsed: StateConflictInput = serde_json::from_slice(&once).unwrap();
491
+ assert_eq!(parsed, input);
492
+ assert_eq!(canonical_input_bytes(&parsed), once);
493
+ assert_eq!(input_digest(&parsed), input_digest(&input));
494
+ }
495
+
496
+ #[test]
497
+ fn the_adapter_is_the_existing_classifier() {
498
+ // The adapter must be the classification FeltDB already computes, not a
499
+ // second one that happens to agree.
500
+ for (base, left, right) in [
501
+ (r#"{"x":1}"#, r#"{"x":2}"#, r#"{"x":3}"#),
502
+ (r#"{"a":1,"b":1}"#, r#"{"a":2,"b":1}"#, r#"{"a":1,"b":2}"#),
503
+ ("[1,2]", "[9,2]", "[8,2]"),
504
+ ] {
505
+ assert_eq!(
506
+ serde_json::to_string(&classify_states(base, left, right)).unwrap(),
507
+ serde_json::to_string(&ConflictClassification::classify(
508
+ &revision(base),
509
+ &revision(left),
510
+ &revision(right)
511
+ ))
512
+ .unwrap()
513
+ );
514
+ }
515
+ }
516
+ }