@feltdb/core 0.6.8 → 0.6.10

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 (99) hide show
  1. package/dist/cli/application.js +55 -88
  2. package/dist/cli/commands.js +206 -95
  3. package/dist/cli/index.js +1 -1
  4. package/dist/collection.d.ts +110 -2
  5. package/dist/collection.d.ts.map +1 -1
  6. package/dist/collection.js +228 -3
  7. package/dist/create/package-versions.js +1 -1
  8. package/dist/create/server-source/crates/feltdb/src/bin/feltdb_node.rs +408 -178
  9. package/dist/create/server-source/crates/feltdb/src/lib.rs +49 -5
  10. package/dist/create/server-source/crates/feltdb/src/multi_operation_transaction.rs +659 -0
  11. package/dist/create/server-source/crates/feltdb/src/p1_application_atomicity.rs +285 -0
  12. package/dist/create/server-source/crates/feltdb/src/p1_atomicity_acceptance.rs +582 -0
  13. package/dist/create/server-source/crates/feltdb-server/src/main.rs +141 -0
  14. package/dist/db.d.ts +59 -0
  15. package/dist/db.d.ts.map +1 -1
  16. package/dist/db.js +94 -2
  17. package/dist/embedded-transaction.d.ts +77 -0
  18. package/dist/embedded-transaction.d.ts.map +1 -0
  19. package/dist/embedded-transaction.js +102 -0
  20. package/dist/feltdb.d.ts +49 -1
  21. package/dist/feltdb.d.ts.map +1 -1
  22. package/dist/file-db.d.ts +33 -0
  23. package/dist/file-db.d.ts.map +1 -1
  24. package/dist/file-db.js +128 -4
  25. package/dist/freshness.d.ts +119 -0
  26. package/dist/freshness.d.ts.map +1 -0
  27. package/dist/freshness.js +115 -0
  28. package/dist/http-db.d.ts +48 -0
  29. package/dist/http-db.d.ts.map +1 -1
  30. package/dist/http-db.js +77 -1
  31. package/dist/index-backend.d.ts +8 -0
  32. package/dist/index-backend.d.ts.map +1 -1
  33. package/dist/index-backend.js +13 -0
  34. package/dist/index-core.d.ts +78 -0
  35. package/dist/index-core.d.ts.map +1 -0
  36. package/dist/index-core.js +72 -0
  37. package/dist/index-manager.d.ts +11 -0
  38. package/dist/index-manager.d.ts.map +1 -1
  39. package/dist/index-manager.js +30 -13
  40. package/dist/index-types.d.ts +17 -0
  41. package/dist/index-types.d.ts.map +1 -1
  42. package/dist/index.browser.d.ts +14 -0
  43. package/dist/index.browser.d.ts.map +1 -0
  44. package/dist/index.browser.js +13 -0
  45. package/dist/index.d.ts +8 -59
  46. package/dist/index.d.ts.map +1 -1
  47. package/dist/index.js +11 -54
  48. package/dist/indexeddb-db.d.ts +32 -0
  49. package/dist/indexeddb-db.d.ts.map +1 -1
  50. package/dist/indexeddb-db.js +151 -1
  51. package/dist/memory-db.d.ts +26 -0
  52. package/dist/memory-db.d.ts.map +1 -1
  53. package/dist/memory-db.js +86 -0
  54. package/dist/runtime-registry.d.ts +32 -0
  55. package/dist/runtime-registry.d.ts.map +1 -0
  56. package/dist/runtime-registry.js +38 -0
  57. package/dist/studio-app/assets/{feltdb_wasm-B4wq4mqp.js → feltdb_wasm-CJv3wHzi.js} +1 -1
  58. package/dist/studio-app/assets/feltdb_wasm_bg-C8TG8r2n.wasm +0 -0
  59. package/dist/studio-app/assets/index-D3rT0SJi.js +28 -0
  60. package/dist/studio-app/index.html +1 -1
  61. package/dist/transaction.d.ts +98 -0
  62. package/dist/transaction.d.ts.map +1 -0
  63. package/dist/transaction.js +86 -0
  64. package/dist/wasm/feltdb_wasm_bg.wasm +0 -0
  65. package/dist/workspace/browser.d.ts +22 -0
  66. package/dist/workspace/browser.d.ts.map +1 -0
  67. package/dist/workspace/browser.js +17 -0
  68. package/dist/workspace/git-identity.d.ts +35 -0
  69. package/dist/workspace/git-identity.d.ts.map +1 -0
  70. package/dist/workspace/git-identity.js +81 -0
  71. package/dist/workspace/index.d.ts +11 -1
  72. package/dist/workspace/index.d.ts.map +1 -1
  73. package/dist/workspace/index.js +6 -0
  74. package/dist/workspace/investigation-analysis.d.ts +47 -0
  75. package/dist/workspace/investigation-analysis.d.ts.map +1 -0
  76. package/dist/workspace/investigation-analysis.js +181 -0
  77. package/dist/workspace/investigation-lifecycle-manager.d.ts +86 -0
  78. package/dist/workspace/investigation-lifecycle-manager.d.ts.map +1 -0
  79. package/dist/workspace/investigation-lifecycle-manager.js +229 -0
  80. package/dist/workspace/investigation-supervisor.d.ts +100 -0
  81. package/dist/workspace/investigation-supervisor.d.ts.map +1 -0
  82. package/dist/workspace/investigation-supervisor.js +236 -0
  83. package/dist/workspace/runtime-investigation.d.ts +1 -1
  84. package/dist/workspace/runtime-investigation.d.ts.map +1 -1
  85. package/dist/workspace/runtime-investigation.js +46 -21
  86. package/dist/workspace/runtime-observation.d.ts +79 -0
  87. package/dist/workspace/runtime-observation.d.ts.map +1 -0
  88. package/dist/workspace/runtime-observation.js +152 -0
  89. package/dist/workspace/runtime-observer.d.ts +51 -0
  90. package/dist/workspace/runtime-observer.d.ts.map +1 -0
  91. package/dist/workspace/runtime-observer.js +268 -0
  92. package/dist/workspace/workspace-connection.d.ts.map +1 -1
  93. package/dist/workspace/workspace-connection.js +14 -5
  94. package/dist/workspace/workspace-types.d.ts +113 -0
  95. package/dist/workspace/workspace-types.d.ts.map +1 -1
  96. package/package.json +12 -4
  97. package/dist/create/server-source/crates/feltdb/src/phase_1c_three_node.rs +0 -523
  98. package/dist/studio-app/assets/feltdb_wasm_bg-Ceyi7l21.wasm +0 -0
  99. package/dist/studio-app/assets/index-BF45M757.js +0 -28
@@ -0,0 +1,659 @@
1
+ //! Multi-Operation Atomicity (Production Gate P1)
2
+ //!
3
+ //! A transaction groups several operations and guarantees that a reader sees
4
+ //! all of them or none of them — never a subset — across commit, crash,
5
+ //! restart, replay, concurrent writers, and replication.
6
+ //!
7
+ //! # How the guarantee is obtained
8
+ //!
9
+ //! The durable log is the *only* source of truth for committed state. A
10
+ //! transaction becomes durable when, and only when, its complete record has
11
+ //! been written and fsynced as a single log entry. Observable state is derived
12
+ //! by replaying committed records.
13
+ //!
14
+ //! ```text
15
+ //! transaction { A, B, C }
16
+ //! |
17
+ //! v
18
+ //! preflight every precondition <- no state has been touched yet
19
+ //! |
20
+ //! v
21
+ //! one record, one write, one fsync <- the atomic commit point
22
+ //! |
23
+ //! v
24
+ //! apply A, B, C to derived state <- cannot fail; preflight proved it
25
+ //! ```
26
+ //!
27
+ //! A crash before the fsync leaves no complete record, so recovery replays
28
+ //! nothing. A crash after the fsync leaves a complete record, so recovery
29
+ //! replays all of A, B, and C. A crash *during* the write leaves a torn tail,
30
+ //! which is not a complete record and is discarded. There is no interleaving
31
+ //! that produces a partial transaction, because partial application is never
32
+ //! durable in the first place.
33
+ //!
34
+ //! Two properties do the real work:
35
+ //!
36
+ //! 1. **Preflight before commit.** Every precondition is evaluated against the
37
+ //! current state before anything is written. A transaction that would fail
38
+ //! part-way through is rejected before it can be committed, so the apply
39
+ //! step after commit cannot fail.
40
+ //! 2. **Integrity per record.** Each record carries a checksum over its body.
41
+ //! A record that does not parse, or whose checksum does not match, was not
42
+ //! completely written and therefore never committed.
43
+ //!
44
+ //! # Boundary
45
+ //!
46
+ //! This guarantee holds because derived state is rebuilt from the log. If a
47
+ //! checkpointing layer is added later, it must checkpoint only at transaction
48
+ //! boundaries; a checkpoint taken mid-apply would reintroduce exactly the
49
+ //! partial-visibility problem this module removes.
50
+
51
+ use crate::state_hash::CanonicalState;
52
+ use serde::{Deserialize, Serialize};
53
+ use serde_json::Value;
54
+ use sha2::{Digest, Sha256};
55
+ use std::collections::HashSet;
56
+ use std::fs::{File, OpenOptions};
57
+ use std::io::{BufRead, BufReader, Seek, SeekFrom, Write};
58
+ use std::path::{Path, PathBuf};
59
+
60
+ /// What a single operation does to one record.
61
+ #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
62
+ pub enum TransactionOp {
63
+ /// Create or replace the record with this value.
64
+ Set(Value),
65
+ /// Remove the record.
66
+ Delete,
67
+ }
68
+
69
+ /// A condition that must hold before the transaction is allowed to commit.
70
+ #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
71
+ pub enum Precondition {
72
+ /// The record must currently exist.
73
+ MustExist,
74
+ /// The record must not currently exist.
75
+ MustNotExist,
76
+ /// The record must currently hold exactly this value.
77
+ ValueEquals(Value),
78
+ }
79
+
80
+ /// One operation within a transaction.
81
+ #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
82
+ pub struct TransactionOperation {
83
+ pub collection: String,
84
+ pub record_id: String,
85
+ pub op: TransactionOp,
86
+ pub precondition: Option<Precondition>,
87
+ }
88
+
89
+ impl TransactionOperation {
90
+ pub fn set(collection: &str, record_id: &str, value: Value) -> Self {
91
+ Self {
92
+ collection: collection.to_string(),
93
+ record_id: record_id.to_string(),
94
+ op: TransactionOp::Set(value),
95
+ precondition: None,
96
+ }
97
+ }
98
+
99
+ pub fn delete(collection: &str, record_id: &str) -> Self {
100
+ Self {
101
+ collection: collection.to_string(),
102
+ record_id: record_id.to_string(),
103
+ op: TransactionOp::Delete,
104
+ precondition: None,
105
+ }
106
+ }
107
+
108
+ pub fn requiring(mut self, precondition: Precondition) -> Self {
109
+ self.precondition = Some(precondition);
110
+ self
111
+ }
112
+
113
+ fn key(&self) -> (String, String) {
114
+ (self.collection.clone(), self.record_id.clone())
115
+ }
116
+ }
117
+
118
+ /// The durable unit of atomicity.
119
+ ///
120
+ /// A record is committed if and only if it appears in the log completely and
121
+ /// its checksum verifies. Identity is `transaction_id`, which is what makes
122
+ /// replay idempotent across restart and replication.
123
+ #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
124
+ pub struct TransactionRecord {
125
+ pub transaction_id: String,
126
+ pub node_id: String,
127
+ pub sequence: u64,
128
+ pub operations: Vec<TransactionOperation>,
129
+ /// Checksum over the canonical body. Detects a partially written record.
130
+ pub checksum: String,
131
+ }
132
+
133
+ impl TransactionRecord {
134
+ pub fn new(
135
+ transaction_id: &str,
136
+ node_id: &str,
137
+ sequence: u64,
138
+ operations: Vec<TransactionOperation>,
139
+ ) -> Self {
140
+ let mut record = Self {
141
+ transaction_id: transaction_id.to_string(),
142
+ node_id: node_id.to_string(),
143
+ sequence,
144
+ operations,
145
+ checksum: String::new(),
146
+ };
147
+ record.checksum = record.compute_checksum();
148
+ record
149
+ }
150
+
151
+ fn compute_checksum(&self) -> String {
152
+ // The checksum covers everything except itself, in a deterministic
153
+ // encoding, so any truncation or mutation of the body is detectable.
154
+ let body = serde_json::json!({
155
+ "transaction_id": self.transaction_id,
156
+ "node_id": self.node_id,
157
+ "sequence": self.sequence,
158
+ "operations": self.operations,
159
+ });
160
+ let mut hasher = Sha256::new();
161
+ hasher.update(body.to_string().as_bytes());
162
+ format!("{:x}", hasher.finalize())
163
+ }
164
+
165
+ /// Whether this record was written completely and has not been altered.
166
+ pub fn verify_checksum(&self) -> bool {
167
+ self.checksum == self.compute_checksum()
168
+ }
169
+
170
+ /// Records touched by this transaction, for conflict detection.
171
+ pub fn touched_keys(&self) -> HashSet<(String, String)> {
172
+ self.operations.iter().map(|operation| operation.key()).collect()
173
+ }
174
+ }
175
+
176
+ /// Why a transaction was refused. No state is modified in any of these cases.
177
+ #[derive(Clone, Debug, PartialEq, Eq)]
178
+ pub enum RejectionReason {
179
+ /// A precondition did not hold. Carries the operation index and a reason.
180
+ PreconditionFailed { operation_index: usize, detail: String },
181
+ /// The transaction contained no operations.
182
+ Empty,
183
+ /// The transaction writes the same record twice, so its outcome would
184
+ /// depend on operation order rather than on the transaction as a whole.
185
+ ConflictingWritesWithinTransaction { collection: String, record_id: String },
186
+ }
187
+
188
+ /// The outcome of applying a record to derived state.
189
+ #[derive(Clone, Debug, PartialEq, Eq)]
190
+ pub enum ApplyOutcome {
191
+ /// Every operation was applied.
192
+ Applied,
193
+ /// This transaction id was already applied; applying it again is a no-op.
194
+ AlreadyApplied,
195
+ /// Nothing was applied.
196
+ Rejected(RejectionReason),
197
+ }
198
+
199
+ /// A log entry that could not be read.
200
+ #[derive(Clone, Debug, PartialEq, Eq)]
201
+ pub enum LogDefect {
202
+ /// The final entry was incomplete: the process died while writing it.
203
+ /// This transaction never committed and is discarded.
204
+ TornTail { bytes: usize },
205
+ /// An entry before the end is unreadable. This is corruption, not a torn
206
+ /// write, and recovery refuses to guess.
207
+ InteriorCorruption { line_number: usize, detail: String },
208
+ }
209
+
210
+ /// What recovery found in the log.
211
+ #[derive(Clone, Debug)]
212
+ pub struct RecoveryReport {
213
+ pub committed: Vec<TransactionRecord>,
214
+ /// Present when an incomplete final entry was discarded and truncated.
215
+ pub discarded_tail: Option<LogDefect>,
216
+ }
217
+
218
+ /// Where to stop when simulating a crash. Used by the crash-injection harness.
219
+ #[derive(Clone, Debug, PartialEq, Eq)]
220
+ pub enum CrashPoint {
221
+ /// Die before any byte reaches the log.
222
+ BeforeWrite,
223
+ /// Die having written only part of the record: a torn tail.
224
+ DuringWrite { keep_percent: u8 },
225
+ /// Die after the bytes were written but before fsync.
226
+ AfterWriteBeforeFsync,
227
+ /// Die after the record is durable but before it was applied to state.
228
+ AfterFsyncBeforeApply,
229
+ /// Die part-way through applying operations to in-memory state.
230
+ DuringApply { after_operations: usize },
231
+ /// Die after everything completed.
232
+ AfterApply,
233
+ }
234
+
235
+ /// Append-only transaction log with per-record integrity.
236
+ pub struct AtomicTransactionLog {
237
+ path: PathBuf,
238
+ file: File,
239
+ }
240
+
241
+ impl AtomicTransactionLog {
242
+ /// Open a log, recovering it first.
243
+ ///
244
+ /// An incomplete final entry is truncated away before the log accepts new
245
+ /// writes. Without this, the next append would splice onto a torn record
246
+ /// and turn a recoverable tail into interior corruption.
247
+ pub fn open<P: AsRef<Path>>(path: P) -> Result<(Self, RecoveryReport), std::io::Error> {
248
+ let path = path.as_ref().to_path_buf();
249
+ if let Some(parent) = path.parent() {
250
+ std::fs::create_dir_all(parent)?;
251
+ }
252
+
253
+ let report = Self::read_log(&path)?;
254
+ if let Some(LogDefect::TornTail { bytes }) = &report.discarded_tail {
255
+ let file = OpenOptions::new().write(true).open(&path)?;
256
+ let length = file.metadata()?.len();
257
+ file.set_len(length.saturating_sub(*bytes as u64))?;
258
+ file.sync_all()?;
259
+ }
260
+
261
+ let file = OpenOptions::new().create(true).append(true).open(&path)?;
262
+ Ok((Self { path, file }, report))
263
+ }
264
+
265
+ /// Read the log without modifying it.
266
+ pub fn read_log(path: &Path) -> Result<RecoveryReport, std::io::Error> {
267
+ if !path.exists() {
268
+ return Ok(RecoveryReport { committed: Vec::new(), discarded_tail: None });
269
+ }
270
+
271
+ let reader = BufReader::new(File::open(path)?);
272
+ let mut committed = Vec::new();
273
+ let mut defect = None;
274
+
275
+ // A line is only trustworthy once we know it is terminated, so entries
276
+ // are collected with their raw bytes and the final one is judged last.
277
+ let mut entries: Vec<(usize, String, bool)> = Vec::new();
278
+ let mut buffer = Vec::new();
279
+ let mut line_number = 0usize;
280
+ let mut reader = reader;
281
+ loop {
282
+ buffer.clear();
283
+ let read = reader.read_until(b'\n', &mut buffer)?;
284
+ if read == 0 {
285
+ break;
286
+ }
287
+ line_number += 1;
288
+ let terminated = buffer.ends_with(b"\n");
289
+ let text = String::from_utf8_lossy(&buffer).trim_end_matches('\n').to_string();
290
+ entries.push((line_number, text, terminated));
291
+ }
292
+
293
+ let last_index = entries.len().saturating_sub(1);
294
+ for (index, (number, text, terminated)) in entries.into_iter().enumerate() {
295
+ if text.trim().is_empty() {
296
+ continue;
297
+ }
298
+ let is_last = index == last_index;
299
+ let parsed = serde_json::from_str::<TransactionRecord>(&text);
300
+ let usable = match &parsed {
301
+ Ok(record) => terminated && record.verify_checksum(),
302
+ Err(_) => false,
303
+ };
304
+
305
+ if usable {
306
+ committed.push(parsed.expect("checked above"));
307
+ continue;
308
+ }
309
+
310
+ if is_last {
311
+ // An unterminated, unparseable, or checksum-failing final entry
312
+ // is a transaction that was still being written when the
313
+ // process died. It never committed.
314
+ defect = Some(LogDefect::TornTail { bytes: text.len() + usize::from(terminated) });
315
+ } else {
316
+ return Err(std::io::Error::new(
317
+ std::io::ErrorKind::InvalidData,
318
+ format!(
319
+ "transaction log corrupted at line {}: {}",
320
+ number,
321
+ parsed.err().map(|error| error.to_string())
322
+ .unwrap_or_else(|| "checksum mismatch".to_string())
323
+ ),
324
+ ));
325
+ }
326
+ }
327
+
328
+ Ok(RecoveryReport { committed, discarded_tail: defect })
329
+ }
330
+
331
+ /// Commit a record: one write, one fsync. This is the atomic commit point.
332
+ pub fn commit(&mut self, record: &TransactionRecord) -> Result<(), std::io::Error> {
333
+ let json = serde_json::to_string(record)
334
+ .map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error))?;
335
+ writeln!(self.file, "{}", json)?;
336
+ self.file.sync_all()?;
337
+ Ok(())
338
+ }
339
+
340
+ /// Commit while simulating a crash, for the crash-injection harness.
341
+ ///
342
+ /// Returns whether the record reached durable storage intact.
343
+ pub fn commit_with_crash(
344
+ &mut self,
345
+ record: &TransactionRecord,
346
+ crash: &CrashPoint,
347
+ ) -> Result<bool, std::io::Error> {
348
+ let json = serde_json::to_string(record)
349
+ .map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error))?;
350
+
351
+ match crash {
352
+ CrashPoint::BeforeWrite => Ok(false),
353
+ CrashPoint::DuringWrite { keep_percent } => {
354
+ // Write only part of the record and never terminate it: exactly
355
+ // what a process death mid-write leaves behind.
356
+ let cut = json.len() * (*keep_percent).min(99) as usize / 100;
357
+ // Cut on a character boundary; the record is ASCII JSON, but a
358
+ // value could carry multibyte text.
359
+ let mut cut = cut.max(1).min(json.len().saturating_sub(1)).max(1);
360
+ while cut > 1 && !json.is_char_boundary(cut) {
361
+ cut -= 1;
362
+ }
363
+ let partial = &json[..cut];
364
+ self.file.write_all(partial.as_bytes())?;
365
+ self.file.sync_all()?;
366
+ Ok(false)
367
+ }
368
+ CrashPoint::AfterWriteBeforeFsync => {
369
+ writeln!(self.file, "{}", json)?;
370
+ self.file.flush()?;
371
+ // Deliberately no sync_all. The record is complete, so whether
372
+ // it survives is the operating system's choice; either way it
373
+ // is all-or-nothing, never partial.
374
+ Ok(true)
375
+ }
376
+ _ => {
377
+ writeln!(self.file, "{}", json)?;
378
+ self.file.sync_all()?;
379
+ Ok(true)
380
+ }
381
+ }
382
+ }
383
+
384
+ pub fn path(&self) -> &Path {
385
+ &self.path
386
+ }
387
+
388
+ /// Bytes currently in the log, for harness assertions.
389
+ pub fn size_bytes(&self) -> Result<u64, std::io::Error> {
390
+ Ok(self.file.metadata()?.len())
391
+ }
392
+
393
+ /// Append raw bytes. Used only to simulate damage in tests.
394
+ pub fn append_raw(&mut self, bytes: &[u8]) -> Result<(), std::io::Error> {
395
+ self.file.write_all(bytes)?;
396
+ self.file.sync_all()?;
397
+ Ok(())
398
+ }
399
+
400
+ /// Overwrite bytes at an offset. Used only to simulate corruption in tests.
401
+ pub fn corrupt_at(&mut self, offset: u64, bytes: &[u8]) -> Result<(), std::io::Error> {
402
+ let mut file = OpenOptions::new().write(true).open(&self.path)?;
403
+ file.seek(SeekFrom::Start(offset))?;
404
+ file.write_all(bytes)?;
405
+ file.sync_all()?;
406
+ Ok(())
407
+ }
408
+ }
409
+
410
+ /// Applies committed transactions to derived state.
411
+ ///
412
+ /// The executor never applies a transaction part-way. Preconditions are
413
+ /// evaluated for every operation before any mutation is staged, and the staged
414
+ /// mutations are then written together.
415
+ pub struct TransactionExecutor {
416
+ state: CanonicalState,
417
+ applied: HashSet<String>,
418
+ applied_order: Vec<String>,
419
+ }
420
+
421
+ impl TransactionExecutor {
422
+ pub fn new() -> Self {
423
+ Self { state: CanonicalState::new(), applied: HashSet::new(), applied_order: Vec::new() }
424
+ }
425
+
426
+ pub fn state(&self) -> &CanonicalState {
427
+ &self.state
428
+ }
429
+
430
+ pub fn applied_transactions(&self) -> &HashSet<String> {
431
+ &self.applied
432
+ }
433
+
434
+ pub fn applied_order(&self) -> &[String] {
435
+ &self.applied_order
436
+ }
437
+
438
+ /// Evaluate every precondition without mutating anything.
439
+ ///
440
+ /// This runs before the commit, which is what allows the post-commit apply
441
+ /// to be infallible.
442
+ pub fn preflight(&self, record: &TransactionRecord) -> Result<(), RejectionReason> {
443
+ if record.operations.is_empty() {
444
+ return Err(RejectionReason::Empty);
445
+ }
446
+
447
+ let mut seen: HashSet<(String, String)> = HashSet::new();
448
+ for operation in &record.operations {
449
+ if !seen.insert(operation.key()) {
450
+ return Err(RejectionReason::ConflictingWritesWithinTransaction {
451
+ collection: operation.collection.clone(),
452
+ record_id: operation.record_id.clone(),
453
+ });
454
+ }
455
+ }
456
+
457
+ for (index, operation) in record.operations.iter().enumerate() {
458
+ let Some(precondition) = &operation.precondition else { continue };
459
+ let current = self.state.get_record(&operation.collection, &operation.record_id);
460
+ let failure = match (precondition, current) {
461
+ (Precondition::MustExist, None) => Some("record does not exist".to_string()),
462
+ (Precondition::MustNotExist, Some(_)) => Some("record already exists".to_string()),
463
+ (Precondition::ValueEquals(expected), Some(actual)) if actual != expected => {
464
+ Some("record does not hold the expected value".to_string())
465
+ }
466
+ (Precondition::ValueEquals(_), None) => Some("record does not exist".to_string()),
467
+ _ => None,
468
+ };
469
+ if let Some(detail) = failure {
470
+ return Err(RejectionReason::PreconditionFailed { operation_index: index, detail });
471
+ }
472
+ }
473
+
474
+ Ok(())
475
+ }
476
+
477
+ /// Apply a committed record. All operations, or none.
478
+ pub fn apply(&mut self, record: &TransactionRecord) -> ApplyOutcome {
479
+ if self.applied.contains(&record.transaction_id) {
480
+ return ApplyOutcome::AlreadyApplied;
481
+ }
482
+ if let Err(reason) = self.preflight(record) {
483
+ return ApplyOutcome::Rejected(reason);
484
+ }
485
+
486
+ // Preflight succeeded, so every mutation below is known to be legal.
487
+ // Staging them first keeps the mutation phase free of any decision that
488
+ // could fail half-way through.
489
+ let staged: Vec<(&TransactionOperation, ())> =
490
+ record.operations.iter().map(|operation| (operation, ())).collect();
491
+ for (operation, ()) in staged {
492
+ match &operation.op {
493
+ TransactionOp::Set(value) => self.state.set_record(
494
+ operation.collection.clone(),
495
+ operation.record_id.clone(),
496
+ value.clone(),
497
+ ),
498
+ TransactionOp::Delete => {
499
+ self.state
500
+ .records
501
+ .remove(&(operation.collection.clone(), operation.record_id.clone()));
502
+ }
503
+ }
504
+ }
505
+
506
+ self.applied.insert(record.transaction_id.clone());
507
+ self.applied_order.push(record.transaction_id.clone());
508
+ ApplyOutcome::Applied
509
+ }
510
+
511
+ /// Rebuild state by replaying committed records in order.
512
+ ///
513
+ /// Replay is idempotent: a record already applied is skipped, so recovery
514
+ /// can run repeatedly and converge on the same state.
515
+ pub fn recover(&mut self, records: &[TransactionRecord]) -> Vec<ApplyOutcome> {
516
+ records.iter().map(|record| self.apply(record)).collect()
517
+ }
518
+
519
+ /// Whether any operation of this transaction is visible in state.
520
+ ///
521
+ /// The atomicity assertion in the harness is that this is either all of
522
+ /// them or none of them.
523
+ pub fn visible_operations(&self, record: &TransactionRecord) -> usize {
524
+ record
525
+ .operations
526
+ .iter()
527
+ .filter(|operation| match &operation.op {
528
+ TransactionOp::Set(value) => {
529
+ self.state.get_record(&operation.collection, &operation.record_id) == Some(value)
530
+ }
531
+ TransactionOp::Delete => {
532
+ self.state.get_record(&operation.collection, &operation.record_id).is_none()
533
+ }
534
+ })
535
+ .count()
536
+ }
537
+ }
538
+
539
+ impl Default for TransactionExecutor {
540
+ fn default() -> Self {
541
+ Self::new()
542
+ }
543
+ }
544
+
545
+ /// A node that commits transactions durably and derives state from the log.
546
+ ///
547
+ /// This is the unit the crash harness kills and restarts.
548
+ pub struct TransactionalNode {
549
+ log: AtomicTransactionLog,
550
+ executor: TransactionExecutor,
551
+ node_id: String,
552
+ next_sequence: u64,
553
+ }
554
+
555
+ impl TransactionalNode {
556
+ /// Start a node, recovering derived state from the durable log.
557
+ pub fn open<P: AsRef<Path>>(path: P, node_id: &str) -> Result<(Self, RecoveryReport), std::io::Error> {
558
+ let (log, report) = AtomicTransactionLog::open(path)?;
559
+ let mut executor = TransactionExecutor::new();
560
+ executor.recover(&report.committed);
561
+ let next_sequence = report.committed.iter().map(|record| record.sequence).max().unwrap_or(0) + 1;
562
+ Ok((Self { log, executor, node_id: node_id.to_string(), next_sequence }, report))
563
+ }
564
+
565
+ pub fn state(&self) -> &CanonicalState {
566
+ self.executor.state()
567
+ }
568
+
569
+ pub fn executor(&self) -> &TransactionExecutor {
570
+ &self.executor
571
+ }
572
+
573
+ pub fn log(&mut self) -> &mut AtomicTransactionLog {
574
+ &mut self.log
575
+ }
576
+
577
+ pub fn build(&mut self, transaction_id: &str, operations: Vec<TransactionOperation>) -> TransactionRecord {
578
+ let record = TransactionRecord::new(transaction_id, &self.node_id, self.next_sequence, operations);
579
+ self.next_sequence += 1;
580
+ record
581
+ }
582
+
583
+ /// Commit a transaction: preflight, durably record, then apply.
584
+ ///
585
+ /// A rejected transaction is never written to the log, so a failed
586
+ /// precondition leaves no trace in durable state.
587
+ pub fn commit(&mut self, record: &TransactionRecord) -> Result<ApplyOutcome, std::io::Error> {
588
+ if self.executor.applied_transactions().contains(&record.transaction_id) {
589
+ return Ok(ApplyOutcome::AlreadyApplied);
590
+ }
591
+ if let Err(reason) = self.executor.preflight(record) {
592
+ return Ok(ApplyOutcome::Rejected(reason));
593
+ }
594
+ self.log.commit(record)?;
595
+ Ok(self.executor.apply(record))
596
+ }
597
+
598
+ /// Commit while simulating a crash at the given point.
599
+ ///
600
+ /// Returns what the in-memory executor saw before the process "died". What
601
+ /// matters is not this value but what a restarted node recovers.
602
+ pub fn commit_with_crash(
603
+ &mut self,
604
+ record: &TransactionRecord,
605
+ crash: &CrashPoint,
606
+ ) -> Result<(), std::io::Error> {
607
+ if self.executor.preflight(record).is_err() {
608
+ return Ok(());
609
+ }
610
+ let durable = self.log.commit_with_crash(record, crash)?;
611
+ if !durable {
612
+ return Ok(());
613
+ }
614
+ match crash {
615
+ CrashPoint::AfterFsyncBeforeApply => Ok(()),
616
+ CrashPoint::DuringApply { after_operations } => {
617
+ // Deliberately apply only a prefix, in memory, to model a
618
+ // process that died mid-apply. This state is never persisted;
619
+ // recovery rebuilds from the log.
620
+ for operation in record.operations.iter().take(*after_operations) {
621
+ if let TransactionOp::Set(value) = &operation.op {
622
+ self.executor.state.set_record(
623
+ operation.collection.clone(),
624
+ operation.record_id.clone(),
625
+ value.clone(),
626
+ );
627
+ }
628
+ }
629
+ Ok(())
630
+ }
631
+ _ => {
632
+ self.executor.apply(record);
633
+ Ok(())
634
+ }
635
+ }
636
+ }
637
+
638
+ /// Accept a transaction replicated from another node.
639
+ ///
640
+ /// Applying a replicated transaction is the same all-or-nothing path, and
641
+ /// a transaction already applied here is ignored, so duplicate delivery is
642
+ /// safe.
643
+ pub fn accept_replicated(&mut self, record: &TransactionRecord) -> Result<ApplyOutcome, std::io::Error> {
644
+ if !record.verify_checksum() {
645
+ return Ok(ApplyOutcome::Rejected(RejectionReason::PreconditionFailed {
646
+ operation_index: 0,
647
+ detail: "replicated record failed its integrity check".to_string(),
648
+ }));
649
+ }
650
+ if self.executor.applied_transactions().contains(&record.transaction_id) {
651
+ return Ok(ApplyOutcome::AlreadyApplied);
652
+ }
653
+ if let Err(reason) = self.executor.preflight(record) {
654
+ return Ok(ApplyOutcome::Rejected(reason));
655
+ }
656
+ self.log.commit(record)?;
657
+ Ok(self.executor.apply(record))
658
+ }
659
+ }