relate-executor 1.0.2

In-memory graph and Cypher physical executor
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
//! `CREATE TEXT INDEX`, `CREATE RANGE INDEX`, and `CREATE POINT INDEX`
//! access methods. Each structure exists only for a catalog pair and is
//! built on create, on startup (`rebuild_indexes`), and incrementally on
//! later writes. A seek with no matching index returns `None` so the
//! caller scans the label and evaluates the predicate.

use std::collections::{BTreeMap, HashSet};
use std::ops::ControlFlow;

use relate_core::{NodeId, Value};

use crate::redo::{IndexDetailSpec, IndexKindSpec};

use super::*;

mod order;
mod point;
mod text;

pub(super) use order::RangeIndex;
pub(crate) use order::{RangeSeek, SpatialSeek};
pub(crate) use point::spatial_holds;
pub(super) use point::PointIndex;
/// Profile-only: the bench harness drives the point backend directly
/// (the R-tree vs. grid comparison of record lives there).
#[cfg(test)]
pub(super) use point::{point_insert, spatial_ids};
pub(crate) use text::trigram_count;
pub(super) use text::GramIndex;

/// One declared index's postings for a `(label, property)` pair. The
/// graph wiring below is written once against this trait.
pub(super) trait DrainState: Default {
    fn dirty(&self) -> &HashSet<NodeId>;
    fn dirty_mut(&mut self) -> &mut HashSet<NodeId>;
    /// Post one version's value for `id`. A value of another type posts
    /// nothing.
    fn insert(&mut self, id: NodeId, value: &Value);
    /// Drop every posting of `id`.
    fn remove_node(&mut self, id: NodeId);
    /// Finalize a full local build (create, reopen rebuild) before the
    /// pair is published: a seek never observes an unsealed pair. The
    /// default is nothing to do.
    fn seal(&mut self) {}
}

impl Graph {
    pub(super) fn declared_dirty(&self, lid: u32, kid: u32, id: NodeId) {
        Self::mark_dirty(&self.indexes.gram_pairs, lid, kid, id);
        Self::mark_dirty(&self.indexes.range_pairs, lid, kid, id);
        Self::mark_dirty(&self.indexes.point_pairs, lid, kid, id);
    }

    fn mark_dirty<St: DrainState>(pairs: &CoreMap<(u32, u32), St>, lid: u32, kid: u32, id: NodeId) {
        if let Some(mut st) = pairs.get_mut(&(lid, kid)) {
            st.dirty_mut().insert(id);
        }
    }

    /// `(gram entries, dirty ids)` when a text index has materialized this pair.
    #[cfg(test)]
    pub(super) fn gram_pair_state(&self, label: &str, key: &str) -> Option<(usize, usize)> {
        let pk = self.string_pair_id(label, key)?;
        self.indexes
            .gram_pairs
            .get(&pk)
            .map(|st| (st.grams.len(), st.dirty.len()))
    }

    pub(super) fn materialize_detail(&self, detail: &IndexDetailSpec) {
        for (label, property, kind) in detail.covered_pairs() {
            match kind {
                IndexKindSpec::Text => self.materialize_text_index(label, property),
                IndexKindSpec::Range => self.materialize_range_index(label, property),
                IndexKindSpec::Point => self.materialize_point_index(label, property),
                _ => {}
            }
        }
    }

    pub(super) fn drop_detail(&self, detail: &IndexDetailSpec) {
        let remaining: Vec<IndexDetailSpec> = self
            .theater
            .lock()
            .unwrap()
            .index_details
            .values()
            .cloned()
            .collect();
        for (label, property, kind) in detail.covered_pairs() {
            let still = remaining.iter().any(|other| {
                other
                    .covered_pairs()
                    .iter()
                    .any(|(l, p, k)| *l == label && *p == property && *k == kind)
            });
            if still {
                continue;
            }
            let Some(pk) = self.string_pair_id(label, property) else {
                continue;
            };
            match kind {
                IndexKindSpec::Text => {
                    self.indexes.gram_pairs.remove(&pk);
                }
                IndexKindSpec::Range => {
                    self.indexes.range_pairs.remove(&pk);
                }
                IndexKindSpec::Point => {
                    self.indexes.point_pairs.remove(&pk);
                }
                _ => {}
            }
        }
    }

    pub(super) fn rebuild_declared_indexes(&self) {
        self.indexes.gram_pairs.clear();
        self.indexes.range_pairs.clear();
        self.indexes.point_pairs.clear();
        let details: Vec<IndexDetailSpec> = self
            .theater
            .lock()
            .unwrap()
            .index_details
            .values()
            .cloned()
            .collect();
        for detail in details {
            self.materialize_detail(&detail);
        }
    }

    /// The node `(label, property)` pairs the store's RANGE indexes serve an
    /// equality seek on, read from the typed catalog details
    /// ([`IndexDetailSpec::range_seek_pairs`]) rather than re-parsed from the
    /// rendered `:Label(property)` text: every component of a composite range
    /// index is covered, a relationship index contributes no node pair, and a
    /// comma-bearing property name stays one name.
    pub fn range_indexed_node_properties(&self) -> Vec<(String, String)> {
        self.theater
            .lock()
            .unwrap()
            .index_details
            .values()
            .flat_map(IndexDetailSpec::range_seek_pairs)
            .map(|(label, property)| (label.to_string(), property.to_string()))
            .collect()
    }

    fn intern_pair(&self, label: &str, key: &str) -> (u32, u32) {
        (self.interner.intern(label), self.interner.intern(key))
    }

    /// Labels among `labels` whose pair for `key` exists in `pairs`.
    /// `None` when none do (the seek must scan). An empty pattern label
    /// list cannot be served: an index on one label would miss the others.
    fn indexed_labels<St>(
        &self,
        labels: &[String],
        key: &str,
        pairs: &CoreMap<(u32, u32), St>,
    ) -> Option<Vec<u32>> {
        if labels.is_empty() {
            return None;
        }
        let kid = self.interner.get_id(key)?;
        let ids: Vec<u32> = labels
            .iter()
            .filter_map(|l| self.interner.get_id(l))
            .filter(|lid| pairs.contains_key(&(*lid, kid)))
            .collect();
        (!ids.is_empty()).then_some(ids)
    }

    /// Build one pair from every version of every node in the label index
    /// (a superset; the seek re-checks the snapshot, ADR-0018).
    fn materialize_pair<St: DrainState>(
        &self,
        pairs: &CoreMap<(u32, u32), St>,
        label: &str,
        property: &str,
    ) {
        let (lid, kid) = self.intern_pair(label, property);
        let mut st = St::default();
        self.for_each_pair_value(lid, kid, |id, value| st.insert(id, value));
        // Sealed before publish: a concurrent seek either sees the fully
        // built pair or none of it.
        st.seal();
        pairs.insert((lid, kid), st);
    }

    pub(super) fn materialize_text_index(&self, label: &str, property: &str) {
        self.materialize_pair(&self.indexes.gram_pairs, label, property);
    }

    pub(super) fn materialize_range_index(&self, label: &str, property: &str) {
        self.materialize_pair(&self.indexes.range_pairs, label, property);
    }

    pub(super) fn materialize_point_index(&self, label: &str, property: &str) {
        self.materialize_pair(&self.indexes.point_pairs, label, property);
    }

    /// Repost every dirty node of one pair. The write guard is held across
    /// the whole drain, so a concurrent `declared_dirty` lands either before
    /// the take (reposted here) or after it (kept for the next drain).
    fn drain_pair<St: DrainState>(&self, pairs: &CoreMap<(u32, u32), St>, lid: u32, kid: u32) {
        let Some(mut st) = pairs.get_mut(&(lid, kid)) else {
            return;
        };
        if st.dirty().is_empty() {
            return;
        }
        let ids = std::mem::take(st.dirty_mut());
        for id in ids {
            st.remove_node(id);
            self.for_each_node_pair_value(id, lid, kid, |value| st.insert(id, value));
        }
    }

    /// The shared seek: drain each indexed label's pair, scan it, intersect
    /// across labels, and re-check the snapshot. `scan` returns `None` to
    /// decline (the caller scans), as does a pair that vanished between
    /// `indexed_labels` and here — a concurrent `DROP INDEX` must not be
    /// reported as zero rows.
    fn lookup_indexed<St: DrainState>(
        &self,
        pairs: &CoreMap<(u32, u32), St>,
        labels: &[String],
        key: &str,
        ts: u64,
        scan: impl Fn(&St) -> Option<HashSet<NodeId>>,
        pred: impl Fn(&Value) -> bool,
    ) -> Option<Vec<NodeId>> {
        let lids = self.indexed_labels(labels, key, pairs)?;
        let kid = self.interner.get_id(key)?;
        let mut acc: Option<HashSet<NodeId>> = None;
        for lid in lids {
            self.drain_pair(pairs, lid, kid);
            let st = pairs.get(&(lid, kid))?;
            let next = scan(&st)?;
            drop(st);
            intersect_acc(&mut acc, next);
        }
        Some(self.finish_ids(acc.into_iter().flatten(), labels, key, ts, pred))
    }

    pub(super) fn lookup_text_contains(
        &self,
        labels: &[String],
        key: &str,
        needle: &str,
        ts: u64,
    ) -> Option<Vec<NodeId>> {
        let grams = text::query_grams(needle)?;
        self.lookup_indexed(
            &self.indexes.gram_pairs,
            labels,
            key,
            ts,
            |st| Some(text::intersect_grams(st, &grams)),
            |v| v.as_string().is_some_and(|s| s.contains(needle)),
        )
    }

    pub(super) fn lookup_text_prefix(
        &self,
        labels: &[String],
        key: &str,
        prefix: &str,
        ts: u64,
    ) -> Option<Vec<NodeId>> {
        self.lookup_indexed(
            &self.indexes.range_pairs,
            labels,
            key,
            ts,
            |st| Some(order::prefix_ids(&st.order, prefix)),
            |v| v.as_string().is_some_and(|s| s.starts_with(prefix)),
        )
    }

    pub(crate) fn lookup_range_seek(
        &self,
        labels: &[String],
        key: &str,
        seek: &RangeSeek,
        ts: u64,
    ) -> Option<Vec<NodeId>> {
        match seek {
            RangeSeek::Eq(v) => self.lookup_range_values(labels, key, std::slice::from_ref(v), ts),
            RangeSeek::In(vs) => self.lookup_range_values(labels, key, vs, ts),
            RangeSeek::Cmp { op, bound } => {
                order::order_key(bound)?;
                let op = *op;
                self.lookup_indexed(
                    &self.indexes.range_pairs,
                    labels,
                    key,
                    ts,
                    // A stored temporal outside the order-key window is not
                    // posted; the index cannot answer a comparison then.
                    |st| {
                        st.unbounded
                            .is_empty()
                            .then(|| order::range_ids(&st.order, op, bound))
                    },
                    |v| order::cmp_holds(v, op, bound),
                )
            }
        }
    }

    /// Upper bound on the ids [`Self::lookup_range_seek`] would collect from
    /// the index, counted from posting lengths. `None` when the index cannot
    /// serve the predicate. A comparison with unbounded temporal postings
    /// declines, matching the id seek. The bound is not snapshot-filtered.
    pub(crate) fn range_seek_cardinality(
        &self,
        labels: &[String],
        key: &str,
        seek: &RangeSeek,
    ) -> Option<usize> {
        match seek {
            RangeSeek::Eq(v) => self.range_values_cardinality(labels, key, std::slice::from_ref(v)),
            RangeSeek::In(vs) => self.range_values_cardinality(labels, key, vs),
            RangeSeek::Cmp { op, bound } => {
                order::order_key(bound)?;
                let op = *op;
                self.range_pair_cost(labels, key, |st| {
                    st.unbounded
                        .is_empty()
                        .then(|| order::range_count(&st.order, op, bound))
                })
            }
        }
    }

    /// Work upper bound for one range seek across the indexed labels. `Some(0)`
    /// when any label posts nothing, because the label intersection is empty.
    fn range_pair_cost(
        &self,
        labels: &[String],
        key: &str,
        count: impl Fn(&order::RangeIndex) -> Option<usize>,
    ) -> Option<usize> {
        let lids = self.indexed_labels(labels, key, &self.indexes.range_pairs)?;
        let kid = self.interner.get_id(key)?;
        let mut cost = 0usize;
        for lid in lids {
            self.drain_pair(&self.indexes.range_pairs, lid, kid);
            let st = self.indexes.range_pairs.get(&(lid, kid))?;
            let n = count(&st)?;
            if n == 0 {
                return Some(0);
            }
            cost = cost.saturating_add(n);
        }
        Some(cost)
    }

    fn range_values_cardinality(
        &self,
        labels: &[String],
        key: &str,
        values: &[Value],
    ) -> Option<usize> {
        let mut total = 0usize;
        let mut served = false;
        for value in values {
            if GroupKey::for_property_index(value).is_none() {
                continue;
            }
            let n =
                self.range_pair_cost(labels, key, |st| Some(order::equality_count(st, value)))?;
            served = true;
            total = total.saturating_add(n);
        }
        served.then_some(total)
    }

    fn lookup_range_values(
        &self,
        labels: &[String],
        key: &str,
        values: &[Value],
        ts: u64,
    ) -> Option<Vec<NodeId>> {
        let lids = self.indexed_labels(labels, key, &self.indexes.range_pairs)?;
        let kid = self.interner.get_id(key)?;
        let mut matched = HashSet::new();
        for v in values {
            if GroupKey::for_property_index(v).is_none() {
                continue;
            }
            let mut acc: Option<HashSet<NodeId>> = None;
            for lid in &lids {
                let ids = self.range_equality_ids(*lid, kid, v)?;
                intersect_acc(&mut acc, ids);
            }
            if let Some(ids) = acc {
                matched.extend(ids);
            }
        }
        Some(self.finish_ids(matched, labels, key, ts, |v| {
            values.iter().any(|b| v.eq_non_null(b))
        }))
    }

    /// The capped form of the declared equality seek: the matches of
    /// `labels` and `props` among the postings of the shortest-posting
    /// `(label, property)` pair, stopping at `cap + 1` matches. No id set
    /// is built and no posting is read past the stop; each posting read
    /// is one node read, counted as examined. Every candidate is checked
    /// against the snapshot at `ts` with [`Graph::node_matches`], the
    /// predicate the unbounded seek's re-check applies. `None` when a pair
    /// vanished (a concurrent `DROP INDEX`): the caller scans instead.
    pub(super) fn range_equality_upto(
        &self,
        labels: &[String],
        props: &BTreeMap<String, Value>,
        ts: u64,
        cap: usize,
    ) -> Option<Vec<NodeId>> {
        let mut best: Option<(usize, u32, u32, &Value)> = None;
        for (key, value) in props {
            if GroupKey::for_property_index(value).is_none() {
                return Some(Vec::new());
            }
            let Some(kid) = self.interner.get_id(key) else {
                return Some(Vec::new());
            };
            for label in labels {
                let Some(lid) = self.interner.get_id(label) else {
                    continue;
                };
                if !self.indexes.range_pairs.contains_key(&(lid, kid)) {
                    continue;
                }
                self.drain_pair(&self.indexes.range_pairs, lid, kid);
                let st = self.indexes.range_pairs.get(&(lid, kid))?;
                let count = order::equality_count(&st, value);
                if best.is_none_or(|(least, ..)| count < least) {
                    best = Some((count, lid, kid, value));
                }
            }
        }
        let (_, lid, kid, value) = best?;
        let st = self.indexes.range_pairs.get(&(lid, kid))?;
        let (mut matched, mut examined) = (Vec::new(), 0u64);
        order::equality_each(&st, value, |id| {
            examined += 1;
            let hit = self
                .node_at(id, ts)
                .is_some_and(|n| Self::node_matches(&n, labels, props));
            if hit {
                matched.push(id);
            }
            if matched.len() > cap {
                ControlFlow::Break(())
            } else {
                ControlFlow::Continue(())
            }
        });
        crate::ctx::count_node_reads(examined);
        matched.sort_unstable();
        Some(matched)
    }

    /// Drain the range pair and read its equality postings. `None` when the
    /// pair vanished (a concurrent `DROP INDEX`), so the caller scans
    /// instead of reporting zero rows.
    pub(super) fn range_equality_ids(
        &self,
        lid: u32,
        kid: u32,
        value: &Value,
    ) -> Option<HashSet<NodeId>> {
        self.drain_pair(&self.indexes.range_pairs, lid, kid);
        let st = self.indexes.range_pairs.get(&(lid, kid))?;
        Some(order::equality_ids(&st, value))
    }

    pub(crate) fn lookup_spatial_seek(
        &self,
        labels: &[String],
        key: &str,
        seek: &SpatialSeek,
        ts: u64,
    ) -> Option<Vec<NodeId>> {
        self.lookup_indexed(
            &self.indexes.point_pairs,
            labels,
            key,
            ts,
            |st| Some(point::spatial_ids(st, seek)),
            |v| point::spatial_holds(v, seek),
        )
    }

    /// Re-check each posted candidate against the snapshot at `ts`: the
    /// visible version must carry every pattern label and a `key` value
    /// that satisfies `pred`. Reads the raw version — interned label ids
    /// and the one-slot `CompactProps::get` — never `node_at`, which
    /// materializes the full property map per candidate (the profile-hot
    /// `to_map` path, ADR-0033; LABS-853).
    fn finish_ids(
        &self,
        acc: impl IntoIterator<Item = NodeId>,
        labels: &[String],
        key: &str,
        ts: u64,
        pred: impl Fn(&Value) -> bool,
    ) -> Vec<NodeId> {
        // Every stored label and key was interned before its version
        // committed, so a pattern label or key the interner never saw is
        // carried by no node: nothing survives the re-check.
        let lids: Option<Vec<u32>> = labels.iter().map(|l| self.interner.get_id(l)).collect();
        let (Some(lids), Some(kid)) = (lids, self.interner.get_id(key)) else {
            return Vec::new();
        };
        let mut ids: Vec<_> = acc
            .into_iter()
            .filter(|id| {
                self.nodes.get(id).is_some_and(|vers| {
                    visible_version(&vers, ts).is_some_and(|ver| {
                        ver.live.has_labels(&lids) && ver.live.props.get(kid).is_some_and(&pred)
                    })
                })
            })
            .collect();
        ids.sort();
        ids.dedup();
        ids
    }

    /// True when every property has a range index on at least one pattern label.
    pub(super) fn range_serves_equality(
        &self,
        labels: &[String],
        props: &BTreeMap<String, Value>,
    ) -> bool {
        if labels.is_empty() || props.is_empty() {
            return false;
        }
        props.keys().all(|k| {
            labels.iter().any(|l| {
                self.string_pair_id(l, k)
                    .is_some_and(|pk| self.indexes.range_pairs.contains_key(&pk))
            })
        })
    }
}

/// Intersect `next` into the accumulator: the first set becomes the
/// accumulator, every later one narrows it. The canonical accumulator fold
/// for every multi-set seek (declared indexes and equality lookups).
pub(super) fn intersect_acc(acc: &mut Option<HashSet<NodeId>>, next: HashSet<NodeId>) {
    *acc = Some(match acc.take() {
        None => next,
        Some(prev) => prev.intersection(&next).copied().collect(),
    });
}

/// Per-kind byte estimate of the lazily built declared index pairs — the
/// research-gated census harness's view (ADR-0476 quarantine). Only
/// the order/by-node arms are counted; the eq-only fallback arms are not.
/// [`Self::text_bytes`] and [`Self::point_bytes`] are per-posting
/// estimates (no byte walk); every printed census row is one of these
/// fields.
#[cfg(feature = "research")]
#[derive(Debug, Default, Clone)]
pub struct DeclaredCensus {
    pub range_pairs: usize,
    pub range_order_keys: u64,
    pub range_posted_ids: u64,
    pub range_bytes: u64,
    pub text_pairs: usize,
    pub text_grams: u64,
    /// 8 bytes per gram posting.
    pub text_bytes: u64,
    pub point_pairs: usize,
    pub point_entries: u64,
    /// 40 bytes per posted point.
    pub point_bytes: u64,
}

impl Graph {
    #[cfg(feature = "research")]
    pub(super) fn declared_index_census(&self) -> DeclaredCensus {
        use std::mem::size_of;

        use crate::memory::{hashset_i64_bytes, vec_heap, OVERHEAD_MAP_ENTRY};

        let mut c = DeclaredCensus::default();
        for pair in self.indexes.range_pairs.iter() {
            c.range_pairs += 1;
            let st = pair.value();
            for postings in st.order.values() {
                c.range_order_keys += 1;
                c.range_bytes += size_of::<order::OrderKey>() as u64
                    + size_of::<order::Postings>() as u64
                    + OVERHEAD_MAP_ENTRY;
                match postings {
                    order::Postings::One(_) => c.range_posted_ids += 1,
                    order::Postings::Many(set) => {
                        c.range_posted_ids += set.len() as u64;
                        c.range_bytes += hashset_i64_bytes(set.capacity());
                    }
                }
            }
            for keys in st.by_node.values() {
                c.range_bytes +=
                    OVERHEAD_MAP_ENTRY + size_of::<order::RevKeys<order::OrderKey>>() as u64;
                if let order::RevKeys::Many(keys) = keys {
                    c.range_bytes += vec_heap(keys.len(), size_of::<order::OrderKey>() as u64);
                }
            }
            // Both sets are charged by element count: they are transient
            // and small next to the postings above.
            c.range_bytes += hashset_i64_bytes(st.dirty.len() + st.unbounded.len());
        }
        for pair in self.indexes.gram_pairs.iter() {
            c.text_pairs += 1;
            let grams = pair.value().grams.len() as u64;
            c.text_grams += grams;
            c.text_bytes += grams * 8;
        }
        for pair in self.indexes.point_pairs.iter() {
            c.point_pairs += 1;
            let entries = pair.value().pt_count() as u64;
            c.point_entries += entries;
            c.point_bytes += entries * 40;
        }
        c
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn order_remove_drops_only_that_node() {
        let mut st = RangeIndex::default();
        order::insert_order(&mut st, &Value::Int(1), 10);
        order::insert_order(&mut st, &Value::Int(2), 11);
        order::order_remove_node(&mut st, 10);
        assert!(!st
            .order
            .contains_key(&order::order_key(&Value::Int(1)).unwrap()));
        assert!(st
            .order
            .get(&order::order_key(&Value::Int(2)).unwrap())
            .unwrap()
            .contains(11));
    }

    #[test]
    fn string_order_key_shares_the_value_payload() {
        let payload: Arc<str> = "Ada".into();
        let value = Value::String(Arc::clone(&payload));
        let mut st = RangeIndex::default();
        order::insert_order(&mut st, &value, 10);
        order::insert_order(&mut st, &Value::String("Bob".into()), 11);
        let posted = st.by_node[&10].first().unwrap();
        assert!(matches!(posted, order::OrderKey::String(s) if Arc::ptr_eq(s, &payload)));
        assert!(st
            .order
            .keys()
            .any(|k| matches!(k, order::OrderKey::String(s) if Arc::ptr_eq(s, &payload))));
        assert_eq!(order::prefix_ids(&st.order, "A"), HashSet::from([10]));
    }

    #[test]
    fn gram_remove_drops_only_that_node() {
        let mut st = GramIndex::default();
        text::gram_insert(&mut st, &Arc::from("abc"), 10);
        text::gram_insert(&mut st, &Arc::from("zzz"), 11);
        text::gram_remove_node(&mut st, 10);
        assert!(st.grams.values().all(|ids| !ids.holds(10)));
        assert!(st.grams.values().any(|ids| ids.holds(11)));
    }

    /// `finish_ids` re-checks posted candidates on the raw version (LABS-853):
    /// a tombstoned node, one missing a pattern label, and one whose visible
    /// value fails the seek are each dropped exactly as the eager `node_at`
    /// re-check dropped them — compared against that oracle at both
    /// snapshots.
    #[test]
    fn finish_ids_filters_like_the_eager_node_at_recheck() {
        let g = Graph::default();
        let node = |labels: &[&str], x: i64| {
            g.create_node(
                labels.iter().map(|l| l.to_string()).collect(),
                BTreeMap::from([("x".into(), Value::Int(x))]),
            )
            .unwrap()
        };
        g.begin_write().unwrap();
        let kept = node(&["N", "M"], 5);
        let dead = node(&["N", "M"], 6);
        let unlabeled = node(&["N"], 7);
        let failing = node(&["N", "M"], 8);
        g.commit_write();
        g.materialize_range_index("N", "x");
        let before = g.commit_ts();
        g.begin_write().unwrap();
        g.delete_node(dead, true).unwrap();
        g.set_property_node(failing, "x", Value::Int(0));
        g.commit_write();
        let after = g.commit_ts();

        let op = relate_ir::BinaryOp::Gt;
        let bound = Value::Int(1);
        let seek = RangeSeek::Cmp {
            op,
            bound: bound.clone(),
        };
        let labels = vec!["N".to_string(), "M".to_string()];
        let eager = |ts: u64| {
            let mut ids: Vec<_> = [kept, dead, unlabeled, failing]
                .into_iter()
                .filter(|id| {
                    g.node_at(*id, ts).is_some_and(|n| {
                        Graph::node_matches(&n, &labels, &BTreeMap::new())
                            && n.properties
                                .get("x")
                                .is_some_and(|v| order::cmp_holds(v, op, &bound))
                    })
                })
                .collect();
            ids.sort();
            ids
        };
        let lazy = |ts: u64| g.lookup_range_seek(&labels, "x", &seek, ts).unwrap();

        assert_eq!(lazy(before), vec![kept, dead, failing]);
        assert_eq!(lazy(before), eager(before));
        assert_eq!(lazy(after), vec![kept]);
        assert_eq!(lazy(after), eager(after));
        // A pattern label the interner never saw is carried by no node.
        let ghost = vec!["N".to_string(), "Ghost".to_string()];
        assert_eq!(g.lookup_range_seek(&ghost, "x", &seek, after), Some(vec![]));
    }
}