@feltdb/core 0.8.5 → 0.8.7

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 (29) 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/common/mod.rs +96 -0
  8. package/dist/create/server-source/crates/feltdb/tests/compaction_stall_contract.rs +272 -0
  9. package/dist/create/server-source/crates/feltdb/tests/crash_durability_contract.rs +467 -0
  10. package/dist/create/server-source/crates/feltdb/tests/current_revision_authority_evidence.rs +26 -5
  11. package/dist/create/server-source/crates/feltdb/tests/durable_backup_contract.rs +445 -0
  12. package/dist/create/server-source/crates/feltdb/tests/durable_corruption_contract.rs +518 -0
  13. package/dist/create/server-source/crates/feltdb/tests/managed_incident_regression.rs +191 -0
  14. package/dist/create/server-source/crates/feltdb/tests/operational_health_contract.rs +278 -0
  15. package/dist/create/server-source/crates/feltdb/tests/production_certification.rs +1153 -0
  16. package/dist/create/server-source/crates/feltdb/tests/production_contract.rs +771 -0
  17. package/dist/create/server-source/crates/feltdb/tests/production_readiness_contract.rs +490 -157
  18. package/dist/create/server-source/crates/feltdb/tests/replicated_history_contract.rs +417 -0
  19. package/dist/create/server-source/crates/feltdb/tests/workload_envelope_contract.rs +442 -0
  20. package/dist/create/server-source/crates/feltdb-server/src/app_state.rs +14 -0
  21. package/dist/create/server-source/crates/feltdb-server/src/main.rs +369 -41
  22. package/dist/create/server-source/crates/feltdb-server/src/metrics.rs +21 -0
  23. package/dist/studio-app/assets/{feltdb_wasm-DaNwCLRX.js → feltdb_wasm-C1VhI-U5.js} +1 -1
  24. package/dist/studio-app/assets/feltdb_wasm_bg-C8HXbAXb.wasm +0 -0
  25. package/dist/studio-app/assets/{index-j8IlhNqJ.js → index-Bbos1m2U.js} +1 -1
  26. package/dist/studio-app/index.html +1 -1
  27. package/dist/wasm/feltdb_wasm_bg.wasm +0 -0
  28. package/package.json +1 -1
  29. package/dist/studio-app/assets/feltdb_wasm_bg-DnsHNv6g.wasm +0 -0
@@ -0,0 +1,518 @@
1
+ //! Corruption detection and fail-closed recovery.
2
+ //!
3
+ //! The invariant this file enforces:
4
+ //!
5
+ //! > **A database open may recover from a documented, provably incomplete final
6
+ //! > write, but it must never silently discard bytes that could represent a
7
+ //! > committed durable record.**
8
+ //!
9
+ //! Three classes, and the boundary between them is the whole subject:
10
+ //!
11
+ //! | condition | behaviour |
12
+ //! | --- | --- |
13
+ //! | valid complete record | replayed |
14
+ //! | final record with **no terminator** | discarded, and the recovery is reported |
15
+ //! | anything else invalid, anywhere | **open refused** |
16
+ //!
17
+ //! The dangerous idea this rejects is that "last line" means "safe to discard".
18
+ //! A *complete* record that is invalid is corruption wherever it sits, and
19
+ //! treating it as a torn write would convert a disk fault into apparently
20
+ //! successful data loss merely because it happened at the end of the file.
21
+ //!
22
+ //! See `docs/architecture/durable-corruption.md`.
23
+
24
+ use feltdb::{FeltDb, FlowError, LogRecovery};
25
+ use serde_json::{json, Value};
26
+ use std::io::Write;
27
+ use std::path::Path;
28
+ use tempfile::TempDir;
29
+
30
+ fn format_record() -> String {
31
+ json!({"record_type": "feltdb.format.v1", "format_version": feltdb::DURABLE_FORMAT_VERSION})
32
+ .to_string()
33
+ }
34
+
35
+ fn row(key: &str, n: i64) -> String {
36
+ json!({
37
+ "capability": key.split(':').next().unwrap(),
38
+ "key": key,
39
+ "rust_type": "serde_json::value::Value",
40
+ "value": {"n": n},
41
+ "unix_ms": 1,
42
+ "content_hash": null,
43
+ "flow_ref": null,
44
+ "deleted": false,
45
+ "operation": null
46
+ })
47
+ .to_string()
48
+ }
49
+
50
+ /// A transaction as the log stores it: **one record carrying all its rows**.
51
+ fn transaction(id: &str, keys: &[(&str, i64)], revision: u64) -> String {
52
+ let rows: Vec<Value> = keys
53
+ .iter()
54
+ .map(|(key, n)| serde_json::from_str::<Value>(&row(key, *n)).unwrap())
55
+ .collect();
56
+ json!({
57
+ "record_type": "feltdb.transaction.v1",
58
+ "transaction_id": id,
59
+ "payload_hash": null,
60
+ "state_before": revision,
61
+ "state_after": revision + 1,
62
+ "base_revision": revision,
63
+ "commit_revision": revision + 1,
64
+ "rows": rows,
65
+ "audit": null
66
+ })
67
+ .to_string()
68
+ }
69
+
70
+ /// Write a log verbatim. `terminate_last` controls whether the final record
71
+ /// gets its newline — the difference between a finished append and a torn one.
72
+ fn write_log(path: &Path, records: &[String], terminate_last: bool) {
73
+ let mut file = std::fs::File::create(path).unwrap();
74
+ for (index, record) in records.iter().enumerate() {
75
+ if index + 1 == records.len() && !terminate_last {
76
+ write!(file, "{record}").unwrap();
77
+ } else {
78
+ writeln!(file, "{record}").unwrap();
79
+ }
80
+ }
81
+ }
82
+
83
+ fn present(db: &FeltDb, key: &str) -> bool {
84
+ db.get::<Value>(key).unwrap().is_some()
85
+ }
86
+
87
+ /// Open, and assert the durable bytes are unchanged whatever the outcome.
88
+ fn open_without_touching(path: &Path) -> Result<FeltDb, FlowError> {
89
+ let before = std::fs::read(path).unwrap();
90
+ let outcome = FeltDb::open(path);
91
+ if outcome.is_err() {
92
+ assert_eq!(
93
+ std::fs::read(path).unwrap(),
94
+ before,
95
+ "a refused open must leave the database byte-identical"
96
+ );
97
+ }
98
+ outcome
99
+ }
100
+
101
+ fn expect_corrupt(path: &Path) -> feltdb::LogCorruption {
102
+ match open_without_touching(path) {
103
+ Err(FlowError::CorruptLogLine(corruption)) => *corruption,
104
+ Err(other) => panic!("expected corruption, got {other}"),
105
+ Ok(_) => panic!("the corrupt database opened — this is the defect"),
106
+ }
107
+ }
108
+
109
+ // ---------------------------------------------------------------------------
110
+ // C1 — a clean log
111
+ // ---------------------------------------------------------------------------
112
+
113
+ /// A valid log replays completely and reports that it did.
114
+ #[test]
115
+ fn a_clean_log_replays_completely_and_reports_clean() {
116
+ let directory = TempDir::new().unwrap();
117
+ let path = directory.path().join("clean.log");
118
+ let db = FeltDb::open(&path).unwrap();
119
+ for n in 1..=3 {
120
+ db.insert(&format!("tasks:{n}"), json!({ "n": n })).unwrap();
121
+ }
122
+ drop(db);
123
+
124
+ let before = std::fs::read(&path).unwrap();
125
+ let reopened = FeltDb::open(&path).unwrap();
126
+ for n in 1..=3 {
127
+ assert!(present(&reopened, &format!("tasks:{n}")));
128
+ }
129
+ assert_eq!(reopened.log_recovery(), LogRecovery::Clean);
130
+ assert!(reopened.log_recovery().is_clean());
131
+ assert_eq!(
132
+ std::fs::read(&path).unwrap(),
133
+ before,
134
+ "a clean open changes nothing"
135
+ );
136
+ }
137
+
138
+ // ---------------------------------------------------------------------------
139
+ // C2 / C7 / C8 — the one thing that may be discarded
140
+ // ---------------------------------------------------------------------------
141
+
142
+ /// An unterminated final record is a torn append: discarded, and **reported**.
143
+ ///
144
+ /// This is the only condition under which durable bytes are dropped. The
145
+ /// database is usable; its last write did not land; and the difference between
146
+ /// that and a clean open survives past an internal debug message.
147
+ #[test]
148
+ fn an_unterminated_final_record_is_recovered_and_reported() {
149
+ let directory = TempDir::new().unwrap();
150
+ let path = directory.path().join("torn.log");
151
+ write_log(
152
+ &path,
153
+ &[
154
+ format_record(),
155
+ row("tasks:1", 1),
156
+ row("tasks:2", 2),
157
+ row("tasks:3", 3),
158
+ ],
159
+ false,
160
+ );
161
+ let torn_offset = std::fs::read_to_string(&path)
162
+ .unwrap()
163
+ .rfind(&row("tasks:3", 3))
164
+ .unwrap() as u64;
165
+
166
+ let db = FeltDb::open(&path).unwrap();
167
+
168
+ // Everything committed before it is intact.
169
+ assert!(present(&db, "tasks:1"));
170
+ assert!(present(&db, "tasks:2"));
171
+ // The incomplete record was not replayed.
172
+ assert!(!present(&db, "tasks:3"));
173
+
174
+ // C7: the recovery is observable, with a location.
175
+ match db.log_recovery() {
176
+ LogRecovery::RecoveredTornTail {
177
+ byte_offset,
178
+ discarded_bytes,
179
+ } => {
180
+ assert_eq!(byte_offset, torn_offset);
181
+ assert!(discarded_bytes > 0);
182
+ }
183
+ other => panic!("expected a reported torn-tail recovery, got {other}"),
184
+ }
185
+
186
+ // C8: and it is distinguishable from a clean open, which is the fact the
187
+ // health contract will later need.
188
+ assert!(
189
+ !db.log_recovery().is_clean(),
190
+ "an open that discarded data must not look clean"
191
+ );
192
+ }
193
+
194
+ /// A partially written record is discarded whole, not half-applied.
195
+ #[test]
196
+ fn a_partial_final_record_is_discarded_whole() {
197
+ let directory = TempDir::new().unwrap();
198
+ let path = directory.path().join("partial.log");
199
+ let complete = row("tasks:3", 3);
200
+ let half = complete[..complete.len() / 2].to_string();
201
+ write_log(
202
+ &path,
203
+ &[format_record(), row("tasks:1", 1), row("tasks:2", 2), half],
204
+ false,
205
+ );
206
+
207
+ let db = FeltDb::open(&path).unwrap();
208
+ assert!(present(&db, "tasks:1"));
209
+ assert!(present(&db, "tasks:2"));
210
+ assert!(!present(&db, "tasks:3"));
211
+ assert!(!db.log_recovery().is_clean());
212
+ }
213
+
214
+ /// After a torn tail is discarded, the log is a valid database again and the
215
+ /// next open is clean.
216
+ ///
217
+ /// This is why the truncation happens: without it the next append would splice
218
+ /// onto a partial record and turn a recoverable torn write into permanent
219
+ /// corruption. It is a repair, and it is reported rather than silent.
220
+ #[test]
221
+ fn a_recovered_log_reopens_cleanly_and_accepts_writes() {
222
+ let directory = TempDir::new().unwrap();
223
+ let path = directory.path().join("reopen.log");
224
+ let complete = row("tasks:3", 3);
225
+ write_log(
226
+ &path,
227
+ &[
228
+ format_record(),
229
+ row("tasks:1", 1),
230
+ complete[..complete.len() / 2].to_string(),
231
+ ],
232
+ false,
233
+ );
234
+
235
+ let db = FeltDb::open(&path).unwrap();
236
+ assert!(!db.log_recovery().is_clean());
237
+ db.insert("tasks:9", json!({"n": 9})).unwrap();
238
+ drop(db);
239
+
240
+ let reopened = FeltDb::open(&path).unwrap();
241
+ assert_eq!(
242
+ reopened.log_recovery(),
243
+ LogRecovery::Clean,
244
+ "the repair leaves a clean log behind it"
245
+ );
246
+ assert!(present(&reopened, "tasks:1"));
247
+ assert!(present(&reopened, "tasks:9"));
248
+ }
249
+
250
+ // ---------------------------------------------------------------------------
251
+ // C3 — a complete final record is never "safe to discard"
252
+ // ---------------------------------------------------------------------------
253
+
254
+ /// **The dangerous case.** A terminated final line containing invalid data is
255
+ /// corruption, not a torn write.
256
+ ///
257
+ /// It was silently dropped before, which converted a disk fault at end-of-file
258
+ /// into an apparently successful open with data missing. Position in the file
259
+ /// is not evidence about whether a record was finished — the **terminator** is.
260
+ #[test]
261
+ fn a_complete_but_invalid_final_record_refuses_the_open() {
262
+ let directory = TempDir::new().unwrap();
263
+ let path = directory.path().join("eof-garbage.log");
264
+ write_log(
265
+ &path,
266
+ &[
267
+ format_record(),
268
+ row("tasks:1", 1),
269
+ row("tasks:2", 2),
270
+ "{not valid json}".to_string(),
271
+ ],
272
+ true,
273
+ );
274
+
275
+ let corruption = expect_corrupt(&path);
276
+ assert_eq!(corruption.line_number, 4);
277
+ assert!(corruption.reason.contains("not valid JSON"));
278
+ }
279
+
280
+ /// The same, for a final record that is valid JSON and not a durable record.
281
+ #[test]
282
+ fn a_complete_final_record_of_the_wrong_shape_refuses_the_open() {
283
+ let directory = TempDir::new().unwrap();
284
+ let path = directory.path().join("eof-shape.log");
285
+ write_log(
286
+ &path,
287
+ &[
288
+ format_record(),
289
+ row("tasks:1", 1),
290
+ json!({"hello": "world"}).to_string(),
291
+ ],
292
+ true,
293
+ );
294
+
295
+ let corruption = expect_corrupt(&path);
296
+ assert_eq!(corruption.line_number, 3);
297
+ assert!(corruption.reason.contains("durable record"));
298
+ }
299
+
300
+ // ---------------------------------------------------------------------------
301
+ // C4 / C5 — corruption anywhere else
302
+ // ---------------------------------------------------------------------------
303
+
304
+ /// Corruption in the middle refuses the open. It never replays what surrounds
305
+ /// it and skips the damage.
306
+ #[test]
307
+ fn corruption_in_the_middle_refuses_the_open() {
308
+ let directory = TempDir::new().unwrap();
309
+ let path = directory.path().join("middle.log");
310
+ write_log(
311
+ &path,
312
+ &[
313
+ format_record(),
314
+ row("tasks:1", 1),
315
+ "{not valid json}".to_string(),
316
+ row("tasks:3", 3),
317
+ ],
318
+ true,
319
+ );
320
+
321
+ let corruption = expect_corrupt(&path);
322
+ assert_eq!(corruption.line_number, 3, "the damage is located");
323
+ assert!(corruption.byte_offset > 0);
324
+ assert!(corruption.excerpt.contains("not valid json"));
325
+ }
326
+
327
+ /// **Semantic corruption**, which is the more important half: records that
328
+ /// parse as JSON but are not valid durable records.
329
+ #[test]
330
+ fn semantically_invalid_records_refuse_the_open() {
331
+ let cases: Vec<(&str, String)> = vec![
332
+ (
333
+ "missing required fields",
334
+ json!({"capability": "tasks", "key": "tasks:2", "value": {"n": 2}}).to_string(),
335
+ ),
336
+ (
337
+ "a record kind this build does not know",
338
+ json!({"record_type": "feltdb.something.v9", "payload": 1}).to_string(),
339
+ ),
340
+ (
341
+ "a row whose value field is absent",
342
+ json!({
343
+ "capability": "tasks", "key": "tasks:2",
344
+ "rust_type": "serde_json::value::Value",
345
+ "unix_ms": 1, "content_hash": null, "flow_ref": null,
346
+ "deleted": false, "operation": null
347
+ })
348
+ .to_string(),
349
+ ),
350
+ ];
351
+
352
+ for (label, damaged) in cases {
353
+ let directory = TempDir::new().unwrap();
354
+ let path = directory.path().join("semantic.log");
355
+ write_log(
356
+ &path,
357
+ &[
358
+ format_record(),
359
+ row("tasks:1", 1),
360
+ damaged,
361
+ row("tasks:3", 3),
362
+ ],
363
+ true,
364
+ );
365
+ let corruption = expect_corrupt(&path);
366
+ assert_eq!(corruption.line_number, 3, "{label}");
367
+ }
368
+ }
369
+
370
+ // ---------------------------------------------------------------------------
371
+ // C6 — refusal is never destructive
372
+ // ---------------------------------------------------------------------------
373
+
374
+ /// **A refused open does not repair the database on its way out.**
375
+ ///
376
+ /// The decisive case is a log with *both* a torn tail and corruption earlier in
377
+ /// it. Truncating the tail is legitimate only when the rest of the log replayed;
378
+ /// doing it before discovering the corruption would mean a database that
379
+ /// refuses to open has still been modified by the attempt.
380
+ #[test]
381
+ fn a_refused_open_does_not_truncate_a_torn_tail() {
382
+ let directory = TempDir::new().unwrap();
383
+ let path = directory.path().join("both.log");
384
+ let complete = row("tasks:9", 9);
385
+ write_log(
386
+ &path,
387
+ &[
388
+ format_record(),
389
+ row("tasks:1", 1),
390
+ "{not valid json}".to_string(),
391
+ complete[..complete.len() / 2].to_string(),
392
+ ],
393
+ false,
394
+ );
395
+ let before = std::fs::read(&path).unwrap();
396
+
397
+ let corruption = expect_corrupt(&path);
398
+ assert_eq!(corruption.line_number, 3);
399
+ assert_eq!(
400
+ std::fs::read(&path).unwrap(),
401
+ before,
402
+ "the torn tail was not truncated by a refused open"
403
+ );
404
+ }
405
+
406
+ /// Format inspection is read-only too, even on a database with a torn tail.
407
+ ///
408
+ /// This closes a hole in the format-versioning work: inspection shares the log
409
+ /// reader, and a reader that repaired as it went would have made the
410
+ /// byte-identical guarantee conditional on the file having no torn tail.
411
+ #[test]
412
+ fn format_inspection_does_not_modify_a_torn_log() {
413
+ let directory = TempDir::new().unwrap();
414
+ let path = directory.path().join("inspect.log");
415
+ let complete = row("tasks:2", 2);
416
+ write_log(
417
+ &path,
418
+ &[
419
+ format_record(),
420
+ row("tasks:1", 1),
421
+ complete[..complete.len() / 2].to_string(),
422
+ ],
423
+ false,
424
+ );
425
+ let before = std::fs::read(&path).unwrap();
426
+
427
+ let compatibility = feltdb::inspect_durable_format(&path).unwrap();
428
+ assert!(compatibility.is_compatible());
429
+ assert_eq!(
430
+ std::fs::read(&path).unwrap(),
431
+ before,
432
+ "inspecting a database must never modify it"
433
+ );
434
+ }
435
+
436
+ // ---------------------------------------------------------------------------
437
+ // C10 — transaction boundaries
438
+ // ---------------------------------------------------------------------------
439
+
440
+ /// A transaction is **one durable record**, so a torn transaction is discarded
441
+ /// whole and none of its mutations is exposed.
442
+ ///
443
+ /// This result derives from the existing commit protocol rather than being
444
+ /// invented here: `append_transaction` writes the whole transaction — every row
445
+ /// and its commit revision — as a single line, before any in-memory state
446
+ /// changes. There is no window in which some of a transaction's rows are
447
+ /// durable and the rest are not.
448
+ #[test]
449
+ fn a_torn_transaction_exposes_none_of_its_mutations() {
450
+ let directory = TempDir::new().unwrap();
451
+ let path = directory.path().join("torn-txn.log");
452
+ let committed = transaction("t1", &[("tasks:1", 1), ("tasks:2", 2)], 0);
453
+ let torn = transaction("t2", &[("tasks:3", 3), ("tasks:4", 4)], 1);
454
+
455
+ write_log(
456
+ &path,
457
+ &[
458
+ format_record(),
459
+ committed,
460
+ torn[..torn.len() / 2].to_string(),
461
+ ],
462
+ false,
463
+ );
464
+
465
+ let db = FeltDb::open(&path).unwrap();
466
+ assert!(present(&db, "tasks:1"), "the committed transaction applied");
467
+ assert!(present(&db, "tasks:2"));
468
+ assert!(
469
+ !present(&db, "tasks:3") && !present(&db, "tasks:4"),
470
+ "the torn transaction applied none of its rows — not even the first"
471
+ );
472
+ assert!(!db.log_recovery().is_clean());
473
+ }
474
+
475
+ /// A complete transaction followed by a torn ordinary record keeps the
476
+ /// transaction and drops only the record.
477
+ #[test]
478
+ fn a_complete_transaction_survives_a_torn_record_after_it() {
479
+ let directory = TempDir::new().unwrap();
480
+ let path = directory.path().join("txn-then-torn.log");
481
+ let committed = transaction("t1", &[("tasks:1", 1), ("tasks:2", 2)], 0);
482
+ let trailing = row("tasks:5", 5);
483
+
484
+ write_log(
485
+ &path,
486
+ &[
487
+ format_record(),
488
+ committed,
489
+ trailing[..trailing.len() / 2].to_string(),
490
+ ],
491
+ false,
492
+ );
493
+
494
+ let db = FeltDb::open(&path).unwrap();
495
+ assert!(present(&db, "tasks:1"));
496
+ assert!(present(&db, "tasks:2"));
497
+ assert!(!present(&db, "tasks:5"));
498
+ }
499
+
500
+ /// A **complete** but malformed transaction record refuses the open, exactly
501
+ /// like any other complete invalid record.
502
+ #[test]
503
+ fn a_malformed_complete_transaction_refuses_the_open() {
504
+ let directory = TempDir::new().unwrap();
505
+ let path = directory.path().join("bad-txn.log");
506
+ write_log(
507
+ &path,
508
+ &[
509
+ format_record(),
510
+ row("tasks:1", 1),
511
+ json!({"record_type": "feltdb.transaction.v1", "transaction_id": "t1"}).to_string(),
512
+ ],
513
+ true,
514
+ );
515
+
516
+ let corruption = expect_corrupt(&path);
517
+ assert_eq!(corruption.line_number, 3);
518
+ }