@feltdb/core 0.6.9 → 0.6.11

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 (122) hide show
  1. package/dist/cli/application-lifecycle.js +112 -0
  2. package/dist/cli/application.js +10 -0
  3. package/dist/cli/commands.js +407 -119
  4. package/dist/cli/development-session.js +54 -0
  5. package/dist/cli/index.js +1 -1
  6. package/dist/cli/workspace-integration.js +146 -20
  7. package/dist/collection.d.ts +110 -2
  8. package/dist/collection.d.ts.map +1 -1
  9. package/dist/collection.js +228 -3
  10. package/dist/create/cli.js +4 -2
  11. package/dist/create/create.js +42 -6
  12. package/dist/create/frameworks.js +18 -0
  13. package/dist/create/package-versions.js +1 -1
  14. package/dist/create/server-source/crates/feltdb/src/bin/feltdb_node.rs +408 -178
  15. package/dist/create/server-source/crates/feltdb/src/lib.rs +49 -5
  16. package/dist/create/server-source/crates/feltdb/src/multi_operation_transaction.rs +659 -0
  17. package/dist/create/server-source/crates/feltdb/src/p1_application_atomicity.rs +285 -0
  18. package/dist/create/server-source/crates/feltdb/src/p1_atomicity_acceptance.rs +582 -0
  19. package/dist/create/server-source/crates/feltdb-server/src/main.rs +141 -0
  20. package/dist/create/workspace-initialization.js +4 -5
  21. package/dist/db.d.ts +63 -1
  22. package/dist/db.d.ts.map +1 -1
  23. package/dist/db.js +145 -4
  24. package/dist/development-runtime-bridge.d.ts +60 -0
  25. package/dist/development-runtime-bridge.d.ts.map +1 -0
  26. package/dist/development-runtime-bridge.js +171 -0
  27. package/dist/embedded-transaction.d.ts +77 -0
  28. package/dist/embedded-transaction.d.ts.map +1 -0
  29. package/dist/embedded-transaction.js +102 -0
  30. package/dist/feltdb.d.ts +49 -1
  31. package/dist/feltdb.d.ts.map +1 -1
  32. package/dist/file-db.d.ts +33 -0
  33. package/dist/file-db.d.ts.map +1 -1
  34. package/dist/file-db.js +128 -4
  35. package/dist/freshness.d.ts +119 -0
  36. package/dist/freshness.d.ts.map +1 -0
  37. package/dist/freshness.js +115 -0
  38. package/dist/http-db.d.ts +48 -0
  39. package/dist/http-db.d.ts.map +1 -1
  40. package/dist/http-db.js +77 -1
  41. package/dist/index-backend.d.ts +8 -0
  42. package/dist/index-backend.d.ts.map +1 -1
  43. package/dist/index-backend.js +13 -0
  44. package/dist/index-core.d.ts +80 -0
  45. package/dist/index-core.d.ts.map +1 -0
  46. package/dist/index-core.js +74 -0
  47. package/dist/index-manager.d.ts +11 -0
  48. package/dist/index-manager.d.ts.map +1 -1
  49. package/dist/index-manager.js +30 -13
  50. package/dist/index-types.d.ts +17 -0
  51. package/dist/index-types.d.ts.map +1 -1
  52. package/dist/index.browser.d.ts +14 -0
  53. package/dist/index.browser.d.ts.map +1 -0
  54. package/dist/index.browser.js +13 -0
  55. package/dist/index.d.ts +8 -59
  56. package/dist/index.d.ts.map +1 -1
  57. package/dist/index.js +11 -54
  58. package/dist/indexeddb-db.d.ts +32 -0
  59. package/dist/indexeddb-db.d.ts.map +1 -1
  60. package/dist/indexeddb-db.js +151 -1
  61. package/dist/memory-db.d.ts +26 -0
  62. package/dist/memory-db.d.ts.map +1 -1
  63. package/dist/memory-db.js +86 -0
  64. package/dist/runtime-registry.d.ts +32 -0
  65. package/dist/runtime-registry.d.ts.map +1 -0
  66. package/dist/runtime-registry.js +38 -0
  67. package/dist/studio/app.d.ts +2 -1
  68. package/dist/studio/app.d.ts.map +1 -1
  69. package/dist/studio/components/StateExplorer.d.ts +2 -1
  70. package/dist/studio/components/StateExplorer.d.ts.map +1 -1
  71. package/dist/studio/components/index.js +1 -1
  72. package/dist/studio/{components-9kDSWiGL.js → components-C5p2TfIU.js} +25 -14
  73. package/dist/studio/index.js +234 -160
  74. package/dist/studio-app/assets/{feltdb_wasm-B4wq4mqp.js → feltdb_wasm-CJv3wHzi.js} +1 -1
  75. package/dist/studio-app/assets/feltdb_wasm_bg-C8TG8r2n.wasm +0 -0
  76. package/dist/studio-app/assets/index-DospFFYE.js +28 -0
  77. package/dist/studio-app/index.html +1 -1
  78. package/dist/transaction.d.ts +98 -0
  79. package/dist/transaction.d.ts.map +1 -0
  80. package/dist/transaction.js +86 -0
  81. package/dist/wasm/feltdb_wasm_bg.wasm +0 -0
  82. package/dist/workspace/browser.d.ts +22 -0
  83. package/dist/workspace/browser.d.ts.map +1 -0
  84. package/dist/workspace/browser.js +17 -0
  85. package/dist/workspace/development-node.d.ts +16 -0
  86. package/dist/workspace/development-node.d.ts.map +1 -1
  87. package/dist/workspace/development-node.js +85 -1
  88. package/dist/workspace/git-identity.d.ts +35 -0
  89. package/dist/workspace/git-identity.d.ts.map +1 -0
  90. package/dist/workspace/git-identity.js +81 -0
  91. package/dist/workspace/index.d.ts +12 -2
  92. package/dist/workspace/index.d.ts.map +1 -1
  93. package/dist/workspace/index.js +7 -1
  94. package/dist/workspace/investigation-analysis.d.ts +47 -0
  95. package/dist/workspace/investigation-analysis.d.ts.map +1 -0
  96. package/dist/workspace/investigation-analysis.js +181 -0
  97. package/dist/workspace/investigation-lifecycle-manager.d.ts +88 -0
  98. package/dist/workspace/investigation-lifecycle-manager.d.ts.map +1 -0
  99. package/dist/workspace/investigation-lifecycle-manager.js +259 -0
  100. package/dist/workspace/investigation-supervisor.d.ts +100 -0
  101. package/dist/workspace/investigation-supervisor.d.ts.map +1 -0
  102. package/dist/workspace/investigation-supervisor.js +238 -0
  103. package/dist/workspace/runtime-investigation.d.ts +5 -1
  104. package/dist/workspace/runtime-investigation.d.ts.map +1 -1
  105. package/dist/workspace/runtime-investigation.js +50 -21
  106. package/dist/workspace/runtime-observation.d.ts +82 -0
  107. package/dist/workspace/runtime-observation.d.ts.map +1 -0
  108. package/dist/workspace/runtime-observation.js +170 -0
  109. package/dist/workspace/runtime-observer.d.ts +57 -0
  110. package/dist/workspace/runtime-observer.d.ts.map +1 -0
  111. package/dist/workspace/runtime-observer.js +272 -0
  112. package/dist/workspace/workspace-connection.d.ts.map +1 -1
  113. package/dist/workspace/workspace-connection.js +14 -5
  114. package/dist/workspace/workspace-identity.d.ts +1 -1
  115. package/dist/workspace/workspace-identity.d.ts.map +1 -1
  116. package/dist/workspace/workspace-identity.js +4 -4
  117. package/dist/workspace/workspace-types.d.ts +208 -0
  118. package/dist/workspace/workspace-types.d.ts.map +1 -1
  119. package/package.json +12 -4
  120. package/dist/create/server-source/crates/feltdb/src/phase_1c_three_node.rs +0 -523
  121. package/dist/studio-app/assets/feltdb_wasm_bg-Ceyi7l21.wasm +0 -0
  122. package/dist/studio-app/assets/index-BF45M757.js +0 -28
@@ -0,0 +1,582 @@
1
+ //! Production Gate P1 — Multi-Operation Atomicity Acceptance
2
+ //!
3
+ //! The gate asserts one property, adversarially:
4
+ //!
5
+ //! ```text
6
+ //! COMMIT -> A + B + C all visible
7
+ //! FAIL or CRASH -> A + B + C none visible
8
+ //! never -> A visible, B visible, C missing
9
+ //! ```
10
+ //!
11
+ //! Every test here restarts a node from its durable log and inspects what
12
+ //! recovery produced. Nothing asserts on in-memory state that survived a
13
+ //! simulated crash, because in a real crash it would not have.
14
+
15
+ #[cfg(test)]
16
+ mod tests {
17
+ use crate::multi_operation_transaction::*;
18
+ use serde_json::json;
19
+ use std::collections::HashSet;
20
+ use tempfile::TempDir;
21
+
22
+ /// A three-operation transaction: the canonical A + B + C.
23
+ fn abc(transaction_id: &str) -> Vec<TransactionOperation> {
24
+ vec![
25
+ TransactionOperation::set("accounts", "A", json!({ "balance": 100 })),
26
+ TransactionOperation::set("accounts", "B", json!({ "balance": 200 })),
27
+ TransactionOperation::set("accounts", "C", json!({ "balance": 300 })),
28
+ ]
29
+ .into_iter()
30
+ .map(|mut operation| {
31
+ operation.record_id = format!("{}-{}", operation.record_id, transaction_id);
32
+ operation
33
+ })
34
+ .collect()
35
+ }
36
+
37
+ /// How many of a transaction's records are present after recovery.
38
+ fn visible(node: &TransactionalNode, record: &TransactionRecord) -> usize {
39
+ node.executor().visible_operations(record)
40
+ }
41
+
42
+ /// The gate's core assertion: all of them, or none of them.
43
+ fn assert_atomic(node: &TransactionalNode, record: &TransactionRecord, context: &str) -> bool {
44
+ let seen = visible(node, record);
45
+ let total = record.operations.len();
46
+ assert!(
47
+ seen == 0 || seen == total,
48
+ "{}: transaction was partially visible ({} of {} operations)",
49
+ context,
50
+ seen,
51
+ total
52
+ );
53
+ seen == total
54
+ }
55
+
56
+ // ---------------------------------------------------------------- normal
57
+
58
+ #[test]
59
+ fn commit_makes_every_operation_visible() -> Result<(), Box<dyn std::error::Error>> {
60
+ let dir = TempDir::new()?;
61
+ let (mut node, _) = TransactionalNode::open(dir.path().join("tx.log"), "node1")?;
62
+
63
+ let record = node.build("tx1", abc("tx1"));
64
+ assert_eq!(node.commit(&record)?, ApplyOutcome::Applied);
65
+
66
+ assert_eq!(visible(&node, &record), 3);
67
+ assert!(assert_atomic(&node, &record, "after commit"));
68
+ Ok(())
69
+ }
70
+
71
+ #[test]
72
+ fn a_rejected_transaction_leaves_no_trace() -> Result<(), Box<dyn std::error::Error>> {
73
+ let dir = TempDir::new()?;
74
+ let path = dir.path().join("tx.log");
75
+ let (mut node, _) = TransactionalNode::open(&path, "node1")?;
76
+
77
+ // The middle operation cannot succeed: the record does not exist.
78
+ let operations = vec![
79
+ TransactionOperation::set("accounts", "A", json!({ "balance": 1 })),
80
+ TransactionOperation::set("accounts", "B", json!({ "balance": 2 }))
81
+ .requiring(Precondition::MustExist),
82
+ TransactionOperation::set("accounts", "C", json!({ "balance": 3 })),
83
+ ];
84
+ let record = node.build("tx-reject", operations);
85
+
86
+ match node.commit(&record)? {
87
+ ApplyOutcome::Rejected(RejectionReason::PreconditionFailed { operation_index, .. }) => {
88
+ assert_eq!(operation_index, 1);
89
+ }
90
+ other => panic!("expected a precondition rejection, got {:?}", other),
91
+ }
92
+
93
+ // A rejected transaction must leave nothing behind, including the
94
+ // operations that were legal on their own.
95
+ assert_eq!(visible(&node, &record), 0, "no operation may be visible");
96
+ assert!(node.state().get_record("accounts", "A").is_none(), "A must not be applied");
97
+ assert!(node.state().get_record("accounts", "C").is_none(), "C must not be applied");
98
+
99
+ drop(node);
100
+ let (restarted, report) = TransactionalNode::open(&path, "node1")?;
101
+ assert!(report.committed.is_empty(), "a rejected transaction must never be logged");
102
+ assert!(restarted.state().get_record("accounts", "A").is_none());
103
+ Ok(())
104
+ }
105
+
106
+ #[test]
107
+ fn a_transaction_writing_one_record_twice_is_refused() -> Result<(), Box<dyn std::error::Error>> {
108
+ let dir = TempDir::new()?;
109
+ let (mut node, _) = TransactionalNode::open(dir.path().join("tx.log"), "node1")?;
110
+
111
+ let record = node.build(
112
+ "tx-conflict",
113
+ vec![
114
+ TransactionOperation::set("accounts", "A", json!({ "balance": 1 })),
115
+ TransactionOperation::set("accounts", "A", json!({ "balance": 2 })),
116
+ ],
117
+ );
118
+
119
+ assert!(matches!(
120
+ node.commit(&record)?,
121
+ ApplyOutcome::Rejected(RejectionReason::ConflictingWritesWithinTransaction { .. })
122
+ ));
123
+ Ok(())
124
+ }
125
+
126
+ // ----------------------------------------------------------------- crash
127
+
128
+ /// Every crash point, on a fresh node, recovered from disk.
129
+ ///
130
+ /// This is the heart of the gate.
131
+ #[test]
132
+ fn every_crash_point_leaves_the_transaction_atomic() -> Result<(), Box<dyn std::error::Error>> {
133
+ let crash_points = vec![
134
+ CrashPoint::BeforeWrite,
135
+ CrashPoint::DuringWrite { keep_percent: 10 },
136
+ CrashPoint::DuringWrite { keep_percent: 50 },
137
+ CrashPoint::DuringWrite { keep_percent: 90 },
138
+ CrashPoint::AfterWriteBeforeFsync,
139
+ CrashPoint::AfterFsyncBeforeApply,
140
+ CrashPoint::DuringApply { after_operations: 1 },
141
+ CrashPoint::DuringApply { after_operations: 2 },
142
+ CrashPoint::AfterApply,
143
+ ];
144
+
145
+ for crash in crash_points {
146
+ let dir = TempDir::new()?;
147
+ let path = dir.path().join("tx.log");
148
+
149
+ let record = {
150
+ let (mut node, _) = TransactionalNode::open(&path, "node1")?;
151
+ let record = node.build("tx-crash", abc("tx-crash"));
152
+ node.commit_with_crash(&record, &crash)?;
153
+ record
154
+ // The node is dropped here: the process died.
155
+ };
156
+
157
+ let (recovered, report) = TransactionalNode::open(&path, "node1")?;
158
+ let context = format!("crash at {:?}", crash);
159
+ let fully_visible = assert_atomic(&recovered, &record, &context);
160
+
161
+ match &crash {
162
+ // Nothing durable was written, so nothing may be visible.
163
+ CrashPoint::BeforeWrite | CrashPoint::DuringWrite { .. } => {
164
+ assert!(!fully_visible, "{}: nothing should have committed", context);
165
+ assert!(report.committed.is_empty(), "{}: log must hold no record", context);
166
+ }
167
+ // The record was fsynced, so recovery must replay all of it —
168
+ // including when the crash happened part-way through applying.
169
+ CrashPoint::AfterFsyncBeforeApply
170
+ | CrashPoint::DuringApply { .. }
171
+ | CrashPoint::AfterApply => {
172
+ assert!(fully_visible, "{}: a committed transaction must fully recover", context);
173
+ assert_eq!(report.committed.len(), 1, "{}", context);
174
+ }
175
+ // Written but not fsynced: the operating system decides. Either
176
+ // outcome is correct; a partial one is not, and assert_atomic
177
+ // already ruled that out.
178
+ CrashPoint::AfterWriteBeforeFsync => {}
179
+ }
180
+ }
181
+ Ok(())
182
+ }
183
+
184
+ #[test]
185
+ fn a_torn_final_record_is_discarded_and_the_log_stays_writable()
186
+ -> Result<(), Box<dyn std::error::Error>> {
187
+ let dir = TempDir::new()?;
188
+ let path = dir.path().join("tx.log");
189
+
190
+ // One good transaction, then a crash mid-write on the next.
191
+ let first = {
192
+ let (mut node, _) = TransactionalNode::open(&path, "node1")?;
193
+ let first = node.build("tx1", abc("tx1"));
194
+ node.commit(&first)?;
195
+ let second = node.build("tx2", abc("tx2"));
196
+ node.commit_with_crash(&second, &CrashPoint::DuringWrite { keep_percent: 60 })?;
197
+ first
198
+ };
199
+
200
+ // Recovery keeps the committed transaction and discards the torn one.
201
+ let (mut node, report) = TransactionalNode::open(&path, "node1")?;
202
+ assert_eq!(report.committed.len(), 1);
203
+ assert!(matches!(report.discarded_tail, Some(LogDefect::TornTail { .. })));
204
+ assert_eq!(visible(&node, &first), 3);
205
+
206
+ // The torn bytes were truncated, so a later write cannot splice onto
207
+ // them and turn a recoverable tail into interior corruption.
208
+ let third = node.build("tx3", abc("tx3"));
209
+ node.commit(&third)?;
210
+ drop(node);
211
+
212
+ let (again, report) = TransactionalNode::open(&path, "node1")?;
213
+ assert!(report.discarded_tail.is_none(), "the log must be clean after truncation");
214
+ assert_eq!(report.committed.len(), 2);
215
+ assert_eq!(visible(&again, &first), 3);
216
+ assert_eq!(visible(&again, &third), 3);
217
+ Ok(())
218
+ }
219
+
220
+ #[test]
221
+ fn interior_corruption_is_refused_rather_than_guessed() -> Result<(), Box<dyn std::error::Error>> {
222
+ let dir = TempDir::new()?;
223
+ let path = dir.path().join("tx.log");
224
+
225
+ let (mut node, _) = TransactionalNode::open(&path, "node1")?;
226
+ let first = node.build("tx1", abc("tx1"));
227
+ node.commit(&first)?;
228
+ let second = node.build("tx2", abc("tx2"));
229
+ node.commit(&second)?;
230
+
231
+ // Damage a byte inside the first record. It is not the final entry, so
232
+ // this is corruption, not an interrupted write.
233
+ node.log().corrupt_at(20, b"X")?;
234
+ drop(node);
235
+
236
+ let outcome = TransactionalNode::open(&path, "node1");
237
+ assert!(outcome.is_err(), "recovery must refuse a corrupted interior record");
238
+ let message = outcome.err().map(|error| error.to_string()).unwrap_or_default();
239
+ assert!(message.contains("corrupted"), "unexpected error: {}", message);
240
+ Ok(())
241
+ }
242
+
243
+ #[test]
244
+ fn a_checksum_mismatch_is_not_treated_as_committed() -> Result<(), Box<dyn std::error::Error>> {
245
+ let mut record = TransactionRecord::new("tx1", "node1", 1, abc("tx1"));
246
+ assert!(record.verify_checksum());
247
+
248
+ // Alter the body without recomputing the checksum, as a partial write
249
+ // or a bit flip would.
250
+ record.operations.push(TransactionOperation::set("accounts", "D", json!({ "balance": 9 })));
251
+ assert!(!record.verify_checksum(), "a mutated record must fail its integrity check");
252
+ Ok(())
253
+ }
254
+
255
+ // ---------------------------------------------------------------- replay
256
+
257
+ #[test]
258
+ fn replaying_a_committed_transaction_changes_nothing() -> Result<(), Box<dyn std::error::Error>> {
259
+ let dir = TempDir::new()?;
260
+ let (mut node, _) = TransactionalNode::open(dir.path().join("tx.log"), "node1")?;
261
+
262
+ let record = node.build("tx1", abc("tx1"));
263
+ node.commit(&record)?;
264
+ let hash_after_first = node.state().hash().as_hex().to_string();
265
+
266
+ // Deliver the same transaction repeatedly.
267
+ for _ in 0..5 {
268
+ assert_eq!(node.accept_replicated(&record)?, ApplyOutcome::AlreadyApplied);
269
+ }
270
+
271
+ assert_eq!(node.state().hash().as_hex(), hash_after_first, "replay must not change state");
272
+ Ok(())
273
+ }
274
+
275
+ #[test]
276
+ fn recovery_is_idempotent_across_repeated_restarts() -> Result<(), Box<dyn std::error::Error>> {
277
+ let dir = TempDir::new()?;
278
+ let path = dir.path().join("tx.log");
279
+
280
+ {
281
+ let (mut node, _) = TransactionalNode::open(&path, "node1")?;
282
+ for index in 1..=4 {
283
+ let record = node.build(&format!("tx{}", index), abc(&format!("tx{}", index)));
284
+ node.commit(&record)?;
285
+ }
286
+ }
287
+
288
+ let mut hashes = Vec::new();
289
+ for _ in 0..4 {
290
+ let (node, report) = TransactionalNode::open(&path, "node1")?;
291
+ assert_eq!(report.committed.len(), 4);
292
+ hashes.push(node.state().hash().as_hex().to_string());
293
+ }
294
+
295
+ assert!(hashes.windows(2).all(|pair| pair[0] == pair[1]),
296
+ "every restart must recover identical state");
297
+ Ok(())
298
+ }
299
+
300
+ #[test]
301
+ fn a_crash_during_recovery_still_recovers() -> Result<(), Box<dyn std::error::Error>> {
302
+ let dir = TempDir::new()?;
303
+ let path = dir.path().join("tx.log");
304
+
305
+ {
306
+ let (mut node, _) = TransactionalNode::open(&path, "node1")?;
307
+ for index in 1..=3 {
308
+ let record = node.build(&format!("tx{}", index), abc(&format!("tx{}", index)));
309
+ node.commit(&record)?;
310
+ }
311
+ }
312
+
313
+ // Abandon recovery part-way, repeatedly, then complete it.
314
+ for _ in 0..3 {
315
+ let (partial, _) = TransactionalNode::open(&path, "node1")?;
316
+ drop(partial);
317
+ }
318
+
319
+ let (node, report) = TransactionalNode::open(&path, "node1")?;
320
+ assert_eq!(report.committed.len(), 3);
321
+ for index in 1..=3 {
322
+ let key = format!("A-tx{}", index);
323
+ assert!(node.state().get_record("accounts", &key).is_some(), "tx{} lost", index);
324
+ }
325
+ Ok(())
326
+ }
327
+
328
+ // ----------------------------------------------------------- concurrency
329
+
330
+ #[test]
331
+ fn concurrent_transactions_never_interleave() -> Result<(), Box<dyn std::error::Error>> {
332
+ let dir = TempDir::new()?;
333
+ let path = dir.path().join("tx.log");
334
+ let (mut node, _) = TransactionalNode::open(&path, "node1")?;
335
+
336
+ // Three writers each commit a three-operation transaction against the
337
+ // same node. Commits are serialized, so no transaction may be split by
338
+ // another.
339
+ let mut records = Vec::new();
340
+ for writer in 0..3 {
341
+ let id = format!("writer{}", writer);
342
+ let record = node.build(&id, abc(&id));
343
+ assert_eq!(node.commit(&record)?, ApplyOutcome::Applied);
344
+ records.push(record);
345
+ }
346
+ drop(node);
347
+
348
+ let (recovered, report) = TransactionalNode::open(&path, "node1")?;
349
+ assert_eq!(report.committed.len(), 3);
350
+ for record in &records {
351
+ assert_atomic(&recovered, record, "concurrent writers");
352
+ assert_eq!(visible(&recovered, record), 3);
353
+ }
354
+
355
+ // Sequences are unique and ordered, so the log defines one history.
356
+ let sequences: Vec<u64> = report.committed.iter().map(|record| record.sequence).collect();
357
+ let unique: HashSet<u64> = sequences.iter().copied().collect();
358
+ assert_eq!(unique.len(), sequences.len(), "sequences must be unique");
359
+ assert!(sequences.windows(2).all(|pair| pair[0] < pair[1]), "log must be ordered");
360
+ Ok(())
361
+ }
362
+
363
+ #[test]
364
+ fn a_losing_writer_is_rejected_without_partial_effect() -> Result<(), Box<dyn std::error::Error>> {
365
+ let dir = TempDir::new()?;
366
+ let path = dir.path().join("tx.log");
367
+ let (mut node, _) = TransactionalNode::open(&path, "node1")?;
368
+
369
+ // Two writers race to create the same record. Both transactions also
370
+ // touch a record of their own.
371
+ let first = node.build(
372
+ "writer-a",
373
+ vec![
374
+ TransactionOperation::set("accounts", "shared", json!({ "owner": "a" }))
375
+ .requiring(Precondition::MustNotExist),
376
+ TransactionOperation::set("accounts", "only-a", json!({ "balance": 1 })),
377
+ ],
378
+ );
379
+ let second = node.build(
380
+ "writer-b",
381
+ vec![
382
+ TransactionOperation::set("accounts", "shared", json!({ "owner": "b" }))
383
+ .requiring(Precondition::MustNotExist),
384
+ TransactionOperation::set("accounts", "only-b", json!({ "balance": 2 })),
385
+ ],
386
+ );
387
+
388
+ assert_eq!(node.commit(&first)?, ApplyOutcome::Applied);
389
+ assert!(matches!(node.commit(&second)?, ApplyOutcome::Rejected(_)));
390
+
391
+ // The loser must leave nothing behind, including its uncontended write.
392
+ assert!(node.state().get_record("accounts", "only-b").is_none(),
393
+ "a rejected transaction must not apply its other operations");
394
+ assert_eq!(node.state().get_record("accounts", "shared"), Some(&json!({ "owner": "a" })));
395
+ drop(node);
396
+
397
+ let (recovered, report) = TransactionalNode::open(&path, "node1")?;
398
+ assert_eq!(report.committed.len(), 1, "only the winner may be durable");
399
+ assert!(recovered.state().get_record("accounts", "only-b").is_none());
400
+ Ok(())
401
+ }
402
+
403
+ // ---------------------------------------------------------- replication
404
+
405
+ #[test]
406
+ fn a_transaction_stays_atomic_across_replication() -> Result<(), Box<dyn std::error::Error>> {
407
+ let dir = TempDir::new()?;
408
+ let (mut leader, _) = TransactionalNode::open(dir.path().join("a.log"), "nodeA")?;
409
+ let (mut follower_b, _) = TransactionalNode::open(dir.path().join("b.log"), "nodeB")?;
410
+ let (mut follower_c, _) = TransactionalNode::open(dir.path().join("c.log"), "nodeC")?;
411
+
412
+ let record = leader.build("tx1", abc("tx1"));
413
+ assert_eq!(leader.commit(&record)?, ApplyOutcome::Applied);
414
+
415
+ assert_eq!(follower_b.accept_replicated(&record)?, ApplyOutcome::Applied);
416
+ assert_eq!(follower_c.accept_replicated(&record)?, ApplyOutcome::Applied);
417
+
418
+ // Duplicate delivery is safe.
419
+ assert_eq!(follower_b.accept_replicated(&record)?, ApplyOutcome::AlreadyApplied);
420
+ assert_eq!(follower_c.accept_replicated(&record)?, ApplyOutcome::AlreadyApplied);
421
+
422
+ let leader_hash = leader.state().hash().as_hex().to_string();
423
+ assert_eq!(follower_b.state().hash().as_hex(), leader_hash, "B diverged");
424
+ assert_eq!(follower_c.state().hash().as_hex(), leader_hash, "C diverged");
425
+
426
+ for node in [&follower_b, &follower_c] {
427
+ assert_atomic(node, &record, "replicated follower");
428
+ }
429
+ Ok(())
430
+ }
431
+
432
+ #[test]
433
+ fn a_follower_that_crashes_mid_replication_recovers_atomically()
434
+ -> Result<(), Box<dyn std::error::Error>> {
435
+ let dir = TempDir::new()?;
436
+ let leader_path = dir.path().join("a.log");
437
+ let follower_path = dir.path().join("b.log");
438
+
439
+ let record = {
440
+ let (mut leader, _) = TransactionalNode::open(&leader_path, "nodeA")?;
441
+ let record = leader.build("tx1", abc("tx1"));
442
+ leader.commit(&record)?;
443
+ record
444
+ };
445
+
446
+ // The follower dies while writing the replicated record.
447
+ {
448
+ let (mut follower, _) = TransactionalNode::open(&follower_path, "nodeB")?;
449
+ follower.commit_with_crash(&record, &CrashPoint::DuringWrite { keep_percent: 40 })?;
450
+ }
451
+
452
+ let (mut follower, report) = TransactionalNode::open(&follower_path, "nodeB")?;
453
+ assert!(report.committed.is_empty(), "a torn replicated record must not commit");
454
+ assert_atomic(&follower, &record, "follower after torn write");
455
+ assert_eq!(follower.executor().visible_operations(&record), 0);
456
+
457
+ // Retransmission after recovery succeeds and converges.
458
+ assert_eq!(follower.accept_replicated(&record)?, ApplyOutcome::Applied);
459
+ let (leader, _) = TransactionalNode::open(&leader_path, "nodeA")?;
460
+ assert_eq!(follower.state().hash().as_hex(), leader.state().hash().as_hex());
461
+ Ok(())
462
+ }
463
+
464
+ #[test]
465
+ fn a_replicated_record_that_fails_integrity_is_refused() -> Result<(), Box<dyn std::error::Error>> {
466
+ let dir = TempDir::new()?;
467
+ let (mut follower, _) = TransactionalNode::open(dir.path().join("b.log"), "nodeB")?;
468
+
469
+ let mut record = TransactionRecord::new("tx1", "nodeA", 1, abc("tx1"));
470
+ record.operations[0].record_id = "tampered".to_string();
471
+
472
+ assert!(matches!(follower.accept_replicated(&record)?, ApplyOutcome::Rejected(_)));
473
+ assert!(follower.state().records.is_empty(), "a tampered record must not apply");
474
+ Ok(())
475
+ }
476
+
477
+ // -------------------------------------------------------------- identity
478
+
479
+ #[test]
480
+ fn durable_transaction_identity_survives_restart() -> Result<(), Box<dyn std::error::Error>> {
481
+ let dir = TempDir::new()?;
482
+ let path = dir.path().join("tx.log");
483
+
484
+ let record = {
485
+ let (mut node, _) = TransactionalNode::open(&path, "node1")?;
486
+ let record = node.build("stable-id", abc("stable-id"));
487
+ node.commit(&record)?;
488
+ record
489
+ };
490
+
491
+ let (mut node, report) = TransactionalNode::open(&path, "node1")?;
492
+ assert_eq!(report.committed[0].transaction_id, "stable-id");
493
+ assert!(node.executor().applied_transactions().contains("stable-id"),
494
+ "identity must be restored so replay stays idempotent");
495
+
496
+ // Redelivery after restart is still a no-op.
497
+ assert_eq!(node.accept_replicated(&record)?, ApplyOutcome::AlreadyApplied);
498
+ Ok(())
499
+ }
500
+
501
+ #[test]
502
+ fn deletes_are_atomic_with_writes() -> Result<(), Box<dyn std::error::Error>> {
503
+ let dir = TempDir::new()?;
504
+ let path = dir.path().join("tx.log");
505
+ let (mut node, _) = TransactionalNode::open(&path, "node1")?;
506
+
507
+ let seed = node.build(
508
+ "seed",
509
+ vec![
510
+ TransactionOperation::set("accounts", "old", json!({ "balance": 5 })),
511
+ TransactionOperation::set("accounts", "keep", json!({ "balance": 6 })),
512
+ ],
513
+ );
514
+ node.commit(&seed)?;
515
+
516
+ // Move: delete one record and create another, atomically.
517
+ let moved = node.build(
518
+ "move",
519
+ vec![
520
+ TransactionOperation::delete("accounts", "old").requiring(Precondition::MustExist),
521
+ TransactionOperation::set("accounts", "new", json!({ "balance": 5 }))
522
+ .requiring(Precondition::MustNotExist),
523
+ ],
524
+ );
525
+ assert_eq!(node.commit(&moved)?, ApplyOutcome::Applied);
526
+ drop(node);
527
+
528
+ let (recovered, _) = TransactionalNode::open(&path, "node1")?;
529
+ assert!(recovered.state().get_record("accounts", "old").is_none(), "delete must persist");
530
+ assert!(recovered.state().get_record("accounts", "new").is_some(), "insert must persist");
531
+ assert!(recovered.state().get_record("accounts", "keep").is_some(), "untouched record kept");
532
+ Ok(())
533
+ }
534
+
535
+ /// A long mixed history under repeated crashes: no transaction may ever be
536
+ /// partially visible, at any point, under any interleaving.
537
+ #[test]
538
+ fn a_long_crash_ridden_history_never_exposes_a_partial_transaction()
539
+ -> Result<(), Box<dyn std::error::Error>> {
540
+ let dir = TempDir::new()?;
541
+ let path = dir.path().join("tx.log");
542
+ let crashes = [
543
+ CrashPoint::AfterApply,
544
+ CrashPoint::DuringWrite { keep_percent: 30 },
545
+ CrashPoint::DuringApply { after_operations: 2 },
546
+ CrashPoint::BeforeWrite,
547
+ CrashPoint::AfterFsyncBeforeApply,
548
+ CrashPoint::DuringWrite { keep_percent: 80 },
549
+ ];
550
+
551
+ let mut issued = Vec::new();
552
+ for (index, crash) in crashes.iter().enumerate() {
553
+ let (mut node, _) = TransactionalNode::open(&path, "node1")?;
554
+ let id = format!("tx{}", index);
555
+ let record = node.build(&id, abc(&id));
556
+ node.commit_with_crash(&record, crash)?;
557
+ issued.push(record);
558
+
559
+ // Restart after every crash and check the whole history.
560
+ drop(node);
561
+ let (recovered, _) = TransactionalNode::open(&path, "node1")?;
562
+ for previous in &issued {
563
+ assert_atomic(&recovered, previous, &format!("after crash {}", index));
564
+ }
565
+ }
566
+
567
+ // Final state: every transaction is wholly present or wholly absent,
568
+ // and the committed count matches what the log actually holds.
569
+ let (recovered, report) = TransactionalNode::open(&path, "node1")?;
570
+ let committed_ids: HashSet<String> =
571
+ report.committed.iter().map(|record| record.transaction_id.clone()).collect();
572
+ for record in &issued {
573
+ let seen = recovered.executor().visible_operations(record);
574
+ if committed_ids.contains(&record.transaction_id) {
575
+ assert_eq!(seen, record.operations.len(), "{} committed but not whole", record.transaction_id);
576
+ } else {
577
+ assert_eq!(seen, 0, "{} not committed but visible", record.transaction_id);
578
+ }
579
+ }
580
+ Ok(())
581
+ }
582
+ }