@feltdb/core 0.8.5 → 0.8.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (25) hide show
  1. package/dist/create/package-versions.js +1 -1
  2. package/dist/create/server-source/crates/feltdb/src/lib.rs +1173 -72
  3. package/dist/create/server-source/crates/feltdb/src/operation.rs +39 -0
  4. package/dist/create/server-source/crates/feltdb/src/state_model.rs +52 -0
  5. package/dist/create/server-source/crates/feltdb/src/storage.rs +9 -3
  6. package/dist/create/server-source/crates/feltdb/tests/bounded_read_contract.rs +132 -0
  7. package/dist/create/server-source/crates/feltdb/tests/compaction_stall_contract.rs +272 -0
  8. package/dist/create/server-source/crates/feltdb/tests/crash_durability_contract.rs +467 -0
  9. package/dist/create/server-source/crates/feltdb/tests/current_revision_authority_evidence.rs +26 -5
  10. package/dist/create/server-source/crates/feltdb/tests/durable_backup_contract.rs +445 -0
  11. package/dist/create/server-source/crates/feltdb/tests/durable_corruption_contract.rs +518 -0
  12. package/dist/create/server-source/crates/feltdb/tests/operational_health_contract.rs +278 -0
  13. package/dist/create/server-source/crates/feltdb/tests/production_readiness_contract.rs +490 -157
  14. package/dist/create/server-source/crates/feltdb/tests/replicated_history_contract.rs +417 -0
  15. package/dist/create/server-source/crates/feltdb/tests/workload_envelope_contract.rs +442 -0
  16. package/dist/create/server-source/crates/feltdb-server/src/app_state.rs +14 -0
  17. package/dist/create/server-source/crates/feltdb-server/src/main.rs +369 -41
  18. package/dist/create/server-source/crates/feltdb-server/src/metrics.rs +21 -0
  19. package/dist/studio-app/assets/{feltdb_wasm-DaNwCLRX.js → feltdb_wasm-C1VhI-U5.js} +1 -1
  20. package/dist/studio-app/assets/feltdb_wasm_bg-C8HXbAXb.wasm +0 -0
  21. package/dist/studio-app/assets/{index-j8IlhNqJ.js → index-Bbos1m2U.js} +1 -1
  22. package/dist/studio-app/index.html +1 -1
  23. package/dist/wasm/feltdb_wasm_bg.wasm +0 -0
  24. package/package.json +1 -1
  25. package/dist/studio-app/assets/feltdb_wasm_bg-DnsHNv6g.wasm +0 -0
@@ -0,0 +1,467 @@
1
+ //! Crash and power-loss durability.
2
+ //!
3
+ //! The question is not whether `fsync` appears somewhere. It is:
4
+ //!
5
+ //! > **After a process dies at every relevant point in a mutation, what durable
6
+ //! > states are actually possible, and are all of them valid under FeltDB's
7
+ //! > contract?**
8
+ //!
9
+ //! # How every crash point is reached
10
+ //!
11
+ //! Killing a process at a chosen instruction is not deterministic. Truncating a
12
+ //! durable log at every byte offset is, and it is strictly stronger: it reaches
13
+ //! every boundary a crash could land on, including boundaries *inside* a single
14
+ //! write, which a signal cannot target. The exhaustive harness below opens the
15
+ //! database at all of them.
16
+ //!
17
+ //! A real process abort is also tested, because truncation models the durable
18
+ //! bytes and not the operating system's behaviour when a process dies.
19
+ //!
20
+ //! # What is deliberately not claimed
21
+ //!
22
+ //! `append_event` writes and flushes to the operating system. It does **not**
23
+ //! `fsync`; only `append_transaction` does. So process-crash durability is
24
+ //! proven here and **stable-storage durability is not**. Those are different
25
+ //! claims and this file does not let the first stand in for the second. See
26
+ //! `docs/architecture/crash-durability.md`.
27
+
28
+ use feltdb::state_model::StateStore;
29
+ use feltdb::{AtomicMutation, FeltDb, FlowError};
30
+ use serde_json::{json, Value};
31
+ use std::collections::HashMap;
32
+ use std::path::Path;
33
+ use std::sync::Arc;
34
+ use tempfile::TempDir;
35
+
36
+ /// What a database looks like after recovering from a crash.
37
+ #[derive(Debug, PartialEq)]
38
+ struct Recovered {
39
+ /// The value of `tasks:1`, if the record survived.
40
+ value: Option<i64>,
41
+ /// How many revisions its history holds.
42
+ revisions: usize,
43
+ }
44
+
45
+ fn inspect(db: &Arc<FeltDb>) -> Recovered {
46
+ let store = StateStore::with_feltdb(db.clone()).unwrap();
47
+ let history = store.history_of("tasks:1");
48
+
49
+ // Invariants that must hold at every crash point, checked here so no
50
+ // caller can forget them.
51
+ assert!(
52
+ history
53
+ .windows(2)
54
+ .all(|pair| pair[1].parent_id.as_ref() == Some(&pair[0].id)),
55
+ "ancestry is a chain at every crash point"
56
+ );
57
+ assert!(
58
+ history
59
+ .iter()
60
+ .enumerate()
61
+ .all(|(index, revision)| revision.sequence == index as u64),
62
+ "sequences are contiguous from zero at every crash point"
63
+ );
64
+ if let Some(first) = history.first() {
65
+ assert_eq!(first.parent_id, None, "the first revision begins history");
66
+ }
67
+
68
+ Recovered {
69
+ value: db
70
+ .get::<Value>("tasks:1")
71
+ .unwrap()
72
+ .map(|value| value["n"].as_i64().unwrap()),
73
+ revisions: history.len(),
74
+ }
75
+ }
76
+
77
+ /// Build a log by a known mutation sequence and return its bytes.
78
+ fn log_of_three_writes(path: &Path) -> Vec<u8> {
79
+ let db = Arc::new(FeltDb::open(path).unwrap());
80
+ db.insert("tasks:1", json!({"n": 0})).unwrap();
81
+ db.update("tasks:1", json!({"n": 1})).unwrap();
82
+ db.update("tasks:1", json!({"n": 2})).unwrap();
83
+ drop(db);
84
+ std::fs::read(path).unwrap()
85
+ }
86
+
87
+ // ---------------------------------------------------------------------------
88
+ // D1 — every crash point
89
+ // ---------------------------------------------------------------------------
90
+
91
+ /// **Every crash point leaves a clean prefix of the mutation sequence.**
92
+ ///
93
+ /// Three writes, and the durable log cut at all 4,314 byte offsets. Every one
94
+ /// opens, and every recovered database is one of exactly four states:
95
+ ///
96
+ /// ```text
97
+ /// nothing no record, no history
98
+ /// n = 0 one revision
99
+ /// n = 1 two revisions
100
+ /// n = 2 three revisions
101
+ /// ```
102
+ ///
103
+ /// There is no state in which a record exists without the revision recording
104
+ /// it, none in which a revision exists for a record that was never written, and
105
+ /// none with broken ancestry or a gap in the sequence. A crash truncates
106
+ /// history; it cannot corrupt or invent it.
107
+ #[test]
108
+ fn every_crash_point_leaves_a_clean_prefix() {
109
+ let directory = TempDir::new().unwrap();
110
+ let path = directory.path().join("crash.log");
111
+ let full = log_of_three_writes(&path);
112
+
113
+ let legitimate = [
114
+ Recovered {
115
+ value: None,
116
+ revisions: 0,
117
+ },
118
+ Recovered {
119
+ value: Some(0),
120
+ revisions: 1,
121
+ },
122
+ Recovered {
123
+ value: Some(1),
124
+ revisions: 2,
125
+ },
126
+ Recovered {
127
+ value: Some(2),
128
+ revisions: 3,
129
+ },
130
+ ];
131
+
132
+ let mut seen = std::collections::BTreeSet::new();
133
+ for cut in 0..=full.len() {
134
+ // In place: an instance's identity is derived from its path, so a crash
135
+ // has to be simulated on the same file.
136
+ std::fs::write(&path, &full[..cut]).unwrap();
137
+ let db = Arc::new(
138
+ FeltDb::open(&path).unwrap_or_else(|error| panic!("cut {cut} did not open: {error}")),
139
+ );
140
+ let recovered = inspect(&db);
141
+ assert!(
142
+ legitimate.contains(&recovered),
143
+ "cut {cut} recovered to {recovered:?}, which is not a prefix of the writes"
144
+ );
145
+ seen.insert(format!("{recovered:?}"));
146
+ }
147
+
148
+ assert_eq!(
149
+ seen.len(),
150
+ 4,
151
+ "all four prefixes are reachable, and nothing else is"
152
+ );
153
+ }
154
+
155
+ /// **No crash produces a revision for a record that was never written.**
156
+ ///
157
+ /// The ordering is what guarantees this: a record is made durable before the
158
+ /// revision recording it. A crash between them loses the revision, never the
159
+ /// other way round — so recovery can omit a historical fact, and can never
160
+ /// assert one that did not happen.
161
+ ///
162
+ /// The omission is then repaired, which is the next test.
163
+ #[test]
164
+ fn no_crash_point_produces_a_phantom_revision() {
165
+ let directory = TempDir::new().unwrap();
166
+ let path = directory.path().join("phantom.log");
167
+ let full = log_of_three_writes(&path);
168
+
169
+ for cut in 0..=full.len() {
170
+ std::fs::write(&path, &full[..cut]).unwrap();
171
+ let db = Arc::new(FeltDb::open(&path).unwrap());
172
+ let recovered = inspect(&db);
173
+ let implied = recovered.value.map(|n| n as usize + 1).unwrap_or(0);
174
+ assert!(
175
+ recovered.revisions <= implied,
176
+ "cut {cut}: {} revisions for a record that reached only {:?}",
177
+ recovered.revisions,
178
+ recovered.value
179
+ );
180
+ }
181
+ }
182
+
183
+ /// **A revision lost to a crash is rebuilt from the operation that produced it.**
184
+ ///
185
+ /// The crash window between appending a record and appending its revision used
186
+ /// to leave an authority holding less history than its own operation stream
187
+ /// implied. It no longer can: a revision is a deterministic function of the
188
+ /// operation — resource, content, parent, sequence and authority all travel
189
+ /// with it — so recovery reconstructs it.
190
+ ///
191
+ /// Nothing is invented. The identity is recomputed from its parts and discarded
192
+ /// if it does not follow from them, exactly as a replicating peer does.
193
+ #[test]
194
+ fn a_revision_lost_to_a_crash_is_rebuilt_from_its_operation() {
195
+ let directory = TempDir::new().unwrap();
196
+ let path = directory.path().join("rebuild.log");
197
+ let full = log_of_three_writes(&path);
198
+
199
+ for cut in 0..=full.len() {
200
+ std::fs::write(&path, &full[..cut]).unwrap();
201
+ let db = Arc::new(FeltDb::open(&path).unwrap());
202
+ let recovered = inspect(&db);
203
+ let implied = recovered.value.map(|n| n as usize + 1).unwrap_or(0);
204
+ assert_eq!(
205
+ recovered.revisions, implied,
206
+ "cut {cut}: a surviving record must carry its history"
207
+ );
208
+ }
209
+ }
210
+
211
+ // ---------------------------------------------------------------------------
212
+ // D1 — a real process death
213
+ // ---------------------------------------------------------------------------
214
+
215
+ /// **A committed write survives the process dying.**
216
+ ///
217
+ /// Truncation models durable bytes; this models the operating system. The child
218
+ /// re-runs this binary, writes, and calls `abort()` — a real `SIGABRT` with no
219
+ /// unwinding, no destructors and no flush on the way out.
220
+ #[test]
221
+ fn a_committed_write_survives_process_death() {
222
+ if std::env::var("FELTDB_CRASH_CHILD").is_ok() {
223
+ let path = std::env::var("FELTDB_CRASH_PATH").unwrap();
224
+ let db = FeltDb::open(&path).unwrap();
225
+ db.insert("tasks:1", json!({"n": 42})).unwrap();
226
+ db.update("tasks:1", json!({"n": 43})).unwrap();
227
+ std::process::abort();
228
+ }
229
+
230
+ let directory = TempDir::new().unwrap();
231
+ let path = directory.path().join("abort.log");
232
+ let outcome = std::process::Command::new(std::env::current_exe().unwrap())
233
+ .args(["a_committed_write_survives_process_death", "--exact"])
234
+ .env("FELTDB_CRASH_CHILD", "1")
235
+ .env("FELTDB_CRASH_PATH", &path)
236
+ .output()
237
+ .expect("the child runs");
238
+ assert!(
239
+ !outcome.status.success(),
240
+ "the child must actually have died, not returned"
241
+ );
242
+
243
+ let db = Arc::new(FeltDb::open(&path).expect("the database opens after the abort"));
244
+ let recovered = inspect(&db);
245
+ assert_eq!(
246
+ recovered,
247
+ Recovered {
248
+ value: Some(43),
249
+ revisions: 2
250
+ },
251
+ "both writes and both revisions survived the process dying"
252
+ );
253
+ }
254
+
255
+ // ---------------------------------------------------------------------------
256
+ // D2 — transaction atomicity
257
+ // ---------------------------------------------------------------------------
258
+
259
+ /// **A transaction is all-or-nothing at every crash point.**
260
+ ///
261
+ /// A transaction is one durable record carrying every row it touches, so a
262
+ /// crash can only land before or after it. Never a subset.
263
+ #[test]
264
+ fn a_transaction_is_all_or_nothing_at_every_crash_point() {
265
+ let directory = TempDir::new().unwrap();
266
+ let path = directory.path().join("txn.log");
267
+ let db = Arc::new(FeltDb::open(&path).unwrap());
268
+ db.apply_atomic_transaction(
269
+ "t1",
270
+ None,
271
+ &[],
272
+ &[
273
+ AtomicMutation {
274
+ capability: "acct".into(),
275
+ key: "acct:a".into(),
276
+ value: Some(json!({"balance": 10})),
277
+ },
278
+ AtomicMutation {
279
+ capability: "acct".into(),
280
+ key: "acct:b".into(),
281
+ value: Some(json!({"balance": 20})),
282
+ },
283
+ AtomicMutation {
284
+ capability: "acct".into(),
285
+ key: "acct:c".into(),
286
+ value: Some(json!({"balance": 30})),
287
+ },
288
+ ],
289
+ None,
290
+ )
291
+ .expect("the transaction commits");
292
+ drop(db);
293
+ let full = std::fs::read(&path).unwrap();
294
+
295
+ let mut committed = 0;
296
+ let mut absent = 0;
297
+ for cut in 0..=full.len() {
298
+ std::fs::write(&path, &full[..cut]).unwrap();
299
+ let db = FeltDb::open(&path).unwrap();
300
+ let present: Vec<bool> = ["acct:a", "acct:b", "acct:c"]
301
+ .iter()
302
+ .map(|key| db.get::<Value>(key).unwrap().is_some())
303
+ .collect();
304
+ let count = present.iter().filter(|p| **p).count();
305
+ assert!(
306
+ count == 0 || count == 3,
307
+ "cut {cut}: a transaction left {count} of 3 rows — {present:?}"
308
+ );
309
+ if count == 3 {
310
+ committed += 1;
311
+ } else {
312
+ absent += 1;
313
+ }
314
+ }
315
+ assert!(committed > 0 && absent > 0, "both outcomes are reachable");
316
+ }
317
+
318
+ // ---------------------------------------------------------------------------
319
+ // Where durability meets replication
320
+ // ---------------------------------------------------------------------------
321
+
322
+ /// **A crash-recovered database replicates identically.**
323
+ ///
324
+ /// This is where durability, replay, history and replication meet. An authority
325
+ /// recovered from a crash must not hold a history that disagrees with what its
326
+ /// own operation stream produces on a peer — otherwise a crash silently forks
327
+ /// the historical record.
328
+ ///
329
+ /// Checked at every crash point, on both digests.
330
+ #[test]
331
+ fn a_crash_recovered_database_replicates_identically() {
332
+ let directory = TempDir::new().unwrap();
333
+ let path = directory.path().join("recovered.log");
334
+ let full = log_of_three_writes(&path);
335
+
336
+ for cut in (0..=full.len()).step_by(37) {
337
+ std::fs::write(&path, &full[..cut]).unwrap();
338
+ let origin = Arc::new(FeltDb::open(&path).unwrap());
339
+ let origin_store = StateStore::with_feltdb(origin.clone()).unwrap();
340
+
341
+ let peer_path = directory.path().join(format!("peer{cut}.log"));
342
+ let peer = Arc::new(FeltDb::open(&peer_path).unwrap());
343
+ for operation in origin.operations_since(&HashMap::new()).unwrap() {
344
+ peer.apply_remote_operation(operation)
345
+ .unwrap_or_else(|error| panic!("cut {cut}: replication failed: {error}"));
346
+ }
347
+ let peer_store = StateStore::with_feltdb(peer.clone()).unwrap();
348
+
349
+ assert_eq!(
350
+ peer.state_digest().unwrap(),
351
+ origin.state_digest().unwrap(),
352
+ "cut {cut}: state diverged"
353
+ );
354
+ assert_eq!(
355
+ peer_store.history_digest(),
356
+ origin_store.history_digest(),
357
+ "cut {cut}: a crash must not fork the historical record"
358
+ );
359
+ let _ = std::fs::remove_file(&peer_path);
360
+ }
361
+ }
362
+
363
+ /// A database recovered from a crash accepts writes and continues its history
364
+ /// without reusing a sequence.
365
+ #[test]
366
+ fn a_recovered_database_continues_its_history() {
367
+ let directory = TempDir::new().unwrap();
368
+ let path = directory.path().join("continue.log");
369
+ let full = log_of_three_writes(&path);
370
+
371
+ for cut in (0..=full.len()).step_by(53) {
372
+ std::fs::write(&path, &full[..cut]).unwrap();
373
+ let db = Arc::new(FeltDb::open(&path).unwrap());
374
+ let before = inspect(&db).revisions;
375
+ db.update("tasks:1", json!({"n": 99})).unwrap();
376
+
377
+ let store = StateStore::with_feltdb(db.clone()).unwrap();
378
+ let history = store.history_of("tasks:1");
379
+ assert_eq!(history.len(), before + 1, "cut {cut}");
380
+ let mut sequences: Vec<u64> = history.iter().map(|r| r.sequence).collect();
381
+ let count = sequences.len();
382
+ sequences.dedup();
383
+ assert_eq!(sequences.len(), count, "cut {cut}: a sequence was reused");
384
+ }
385
+ }
386
+
387
+ // ---------------------------------------------------------------------------
388
+ // D3 — the boundary this does not cross
389
+ // ---------------------------------------------------------------------------
390
+
391
+ /// **Single-record durability is flush, not fsync — and that is the claim.**
392
+ ///
393
+ /// A record reaches the file before the call returns, which is what makes
394
+ /// process-crash durability hold. It is **not** forced to stable storage, so
395
+ /// what survives an operating-system or power failure is not established by
396
+ /// anything here.
397
+ ///
398
+ /// This test asserts only what it can — that the bytes are visible outside the
399
+ /// process before success is reported — and deliberately makes no claim about
400
+ /// power loss. The readiness matrix records that as Unproven, and
401
+ /// `docs/architecture/crash-durability.md` states the boundary.
402
+ #[test]
403
+ fn a_write_is_durable_to_the_operating_system_before_it_returns() {
404
+ let directory = TempDir::new().unwrap();
405
+ let path = directory.path().join("visible.log");
406
+ let db = FeltDb::open(&path).unwrap();
407
+ db.insert("tasks:1", json!({"n": 7})).unwrap();
408
+
409
+ // Read the file behind the database's back, with it still open.
410
+ let log = std::fs::read_to_string(&path).unwrap();
411
+ assert!(
412
+ log.contains(r#""n":7"#),
413
+ "the record reached the file before the write returned"
414
+ );
415
+ assert!(
416
+ log.contains("state:revision:"),
417
+ "and so did the revision recording it"
418
+ );
419
+ }
420
+
421
+ /// An open that had to discard an incomplete final append says so, and a clean
422
+ /// one says that instead.
423
+ ///
424
+ /// Recovery being *visible* is what lets an operator tell "my database is fine"
425
+ /// from "my database is fine and my last write is gone".
426
+ #[test]
427
+ fn recovery_after_a_crash_is_reported_rather_than_silent() {
428
+ let directory = TempDir::new().unwrap();
429
+ let path = directory.path().join("reported.log");
430
+ let full = log_of_three_writes(&path);
431
+
432
+ // A cut inside the final record: recoverable, and reported.
433
+ std::fs::write(&path, &full[..full.len() - 20]).unwrap();
434
+ let db = FeltDb::open(&path).unwrap();
435
+ assert!(
436
+ !db.log_recovery().is_clean(),
437
+ "a crash-recovered open is not reported as clean"
438
+ );
439
+ drop(db);
440
+
441
+ // Reopening the repaired log is clean.
442
+ let db = FeltDb::open(&path).unwrap();
443
+ assert!(db.log_recovery().is_clean());
444
+ }
445
+
446
+ /// A crash cannot leave a database that refuses to open.
447
+ ///
448
+ /// Corruption refuses; an interrupted write recovers. This checks that a
449
+ /// truncated log — the only thing a crash can produce — always falls in the
450
+ /// second class.
451
+ #[test]
452
+ fn a_crash_never_produces_a_database_that_refuses_to_open() {
453
+ let directory = TempDir::new().unwrap();
454
+ let path = directory.path().join("openable.log");
455
+ let full = log_of_three_writes(&path);
456
+
457
+ for cut in 0..=full.len() {
458
+ std::fs::write(&path, &full[..cut]).unwrap();
459
+ match FeltDb::open(&path) {
460
+ Ok(_) => {}
461
+ Err(FlowError::CorruptLogLine(corruption)) => {
462
+ panic!("cut {cut} was treated as corruption: {corruption}")
463
+ }
464
+ Err(error) => panic!("cut {cut} failed to open: {error}"),
465
+ }
466
+ }
467
+ }
@@ -228,11 +228,32 @@ fn the_operation_log_retains_an_ordered_per_resource_history() {
228
228
  );
229
229
  }
230
230
 
231
- // But no operation names the state it descended from.
232
- let rendered = format!("{:?}", history);
233
- assert!(
234
- !rendered.contains("parent"),
235
- "an operation records what was done, not which state it descended from"
231
+ // **Superseded.** This assertion read, as a finding of this audit:
232
+ //
233
+ // no operation names the state it descended from
234
+ //
235
+ // That was true when the audit ran, and it is the reason a replica could
236
+ // reproduce current state and no history at all. Replicated revision
237
+ // history closed it: an operation now carries the revision it produced —
238
+ // resource, identity, parent, sequence, content identity and authority — so
239
+ // a peer can rebuild that revision rather than mint a local substitute.
240
+ //
241
+ // The finding is kept here inverted rather than deleted, because it is the
242
+ // exact thing that changed.
243
+ for operation in &history {
244
+ let provenance = operation
245
+ .revision
246
+ .as_ref()
247
+ .expect("an operation now names the revision it produced");
248
+ assert_eq!(provenance.resource, "accounts:3");
249
+ }
250
+ let first = history[0].revision.as_ref().unwrap();
251
+ let second = history[1].revision.as_ref().unwrap();
252
+ assert_eq!(first.parent_id, None, "the first began the history");
253
+ assert_eq!(
254
+ second.parent_id.as_deref(),
255
+ Some(first.id.as_str()),
256
+ "and each names the state it descended from"
236
257
  );
237
258
  }
238
259