@feltdb/core 0.6.12 → 0.6.14

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 (69) hide show
  1. package/dist/agent-registry.js +1 -3
  2. package/dist/agent-runtime.js +8 -7
  3. package/dist/analytics-backend.js +3 -1
  4. package/dist/application-contract.js +1 -0
  5. package/dist/application-manifest.js +1 -0
  6. package/dist/artifact.js +2 -0
  7. package/dist/authorization.js +2 -0
  8. package/dist/bundle.js +2 -0
  9. package/dist/capability.js +1 -3
  10. package/dist/cell.js +9 -4
  11. package/dist/cli/application.js +1 -1
  12. package/dist/cli/browser-opening.js +35 -0
  13. package/dist/cli/commands.js +50 -17
  14. package/dist/cli/index.js +1 -1
  15. package/dist/collection.js +39 -31
  16. package/dist/create/cli.js +7 -5
  17. package/dist/create/create.js +9 -7
  18. package/dist/create/development-handoff.js +4 -0
  19. package/dist/create/docker-compose-generator.js +4 -4
  20. package/dist/create/package-versions.js +1 -1
  21. package/dist/create/server-source/crates/feltdb/src/bin/feltdb_node.rs +497 -27
  22. package/dist/create/server-source/crates/feltdb/src/causal_backlog_bound.rs +452 -0
  23. package/dist/create/server-source/crates/feltdb/src/causal_dependency_barrier.rs +208 -0
  24. package/dist/create/server-source/crates/feltdb/src/convergence.rs +16 -0
  25. package/dist/create/server-source/crates/feltdb/src/dedup_bound_investigation.rs +402 -0
  26. package/dist/create/server-source/crates/feltdb/src/distributed_transactions.rs +765 -24
  27. package/dist/create/server-source/crates/feltdb/src/durable_operation_identity.rs +418 -0
  28. package/dist/create/server-source/crates/feltdb/src/lib.rs +4 -0
  29. package/dist/create/server-source/crates/feltdb/src/replica_membership.rs +661 -0
  30. package/dist/db.js +19 -13
  31. package/dist/development-runtime-bridge.js +1 -1
  32. package/dist/distributed-indexing.js +7 -5
  33. package/dist/file-db.js +8 -3
  34. package/dist/flowspec.js +2 -1
  35. package/dist/http-client.js +2 -0
  36. package/dist/http-db.js +16 -1
  37. package/dist/identity.js +1 -0
  38. package/dist/index-analytics.js +6 -7
  39. package/dist/index-backend.js +3 -3
  40. package/dist/index-dashboard.js +10 -13
  41. package/dist/index-manager.js +12 -11
  42. package/dist/index-monitoring.js +9 -4
  43. package/dist/index-store.js +2 -0
  44. package/dist/indexeddb-db.js +27 -23
  45. package/dist/memory-db.js +7 -4
  46. package/dist/observe.js +2 -0
  47. package/dist/provider.js +2 -0
  48. package/dist/query-planner.js +2 -4
  49. package/dist/reactive-graph.js +6 -8
  50. package/dist/release.js +2 -0
  51. package/dist/sharding.js +11 -6
  52. package/dist/state-contract.js +3 -3
  53. package/dist/studio-app/assets/{feltdb_wasm-CJv3wHzi.js → feltdb_wasm-C9xpYtna.js} +1 -1
  54. package/dist/studio-app/assets/feltdb_wasm_bg-BsXHw7eX.wasm +0 -0
  55. package/dist/studio-app/assets/{index-DospFFYE.js → index-D4RZ44qs.js} +4 -4
  56. package/dist/studio-app/index.html +1 -1
  57. package/dist/sync-contract.js +9 -2
  58. package/dist/telemetry.d.ts.map +1 -1
  59. package/dist/telemetry.js +32 -12
  60. package/dist/transaction.js +4 -2
  61. package/dist/wasm/feltdb_wasm_bg.wasm +0 -0
  62. package/dist/worker.js +2 -0
  63. package/dist/workload.js +2 -0
  64. package/dist/workspace/development-node.js +11 -10
  65. package/dist/workspace/investigation-lifecycle-manager.js +2 -0
  66. package/dist/workspace/investigation-supervisor.js +5 -3
  67. package/dist/workspace/workspace-connection.js +14 -5
  68. package/package.json +1 -1
  69. package/dist/studio-app/assets/feltdb_wasm_bg-C8TG8r2n.wasm +0 -0
@@ -88,6 +88,12 @@ pub struct PendingOperation {
88
88
  pub operation_id: String,
89
89
  pub required_dependencies: VectorClock,
90
90
  pub state: OperationState,
91
+ /// Size on the durable log of the envelope this entry stands for.
92
+ ///
93
+ /// The entry does not hold the payload -- that stays in the operation log
94
+ /// -- but the backlog's byte bound is about payload volume, so the size has
95
+ /// to be carried even though the bytes are not.
96
+ pub payload_bytes: usize,
91
97
  }
92
98
 
93
99
  impl PendingOperation {
@@ -96,6 +102,7 @@ impl PendingOperation {
96
102
  operation_id,
97
103
  required_dependencies,
98
104
  state: OperationState::Received,
105
+ payload_bytes: 0,
99
106
  }
100
107
  }
101
108
  }
@@ -114,6 +121,10 @@ pub struct CausalDependencyBarrier {
114
121
  metrics: BarrierMetrics,
115
122
  /// Phase 7.1-opt: Dependency index for selective candidate discovery
116
123
  dependency_index: DependencyIndex,
124
+ /// High-water mark of pending entries, for occupancy metrics.
125
+ max_pending_entries_seen: usize,
126
+ /// High-water mark of pending payload bytes, for occupancy metrics.
127
+ max_pending_payload_bytes_seen: usize,
117
128
  }
118
129
 
119
130
  impl CausalDependencyBarrier {
@@ -125,6 +136,8 @@ impl CausalDependencyBarrier {
125
136
  applied: Vec::new(),
126
137
  metrics: BarrierMetrics::default(),
127
138
  dependency_index: DependencyIndex::default(),
139
+ max_pending_entries_seen: 0,
140
+ max_pending_payload_bytes_seen: 0,
128
141
  }
129
142
  }
130
143
 
@@ -181,6 +194,7 @@ impl CausalDependencyBarrier {
181
194
  required_clock: required_dependencies.clone(),
182
195
  missing_dependencies: missing,
183
196
  },
197
+ payload_bytes: 0,
184
198
  };
185
199
  self.pending.insert(operation_id.clone(), pending_op);
186
200
 
@@ -387,6 +401,200 @@ impl CausalDependencyBarrier {
387
401
  &self.local_frontier
388
402
  }
389
403
 
404
+ // ---------------------------------------------------------------------
405
+ // Production causal-delivery API.
406
+ //
407
+ // The methods above were built for, and are exercised by, in-process tests
408
+ // that drive the barrier directly. The methods below are what the
409
+ // replicated receive path uses. They differ in three ways that matter:
410
+ //
411
+ // 1. Eligibility is dominance, not `happens_before`. `receive_operation`
412
+ // buffers when `local_frontier.happens_before(deps)`, which returns
413
+ // false for concurrent clocks and would therefore admit an operation
414
+ // whose dependencies are unmet whenever the frontier is ahead in some
415
+ // unrelated dimension.
416
+ // 2. Release scanning does not consult the dependency index, because
417
+ // `index_operation` is `#[cfg(test)]` and so the index is empty in a
418
+ // shipping build. A full scan is correct at any build setting.
419
+ // 3. Nothing here holds a payload. Pending entries carry an identifier and
420
+ // the dependency clock; the envelope itself is replayed from the
421
+ // durable operation log when it becomes eligible.
422
+ // ---------------------------------------------------------------------
423
+
424
+ /// True when every dependency this clock names has already been applied.
425
+ pub fn is_eligible(&self, dependencies: &VectorClock) -> bool {
426
+ self.local_frontier.dominates(dependencies)
427
+ }
428
+
429
+ /// Retain an operation that cannot be applied yet.
430
+ ///
431
+ /// Returns false when the key is already pending, so a duplicate delivery
432
+ /// of a blocked envelope stays one logical operation.
433
+ pub fn retain_pending(&mut self, key: String, dependencies: VectorClock) -> bool {
434
+ self.retain_pending_sized(key, dependencies, 0)
435
+ }
436
+
437
+ /// Retain an operation that cannot be applied yet, recording the size of
438
+ /// the envelope it stands for.
439
+ ///
440
+ /// The entry still holds no payload. The size is carried because the
441
+ /// backlog's byte bound is about how much durable payload is outstanding,
442
+ /// and that number is not recoverable from metadata alone.
443
+ ///
444
+ /// Returns false when the key is already pending, so a duplicate delivery
445
+ /// of a blocked envelope stays one logical operation.
446
+ pub fn retain_pending_sized(
447
+ &mut self,
448
+ key: String,
449
+ dependencies: VectorClock,
450
+ payload_bytes: usize,
451
+ ) -> bool {
452
+ if self.pending.contains_key(&key) {
453
+ return false;
454
+ }
455
+ let missing = self.compute_missing_dependencies(&dependencies);
456
+ self.pending.insert(
457
+ key.clone(),
458
+ PendingOperation {
459
+ operation_id: key,
460
+ required_dependencies: dependencies.clone(),
461
+ state: OperationState::WaitingForDependencies {
462
+ required_clock: dependencies,
463
+ missing_dependencies: missing,
464
+ },
465
+ payload_bytes,
466
+ },
467
+ );
468
+ self.observe_occupancy();
469
+ true
470
+ }
471
+
472
+ /// Record the high-water marks after the pending set grows.
473
+ ///
474
+ /// Occupancy metrics have to report maximum as well as current, because a
475
+ /// backlog that filled and drained between two reads is invisible to a
476
+ /// current-value gauge, and "did this ever approach its bound" is the
477
+ /// question an operator actually has.
478
+ fn observe_occupancy(&mut self) {
479
+ let entries = self.pending.len();
480
+ if entries > self.max_pending_entries_seen {
481
+ self.max_pending_entries_seen = entries;
482
+ }
483
+ let bytes = self.pending_payload_bytes();
484
+ if bytes > self.max_pending_payload_bytes_seen {
485
+ self.max_pending_payload_bytes_seen = bytes;
486
+ }
487
+ }
488
+
489
+ /// Durable payload bytes the backlog is currently waiting on.
490
+ ///
491
+ /// This is the volume of log the pending entries stand for, not a heap
492
+ /// measurement: the payloads are on disk. It is what the byte bound is
493
+ /// expressed in.
494
+ pub fn pending_payload_bytes(&self) -> usize {
495
+ self.pending.values().map(|op| op.payload_bytes).sum()
496
+ }
497
+
498
+ /// The most pending entries ever held at once.
499
+ pub fn max_pending_entries_seen(&self) -> usize {
500
+ self.max_pending_entries_seen
501
+ }
502
+
503
+ /// The most pending payload bytes ever held at once.
504
+ pub fn max_pending_payload_bytes_seen(&self) -> usize {
505
+ self.max_pending_payload_bytes_seen
506
+ }
507
+
508
+ /// Record that an operation was applied, advancing the frontier.
509
+ ///
510
+ /// The frontier advances here and nowhere else on the production path, so
511
+ /// it always describes what has been *successfully applied* rather than
512
+ /// what has been received or claimed.
513
+ pub fn record_applied(&mut self, key: &str, applied_clock: &VectorClock) {
514
+ self.pending.remove(key);
515
+ self.local_frontier.merge(applied_clock);
516
+ self.applied.push(key.to_string());
517
+ }
518
+
519
+ /// Every pending operation whose dependencies the frontier now satisfies.
520
+ ///
521
+ /// Returns them in a stable order so that two replicas releasing the same
522
+ /// set release it identically.
523
+ pub fn eligible_pending(&self) -> Vec<String> {
524
+ let mut ready: Vec<String> = self
525
+ .pending
526
+ .iter()
527
+ .filter(|(_, op)| self.local_frontier.dominates(&op.required_dependencies))
528
+ .map(|(key, _)| key.clone())
529
+ .collect();
530
+ ready.sort();
531
+ ready
532
+ }
533
+
534
+ /// Whether this key is currently held as pending.
535
+ pub fn is_pending(&self, key: &str) -> bool {
536
+ self.pending.contains_key(key)
537
+ }
538
+
539
+ /// Keys of applied operations, in the order they were applied.
540
+ pub fn applied_keys(&self) -> &[String] {
541
+ &self.applied
542
+ }
543
+
544
+ /// Keys currently held as pending, sorted.
545
+ pub fn pending_keys(&self) -> Vec<String> {
546
+ let mut keys: Vec<String> = self.pending.keys().cloned().collect();
547
+ keys.sort();
548
+ keys
549
+ }
550
+
551
+ /// Occupancy of the pending set: how many operations are waiting.
552
+ ///
553
+ /// Instrumentation only. What may be retained, and what happens when that
554
+ /// limit is reached, is deliberately not decided here -- see
555
+ /// docs/architecture/causal-backlog-bound.md.
556
+ pub fn pending_count(&self) -> usize {
557
+ self.pending.len()
558
+ }
559
+
560
+ /// Approximate heap footprint of the pending metadata, in bytes.
561
+ ///
562
+ /// Counts the key, both clock copies an entry carries, and the missing
563
+ /// dependency set, because the cost of a pending entry scales with cluster
564
+ /// size rather than with the size of the operation it stands for.
565
+ pub fn pending_metadata_bytes(&self) -> usize {
566
+ self.pending
567
+ .iter()
568
+ .map(|(key, op)| {
569
+ let clock_bytes = |clock: &VectorClock| {
570
+ clock
571
+ .clocks
572
+ .keys()
573
+ .map(|node| node.len() + std::mem::size_of::<u64>())
574
+ .sum::<usize>()
575
+ };
576
+ let state_bytes = match &op.state {
577
+ OperationState::WaitingForDependencies {
578
+ required_clock,
579
+ missing_dependencies,
580
+ } => {
581
+ clock_bytes(required_clock)
582
+ + missing_dependencies
583
+ .iter()
584
+ .map(|dep| dep.len() + std::mem::size_of::<u64>())
585
+ .sum::<usize>()
586
+ }
587
+ _ => 0,
588
+ };
589
+ key.len()
590
+ + op.operation_id.len()
591
+ + clock_bytes(&op.required_dependencies)
592
+ + state_bytes
593
+ + std::mem::size_of::<PendingOperation>()
594
+ })
595
+ .sum()
596
+ }
597
+
390
598
  /// Manually advance frontier (for testing or external coordination)
391
599
  pub fn advance_frontier(&mut self, clock: &VectorClock) {
392
600
  #[cfg(test)]
@@ -74,6 +74,22 @@ impl VectorClock {
74
74
  !self.happens_before(other) && !other.happens_before(self)
75
75
  }
76
76
 
77
+ /// True when this clock has seen at least everything `other` has, in every
78
+ /// dimension.
79
+ ///
80
+ /// This is the test a causal receiver needs, and it is not `happens_before`.
81
+ /// `happens_before` answers a question about ordering and returns false for
82
+ /// concurrent clocks, so a receiver using it would admit an operation whose
83
+ /// dependencies are genuinely unmet whenever the frontier happened to be
84
+ /// ahead in some unrelated dimension. Dominance asks only "have I seen
85
+ /// everything this operation needs", which is what eligibility means.
86
+ pub fn dominates(&self, other: &VectorClock) -> bool {
87
+ other
88
+ .clocks
89
+ .iter()
90
+ .all(|(instance_id, required)| self.get(instance_id) >= *required)
91
+ }
92
+
77
93
  /// Compare two vector clocks for causal ordering
78
94
  pub fn causal_cmp(&self, other: &VectorClock) -> Ordering {
79
95
  if self == other {
@@ -0,0 +1,402 @@
1
+ //! Is `envelopes_seen` bounded by the causal backlog, or is it independent?
2
+ //!
3
+ //! An investigation, not a change. Nothing here modifies the implementation;
4
+ //! every test asserts what the code does today, including where that is wrong.
5
+ //!
6
+ //! `adrs/replication-retention-and-recovery-lag.md` §8 raised this as the
7
+ //! cheapest unresolved question under P5.3, and recorded it as a question
8
+ //! rather than a decision because it argues against a frozen contract. The
9
+ //! hypothesis was:
10
+ //!
11
+ //! > since causal enforcement landed, `frontier[origin] = n` may imply that
12
+ //! > every clock position `1..n` from that origin has been applied, in which
13
+ //! > case the frontier is a complete deduplication test for everything it
14
+ //! > covers and `envelopes_seen` need only hold what is above it -- which the
15
+ //! > backlog bound already bounds.
16
+ //!
17
+ //! The tests below establish the four steps that hypothesis needs, find that it
18
+ //! holds, and then find that the deduplication *key* did not -- it was unsound
19
+ //! across a restart of the originating node, and lost writes silently.
20
+ //!
21
+ //! That second finding has since been fixed: identity is now allocated by the
22
+ //! executor from the durable log, in `durable_operation_identity.rs`. The two
23
+ //! tests at the bottom are kept and still pass, because what they assert is the
24
+ //! *receiver's* behaviour when it is handed a colliding identity, and that has
25
+ //! deliberately not changed -- a receiver cannot tell a re-used identity from a
26
+ //! retransmission, which is precisely why the origin must never produce one.
27
+ //! They are the reason durable identity allocation is load-bearing rather than
28
+ //! tidy.
29
+ //!
30
+ //! Two counters are involved and the whole question turns on their difference:
31
+ //!
32
+ //! ```text
33
+ //! envelope_id.sequence caller-supplied; the node binary resets it to 1
34
+ //! on restart and never restores it from the log
35
+ //! vector_clock[origin] frontier.increment(origin) at stamp time; the
36
+ //! frontier IS rebuilt from the log on restart
37
+ //! ```
38
+
39
+ #[cfg(test)]
40
+ mod tests {
41
+ use crate::convergence::VectorClock;
42
+ use crate::distributed_transactions::{
43
+ DistributedTransactionExecutor, ReceiveOutcome, ReplicationMessage, TransactionEnvelope,
44
+ };
45
+ use crate::state_hash::StateHash;
46
+ use crate::transactions::{
47
+ ConsistencyContract, Operation, OperationCommand, OperationId, StateVersion,
48
+ };
49
+ use std::collections::HashMap;
50
+
51
+ fn zero_version() -> StateVersion {
52
+ StateVersion::new(VectorClock::new(), "0".repeat(64))
53
+ }
54
+
55
+ /// Build an envelope with an explicitly chosen envelope sequence and an
56
+ /// explicitly chosen causal clock, so the two counters can be moved
57
+ /// independently -- which is exactly what a restart of the origin does.
58
+ fn envelope(origin: &str, sequence: u64, clock: &[(&str, u64)], payload: &str) -> TransactionEnvelope {
59
+ let mut fields = HashMap::new();
60
+ fields.insert("record".to_string(), serde_json::json!(payload));
61
+ let operation = Operation::new(
62
+ OperationId::new(origin.to_string(), sequence),
63
+ zero_version(),
64
+ format!("tx_{payload}"),
65
+ OperationCommand {
66
+ op_type: "set".to_string(),
67
+ collection: "items".to_string(),
68
+ record_id: payload.to_string(),
69
+ fields,
70
+ },
71
+ origin.to_string(),
72
+ );
73
+ let mut built = TransactionEnvelope::new(
74
+ origin.to_string(),
75
+ sequence,
76
+ format!("tx_{payload}"),
77
+ vec![operation],
78
+ ConsistencyContract::local(),
79
+ );
80
+ let mut vector_clock = VectorClock::new();
81
+ for (node, value) in clock {
82
+ vector_clock.clocks.insert((*node).to_string(), *value);
83
+ }
84
+ built.vector_clock = vector_clock;
85
+ built
86
+ }
87
+
88
+ fn message(envelope: TransactionEnvelope) -> ReplicationMessage {
89
+ let origin = envelope.originating_node.clone();
90
+ let sequence = envelope.envelope_id.sequence;
91
+ ReplicationMessage::new(envelope, origin, "receiver".to_string(), sequence)
92
+ }
93
+
94
+ fn receiver() -> (DistributedTransactionExecutor, tempfile::TempDir) {
95
+ let dir = tempfile::tempdir().expect("tempdir");
96
+ let executor = DistributedTransactionExecutor::with_log(
97
+ "receiver".to_string(),
98
+ StateHash::from_hex("0".repeat(64)),
99
+ Some(dir.path().join("operations.jsonl")),
100
+ )
101
+ .expect("executor");
102
+ (executor, dir)
103
+ }
104
+
105
+ // ---------------------------------------------------------------------
106
+ // Step 1: the frontier only advances one position at a time, per origin.
107
+ // ---------------------------------------------------------------------
108
+
109
+ #[test]
110
+ fn dedup_frontier_advances_exactly_one_position_per_applied_envelope() {
111
+ let (mut executor, _dir) = receiver();
112
+ for position in 1..=5u64 {
113
+ let outcome = executor
114
+ .receive_replicated(
115
+ message(envelope("A", position, &[("A", position)], &format!("r{position}"))),
116
+ zero_version(),
117
+ )
118
+ .expect("receive");
119
+ assert!(matches!(outcome, ReceiveOutcome::Applied { .. }));
120
+ assert_eq!(
121
+ executor.causal_frontier().get("A"),
122
+ position,
123
+ "the frontier tracks applied positions exactly, with no jumps"
124
+ );
125
+ }
126
+ }
127
+
128
+ // ---------------------------------------------------------------------
129
+ // Step 2: a foreign envelope cannot raise the frontier for another origin.
130
+ //
131
+ // This is the step the hypothesis actually rests on. `record_applied` calls
132
+ // `VectorClock::merge`, which takes the maximum per component, so an
133
+ // envelope from B carrying {A: 5} would raise this replica's frontier for A
134
+ // to 5 -- inventing knowledge of five A operations it never applied. Causal
135
+ // enforcement is what prevents it: that envelope's dependencies include
136
+ // A@5, so it cannot be applied until A@5 already has been, at which point
137
+ // the merge is a no-op for A.
138
+ // ---------------------------------------------------------------------
139
+
140
+ #[test]
141
+ fn dedup_a_foreign_envelope_cannot_invent_frontier_for_another_origin() {
142
+ let (mut executor, _dir) = receiver();
143
+
144
+ // B's envelope claims to have seen A through position 5.
145
+ let outcome = executor
146
+ .receive_replicated(message(envelope("B", 1, &[("A", 5), ("B", 1)], "b1")), zero_version())
147
+ .expect("receive");
148
+
149
+ assert!(
150
+ matches!(outcome, ReceiveOutcome::PendingDependencies { .. }),
151
+ "an envelope that depends on five unseen A operations must be held, got {outcome:?}"
152
+ );
153
+ assert_eq!(
154
+ executor.causal_frontier().get("A"),
155
+ 0,
156
+ "and it must not have advanced the frontier for A: merge takes a maximum, \
157
+ so applying this would have invented knowledge of A@1..5"
158
+ );
159
+ }
160
+
161
+ #[test]
162
+ fn dedup_a_foreign_envelope_merge_is_a_noop_for_an_origin_already_covered() {
163
+ let (mut executor, _dir) = receiver();
164
+ for position in 1..=3u64 {
165
+ executor
166
+ .receive_replicated(
167
+ message(envelope("A", position, &[("A", position)], &format!("a{position}"))),
168
+ zero_version(),
169
+ )
170
+ .expect("receive");
171
+ }
172
+ assert_eq!(executor.causal_frontier().get("A"), 3);
173
+
174
+ // B has seen A through 3, which this replica has too.
175
+ executor
176
+ .receive_replicated(message(envelope("B", 1, &[("A", 3), ("B", 1)], "b1")), zero_version())
177
+ .expect("receive");
178
+
179
+ assert_eq!(
180
+ executor.causal_frontier().get("A"),
181
+ 3,
182
+ "applying a foreign envelope leaves the covered origin where it was"
183
+ );
184
+ }
185
+
186
+ // ---------------------------------------------------------------------
187
+ // Step 3: therefore the frontier covers exactly what was applied.
188
+ // ---------------------------------------------------------------------
189
+
190
+ #[test]
191
+ fn dedup_every_applied_envelope_is_covered_by_the_frontier() {
192
+ let (mut executor, _dir) = receiver();
193
+
194
+ // Two origins, interleaved, plus an out-of-order arrival that is held
195
+ // and later released -- so the applied set is not simply arrival order.
196
+ executor.receive_replicated(message(envelope("A", 1, &[("A", 1)], "a1")), zero_version()).unwrap();
197
+ executor.receive_replicated(message(envelope("A", 3, &[("A", 3)], "a3")), zero_version()).unwrap();
198
+ executor.receive_replicated(message(envelope("A", 2, &[("A", 2)], "a2")), zero_version()).unwrap();
199
+ executor.receive_replicated(message(envelope("B", 1, &[("A", 3), ("B", 1)], "b1")), zero_version()).unwrap();
200
+
201
+ assert_eq!(executor.pending_causal_count(), 0, "everything was released");
202
+ assert_eq!(executor.causal_frontier().get("A"), 3);
203
+ assert_eq!(executor.causal_frontier().get("B"), 1);
204
+
205
+ // The claim: for every envelope this replica considers seen, the
206
+ // frontier already covers its clock position. So a frontier test would
207
+ // answer "already applied" for all of them.
208
+ let frontier = executor.causal_frontier().clone();
209
+ let log = executor.operation_log.as_ref().expect("log").load_all().expect("load");
210
+ for envelope in &log {
211
+ let origin = &envelope.originating_node;
212
+ let position = envelope.vector_clock.get(origin);
213
+ assert!(
214
+ frontier.get(origin) >= position,
215
+ "{origin}@{position} was applied but the frontier reports {}",
216
+ frontier.get(origin)
217
+ );
218
+ }
219
+ assert_eq!(log.len(), 4);
220
+ }
221
+
222
+ // ---------------------------------------------------------------------
223
+ // Step 4: and it survives a restart, because the frontier is rebuilt from
224
+ // the log while `envelopes_seen` is rebuilt from the same place.
225
+ // ---------------------------------------------------------------------
226
+
227
+ #[test]
228
+ fn dedup_frontier_coverage_survives_restart_and_still_refuses_duplicates() {
229
+ let dir = tempfile::tempdir().expect("tempdir");
230
+ let path = dir.path().join("operations.jsonl");
231
+ {
232
+ let mut executor = DistributedTransactionExecutor::with_log(
233
+ "receiver".to_string(),
234
+ StateHash::from_hex("0".repeat(64)),
235
+ Some(path.clone()),
236
+ )
237
+ .expect("executor");
238
+ for position in 1..=3u64 {
239
+ executor
240
+ .receive_replicated(
241
+ message(envelope("A", position, &[("A", position)], &format!("a{position}"))),
242
+ zero_version(),
243
+ )
244
+ .expect("receive");
245
+ }
246
+ }
247
+
248
+ let mut recovered = DistributedTransactionExecutor::with_log(
249
+ "receiver".to_string(),
250
+ StateHash::from_hex("0".repeat(64)),
251
+ Some(path.clone()),
252
+ )
253
+ .expect("executor");
254
+ recovered.load_from_disk(path).expect("recover");
255
+
256
+ assert_eq!(recovered.causal_frontier().get("A"), 3, "the frontier is rebuilt from the log");
257
+
258
+ // A retransmission of an already-applied operation after the restart.
259
+ let again = recovered
260
+ .receive_replicated(message(envelope("A", 2, &[("A", 2)], "a2")), zero_version())
261
+ .expect("receive");
262
+ assert_eq!(again, ReceiveOutcome::AlreadyKnown, "a duplicate after restart is refused");
263
+ }
264
+
265
+ // ---------------------------------------------------------------------
266
+ // Growth: does `envelopes_seen` grow independently of the bounded
267
+ // pending/deferred population? It does, and that is the whole question.
268
+ // ---------------------------------------------------------------------
269
+
270
+ #[test]
271
+ fn dedup_seen_set_grows_with_history_while_the_backlog_stays_empty() {
272
+ let (mut executor, _dir) = receiver();
273
+ for position in 1..=200u64 {
274
+ executor
275
+ .receive_replicated(
276
+ message(envelope("A", position, &[("A", position)], &format!("a{position}"))),
277
+ zero_version(),
278
+ )
279
+ .expect("receive");
280
+ }
281
+
282
+ assert_eq!(executor.pending_causal_count(), 0, "the bounded population is empty");
283
+ assert_eq!(executor.deferred_causal_count(), 0);
284
+ assert_eq!(
285
+ executor.envelopes_seen.len(),
286
+ 200,
287
+ "yet the deduplication set holds one entry per operation ever applied: \
288
+ it grows with history, not with the backlog, so the backlog bound does not bound it"
289
+ );
290
+
291
+ // And the frontier that could replace it is one integer per origin.
292
+ assert_eq!(
293
+ executor.causal_frontier().clocks.len(),
294
+ 1,
295
+ "the frontier covering the same 200 operations is O(origins), not O(operations)"
296
+ );
297
+ }
298
+
299
+ // ---------------------------------------------------------------------
300
+ // Why identity must be durable: what a receiver does with a colliding one.
301
+ //
302
+ // These assert the receive path's behaviour when it is *handed* a re-used
303
+ // identity. That behaviour is unchanged and correct in isolation -- a
304
+ // receiver has no way to distinguish a re-used identity from a
305
+ // retransmission. The defect was that origins produced such identities
306
+ // after a restart, and that is fixed in durable_operation_identity.rs.
307
+ // These remain as the demonstration of what that fix prevents.
308
+ // ---------------------------------------------------------------------
309
+
310
+ #[test]
311
+ fn dedup_a_colliding_identity_is_dropped_silently_which_is_why_identity_must_be_durable() {
312
+ // Deduplication keys on `(origin, sequence)`. Hand the receiver a
313
+ // second operation carrying an identity it has already applied -- which
314
+ // is what a restarted origin used to produce, before identity was
315
+ // recovered from the durable log -- and it is discarded as a duplicate.
316
+ //
317
+ // The receiver is not wrong to do this. It cannot distinguish a re-used
318
+ // identity from a retransmission, and treating retransmissions as
319
+ // duplicates is a property the rest of the system depends on. The fix
320
+ // belongs on the allocating side, and this is what it prevents.
321
+ let (mut executor, _dir) = receiver();
322
+
323
+ // Before the origin restarts: A's first operation, sequence 1, clock 1.
324
+ let first = executor
325
+ .receive_replicated(message(envelope("A", 1, &[("A", 1)], "before")), zero_version())
326
+ .expect("receive");
327
+ assert!(matches!(first, ReceiveOutcome::Applied { .. }));
328
+
329
+ // A restarts. Its sequence counter resets to 1; its frontier is rebuilt
330
+ // from its own log, so the next operation is clock position 2. This is
331
+ // a genuinely new write, carrying different data.
332
+ let after_restart = envelope("A", 1, &[("A", 2)], "after");
333
+ let outcome = executor
334
+ .receive_replicated(message(after_restart.clone()), zero_version())
335
+ .expect("receive");
336
+
337
+ assert_eq!(
338
+ outcome,
339
+ ReceiveOutcome::AlreadyKnown,
340
+ "a write carrying an already-applied identity is discarded, silently"
341
+ );
342
+ assert_eq!(
343
+ executor.causal_frontier().get("A"),
344
+ 1,
345
+ "the receiver's frontier stalls, so every later A operation is blocked behind \
346
+ a dependency that will never arrive"
347
+ );
348
+ let state = executor.canonical_state().expect("state");
349
+ assert!(
350
+ !state.records.contains_key(&("items".to_string(), "after".to_string())),
351
+ "and the write is simply absent: no error, no divergence signal, no retry"
352
+ );
353
+
354
+ // Note that the frontier test the ADR proposed would not have made this
355
+ // mistake -- the arriving clock position is 2 and the frontier is 1 --
356
+ // which is a second, independent reason to prefer it. Identity
357
+ // allocation was fixed first because it is the cheaper change and does
358
+ // not alter what deduplication means on the receive path.
359
+ let position = after_restart.vector_clock.get("A");
360
+ assert!(
361
+ position > executor.causal_frontier().get("A"),
362
+ "a deduplication test keyed on the causal position would have admitted this write"
363
+ );
364
+ }
365
+
366
+ #[test]
367
+ fn dedup_a_partial_identity_collision_strands_the_replica_permanently() {
368
+ // The compounding case, and the reason this was a correctness problem
369
+ // rather than a lost write. Of two operations from a restarted origin,
370
+ // the first collides and is dropped while the second does not collide
371
+ // and is admitted -- so the replica ends up holding an operation whose
372
+ // dependency was silently discarded, and waits for it forever. Which
373
+ // operations collide depends only on how many the origin committed
374
+ // before it died.
375
+ let (mut executor, _dir) = receiver();
376
+ executor
377
+ .receive_replicated(message(envelope("A", 1, &[("A", 1)], "one")), zero_version())
378
+ .expect("receive");
379
+
380
+ // Origin restarts after one operation and commits two more. Sequences
381
+ // 1 and 2; clock positions 2 and 3.
382
+ let dropped = executor
383
+ .receive_replicated(message(envelope("A", 1, &[("A", 2)], "two")), zero_version())
384
+ .expect("receive");
385
+ let admitted = executor
386
+ .receive_replicated(message(envelope("A", 2, &[("A", 3)], "three")), zero_version())
387
+ .expect("receive");
388
+
389
+ assert_eq!(dropped, ReceiveOutcome::AlreadyKnown, "the first collides and is lost");
390
+ assert!(
391
+ matches!(admitted, ReceiveOutcome::PendingDependencies { .. }),
392
+ "the second does not collide, is admitted, and is then held forever waiting on \
393
+ the operation that was silently dropped: {admitted:?}"
394
+ );
395
+ assert_eq!(executor.pending_causal_count(), 1);
396
+ assert_eq!(
397
+ executor.causal_frontier().get("A"),
398
+ 1,
399
+ "the replica is permanently stuck one operation behind an origin that is still writing"
400
+ );
401
+ }
402
+ }