@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,595 @@
1
+ //! A deterministic equality index over authoritative collection state.
2
+ //!
3
+ //! PR33 attributed sustained-workload degradation to bounded query execution.
4
+ //! PR34 removed the whole-collection clone that dominated it, leaving execution
5
+ //! at `O(N)` because the conjunction still had to be evaluated against every
6
+ //! record of the collection. This module removes that remaining scan for the
7
+ //! queries it can answer, and *only* for those.
8
+ //!
9
+ //! The shape is deliberately narrow:
10
+ //!
11
+ //! ```text
12
+ //! collection -> field -> canonical value -> { record key, ... }
13
+ //! ```
14
+ //!
15
+ //! Three properties make this an execution structure rather than a second
16
+ //! database, and every one of them is load-bearing:
17
+ //!
18
+ //! 1. **It is derived.** The authoritative record map is the source of truth.
19
+ //! Nothing here is durable, replicated, or consulted for anything but
20
+ //! *candidate selection*. [`EqualityIndex::rebuild`] reconstructs the entire
21
+ //! index from authoritative state, and a restart does exactly that.
22
+ //! 2. **It never decides a query.** A lookup returns record keys a query still
23
+ //! has to evaluate its full predicate against. The index narrows what is
24
+ //! examined; it does not define what matches.
25
+ //! 3. **It is maintained inside the state mutation boundary.** Every write goes
26
+ //! through [`crate::Inner::put_row`] / [`crate::Inner::remove_row`], which
27
+ //! hold the state lock across both the record change and the index change,
28
+ //! so no externally observable committed state has one without the other.
29
+ //!
30
+ //! # Canonical values
31
+ //!
32
+ //! An index key must collide exactly when [`serde_json::Value`] equality holds,
33
+ //! because `serde_json::Value` equality is what the existing predicate applies.
34
+ //! [`IndexKey::of`] is therefore written against `serde_json`'s own equality
35
+ //! rules rather than against a serialization: `42`, `"42"`, `true`, `"true"`,
36
+ //! `null`, `0`, `"0"` and `false` all take distinct keys, and `42` and `42.0`
37
+ //! stay distinct because `serde_json` reports them unequal.
38
+ //!
39
+ //! PR35 indexes **scalar JSON values only**. Objects and arrays — and the
40
+ //! non-finite floats JSON cannot represent anyway — are *not indexable*, and a
41
+ //! record holding one contributes no entry for that field. That is safe rather
42
+ //! than lossy: an unindexable value can never equal an indexable one, so a
43
+ //! candidate set for a scalar condition is complete without it. A condition
44
+ //! whose expected value is unindexable makes the index inapplicable, and
45
+ //! execution falls back to the scan. Nothing is coerced to a string.
46
+
47
+ use crate::StoredRow;
48
+ use serde_json::Value;
49
+ use std::collections::{BTreeMap, BTreeSet, HashMap};
50
+
51
+ /// The canonical, deterministic key one indexable JSON scalar maps to.
52
+ ///
53
+ /// Determinism here is a correctness requirement, not a nicety: the same value
54
+ /// must produce the same key across a process lifetime, a restart, and a
55
+ /// rebuild, or a rebuilt index would answer differently from the live one.
56
+ /// Every variant is derived from the value's own contents — never from an
57
+ /// address, an iteration order, or a hash seed.
58
+ #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
59
+ pub enum IndexKey {
60
+ Null,
61
+ Bool(bool),
62
+ /// A `serde_json` positive integer, which is never equal to a float or a
63
+ /// negative integer even when the arithmetic value would match.
64
+ UnsignedInt(u64),
65
+ /// A `serde_json` negative integer.
66
+ SignedInt(i64),
67
+ /// A finite float, keyed by its bit pattern with `-0.0` normalized to `0.0`
68
+ /// because `-0.0 == 0.0` holds for the predicate too.
69
+ Float(u64),
70
+ Text(String),
71
+ }
72
+
73
+ impl IndexKey {
74
+ /// The canonical key for a value, or `None` when the value is not indexable.
75
+ ///
76
+ /// `None` is not a failure: it is how this module refuses to invent a
77
+ /// representation for something it cannot compare exactly.
78
+ pub fn of(value: &Value) -> Option<Self> {
79
+ match value {
80
+ Value::Null => Some(Self::Null),
81
+ Value::Bool(flag) => Some(Self::Bool(*flag)),
82
+ Value::String(text) => Some(Self::Text(text.clone())),
83
+ Value::Number(number) => {
84
+ if let Some(unsigned) = number.as_u64() {
85
+ return Some(Self::UnsignedInt(unsigned));
86
+ }
87
+ if let Some(signed) = number.as_i64() {
88
+ return Some(Self::SignedInt(signed));
89
+ }
90
+ let float = number.as_f64()?;
91
+ if !float.is_finite() {
92
+ return None;
93
+ }
94
+ // `-0.0 == 0.0` for the predicate, so the two must not take
95
+ // different keys. Adding zero collapses the sign of zero and
96
+ // leaves every other finite float untouched.
97
+ Some(Self::Float((float + 0.0).to_bits()))
98
+ }
99
+ Value::Array(_) | Value::Object(_) => None,
100
+ }
101
+ }
102
+
103
+ /// A stable textual rendering, for diagnostics and test comparison only.
104
+ /// Nothing in execution depends on this form.
105
+ pub fn describe(&self) -> String {
106
+ match self {
107
+ Self::Null => "null".to_string(),
108
+ Self::Bool(flag) => format!("bool:{flag}"),
109
+ Self::UnsignedInt(value) => format!("u64:{value}"),
110
+ Self::SignedInt(value) => format!("i64:{value}"),
111
+ Self::Float(bits) => format!("f64:{}", f64::from_bits(*bits)),
112
+ Self::Text(text) => format!("str:{text}"),
113
+ }
114
+ }
115
+ }
116
+
117
+ /// The field identity the query surface exposes as the authority's record id.
118
+ ///
119
+ /// It is deliberately never indexed. On the query surface `recordId` is
120
+ /// authority metadata that shadows a document field of the same name — but only
121
+ /// on object-valued records, a legacy asymmetry PR34 preserved verbatim. An
122
+ /// index over the document field would answer a different question from the one
123
+ /// the predicate asks, so a condition on this field is simply not index
124
+ /// eligible and falls back to the scan.
125
+ pub const RESERVED_RECORD_ID_FIELD: &str = "recordId";
126
+
127
+ /// Which fields of which collections are indexed, and the buckets for each.
128
+ ///
129
+ /// Empty buckets are absent rather than retained: a value nothing holds has no
130
+ /// entry at all. That is the representation a rebuild produces, so it is the
131
+ /// representation live maintenance must converge to.
132
+ #[derive(Debug, Default, Clone)]
133
+ pub struct EqualityIndex {
134
+ /// Declared indexes, as collection -> fields.
135
+ declared: BTreeMap<String, BTreeSet<String>>,
136
+ /// collection -> field -> canonical value -> record keys, in key order.
137
+ ///
138
+ /// Nested rather than keyed by a `(collection, field)` tuple so that
139
+ /// maintenance can look a bucket up from `&str` without allocating. This is
140
+ /// the write path of every indexed collection, so an allocation per mutated
141
+ /// field would be a tax on inserts to buy nothing.
142
+ buckets: HashMap<String, HashMap<String, ValueBuckets>>,
143
+ }
144
+
145
+ type ValueBuckets = HashMap<IndexKey, BTreeSet<String>>;
146
+
147
+ /// Add one record to one field's buckets, or do nothing when the record holds no
148
+ /// indexable value for that field.
149
+ ///
150
+ /// A free function rather than a method so callers can hold a disjoint borrow of
151
+ /// `declared` while writing `buckets`.
152
+ fn insert_entry(
153
+ buckets: &mut HashMap<String, HashMap<String, ValueBuckets>>,
154
+ collection: &str,
155
+ field: &str,
156
+ key: &str,
157
+ value: &Value,
158
+ ) {
159
+ let Some(index_key) = value.get(field).and_then(IndexKey::of) else {
160
+ // A missing field and an unindexable value both contribute nothing.
161
+ // They stay distinguishable from an explicit `null`, which is a value
162
+ // and takes `IndexKey::Null`, because the predicate treats them as
163
+ // distinct too.
164
+ return;
165
+ };
166
+ let field_buckets = match buckets.get_mut(collection) {
167
+ Some(existing) => existing,
168
+ None => buckets.entry(collection.to_string()).or_default(),
169
+ };
170
+ let value_buckets = match field_buckets.get_mut(field) {
171
+ Some(existing) => existing,
172
+ None => field_buckets.entry(field.to_string()).or_default(),
173
+ };
174
+ value_buckets
175
+ .entry(index_key)
176
+ .or_default()
177
+ .insert(key.to_string());
178
+ }
179
+
180
+ /// Remove one record from one field's buckets, dropping buckets that empty.
181
+ fn remove_entry(
182
+ buckets: &mut HashMap<String, HashMap<String, ValueBuckets>>,
183
+ collection: &str,
184
+ field: &str,
185
+ key: &str,
186
+ value: &Value,
187
+ ) {
188
+ let Some(index_key) = value.get(field).and_then(IndexKey::of) else {
189
+ return;
190
+ };
191
+ let Some(field_buckets) = buckets.get_mut(collection) else {
192
+ return;
193
+ };
194
+ let Some(value_buckets) = field_buckets.get_mut(field) else {
195
+ return;
196
+ };
197
+ if let Some(keys) = value_buckets.get_mut(&index_key) {
198
+ keys.remove(key);
199
+ if keys.is_empty() {
200
+ value_buckets.remove(&index_key);
201
+ }
202
+ }
203
+ if value_buckets.is_empty() {
204
+ field_buckets.remove(field);
205
+ }
206
+ if field_buckets.is_empty() {
207
+ buckets.remove(collection);
208
+ }
209
+ }
210
+
211
+ impl EqualityIndex {
212
+ pub fn new() -> Self {
213
+ Self::default()
214
+ }
215
+
216
+ /// Every declared index, as `(collection, field)` pairs in a stable order.
217
+ pub fn declarations(&self) -> Vec<(String, String)> {
218
+ self.declared
219
+ .iter()
220
+ .flat_map(|(collection, fields)| {
221
+ fields
222
+ .iter()
223
+ .map(move |field| (collection.clone(), field.clone()))
224
+ })
225
+ .collect()
226
+ }
227
+
228
+ /// Is this collection/field pair indexed?
229
+ pub fn is_indexed(&self, collection: &str, field: &str) -> bool {
230
+ self.declared
231
+ .get(collection)
232
+ .is_some_and(|fields| fields.contains(field))
233
+ }
234
+
235
+ /// Does this collection carry any index at all?
236
+ ///
237
+ /// Maintenance asks this first, so a collection nobody indexed costs one
238
+ /// map lookup per mutation rather than a walk over its fields.
239
+ pub fn indexes_collection(&self, collection: &str) -> bool {
240
+ self.declared
241
+ .get(collection)
242
+ .is_some_and(|fields| !fields.is_empty())
243
+ }
244
+
245
+ /// Declare an index. Returns whether this call created it.
246
+ ///
247
+ /// Declaring is only half of `create`: the caller must populate the new
248
+ /// index from authoritative state, which [`crate::FeltDb::create_equality_index`]
249
+ /// does under the same lock. Declaring `recordId` is refused rather than
250
+ /// silently ignored — see [`RESERVED_RECORD_ID_FIELD`].
251
+ pub fn declare(&mut self, collection: &str, field: &str) -> Result<bool, String> {
252
+ if collection.trim().is_empty() || field.trim().is_empty() {
253
+ return Err("an equality index needs a collection and a field".to_string());
254
+ }
255
+ if field == RESERVED_RECORD_ID_FIELD {
256
+ return Err(format!(
257
+ "{RESERVED_RECORD_ID_FIELD} is authority metadata on the query surface and is not indexable"
258
+ ));
259
+ }
260
+ Ok(self
261
+ .declared
262
+ .entry(collection.to_string())
263
+ .or_default()
264
+ .insert(field.to_string()))
265
+ }
266
+
267
+ /// Undeclare an index and drop its buckets. Returns whether one existed.
268
+ pub fn undeclare(&mut self, collection: &str, field: &str) -> bool {
269
+ let removed = self
270
+ .declared
271
+ .get_mut(collection)
272
+ .is_some_and(|fields| fields.remove(field));
273
+ if removed {
274
+ if let Some(field_buckets) = self.buckets.get_mut(collection) {
275
+ field_buckets.remove(field);
276
+ if field_buckets.is_empty() {
277
+ self.buckets.remove(collection);
278
+ }
279
+ }
280
+ if self
281
+ .declared
282
+ .get(collection)
283
+ .is_some_and(|fields| fields.is_empty())
284
+ {
285
+ self.declared.remove(collection);
286
+ }
287
+ }
288
+ removed
289
+ }
290
+
291
+ /// Forget every bucket, keeping declarations. The lifecycle's `clear`.
292
+ pub fn clear(&mut self) {
293
+ self.buckets.clear();
294
+ }
295
+
296
+ /// Forget declarations and buckets alike.
297
+ pub fn reset(&mut self) {
298
+ self.declared.clear();
299
+ self.buckets.clear();
300
+ }
301
+
302
+ /// Add one record's entries for every declared field of its collection.
303
+ ///
304
+ /// `declared` and `buckets` are borrowed disjointly, so the write path walks
305
+ /// the declared fields in place: no field name is cloned to mutate an index.
306
+ pub fn insert_record(&mut self, collection: &str, key: &str, value: &Value) {
307
+ let Self { declared, buckets } = self;
308
+ let Some(fields) = declared.get(collection) else {
309
+ return;
310
+ };
311
+ for field in fields {
312
+ insert_entry(buckets, collection, field, key, value);
313
+ }
314
+ }
315
+
316
+ /// Remove one record's entries for every declared field of its collection.
317
+ pub fn remove_record(&mut self, collection: &str, key: &str, value: &Value) {
318
+ let Self { declared, buckets } = self;
319
+ let Some(fields) = declared.get(collection) else {
320
+ return;
321
+ };
322
+ for field in fields {
323
+ remove_entry(buckets, collection, field, key, value);
324
+ }
325
+ }
326
+
327
+ /// Candidate record keys for one equality condition.
328
+ ///
329
+ /// `None` means *this index cannot answer that condition* — the field is not
330
+ /// indexed, or the expected value is not indexable — and the caller must
331
+ /// fall back. `Some(empty)` is an answer: no record holds that value.
332
+ pub fn candidates(
333
+ &self,
334
+ collection: &str,
335
+ field: &str,
336
+ value: &Value,
337
+ ) -> Option<&BTreeSet<String>> {
338
+ if !self.is_indexed(collection, field) {
339
+ return None;
340
+ }
341
+ let index_key = IndexKey::of(value)?;
342
+ static EMPTY: std::sync::OnceLock<BTreeSet<String>> = std::sync::OnceLock::new();
343
+ Some(
344
+ self.buckets
345
+ .get(collection)
346
+ .and_then(|field_buckets| field_buckets.get(field))
347
+ .and_then(|value_buckets| value_buckets.get(&index_key))
348
+ .unwrap_or_else(|| EMPTY.get_or_init(BTreeSet::new)),
349
+ )
350
+ }
351
+
352
+ /// Rebuild every declared index from authoritative state.
353
+ ///
354
+ /// This is the whole recovery story: an index is never loaded, replicated,
355
+ /// or repaired — it is re-derived from the records that survived.
356
+ pub fn rebuild(&mut self, rows: &HashMap<String, BTreeMap<String, StoredRow>>) {
357
+ let Self { declared, buckets } = self;
358
+ buckets.clear();
359
+ for (collection, fields) in declared.iter() {
360
+ let Some(bucket) = rows.get(collection) else {
361
+ continue;
362
+ };
363
+ for field in fields {
364
+ for (key, row) in bucket {
365
+ insert_entry(buckets, collection, field, key, &row.value);
366
+ }
367
+ }
368
+ }
369
+ }
370
+
371
+ /// Rebuild the buckets of one declared field only.
372
+ pub fn rebuild_field(
373
+ &mut self,
374
+ collection: &str,
375
+ field: &str,
376
+ rows: &HashMap<String, BTreeMap<String, StoredRow>>,
377
+ ) {
378
+ if let Some(field_buckets) = self.buckets.get_mut(collection) {
379
+ field_buckets.remove(field);
380
+ }
381
+ let Some(bucket) = rows.get(collection) else {
382
+ return;
383
+ };
384
+ for (key, row) in bucket {
385
+ insert_entry(&mut self.buckets, collection, field, key, &row.value);
386
+ }
387
+ }
388
+
389
+ /// A fully ordered rendering of the index, for tests and diagnostics.
390
+ ///
391
+ /// Comparing two of these is how the consistency invariant is asserted:
392
+ /// the live index must equal one rebuilt from authoritative state. The form
393
+ /// is deterministic — sorted collections, fields, keys and record ids — so
394
+ /// equality of the rendering is equality of the index.
395
+ pub fn snapshot(&self) -> BTreeMap<String, BTreeMap<String, BTreeMap<String, Vec<String>>>> {
396
+ let mut snapshot: BTreeMap<String, BTreeMap<String, BTreeMap<String, Vec<String>>>> =
397
+ BTreeMap::new();
398
+ for (collection, field_buckets) in &self.buckets {
399
+ for (field, value_buckets) in field_buckets {
400
+ if value_buckets.is_empty() {
401
+ continue;
402
+ }
403
+ let entry = snapshot
404
+ .entry(collection.clone())
405
+ .or_default()
406
+ .entry(field.clone())
407
+ .or_default();
408
+ for (index_key, keys) in value_buckets {
409
+ if keys.is_empty() {
410
+ continue;
411
+ }
412
+ entry.insert(index_key.describe(), keys.iter().cloned().collect());
413
+ }
414
+ }
415
+ }
416
+ snapshot
417
+ }
418
+
419
+ /// Aggregate shape of the index: declared indexes, buckets, and entries.
420
+ /// Counts only — never a value and never a record id.
421
+ pub fn stats(&self) -> EqualityIndexStats {
422
+ let value_buckets = self.buckets.values().flat_map(HashMap::values);
423
+ EqualityIndexStats {
424
+ indexed_fields: self.declarations().len(),
425
+ value_buckets: value_buckets.clone().map(HashMap::len).sum(),
426
+ entries: value_buckets
427
+ .flat_map(HashMap::values)
428
+ .map(BTreeSet::len)
429
+ .sum(),
430
+ }
431
+ }
432
+ }
433
+
434
+ /// Counts describing index size. Carries no record data.
435
+ #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
436
+ pub struct EqualityIndexStats {
437
+ pub indexed_fields: usize,
438
+ pub value_buckets: usize,
439
+ pub entries: usize,
440
+ }
441
+
442
+ #[cfg(test)]
443
+ mod tests {
444
+ use super::*;
445
+ use serde_json::json;
446
+
447
+ fn row(key: &str, value: Value) -> StoredRow {
448
+ StoredRow {
449
+ capability: "items".to_string(),
450
+ key: key.to_string(),
451
+ rust_type: "serde_json::Value".to_string(),
452
+ value,
453
+ unix_ms: 0,
454
+ content_hash: None,
455
+ flow_ref: None,
456
+ deleted: false,
457
+ operation: None,
458
+ }
459
+ }
460
+
461
+ fn state(rows: Vec<StoredRow>) -> HashMap<String, BTreeMap<String, StoredRow>> {
462
+ let mut state: HashMap<String, BTreeMap<String, StoredRow>> = HashMap::new();
463
+ for row in rows {
464
+ state
465
+ .entry(row.capability.clone())
466
+ .or_default()
467
+ .insert(row.key.clone(), row);
468
+ }
469
+ state
470
+ }
471
+
472
+ #[test]
473
+ fn distinguishable_scalars_never_collide() {
474
+ let values = [
475
+ json!(null),
476
+ json!(true),
477
+ json!(false),
478
+ json!(0),
479
+ json!(1),
480
+ json!(-1),
481
+ json!("0"),
482
+ json!("1"),
483
+ json!("true"),
484
+ json!(42),
485
+ json!("42"),
486
+ json!(42.0),
487
+ json!(""),
488
+ ];
489
+ let mut keys = Vec::new();
490
+ for value in &values {
491
+ keys.push(IndexKey::of(value).expect("scalar values are indexable"));
492
+ }
493
+ for (left_index, left) in values.iter().enumerate() {
494
+ for (right_index, right) in values.iter().enumerate() {
495
+ assert_eq!(
496
+ keys[left_index] == keys[right_index],
497
+ left == right,
498
+ "key equality must mirror value equality for {left} and {right}",
499
+ );
500
+ }
501
+ }
502
+ }
503
+
504
+ #[test]
505
+ fn signed_zero_shares_a_key_because_the_predicate_says_it_is_equal() {
506
+ assert_eq!(json!(-0.0), json!(0.0));
507
+ assert_eq!(IndexKey::of(&json!(-0.0)), IndexKey::of(&json!(0.0)));
508
+ }
509
+
510
+ #[test]
511
+ fn compound_values_are_not_indexable() {
512
+ assert_eq!(IndexKey::of(&json!({ "a": 1 })), None);
513
+ assert_eq!(IndexKey::of(&json!([1, 2])), None);
514
+ }
515
+
516
+ #[test]
517
+ fn record_id_cannot_be_declared() {
518
+ let mut index = EqualityIndex::new();
519
+ assert!(index.declare("items", RESERVED_RECORD_ID_FIELD).is_err());
520
+ assert!(!index.is_indexed("items", RESERVED_RECORD_ID_FIELD));
521
+ }
522
+
523
+ #[test]
524
+ fn maintenance_matches_a_rebuild() {
525
+ let mut index = EqualityIndex::new();
526
+ index.declare("items", "status").expect("declare");
527
+ let rows = state(vec![
528
+ row("items:a", json!({ "status": "active" })),
529
+ row("items:b", json!({ "status": "active" })),
530
+ row("items:c", json!({ "status": null })),
531
+ row("items:d", json!({})),
532
+ row("items:e", json!({ "status": { "nested": true } })),
533
+ row("items:f", json!("not an object")),
534
+ ]);
535
+ for (key, stored) in &rows["items"] {
536
+ index.insert_record("items", key, &stored.value);
537
+ }
538
+
539
+ let mut rebuilt = EqualityIndex::new();
540
+ rebuilt.declare("items", "status").expect("declare");
541
+ rebuilt.rebuild(&rows);
542
+ assert_eq!(index.snapshot(), rebuilt.snapshot());
543
+
544
+ let active = index
545
+ .candidates("items", "status", &json!("active"))
546
+ .expect("indexed field");
547
+ assert_eq!(
548
+ active.iter().cloned().collect::<Vec<_>>(),
549
+ vec!["items:a".to_string(), "items:b".to_string()],
550
+ );
551
+ let null_bucket = index
552
+ .candidates("items", "status", &json!(null))
553
+ .expect("indexed field");
554
+ assert_eq!(
555
+ null_bucket.iter().cloned().collect::<Vec<_>>(),
556
+ vec!["items:c".to_string()],
557
+ "an explicit null is a value; a missing field is not",
558
+ );
559
+ }
560
+
561
+ #[test]
562
+ fn removing_the_last_holder_of_a_value_drops_the_bucket() {
563
+ let mut index = EqualityIndex::new();
564
+ index.declare("items", "status").expect("declare");
565
+ let value = json!({ "status": "active" });
566
+ index.insert_record("items", "items:a", &value);
567
+ index.insert_record("items", "items:b", &value);
568
+ index.remove_record("items", "items:a", &value);
569
+ assert_eq!(index.stats().value_buckets, 1);
570
+ index.remove_record("items", "items:b", &value);
571
+ assert_eq!(
572
+ index.stats(),
573
+ EqualityIndexStats {
574
+ indexed_fields: 1,
575
+ value_buckets: 0,
576
+ entries: 0
577
+ },
578
+ "an empty bucket is absent, which is what a rebuild would produce",
579
+ );
580
+ assert!(index.snapshot().is_empty());
581
+ }
582
+
583
+ #[test]
584
+ fn an_unindexed_field_is_inapplicable_rather_than_empty() {
585
+ let mut index = EqualityIndex::new();
586
+ index.declare("items", "status").expect("declare");
587
+ assert!(index.candidates("items", "tenant", &json!("a")).is_none());
588
+ assert!(index
589
+ .candidates("items", "status", &json!({ "compound": true }))
590
+ .is_none());
591
+ assert!(index
592
+ .candidates("items", "status", &json!("nobody-holds-this"))
593
+ .is_some_and(BTreeSet::is_empty));
594
+ }
595
+ }