@feltdb/core 0.8.3 → 0.8.4

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 (59) hide show
  1. package/dist/cli/commands.js +4 -1
  2. package/dist/cli/provisioning-neutrality.js +79 -0
  3. package/dist/collection.d.ts +43 -1
  4. package/dist/collection.d.ts.map +1 -1
  5. package/dist/collection.js +192 -22
  6. package/dist/create/create.js +25 -21
  7. package/dist/create/managed-account.js +11 -0
  8. package/dist/create/package-versions.js +1 -1
  9. package/dist/create/server-source/crates/feltdb/src/equality_index.rs +595 -0
  10. package/dist/create/server-source/crates/feltdb/src/lib.rs +547 -115
  11. package/dist/create/server-source/crates/feltdb/src/phase1c3_acceptance.rs +11 -2
  12. package/dist/create/server-source/crates/feltdb/src/query_execution_diagnostics.rs +126 -0
  13. package/dist/create/server-source/crates/feltdb/src/state_contract.rs +292 -2
  14. package/dist/create/server-source/crates/feltdb/src/sync.rs +12 -0
  15. package/dist/create/server-source/crates/feltdb/src/workload_diagnostics.rs +443 -0
  16. package/dist/create/server-source/crates/feltdb/tests/pr34_query_collection.rs +233 -0
  17. package/dist/create/server-source/crates/feltdb/tests/pr35_equality_index.rs +892 -0
  18. package/dist/create/server-source/crates/feltdb-server/src/audit.rs +1137 -29
  19. package/dist/create/server-source/crates/feltdb-server/src/main.rs +474 -28
  20. package/dist/db.d.ts +33 -34
  21. package/dist/db.d.ts.map +1 -1
  22. package/dist/db.js +74 -20
  23. package/dist/deployment.d.ts +30 -0
  24. package/dist/deployment.d.ts.map +1 -0
  25. package/dist/deployment.js +130 -0
  26. package/dist/embedded-transaction.d.ts +22 -4
  27. package/dist/embedded-transaction.d.ts.map +1 -1
  28. package/dist/embedded-transaction.js +51 -5
  29. package/dist/feltdb.d.ts +14 -2
  30. package/dist/feltdb.d.ts.map +1 -1
  31. package/dist/file-db.js +1 -1
  32. package/dist/http-client.d.ts +14 -0
  33. package/dist/http-client.d.ts.map +1 -1
  34. package/dist/http-client.js +23 -5
  35. package/dist/http-db.d.ts +119 -1
  36. package/dist/http-db.d.ts.map +1 -1
  37. package/dist/http-db.js +346 -31
  38. package/dist/index-core.d.ts +2 -0
  39. package/dist/index-core.d.ts.map +1 -1
  40. package/dist/index-core.js +2 -0
  41. package/dist/index.d.ts.map +1 -1
  42. package/dist/index.js +9 -0
  43. package/dist/indexeddb-db.d.ts.map +1 -1
  44. package/dist/indexeddb-db.js +35 -21
  45. package/dist/managed-recovery.d.ts +192 -0
  46. package/dist/managed-recovery.d.ts.map +1 -0
  47. package/dist/managed-recovery.js +242 -0
  48. package/dist/memory-db.js +1 -1
  49. package/dist/studio-app/assets/{feltdb_wasm-DB8cX151.js → feltdb_wasm-CVQWgXO-.js} +1 -1
  50. package/dist/studio-app/assets/feltdb_wasm_bg-CNVpvaZV.wasm +0 -0
  51. package/dist/studio-app/assets/index-DwgNAIIX.js +29 -0
  52. package/dist/studio-app/index.html +1 -1
  53. package/dist/transaction.d.ts +30 -0
  54. package/dist/transaction.d.ts.map +1 -1
  55. package/dist/transaction.js +41 -0
  56. package/dist/wasm/feltdb_wasm_bg.wasm +0 -0
  57. package/package.json +1 -1
  58. package/dist/studio-app/assets/feltdb_wasm_bg-ClhDHp0S.wasm +0 -0
  59. package/dist/studio-app/assets/index-B0k4UAlI.js +0 -29
@@ -0,0 +1,892 @@
1
+ //! PR35 — deterministic equality index over authoritative state.
2
+ //!
3
+ //! PR34 removed whole-collection *materialization* from bounded query
4
+ //! execution. What it left behind was still `O(N)`: the conjunction had to be
5
+ //! evaluated against every record of the collection. PR35 adds an equality index
6
+ //! so an applicable query can reach its candidates directly.
7
+ //!
8
+ //! An index is only ever an optimization, which makes correctness the whole
9
+ //! difficulty: a faster query that answers differently is not a faster query, it
10
+ //! is a bug. These tests are therefore organized around the four claims that
11
+ //! have to hold before performance is worth measuring at all.
12
+ //!
13
+ //! 1. **Maintenance.** After every mutation class — insert, update, delete,
14
+ //! CAS accepted and CAS refused, transaction committed and transaction
15
+ //! refused — the live index equals one rebuilt from authoritative state.
16
+ //! `verify_equality_index` performs exactly that comparison, so these
17
+ //! assertions are against the records, not against a second copy of the
18
+ //! index's own bookkeeping.
19
+ //! 2. **Candidate selection, not answers.** A lookup returns record keys. The
20
+ //! predicate still decides.
21
+ //! 3. **Recovery.** Reopening the log and re-declaring the index reproduces
22
+ //! the index exactly, because a rebuild is the only way an index is ever
23
+ //! populated.
24
+ //! 4. **Values.** Strings, numbers, booleans, explicit nulls and missing
25
+ //! fields stay distinguishable, and unindexable values are excluded rather
26
+ //! than coerced.
27
+
28
+ use feltdb::{AtomicMutation, FeltDb, RecordPrecondition, StoredRow};
29
+ use serde_json::{json, Value};
30
+ use std::collections::BTreeMap;
31
+ use tempfile::TempDir;
32
+
33
+ type IndexSnapshot = BTreeMap<String, BTreeMap<String, BTreeMap<String, Vec<String>>>>;
34
+
35
+ fn database() -> (TempDir, FeltDb) {
36
+ let directory = TempDir::new().expect("temp dir");
37
+ let db = FeltDb::open(directory.path().join("pr35.log")).expect("open db");
38
+ (directory, db)
39
+ }
40
+
41
+ /// A database with `status` and `tenantId` indexed on `items`.
42
+ fn indexed() -> (TempDir, FeltDb) {
43
+ let (directory, db) = database();
44
+ db.create_equality_index("items", "status").expect("declare");
45
+ db.create_equality_index("items", "tenantId")
46
+ .expect("declare");
47
+ (directory, db)
48
+ }
49
+
50
+ /// The invariant every mutation must preserve: the maintained index is exactly
51
+ /// what authoritative state derives.
52
+ #[track_caller]
53
+ fn assert_index_matches_state(db: &FeltDb, after: &str) {
54
+ match db.verify_equality_index().expect("verify") {
55
+ Ok(()) => {}
56
+ Err(divergence) => panic!("index diverged from authoritative state after {after}: {divergence}"),
57
+ }
58
+ }
59
+
60
+ fn candidates(db: &FeltDb, field: &str, value: Value) -> Option<Vec<String>> {
61
+ db.equality_index_candidates("items", field, &value)
62
+ .expect("lookup")
63
+ }
64
+
65
+ /// Candidate keys for a value the index can answer, as record ids.
66
+ fn ids(db: &FeltDb, field: &str, value: Value) -> Vec<String> {
67
+ candidates(db, field, value)
68
+ .expect("the field is indexed and the value is indexable")
69
+ .into_iter()
70
+ .map(|key| key.split_once(':').map(|(_, id)| id.to_string()).unwrap_or(key))
71
+ .collect()
72
+ }
73
+
74
+ fn put(db: &FeltDb, id: &str, value: Value) {
75
+ db.insert(&format!("items:{id}"), &value).expect("insert");
76
+ }
77
+
78
+ fn snapshot(db: &FeltDb) -> IndexSnapshot {
79
+ db.equality_index_snapshot().expect("snapshot")
80
+ }
81
+
82
+ // ---------------------------------------------------------------------------
83
+ // Basic indexing
84
+ // ---------------------------------------------------------------------------
85
+
86
+ #[test]
87
+ fn one_indexed_record_is_reachable_by_its_value() {
88
+ let (_directory, db) = indexed();
89
+ put(&db, "a", json!({ "status": "active" }));
90
+
91
+ assert_eq!(ids(&db, "status", json!("active")), vec!["a".to_string()]);
92
+ assert_index_matches_state(&db, "one insert");
93
+ }
94
+
95
+ #[test]
96
+ fn records_sharing_a_value_share_a_bucket_and_different_values_do_not() {
97
+ let (_directory, db) = indexed();
98
+ put(&db, "a", json!({ "status": "active" }));
99
+ put(&db, "b", json!({ "status": "active" }));
100
+ put(&db, "c", json!({ "status": "archived" }));
101
+
102
+ assert_eq!(
103
+ ids(&db, "status", json!("active")),
104
+ vec!["a".to_string(), "b".to_string()],
105
+ );
106
+ assert_eq!(ids(&db, "status", json!("archived")), vec!["c".to_string()]);
107
+ assert!(
108
+ ids(&db, "status", json!("nobody-holds-this")).is_empty(),
109
+ "a value no record holds is an empty answer, not an inapplicable index",
110
+ );
111
+ assert_index_matches_state(&db, "inserts across several values");
112
+ }
113
+
114
+ #[test]
115
+ fn an_unindexed_field_is_inapplicable_rather_than_empty() {
116
+ let (_directory, db) = indexed();
117
+ put(&db, "a", json!({ "status": "active", "role": "admin" }));
118
+
119
+ assert_eq!(
120
+ candidates(&db, "role", json!("admin")),
121
+ None,
122
+ "an unindexed field must report that the index cannot answer, so execution falls back",
123
+ );
124
+ assert_eq!(
125
+ candidates(&db, "status", json!("nobody")),
126
+ Some(Vec::new()),
127
+ "an indexed field with no holder answers emptily, which is a different thing",
128
+ );
129
+ }
130
+
131
+ // ---------------------------------------------------------------------------
132
+ // Updates
133
+ // ---------------------------------------------------------------------------
134
+
135
+ #[test]
136
+ fn changing_an_indexed_field_moves_the_record_between_buckets() {
137
+ let (_directory, db) = indexed();
138
+ put(&db, "a", json!({ "status": "active" }));
139
+ db.update("items:a", &json!({ "status": "archived" }))
140
+ .expect("update");
141
+
142
+ assert!(
143
+ ids(&db, "status", json!("active")).is_empty(),
144
+ "the old value must not retain the record",
145
+ );
146
+ assert_eq!(ids(&db, "status", json!("archived")), vec!["a".to_string()]);
147
+ assert_index_matches_state(&db, "an indexed field changing");
148
+ }
149
+
150
+ #[test]
151
+ fn an_update_that_leaves_the_indexed_field_alone_leaves_the_index_alone() {
152
+ let (_directory, db) = indexed();
153
+ put(&db, "a", json!({ "status": "active", "note": "before" }));
154
+ let before = snapshot(&db);
155
+ db.update("items:a", &json!({ "status": "active", "note": "after" }))
156
+ .expect("update");
157
+
158
+ assert_eq!(snapshot(&db), before, "an unrelated field change is invisible to the index");
159
+ assert_index_matches_state(&db, "an unrelated field changing");
160
+ }
161
+
162
+ #[test]
163
+ fn removing_and_adding_an_indexed_field_adds_and_removes_the_entry() {
164
+ let (_directory, db) = indexed();
165
+ put(&db, "a", json!({ "status": "active" }));
166
+ db.update("items:a", &json!({ "note": "the status is gone" }))
167
+ .expect("update");
168
+
169
+ assert!(
170
+ ids(&db, "status", json!("active")).is_empty(),
171
+ "a record that no longer holds the field holds no entry for it",
172
+ );
173
+ assert_index_matches_state(&db, "an indexed field being removed");
174
+
175
+ db.update("items:a", &json!({ "note": "back", "status": "active" }))
176
+ .expect("update");
177
+ assert_eq!(ids(&db, "status", json!("active")), vec!["a".to_string()]);
178
+ assert_index_matches_state(&db, "an indexed field being added");
179
+ }
180
+
181
+ // ---------------------------------------------------------------------------
182
+ // Deletes
183
+ // ---------------------------------------------------------------------------
184
+
185
+ #[test]
186
+ fn deleting_records_empties_buckets_and_deleting_the_last_one_removes_it() {
187
+ let (_directory, db) = indexed();
188
+ put(&db, "a", json!({ "status": "active" }));
189
+ put(&db, "b", json!({ "status": "active" }));
190
+
191
+ db.delete("items:a").expect("delete");
192
+ assert_eq!(
193
+ ids(&db, "status", json!("active")),
194
+ vec!["b".to_string()],
195
+ "deleting one holder leaves the others",
196
+ );
197
+ assert_index_matches_state(&db, "deleting one of several holders");
198
+
199
+ db.delete("items:b").expect("delete");
200
+ assert!(ids(&db, "status", json!("active")).is_empty());
201
+ assert_eq!(
202
+ db.equality_index_stats().expect("stats").value_buckets,
203
+ 0,
204
+ "an emptied bucket is absent, which is the representation a rebuild produces",
205
+ );
206
+ assert_index_matches_state(&db, "deleting the final holder of a value");
207
+ }
208
+
209
+ // ---------------------------------------------------------------------------
210
+ // Values
211
+ // ---------------------------------------------------------------------------
212
+
213
+ #[test]
214
+ fn distinguishable_values_stay_distinguishable() {
215
+ let (_directory, db) = indexed();
216
+ let values = [
217
+ ("null", json!(null)),
218
+ ("true", json!(true)),
219
+ ("false", json!(false)),
220
+ ("zero", json!(0)),
221
+ ("one", json!(1)),
222
+ ("zero-text", json!("0")),
223
+ ("one-text", json!("1")),
224
+ ("forty-two", json!(42)),
225
+ ("forty-two-text", json!("42")),
226
+ ("true-text", json!("true")),
227
+ ("empty-text", json!("")),
228
+ ];
229
+ for (id, value) in &values {
230
+ put(&db, id, json!({ "status": value }));
231
+ }
232
+
233
+ for (id, value) in &values {
234
+ assert_eq!(
235
+ ids(&db, "status", value.clone()),
236
+ vec![id.to_string()],
237
+ "{value} must reach exactly the record holding it",
238
+ );
239
+ }
240
+ assert_index_matches_state(&db, "records covering every scalar kind");
241
+ }
242
+
243
+ #[test]
244
+ fn a_missing_field_is_not_an_explicit_null() {
245
+ let (_directory, db) = indexed();
246
+ put(&db, "explicit", json!({ "status": null }));
247
+ put(&db, "missing", json!({ "note": "no status here" }));
248
+
249
+ assert_eq!(
250
+ ids(&db, "status", json!(null)),
251
+ vec!["explicit".to_string()],
252
+ "an absent field must not be reachable as null: the predicate does not treat them as equal",
253
+ );
254
+ assert_index_matches_state(&db, "an explicit null beside a missing field");
255
+ }
256
+
257
+ #[test]
258
+ fn unindexable_values_are_excluded_rather_than_coerced() {
259
+ let (_directory, db) = indexed();
260
+ put(&db, "object", json!({ "status": { "state": "active" } }));
261
+ put(&db, "array", json!({ "status": ["active"] }));
262
+ put(&db, "scalar", json!({ "status": "active" }));
263
+ put(&db, "not-an-object", json!("items are usually objects, but need not be"));
264
+
265
+ assert_eq!(
266
+ ids(&db, "status", json!("active")),
267
+ vec!["scalar".to_string()],
268
+ "a compound value is never equal to a scalar, so excluding it keeps the candidate set complete",
269
+ );
270
+ assert_eq!(
271
+ candidates(&db, "status", json!({ "state": "active" })),
272
+ None,
273
+ "a condition the index cannot represent must report inapplicable, never a wrong answer",
274
+ );
275
+ assert_index_matches_state(&db, "compound and non-object records");
276
+ }
277
+
278
+ #[test]
279
+ fn record_id_is_never_indexable() {
280
+ let (_directory, db) = database();
281
+ let refusal = db
282
+ .create_equality_index("items", "recordId")
283
+ .expect_err("recordId is authority metadata on the query surface");
284
+ assert!(
285
+ refusal.to_string().contains("recordId"),
286
+ "the refusal must name the field: {refusal}",
287
+ );
288
+ assert!(db.equality_indexes().expect("indexes").is_empty());
289
+ }
290
+
291
+ // ---------------------------------------------------------------------------
292
+ // Mutation primitives: CAS and conditional creation
293
+ // ---------------------------------------------------------------------------
294
+
295
+ #[test]
296
+ fn an_accepted_cas_moves_the_index_and_a_refused_one_changes_nothing() {
297
+ let (_directory, db) = indexed();
298
+ put(&db, "a", json!({ "status": "active", "__version": 1 }));
299
+
300
+ let refused = db
301
+ .compare_and_set_json(
302
+ "items:a",
303
+ 99,
304
+ None,
305
+ None,
306
+ false,
307
+ json!({ "status": "archived" }),
308
+ )
309
+ .expect("cas");
310
+ assert!(
311
+ matches!(refused, feltdb::JsonCasResult::VersionConflict { .. }),
312
+ "the precondition must fail: {refused:?}",
313
+ );
314
+ assert_eq!(
315
+ ids(&db, "status", json!("active")),
316
+ vec!["a".to_string()],
317
+ "a refused CAS writes neither the record nor the index",
318
+ );
319
+ assert_index_matches_state(&db, "a refused CAS");
320
+
321
+ let accepted = db
322
+ .compare_and_set_json(
323
+ "items:a",
324
+ 1,
325
+ None,
326
+ None,
327
+ false,
328
+ json!({ "status": "archived" }),
329
+ )
330
+ .expect("cas");
331
+ assert!(matches!(accepted, feltdb::JsonCasResult::Updated { .. }));
332
+ assert!(ids(&db, "status", json!("active")).is_empty());
333
+ assert_eq!(ids(&db, "status", json!("archived")), vec!["a".to_string()]);
334
+ assert_index_matches_state(&db, "an accepted CAS");
335
+ }
336
+
337
+ #[test]
338
+ fn conditional_creation_maintains_the_index_when_it_wins_and_not_when_it_loses() {
339
+ let (_directory, db) = indexed();
340
+
341
+ // putIfAbsent, as the transaction surface expresses it: a staged write
342
+ // fenced by `require_absent`.
343
+ let absent = RecordPrecondition {
344
+ capability: "items".into(),
345
+ key: "items:a".into(),
346
+ require_absent: true,
347
+ ..RecordPrecondition::default()
348
+ };
349
+ let write = AtomicMutation {
350
+ capability: "items".into(),
351
+ key: "items:a".into(),
352
+ value: Some(json!({ "status": "active" })),
353
+ };
354
+ db.apply_atomic_transaction_guarded("pr35-put-1", None, None, &[], &[absent.clone()], &[write.clone()], None)
355
+ .expect("the record is absent, so the creation wins");
356
+ assert_eq!(ids(&db, "status", json!("active")), vec!["a".to_string()]);
357
+ assert_index_matches_state(&db, "a conditional creation that won");
358
+
359
+ let losing = AtomicMutation {
360
+ capability: "items".into(),
361
+ key: "items:a".into(),
362
+ value: Some(json!({ "status": "archived" })),
363
+ };
364
+ db.apply_atomic_transaction_guarded("pr35-put-2", None, None, &[], &[absent], &[losing], None)
365
+ .expect_err("the record now exists, so the creation must be refused");
366
+ assert_eq!(
367
+ ids(&db, "status", json!("active")),
368
+ vec!["a".to_string()],
369
+ "a refused conditional creation leaves the index exactly as it was",
370
+ );
371
+ assert!(ids(&db, "status", json!("archived")).is_empty());
372
+ assert_index_matches_state(&db, "a conditional creation that lost");
373
+ }
374
+
375
+ // ---------------------------------------------------------------------------
376
+ // Transactions
377
+ // ---------------------------------------------------------------------------
378
+
379
+ fn mutation(key: &str, value: Option<Value>) -> AtomicMutation {
380
+ AtomicMutation {
381
+ capability: "items".into(),
382
+ key: key.into(),
383
+ value,
384
+ }
385
+ }
386
+
387
+ #[test]
388
+ fn a_transaction_of_one_indexed_mutation_is_atomic_with_the_index() {
389
+ let (_directory, db) = indexed();
390
+ db.apply_atomic_transaction_guarded(
391
+ "pr35-tx-1",
392
+ None,
393
+ None,
394
+ &[],
395
+ &[],
396
+ &[mutation("items:a", Some(json!({ "status": "active" })))],
397
+ None,
398
+ )
399
+ .expect("commit");
400
+
401
+ assert_eq!(ids(&db, "status", json!("active")), vec!["a".to_string()]);
402
+ assert_index_matches_state(&db, "a single-mutation transaction");
403
+ }
404
+
405
+ #[test]
406
+ fn one_transaction_of_insert_update_and_delete_lands_wholly_in_the_index() {
407
+ let (_directory, db) = indexed();
408
+ put(&db, "a", json!({ "status": "active" }));
409
+ put(&db, "b", json!({ "status": "pending" }));
410
+
411
+ db.apply_atomic_transaction_guarded(
412
+ "pr35-tx-mixed",
413
+ None,
414
+ None,
415
+ &[],
416
+ &[],
417
+ &[
418
+ // A: an indexed field changes value.
419
+ mutation("items:a", Some(json!({ "status": "inactive" }))),
420
+ // B: removed entirely.
421
+ mutation("items:b", None),
422
+ // C: created holding the value A just left.
423
+ mutation("items:c", Some(json!({ "status": "active" }))),
424
+ ],
425
+ None,
426
+ )
427
+ .expect("commit");
428
+
429
+ assert_eq!(ids(&db, "status", json!("active")), vec!["c".to_string()]);
430
+ assert_eq!(ids(&db, "status", json!("inactive")), vec!["a".to_string()]);
431
+ assert!(ids(&db, "status", json!("pending")).is_empty());
432
+ assert_index_matches_state(&db, "a transaction of insert, update and delete");
433
+ }
434
+
435
+ #[test]
436
+ fn a_refused_transaction_leaves_the_index_at_its_previous_state() {
437
+ let (_directory, db) = indexed();
438
+ put(&db, "a", json!({ "status": "active" }));
439
+ let before = snapshot(&db);
440
+
441
+ db.apply_atomic_transaction_guarded(
442
+ "pr35-tx-refused",
443
+ None,
444
+ None,
445
+ &[],
446
+ &[RecordPrecondition {
447
+ capability: "items".into(),
448
+ key: "items:a".into(),
449
+ require_absent: true,
450
+ ..RecordPrecondition::default()
451
+ }],
452
+ &[
453
+ mutation("items:a", Some(json!({ "status": "archived" }))),
454
+ mutation("items:z", Some(json!({ "status": "archived" }))),
455
+ ],
456
+ None,
457
+ )
458
+ .expect_err("the precondition must refuse the transaction");
459
+
460
+ assert_eq!(
461
+ snapshot(&db),
462
+ before,
463
+ "a refused transaction publishes no part of itself, the index included",
464
+ );
465
+ assert!(
466
+ ids(&db, "status", json!("archived")).is_empty(),
467
+ "no mutation of a refused transaction is observable through the index",
468
+ );
469
+ assert_index_matches_state(&db, "a refused transaction");
470
+ }
471
+
472
+ #[test]
473
+ fn a_transaction_touching_no_indexed_field_is_still_consistent() {
474
+ let (_directory, db) = indexed();
475
+ db.apply_atomic_transaction_guarded(
476
+ "pr35-tx-unindexed",
477
+ None,
478
+ None,
479
+ &[],
480
+ &[],
481
+ &[mutation("items:a", Some(json!({ "role": "admin" })))],
482
+ None,
483
+ )
484
+ .expect("commit");
485
+
486
+ assert!(ids(&db, "status", json!("active")).is_empty());
487
+ assert_eq!(
488
+ db.equality_index_stats().expect("stats").entries,
489
+ 0,
490
+ "a record holding no indexed field contributes no entries",
491
+ );
492
+ assert_index_matches_state(&db, "a transaction over unindexed fields");
493
+ }
494
+
495
+ #[test]
496
+ fn an_unindexed_collection_is_untouched_by_index_maintenance() {
497
+ let (_directory, db) = indexed();
498
+ db.insert("orders:1", &json!({ "status": "active" }))
499
+ .expect("insert");
500
+ db.update("orders:1", &json!({ "status": "archived" }))
501
+ .expect("update");
502
+ db.delete("orders:1").expect("delete");
503
+
504
+ assert!(snapshot(&db).is_empty());
505
+ assert_index_matches_state(&db, "mutations of a collection nobody indexed");
506
+ }
507
+
508
+ // ---------------------------------------------------------------------------
509
+ // Lifecycle and recovery
510
+ // ---------------------------------------------------------------------------
511
+
512
+ #[test]
513
+ fn declaring_an_index_populates_it_from_state_that_already_exists() {
514
+ let (_directory, db) = database();
515
+ put(&db, "a", json!({ "status": "active" }));
516
+ put(&db, "b", json!({ "status": "archived" }));
517
+
518
+ assert_eq!(
519
+ candidates(&db, "status", json!("active")),
520
+ None,
521
+ "before declaration there is no index to consult",
522
+ );
523
+ assert!(db.create_equality_index("items", "status").expect("declare"));
524
+ assert_eq!(
525
+ ids(&db, "status", json!("active")),
526
+ vec!["a".to_string()],
527
+ "declaration derives the index from the records already held",
528
+ );
529
+ assert!(
530
+ !db.create_equality_index("items", "status").expect("declare"),
531
+ "re-declaring an existing index reports that it created nothing",
532
+ );
533
+ assert_index_matches_state(&db, "declaring an index over existing state");
534
+
535
+ assert!(db.drop_equality_index("items", "status").expect("drop"));
536
+ assert_eq!(candidates(&db, "status", json!("active")), None);
537
+ assert!(!db.drop_equality_index("items", "status").expect("drop"));
538
+ }
539
+
540
+ #[test]
541
+ fn an_explicit_rebuild_reproduces_the_maintained_index_exactly() {
542
+ let (_directory, db) = indexed();
543
+ for step in 0..64 {
544
+ put(
545
+ &db,
546
+ &format!("record-{step:03}"),
547
+ json!({ "status": if step % 3 == 0 { "active" } else { "archived" }, "tenantId": format!("tenant-{}", step % 4) }),
548
+ );
549
+ }
550
+ db.delete("items:record-000").expect("delete");
551
+ db.update("items:record-001", &json!({ "status": "active", "tenantId": "tenant-9" }))
552
+ .expect("update");
553
+
554
+ let maintained = snapshot(&db);
555
+ db.rebuild_equality_indexes().expect("rebuild");
556
+ assert_eq!(
557
+ snapshot(&db),
558
+ maintained,
559
+ "a rebuild is the definition of correct: maintenance must have produced the same thing",
560
+ );
561
+ }
562
+
563
+ #[test]
564
+ fn reopening_the_database_rebuilds_the_index_from_durable_state() {
565
+ let directory = TempDir::new().expect("temp dir");
566
+ let path = directory.path().join("pr35-restart.log");
567
+
568
+ let before = {
569
+ let db = FeltDb::open(&path).expect("open");
570
+ db.create_equality_index("items", "status").expect("declare");
571
+ db.create_equality_index("items", "tenantId").expect("declare");
572
+ for step in 0..48 {
573
+ db.insert(
574
+ &format!("items:record-{step:03}"),
575
+ &json!({ "status": if step % 5 == 0 { "active" } else { "archived" }, "tenantId": format!("tenant-{}", step % 3) }),
576
+ )
577
+ .expect("insert");
578
+ }
579
+ db.delete("items:record-005").expect("delete");
580
+ db.update("items:record-006", &json!({ "status": "active", "tenantId": "tenant-0" }))
581
+ .expect("update");
582
+ db.apply_atomic_transaction_guarded(
583
+ "pr35-restart-tx",
584
+ None,
585
+ None,
586
+ &[],
587
+ &[],
588
+ &[
589
+ mutation("items:record-007", None),
590
+ mutation("items:record-100", Some(json!({ "status": "active", "tenantId": "tenant-1" }))),
591
+ ],
592
+ None,
593
+ )
594
+ .expect("commit");
595
+ snapshot(&db)
596
+ };
597
+
598
+ let reopened = FeltDb::open(&path).expect("reopen");
599
+ assert!(
600
+ reopened.equality_indexes().expect("indexes").is_empty(),
601
+ "an index is derived state: nothing about it is read back from the log",
602
+ );
603
+ reopened.create_equality_index("items", "status").expect("declare");
604
+ reopened.create_equality_index("items", "tenantId").expect("declare");
605
+
606
+ assert_eq!(
607
+ snapshot(&reopened),
608
+ before,
609
+ "the index derived from recovered records must equal the index maintained before the restart",
610
+ );
611
+ assert_index_matches_state(&reopened, "a restart");
612
+ }
613
+
614
+ // ---------------------------------------------------------------------------
615
+ // Candidate selection, conjunctions, and scan equivalence
616
+ // ---------------------------------------------------------------------------
617
+
618
+ /// The scan execution: the predicate against every record of the collection.
619
+ fn scan(db: &FeltDb, conditions: &[(&str, Value)]) -> Vec<String> {
620
+ let rows = db
621
+ .query_collection("items", None, |row| matches_all(row, conditions))
622
+ .expect("scan");
623
+ rows.into_iter().map(|row| row.key).collect()
624
+ }
625
+
626
+ /// The indexed execution: candidates from the index, then the same predicate.
627
+ fn indexed_query(db: &FeltDb, conditions: &[(&str, Value)]) -> Option<Vec<String>> {
628
+ let equalities: Vec<(&str, &Value)> = conditions
629
+ .iter()
630
+ .map(|(field, value)| (*field, value))
631
+ .collect();
632
+ db.query_collection_by_equality("items", &equalities, |row| matches_all(row, conditions))
633
+ .expect("indexed query")
634
+ .map(|rows| rows.into_iter().map(|row| row.key).collect())
635
+ }
636
+
637
+ fn matches_all(row: &StoredRow, conditions: &[(&str, Value)]) -> bool {
638
+ conditions
639
+ .iter()
640
+ .all(|(field, value)| row.value.get(field) == Some(value))
641
+ }
642
+
643
+ #[test]
644
+ fn indexed_execution_returns_exactly_what_the_scan_returns() {
645
+ let (_directory, db) = indexed();
646
+ let statuses = ["active", "archived", "pending"];
647
+ for step in 0..200 {
648
+ put(
649
+ &db,
650
+ &format!("record-{step:03}"),
651
+ json!({
652
+ "status": statuses[step % 3],
653
+ "tenantId": format!("tenant-{}", step % 7),
654
+ "role": if step % 2 == 0 { "admin" } else { "member" },
655
+ }),
656
+ );
657
+ }
658
+
659
+ let corpus: Vec<Vec<(&str, Value)>> = vec![
660
+ vec![("status", json!("active"))],
661
+ vec![("status", json!("pending"))],
662
+ vec![("status", json!("nobody-holds-this"))],
663
+ vec![("tenantId", json!("tenant-3"))],
664
+ // A indexed, B unindexed.
665
+ vec![("status", json!("active")), ("role", json!("admin"))],
666
+ // A unindexed, B indexed.
667
+ vec![("role", json!("member")), ("tenantId", json!("tenant-2"))],
668
+ // Both indexed.
669
+ vec![("status", json!("active")), ("tenantId", json!("tenant-1"))],
670
+ // Both indexed, no common member.
671
+ vec![("status", json!("active")), ("status", json!("archived"))],
672
+ // Three conditions, two of them indexed.
673
+ vec![
674
+ ("status", json!("archived")),
675
+ ("tenantId", json!("tenant-5")),
676
+ ("role", json!("admin")),
677
+ ],
678
+ // One condition matches, the other cannot.
679
+ vec![("status", json!("active")), ("role", json!("nobody"))],
680
+ // Neither indexed.
681
+ vec![("role", json!("admin"))],
682
+ ];
683
+
684
+ for conditions in &corpus {
685
+ let scanned = scan(&db, conditions);
686
+ match indexed_query(&db, conditions) {
687
+ Some(indexed) => assert_eq!(
688
+ indexed, scanned,
689
+ "indexed and scan execution disagreed on {conditions:?}",
690
+ ),
691
+ None => assert!(
692
+ conditions
693
+ .iter()
694
+ .all(|(field, _)| !matches!(*field, "status" | "tenantId")),
695
+ "only a query with no indexed equality may report the index inapplicable: {conditions:?}",
696
+ ),
697
+ }
698
+ }
699
+
700
+ // The conjunction actually narrows rather than merely re-filtering: the
701
+ // intersection is smaller than either side.
702
+ let both = indexed_query(&db, &[("status", json!("active")), ("tenantId", json!("tenant-1"))])
703
+ .expect("both fields are indexed");
704
+ let one = indexed_query(&db, &[("status", json!("active"))]).expect("indexed");
705
+ assert!(!both.is_empty() && both.len() < one.len());
706
+ }
707
+
708
+ #[test]
709
+ fn the_index_selects_candidates_and_the_predicate_still_decides() {
710
+ let (_directory, db) = indexed();
711
+ put(&db, "a", json!({ "status": "active", "role": "admin" }));
712
+ put(&db, "b", json!({ "status": "active", "role": "member" }));
713
+
714
+ let candidates = candidates(&db, "status", json!("active")).expect("indexed");
715
+ assert_eq!(
716
+ candidates,
717
+ vec!["items:a".to_string(), "items:b".to_string()],
718
+ "the index answers with candidates, both of which satisfy only the indexed condition",
719
+ );
720
+
721
+ let result = indexed_query(&db, &[("status", json!("active")), ("role", json!("admin"))])
722
+ .expect("indexed");
723
+ assert_eq!(
724
+ result,
725
+ vec!["items:a".to_string()],
726
+ "the predicate, not the index, decides which candidate matches",
727
+ );
728
+ }
729
+
730
+ // ---------------------------------------------------------------------------
731
+ // Concurrency
732
+ // ---------------------------------------------------------------------------
733
+
734
+ /// Mutations and indexed queries against the same collection, at the same time.
735
+ ///
736
+ /// The claim under test is not a scheduling order — there is no new isolation
737
+ /// guarantee here and none is being asserted. It is that *every* result a query
738
+ /// observes corresponds to a coherent committed state: a candidate the index
739
+ /// produced is a record that exists, a record the predicate accepted really
740
+ /// satisfies it, and a transaction is never half-visible. A defect in the
741
+ /// mutation boundary would show up here as a candidate with no record behind it
742
+ /// or a record whose bucket no longer describes it.
743
+ #[test]
744
+ fn concurrent_mutation_and_indexed_query_stay_coherent() {
745
+ use std::sync::atomic::{AtomicBool, Ordering};
746
+ use std::sync::Arc;
747
+
748
+ let (_directory, db) = indexed();
749
+ for step in 0..400 {
750
+ put(
751
+ &db,
752
+ &format!("seed-{step:03}"),
753
+ json!({ "status": if step % 2 == 0 { "active" } else { "archived" }, "tenantId": "tenant-0" }),
754
+ );
755
+ }
756
+
757
+ let running = Arc::new(AtomicBool::new(true));
758
+ let mut writers = Vec::new();
759
+ for worker in 0..4 {
760
+ let db = db.clone();
761
+ let running = running.clone();
762
+ writers.push(std::thread::spawn(move || {
763
+ let mut step = 0usize;
764
+ while running.load(Ordering::Relaxed) && step < 200 {
765
+ let id = format!("items:churn-{worker}-{step}");
766
+ let created = json!({ "status": "active", "tenantId": "tenant-0", "__version": 1 });
767
+ db.insert(&id, &created).expect("insert");
768
+ db.update(&id, &json!({ "status": "archived", "tenantId": "tenant-1", "__version": 1 }))
769
+ .expect("update");
770
+ db.compare_and_set_json(&id, 1, None, None, false, json!({ "status": "active", "tenantId": "tenant-1" }))
771
+ .expect("cas");
772
+ // A transaction whose two halves must never be seen apart.
773
+ db.apply_atomic_transaction_guarded(
774
+ &format!("pr35-race-{worker}-{step}"),
775
+ None,
776
+ None,
777
+ &[],
778
+ &[],
779
+ &[
780
+ mutation(&format!("{id}-tx-a"), Some(json!({ "status": "paired", "tenantId": "tenant-2", "pair": worker }))),
781
+ mutation(&format!("{id}-tx-b"), Some(json!({ "status": "paired", "tenantId": "tenant-2", "pair": worker }))),
782
+ ],
783
+ None,
784
+ )
785
+ .expect("commit");
786
+ db.delete(&id).expect("delete");
787
+ step += 1;
788
+ }
789
+ step
790
+ }));
791
+ }
792
+
793
+ let mut observations = 0usize;
794
+ let mut failures: Vec<String> = Vec::new();
795
+ for _ in 0..400 {
796
+ // Every record the indexed execution reaches must actually hold the
797
+ // value it was bucketed under.
798
+ //
799
+ // The check runs *inside* the execution, because candidate selection and
800
+ // the record read have to observe one state to mean anything. Copying
801
+ // candidate keys out and reading the records afterwards would be two
802
+ // acquisitions of the state lock with a writer between them, and the
803
+ // dangling key that produces is an artifact of asking the question in
804
+ // two parts — not a defect in the index. The query path does not ask it
805
+ // in two parts, and neither does this.
806
+ for (field, value) in [("status", json!("active")), ("tenantId", json!("tenant-1"))] {
807
+ // The predicate keeps everything the index reached, so what comes
808
+ // back is the candidate set itself, read coherently.
809
+ let reached = db
810
+ .query_collection_by_equality("items", &[(field, &value)], |_| true)
811
+ .expect("indexed query")
812
+ .expect("the field is indexed");
813
+ for row in reached {
814
+ if row.value.get(field) != Some(&value) {
815
+ failures.push(format!(
816
+ "{} was reached through the {field} bucket for {value} but does not hold it",
817
+ row.key,
818
+ ));
819
+ }
820
+ }
821
+ }
822
+
823
+ let paired = indexed_query(&db, &[("status", json!("paired"))]).expect("indexed");
824
+ let mut halves: BTreeMap<String, usize> = BTreeMap::new();
825
+ for key in &paired {
826
+ let sibling = key
827
+ .strip_suffix("-tx-a")
828
+ .or_else(|| key.strip_suffix("-tx-b"))
829
+ .unwrap_or(key)
830
+ .to_string();
831
+ *halves.entry(sibling).or_default() += 1;
832
+ }
833
+ // A pair is written by one transaction. Seeing exactly one half would
834
+ // mean a partially committed transaction became queryable.
835
+ for (sibling, count) in halves {
836
+ if count != 2 {
837
+ failures.push(format!("transaction pair {sibling} was observed {count} times, not 2"));
838
+ }
839
+ }
840
+ observations += 1;
841
+ }
842
+
843
+ running.store(false, Ordering::Relaxed);
844
+ let cycles: usize = writers.into_iter().map(|handle| handle.join().expect("writer")).sum();
845
+
846
+ assert!(cycles > 0, "the writers actually mutated the collection");
847
+ assert!(observations > 0, "the reader actually queried");
848
+ assert_eq!(failures, Vec::<String>::new());
849
+ assert_index_matches_state(&db, "concurrent mutation and query");
850
+ }
851
+
852
+ /// Indexed and scan execution must still agree once the churn has stopped, on a
853
+ /// state that concurrency produced rather than a test wrote by hand.
854
+ #[test]
855
+ fn indexed_and_scan_execution_agree_on_a_concurrently_built_state() {
856
+ use std::sync::Arc;
857
+
858
+ let (_directory, db) = indexed();
859
+ let mut writers = Vec::new();
860
+ for worker in 0..4 {
861
+ let db = Arc::new(db.clone());
862
+ writers.push(std::thread::spawn(move || {
863
+ for step in 0..150 {
864
+ let id = format!("items:w{worker}-{step:03}");
865
+ db.insert(
866
+ &id,
867
+ &json!({ "status": if step % 3 == 0 { "active" } else { "archived" }, "tenantId": format!("tenant-{}", step % 5) }),
868
+ )
869
+ .expect("insert");
870
+ if step % 7 == 0 {
871
+ db.delete(&id).expect("delete");
872
+ }
873
+ }
874
+ }));
875
+ }
876
+ for writer in writers {
877
+ writer.join().expect("writer");
878
+ }
879
+
880
+ assert_index_matches_state(&db, "four concurrent writers");
881
+ for conditions in [
882
+ vec![("status", json!("active"))],
883
+ vec![("tenantId", json!("tenant-3"))],
884
+ vec![("status", json!("archived")), ("tenantId", json!("tenant-2"))],
885
+ ] {
886
+ assert_eq!(
887
+ indexed_query(&db, &conditions).expect("indexed"),
888
+ scan(&db, &conditions),
889
+ "executions disagreed on {conditions:?} after concurrent writes",
890
+ );
891
+ }
892
+ }