Skip to main content

relate_executor/graph/
index.rs

1use relate_ir::BinaryOp;
2
3#[cfg(feature = "test-hooks")]
4use super::build_counter::BuildCounter;
5use super::*;
6
7/// Lazily materialized equality postings for one `(class, key)` pair
8/// (ADR-0063): the postings are a **superset** of true matches — stale ids
9/// from overwritten/deleted versions are filtered by the seek's residual
10/// snapshot re-verification (ADR-0018). A pair exists only after an
11/// equality seek materialized it; writes to unmaterialized pairs cost
12/// nothing, writes after materialization dirty-mark the entity. A node
13/// pair's class is a label id; a relationship pair's class is a type id
14/// (ADR-0185); the ids share `NodeId`'s/`RelId`'s `i64` shape.
15#[derive(Debug, Default)]
16pub(super) struct PropPairIndex {
17    /// True once the pair has been built from the label index at least once.
18    pub(super) built: bool,
19    /// Property value → ids that have carried it for this pair.
20    pub(super) postings: HashMap<GroupKey, HashSet<NodeId>>,
21    /// Ids written since `postings` was last brought current for this pair.
22    pub(super) dirty: HashSet<NodeId>,
23}
24
25/// All lazily maintained index state of a [`Graph`] (ADR-0063 lazy
26/// postings, ADR-0185 relationship pairs): the label index, the equality
27/// and declared pair maps, the interned `*`/empty-label sentinel ids, the
28/// label-posting reclamation candidates (ADR-0595), and the committed
29/// index memory charge. Bundled so `Graph`'s fields name what the graph
30/// is, and the index lifecycle lives beside the index code.
31#[derive(Debug)]
32pub(super) struct Indexes {
33    pub(super) label_index: CoreMap<u32, HashSet<NodeId>>,
34    /// `(label_id, key_id)` → lazily materialized equality postings
35    /// (ADR-0063 contract applied to equality seeks). A pair exists only
36    /// after an equality seek built it; writes after the build dirty-mark.
37    pub(super) prop_pairs: CoreMap<(u32, u32), PropPairIndex>,
38    /// `(rel_type_id, key_id)` → lazily materialized equality postings, the
39    /// relationship twin of `prop_pairs` (ADR-0185).
40    pub(super) rel_prop_pairs: CoreMap<(u32, u32), PropPairIndex>,
41    /// `(label_id, key_id)` → trigram postings for a `CREATE TEXT INDEX`.
42    pub(super) gram_pairs: CoreMap<(u32, u32), GramIndex>,
43    /// `(label_id, key_id)` → ordered postings for a `CREATE RANGE INDEX`.
44    pub(super) range_pairs: CoreMap<(u32, u32), RangeIndex>,
45    /// `(label_id, key_id)` → spatial postings for a `CREATE POINT INDEX`.
46    pub(super) point_pairs: CoreMap<(u32, u32), PointIndex>,
47    /// Interned id of the `*` any-label bucket used when a seek has no label.
48    pub(super) star_label_id: u32,
49    /// Interned id of the empty-string bucket for label-less nodes.
50    pub(super) empty_label_id: u32,
51    /// Label-posting reclamation candidates (ADR-0595): the dying
52    /// postings the removal sites appended through
53    /// [`Graph::suspect_postings`] — a tombstone, a label drop, or a
54    /// first label leaving the empty bucket — held once each, drained at the same
55    /// apply's tail — the single-writer moment — which removes those no
56    /// snapshot at or after the horizon can see and requeues the rest
57    /// while a pin still can. Bounded by one apply's removals.
58    pub(super) label_suspects: CoreMap<u32, HashSet<NodeId>>,
59    /// Committed [`crate::memory::IndexCharge`]. Rebuilt when `index_details`
60    /// changes so each node write clones an `Arc` instead of rescanning the
61    /// catalog.
62    pub(super) charge_cache: Mutex<Arc<crate::memory::IndexCharge>>,
63}
64
65/// One label-posting reclamation candidate's fate at a drain
66/// (ADR-0595): see [`Graph::label_posting_fate`].
67#[derive(Debug)]
68enum PostingFate {
69    /// The live version carries the label — the posting is current.
70    Live,
71    /// A carrying version's interval ends past the horizon — a pinned
72    /// snapshot still sees it; requeue for the next drain.
73    Pinned,
74    /// No snapshot at or after the horizon can see the label — reclaim.
75    Dead,
76}
77
78impl Indexes {
79    pub(super) fn new(interner: &Interner) -> Self {
80        Self {
81            label_index: CoreMap::default(),
82            prop_pairs: CoreMap::default(),
83            rel_prop_pairs: CoreMap::default(),
84            gram_pairs: CoreMap::default(),
85            range_pairs: CoreMap::default(),
86            point_pairs: CoreMap::default(),
87            star_label_id: interner.intern("*"),
88            empty_label_id: interner.intern(""),
89            label_suspects: CoreMap::default(),
90            charge_cache: Mutex::new(Arc::new(crate::memory::IndexCharge::default())),
91        }
92    }
93
94    /// Drop every lazily built structure (ADR-0063): the next seek or probe
95    /// rebuilds from the live graph on demand. `rebuild_indexes` re-fills
96    /// the label index and the declared pairs afterwards. The reclamation
97    /// candidates drop with them — the wholesale repost that follows adds
98    /// back only ids whose visible version carries the label, so no
99    /// pending candidate remains actionable.
100    fn clear(&self) {
101        self.label_index.clear();
102        self.label_suspects.clear();
103        self.prop_pairs.clear();
104        self.rel_prop_pairs.clear();
105        self.gram_pairs.clear();
106        self.range_pairs.clear();
107        self.point_pairs.clear();
108    }
109}
110
111/// Dirty-mark `id` on `key`'s pair when that pair is already built. An
112/// unbuilt pair costs nothing: its build walks the live records. The one
113/// spelling of the lazy-posting dirty policy the node and relationship
114/// write paths share.
115pub(super) fn dirty_mark_built(
116    pairs: &CoreMap<(u32, u32), PropPairIndex>,
117    key: (u32, u32),
118    id: NodeId,
119) {
120    if let Some(mut st) = pairs.get_mut(&key) {
121        if st.built {
122            st.dirty.insert(id);
123        }
124    }
125}
126
127impl Graph {
128    /// The buckets a live record's label set posts into: a label-less
129    /// record posts into the empty-label bucket, a labelled one into
130    /// each of its label buckets. The one policy
131    /// [`label_index_insert`](Self::label_index_insert), the reclamation
132    /// sites ([`suspect_postings`](Self::suspect_postings)) and the fate
133    /// predicate ([`label_posting_fate`](Self::label_posting_fate))
134    /// consult. The checkpoint GC's own prune
135    /// ([`index_drop_unused`](Self::index_drop_unused), over
136    /// `collect_index_keys`' string keys) states the same rule a second
137    /// time on the name side — changing the bucket rule means changing
138    /// both.
139    fn label_buckets<'a>(&'a self, labels: &'a [u32]) -> &'a [u32] {
140        if labels.is_empty() {
141            std::slice::from_ref(&self.indexes.empty_label_id)
142        } else {
143            labels
144        }
145    }
146
147    /// Insert `id` into the label index: the empty-label bucket when it
148    /// carries no labels, then one entry per label. The one spelling the
149    /// write path ([`index_add`](Self::index_add)) and the wholesale rebuild
150    /// ([`rebuild_indexes`](Self::rebuild_indexes)) share.
151    fn label_index_insert(&self, id: NodeId, label_ids: &[u32]) {
152        for &lid in self.label_buckets(label_ids) {
153            self.indexes.label_index.entry(lid).or_default().insert(id);
154        }
155    }
156
157    /// Append `id`'s dying postings as reclamation candidates (ADR-0595):
158    /// one per bucket the dying label set posts into —
159    /// [`label_buckets`'s](Self::label_buckets) one policy, in the
160    /// removal direction. Called from the removal sites (a tombstone, a
161    /// label drop, a first label leaving the empty bucket) inside the
162    /// apply, so the tail drain decides every posting at the moment it
163    /// dies — no probe's walk is needed and no read path mutates index
164    /// state. Lock contract: the `label_suspects` shard is taken and
165    /// released inside this call; the caller takes it with no `nodes` or
166    /// `label_index` guard held, and this call takes neither.
167    pub(super) fn suspect_postings(&self, id: NodeId, dying: &[u32]) {
168        for &lid in self.label_buckets(dying) {
169            self.indexes
170                .label_suspects
171                .entry(lid)
172                .or_default()
173                .insert(id);
174        }
175    }
176
177    /// Drain the reclamation candidates at the apply point (ADR-0595):
178    /// each candidate's posting fate decides it — a live carrier drops
179    /// from the list (a later delete re-suspects it), one whose posting
180    /// is bounded past the snapshot horizon is requeued for the next
181    /// drain (a pin still sees it), and one no snapshot at or after the
182    /// horizon can see leaves the label's posting set. The candidate set
183    /// holds each id once, so a pin cannot multiply the drain's
184    /// per-apply work. Lock order: the `label_suspects` guard is dropped
185    /// (the `remove` returns the set) before any `nodes` guard is taken
186    /// for the fate checks, and removals under the `label_index` write
187    /// guard come last — `index_add`'s order, never reversed. The
188    /// single-writer apply is what makes the check-then-remove
189    /// race-free against a posting insert.
190    pub(super) fn drain_label_suspects(&self) {
191        let horizon = self.gc_horizon();
192        let lids: Vec<u32> = self
193            .indexes
194            .label_suspects
195            .iter()
196            .map(|e| *e.key())
197            .collect();
198        for lid in lids {
199            let Some((_, ids)) = self.indexes.label_suspects.remove(&lid) else {
200                continue;
201            };
202            let (mut dead, mut pinned) = (Vec::new(), Vec::new());
203            for id in ids {
204                match self.label_posting_fate(id, lid, horizon) {
205                    PostingFate::Live => {}
206                    PostingFate::Pinned => pinned.push(id),
207                    PostingFate::Dead => dead.push(id),
208                }
209            }
210            if !pinned.is_empty() {
211                self.indexes
212                    .label_suspects
213                    .entry(lid)
214                    .or_default()
215                    .extend(pinned);
216            }
217            if dead.is_empty() {
218                continue;
219            }
220            if let Some(mut set) = self.indexes.label_index.get_mut(&lid) {
221                for id in dead {
222                    set.remove(&id);
223                }
224            }
225        }
226    }
227
228    /// One reclamation candidate's fate (ADR-0595): whether any version
229    /// of `id` posting into bucket `lid` is visible at or after the
230    /// horizon. The posting rule is [`label_buckets`'s](Self::label_buckets)
231    /// — bucket membership, with the empty-label bucket for a label-less
232    /// record — so the empty bucket's candidates answer like any other's.
233    /// The **canonical** live version (`Chain::live`, the newest
234    /// `xmax == 0` one) decides [`PostingFate::Live`]; a shadowed
235    /// open-ended version (a replayed re-create leaves one) is skipped.
236    /// It is not unreachable — a snapshot pinned in `[xmin, newer.xmin)`
237    /// reads it — but no removal site can suspect a label only a
238    /// shadowed version carries, because they all read the newest live
239    /// version's labels. A bounded posting interval the
240    /// checkpoint GC's own `dead_at` predicate keeps at the horizon is
241    /// [`PostingFate::Pinned`] (a pinned snapshot still sees it); nothing
242    /// reachable is [`PostingFate::Dead`]. A ts probe
243    /// (`node_carries_label_at`) is the wrong shape here: a version
244    /// created after the horizon is invisible to it while its live
245    /// interval is wide open.
246    fn label_posting_fate(&self, id: NodeId, lid: u32, horizon: u64) -> PostingFate {
247        let Some(vers) = self.nodes.get(&id) else {
248            return PostingFate::Dead;
249        };
250        let posts = |live: &LiveNode| self.label_buckets(&live.labels).contains(&lid);
251        if vers.live().is_some_and(|v| posts(v.live)) {
252            return PostingFate::Live;
253        }
254        let pinned = vers
255            .iter()
256            .any(|v| v.xmax != 0 && !v.dead_at(horizon) && posts(v.live));
257        if pinned {
258            PostingFate::Pinned
259        } else {
260            PostingFate::Dead
261        }
262    }
263
264    /// Add `id`'s label/equality postings, read straight from the live
265    /// record — no `Node` materialization on the bulk path (ADR-0063).
266    /// Same visibility rule as `node()`: the version visible at `read_ts`.
267    pub(super) fn index_add(&self, id: NodeId) {
268        let ts = self.read_ts();
269        let Some(vers) = self.nodes.get(&id) else {
270            return;
271        };
272        let Some(v) = vers.visible_at(ts) else {
273            return;
274        };
275        let live = &v.live;
276        self.label_index_insert(id, &live.labels);
277        // Equality postings are lazy (ADR-0063 contract): dirty-mark only the
278        // `(label, key)` pairs already materialized by a seek. A pair nobody
279        // seeks costs nothing on the write path.
280        for (lid, kid) in self.declared_dirty_pairs(live) {
281            dirty_mark_built(&self.indexes.prop_pairs, (lid, kid), id);
282            self.declared_dirty(lid, kid, id);
283        }
284    }
285
286    /// The `(label id, key id)` pairs a live node's declared postings cover:
287    /// its labels plus the any-label bucket, crossed with every property key.
288    /// The one walk `index_add` and `string_dirty_mark_node` share.
289    fn declared_dirty_pairs<'a>(
290        &self,
291        live: &'a LiveNode,
292    ) -> impl Iterator<Item = (u32, u32)> + 'a {
293        let star = self.indexes.star_label_id;
294        live.labels
295            .iter()
296            .copied()
297            .chain(std::iter::once(star))
298            .flat_map(move |lid| live.props.iter().map(move |(kid, _)| (lid, kid)))
299    }
300
301    /// Dirty-mark the built string pairs of `id`'s installed live version —
302    /// the id-taking shape the other lazy-posting helpers use; the caller has
303    /// just installed the version (apply-before-dirty ordering).
304    pub(super) fn string_dirty_mark_node(&self, id: NodeId) {
305        let vers = self
306            .nodes
307            .get(&id)
308            .expect("string dirty-mark follows an installed node version");
309        let live = vers.last().live;
310        for (lid, kid) in self.declared_dirty_pairs(live) {
311            self.declared_dirty(lid, kid, id);
312        }
313    }
314}
315
316#[cfg(feature = "test-hooks")]
317thread_local! {
318    /// Whole-graph index rebuilds (`rebuild_indexes`) on this thread. Behind
319    /// the off-by-default `test-hooks` feature, unlike the cfg(test)-only
320    /// `ADJ_BUILDS` seam in `rebuild.rs`: the facade's reopen tests read it
321    /// across the crate boundary to pin that a clean close's open skips the
322    /// wholesale rebuild (LABS-1112) — behavior with no other observable
323    /// surface.
324    static INDEX_REBUILDS: BuildCounter = const { BuildCounter::new() };
325}
326
327/// Take this thread's whole-graph index-rebuild count, resetting it.
328#[cfg(feature = "test-hooks")]
329#[doc(hidden)]
330pub fn take_index_rebuilds() -> u64 {
331    INDEX_REBUILDS.with(BuildCounter::take)
332}
333
334impl Graph {
335    /// Rebuild the indexes from the live versions. Adjacency is left as it
336    /// is: writes and replayed redo keep it current, and
337    /// `Graph::finish_restore` builds it after a checkpoint load. The open
338    /// flow's single post-replay site owns this rebuild — exactly once per
339    /// open, after the graph is final (snapshot plus replayed tail).
340    pub fn rebuild_indexes(&self) {
341        #[cfg(feature = "test-hooks")]
342        INDEX_REBUILDS.with(BuildCounter::bump);
343        // Equality and string postings are both lazy (ADR-0063), and
344        // relationship equality pairs are lazy the same way (ADR-0185):
345        // drop them; the next seek rebuilds from the live graph on demand.
346        self.indexes.clear();
347        let ts = self.commit_ts();
348        for id in self.all_node_ids_at(ts) {
349            if let Some(n) = self.node_at(id, ts) {
350                let label_ids: Vec<u32> =
351                    n.labels.iter().map(|l| self.interner.intern(l)).collect();
352                self.label_index_insert(id, &label_ids);
353            }
354        }
355        // ADR-0439: the committed constraint-key map rebuilds wholesale from
356        // the live graph on open, checkpoint restore, and abort — like
357        // `label_counts`, and with replay-installed duplicates carried
358        // forward. Its charge is re-tallied by `recompute_used` below.
359        self.rebuild_constraint_keys();
360        // Equality, prefix, trigram, and point postings follow catalog
361        // indexes. `rebuild_declared_indexes` refills the pairs named by
362        // TEXT / RANGE / POINT; anything else stays a scan.
363        self.rebuild_declared_indexes();
364        // Checkpoint restore installs `index_details` without going through
365        // `apply_redo`, so the charge cache is still empty until here.
366        self.refresh_index_charge();
367        self.recompute_used();
368    }
369
370    pub fn gc_versions(&self) {
371        let horizon = self.gc_horizon();
372        // ADR-0551: the checkpoint's GC pass is the one moment the store may
373        // pay the O(chunk) re-encode; a chunk below the watermark stays delta.
374        self.compact_adjacency_at_watermark(horizon);
375        let nids: Vec<NodeId> = self.nodes.keys();
376        for id in nids {
377            self.gc_node_chain(id, horizon);
378        }
379        let rids: Vec<RelId> = self.rels.keys();
380        for id in rids {
381            self.gc_rel_chain(id, horizon);
382        }
383        self.recompute_used();
384    }
385
386    pub(super) fn gc_node_chain(&self, id: NodeId, horizon: u64) {
387        let Some(mut vers) = self.nodes.get_mut(&id) else {
388            return;
389        };
390        if !vers.any_dead(horizon) {
391            return;
392        }
393        let dead: Vec<Node> = vers
394            .iter()
395            .filter(|v| v.dead_at(horizon))
396            .map(|v| v.live.to_node(id, &self.interner))
397            .collect();
398        let empty = !vers.collect(horizon);
399        let remaining: Vec<Node> = if empty {
400            Vec::new()
401        } else {
402            vers.iter()
403                .map(|v| v.live.to_node(id, &self.interner))
404                .collect()
405        };
406        drop(vers);
407        if empty {
408            self.nodes.remove(&id);
409        }
410        self.index_drop_unused(id, &dead, &remaining);
411    }
412
413    pub(super) fn gc_rel_chain(&self, id: RelId, horizon: u64) {
414        // Pairs are lazy (ADR-0185): when none was ever built there is
415        // nothing to prune, so the dead/remaining collection — two
416        // `LiveRel` clones per collected version — is skipped. Checked
417        // before the `rels` guard is taken: the pair guard is never taken
418        // while a `rels` guard is held. A pair built racing this check
419        // keeps the collected ids as stale postings: a superset leak,
420        // never a correctness one.
421        let prune = !self.indexes.rel_prop_pairs.is_empty();
422        let Some(mut vers) = self.rels.get_mut(&id) else {
423            return;
424        };
425        if !vers.any_dead(horizon) {
426            return;
427        }
428        // LABS-1116: the chain's endpoints and type, needed to prune its
429        // adjacency hops when the chain empties. The `any(dead_at)` guard
430        // above proves the chain non-empty, and every version of one rel
431        // id shares its endpoints (`cow` clones the previous version's
432        // endpoints; no operation moves a rel) — and `Chain::last` fails
433        // loud on an empty chain, a broken invariant that must not
434        // silently skip the prune (F-1-11).
435        let newest = vers.last();
436        let (start, end, type_id) = (newest.live.start, newest.live.end, newest.live.type_id);
437        let dead: Vec<LiveRel> = if prune {
438            vers.iter()
439                .filter(|v| v.dead_at(horizon))
440                .map(|v| v.live.clone())
441                .collect()
442        } else {
443            Vec::new()
444        };
445        let empty = !vers.collect(horizon);
446        let remaining: Vec<LiveRel> = if prune && !empty {
447            vers.iter().map(|v| v.live.clone()).collect()
448        } else {
449            Vec::new()
450        };
451        drop(vers);
452        if empty {
453            self.rels.remove(&id);
454            // LABS-1116: prune the orphaned hops — without this, a chain
455            // the GC collected leaves its hops in adjacency forever, and
456            // every later scan pays a `rels` map miss per ghost hop (the
457            // per-hop visibility probe stays the authority; this only
458            // stops offering it a rel it cannot resolve).
459            self.out_side().remove(start, type_id, id);
460            self.in_side().remove(end, type_id, id);
461        }
462        // Prune after the `rels` guard is released — the pair guard is never
463        // taken while a `rels` guard is held. When `prune` is false both
464        // slices are empty and this is a no-op.
465        self.rel_index_drop_unused(id, &dead, &remaining);
466    }
467
468    pub(super) fn index_drop_unused(&self, id: NodeId, dead: &[Node], remaining: &[Node]) {
469        let mut keep_labels = HashSet::new();
470        let mut keep_props = HashSet::new();
471        for n in remaining {
472            collect_index_keys(n, &mut keep_labels, &mut keep_props);
473        }
474        let mut drop_labels = HashSet::new();
475        let mut drop_props = HashSet::new();
476        for n in dead {
477            collect_index_keys(n, &mut drop_labels, &mut drop_props);
478        }
479        for l in drop_labels {
480            if keep_labels.contains(&l) {
481                continue;
482            }
483            let lid = if l.is_empty() {
484                self.indexes.empty_label_id
485            } else {
486                match self.interner.get_id(&l) {
487                    Some(lid) => lid,
488                    None => continue,
489                }
490            };
491            if let Some(mut set) = self.indexes.label_index.get_mut(&lid) {
492                set.remove(&id);
493            }
494        }
495        // The pair-side prune shares `drop_unused_pairs` with the
496        // relationship twin; the string (label, key) triples resolve to
497        // interned ids here through `string_pair_id`, the one pair-id
498        // resolver (`*` bucket included).
499        let drop_props: Vec<(String, String, GroupKey)> = drop_props.into_iter().collect();
500        let keep_props: Vec<(String, String, GroupKey)> = keep_props.into_iter().collect();
501        self.drop_unused_pairs(
502            &self.indexes.prop_pairs,
503            id,
504            &drop_props,
505            &keep_props,
506            |(label, key, gk), f| {
507                let Some((lid, kid)) = self.string_pair_id(label, key) else {
508                    return;
509                };
510                f(lid, kid, gk.clone());
511            },
512        );
513    }
514}
515
516fn collect_index_keys(
517    n: &Node,
518    labels: &mut HashSet<String>,
519    props: &mut HashSet<(String, String, GroupKey)>,
520) {
521    if n.labels.is_empty() {
522        labels.insert(String::new());
523    }
524    labels.extend(n.labels.iter().cloned());
525    for (k, v) in &*n.properties {
526        if let Some(gk) = GroupKey::for_property_index(v) {
527            for l in &*n.labels {
528                props.insert((l.clone(), k.clone(), gk.clone()));
529            }
530            props.insert(("*".into(), k.clone(), gk));
531        }
532    }
533}
534
535/// How many of a label's nodes a sampled `CONTAINS` estimate reads before
536/// it extrapolates (LABS-643): enough that a rare needle still surfaces in
537/// the sample of a million-row label, few enough that the plan-time read
538/// stays a bounded microsecond cost, never a scan. `pub(crate)` for the
539/// pattern-stats tests, which size labels around it.
540pub(crate) const CONTAINS_SAMPLE_BOUND: usize = 1024;
541
542/// The floor on a sampled estimate, as a divisor of the label's rows
543/// (LABS-643): an unindexed `CONTAINS` filter still pays the whole-label
544/// scan, so its estimate never drops below 1% of the label. Low enough
545/// that the survivor count still beats a competing label scan (GBL SF0.1
546/// q19: a 160-row floor on the 16k Tag label still seeds ahead of
547/// Place's 1,460 whole-label rows), high enough that it never undercuts
548/// an index-served seed (GBL q2/q16: the 1%-of-Post floor loses to the
549/// RANGE-equality person/place seed, where anchoring on a whole-post
550/// content scan is the 200 ms plan).
551const CONTAINS_SAMPLE_FLOOR_DIVISOR: u64 = 100;
552
553/// How many needle estimates one committed epoch's
554/// [`ContainsMemo`](struct@ContainsMemo) keeps. The memo is keyed by a
555/// query-supplied needle, so it is a query-controlled map — the memory
556/// discipline the charged stats maps (`pair_counts`, `label_counts`)
557/// solve with `used_bytes`, this one solves with a hard cap: past it the
558/// memo clears and the next caller resamples.
559const CONTAINS_MEMO_CAP: usize = 64;
560
561/// One interned `(label, key)` pair's needle estimates: the needle texts
562/// and their sampled counts, few enough per pair that a borrowed linear
563/// scan beats hashing an owned triple.
564type NeedleEstimates = Vec<(Box<str>, ContainsCount)>;
565
566/// The committed epoch's memoized sampled `CONTAINS` estimates
567/// (LABS-643): the executor's per-row start-selection estimate re-asks
568/// one `(label, property, needle)` question for every row of a clause,
569/// and the sample scan must not ride that loop. Needles nest per interned
570/// `(label, key)` pair, not one flat `(u32, u32, Box<str>)` key, so the
571/// hot lookup borrows the caller's needle text without allocating an
572/// owned key per row.
573#[derive(Default, Debug)]
574pub(super) struct ContainsMemo {
575    /// The `commit_ts` the entries sampled: a commit moves the epoch and
576    /// the next reader resets the map, so no entry can outlive the
577    /// committed data it sampled.
578    ts: u64,
579    /// `(label_id, key_id)` → the epoch's needle estimates.
580    entries: HashMap<(u32, u32), NeedleEstimates>,
581}
582
583impl Graph {
584    /// Nodes stored under `label`. `0` when the label is absent.
585    /// The label index can hold stale ids, so this is an upper bound used
586    /// only to compare pattern costs — the same label-index estimate as
587    /// [`Self::label_count`], which owns the one implementation, so this
588    /// pattern-stats spelling delegates to it.
589    pub fn pattern_label_rows(&self, label: &str) -> u64 {
590        self.label_count(label)
591    }
592
593    /// Equality hits for a RANGE index on `(label, property)`. `None` when
594    /// that index does not exist.
595    pub fn pattern_equality_rows(&self, label: &str, property: &str, value: &Value) -> Option<u64> {
596        let lid = self.interner.get_id(label)?;
597        let kid = self.interner.get_id(property)?;
598        self.pattern_equality_rows_by_id(lid, kid, value)
599    }
600
601    /// [`Graph::pattern_equality_rows`] for already-resolved token ids.
602    pub fn pattern_equality_rows_by_id(&self, lid: u32, kid: u32, value: &Value) -> Option<u64> {
603        let ids = self.range_equality_ids(lid, kid, value)?;
604        Some(ids.len() as u64)
605    }
606
607    /// Range-window hits for one comparison predicate on a RANGE index
608    /// over `(label, property)` (ADR-0486): the posting-length count the
609    /// one [`Graph::range_seek_cardinality`] answers — the same count the
610    /// executor's seek cardinality reads, so the ladder's price and the
611    /// runtime seek cannot drift, and the decline conditions are exactly
612    /// the seek's (no index on the pair, no order key on the bound, or
613    /// unbounded temporal postings). `op` is one of the four comparison
614    /// ops — the planner's recognizer gates the domain, `=` is
615    /// [`Graph::pattern_equality_rows`]'s. The count is an upper bound,
616    /// not snapshot-filtered. `None` is not zero hits.
617    pub fn pattern_range_rows(
618        &self,
619        label: &str,
620        property: &str,
621        op: BinaryOp,
622        bound: &Value,
623    ) -> Option<u64> {
624        // The cheap decline first, the `pattern_equality_rows` way: the
625        // pair's index existence answers "cannot serve" before the
626        // seek's owned forms are built — the ladder prices every
627        // comparison conjunct once per row, and the common no-index
628        // case must pay no label String and no bound clone for its
629        // `None`. This is `indexed_labels`' own pair predicate
630        // (interner ids, `range_pairs` membership) spelled at the
631        // front; the bound's `order_key` gate stays the count's, where
632        // the built seek already carries it.
633        let lid = self.interner.get_id(label)?;
634        let kid = self.interner.get_id(property)?;
635        if !self.indexes.range_pairs.contains_key(&(lid, kid)) {
636            return None;
637        }
638        let seek = RangeSeek::Cmp {
639            op,
640            bound: bound.clone(),
641        };
642        self.range_seek_cardinality(&[label.to_string()], property, &seek)
643            .map(|count| count as u64)
644    }
645
646    /// `CONTAINS` candidates for the pattern-stats ladder (ADR-0218):
647    /// the exact count a TEXT index on `(label, property)` answers, and —
648    /// LABS-643 — without that index the bounded sampled estimate
649    /// carrying its whole-label scan rows, never `None`. The planner's
650    /// CONTAINS level used to be measurable only through a TEXT index, so
651    /// a RANGE-only store fell back to whole-label rows (GBL SF0.1 q19:
652    /// Tag priced at its 16k label rows lost the seed to Place's 1.4k,
653    /// and the walk rode 342k neighbor hops for a query whose needle
654    /// selects ~35 tags). The sampled form's `scan` field is the one the
655    /// compound start estimate (ADR-0474) floors the seed's walk with.
656    pub fn pattern_contains_rows(
657        &self,
658        label: &str,
659        property: &str,
660        needle: &str,
661    ) -> ContainsCount {
662        // One epoch read threaded through both provenance paths (the TEXT
663        // lookup and the sample): the two could observe different commits
664        // if each took its own `commit_ts`.
665        let ts = self.commit_ts();
666        if let Some(ids) = self.lookup_text_contains(&[label.to_string()], property, needle, ts) {
667            return ContainsCount::TextIndex(ids.len() as u64);
668        }
669        self.sampled_contains_rows(label, property, needle, ts)
670    }
671
672    /// The LABS-643 sampled estimate, memoized per committed epoch: the
673    /// first caller of an epoch scans, every later one reads the memo —
674    /// the executor's per-row start-selection estimate re-asks one
675    /// `(label, property, needle)` question per row and must not rescan
676    /// per row. `ts` is the epoch the caller's provenance paths already
677    /// read ([`Self::pattern_contains_rows`]).
678    fn sampled_contains_rows(
679        &self,
680        label: &str,
681        property: &str,
682        needle: &str,
683        ts: u64,
684    ) -> ContainsCount {
685        let pair = match (self.interner.get_id(label), self.interner.get_id(property)) {
686            (Some(lid), Some(kid)) => (lid, kid),
687            // A key the store never interned can match nothing, but the
688            // label's bucket is still the scan a seed there would pay; a
689            // label never interned has no bucket at all. Both stay
690            // measurable zeros.
691            (Some(lid), None) => {
692                let scan = self
693                    .indexes
694                    .label_index
695                    .get(&lid)
696                    .map_or(0, |bucket| bucket.len() as u64);
697                return ContainsCount::SampleScan { rows: 0, scan };
698            }
699            _ => return ContainsCount::SampleScan { rows: 0, scan: 0 },
700        };
701        if let Some(count) = self.contains_memo_hit(ts, pair, needle) {
702            return count;
703        }
704        let count = self.scan_contains_sample(pair, needle, ts);
705        self.contains_memo_store(ts, pair, needle, count);
706        count
707    }
708
709    /// One bounded sample scan: the first `CONTAINS_SAMPLE_BOUND` ids of
710    /// the label's index bucket, each probed for its live string at `ts`.
711    /// The bucket's ids are copied under one short `label_index` guard
712    /// that is dropped before the first `nodes` guard — the lock order of
713    /// [`label_probe`](super::label_probe)'s copies, never reversing
714    /// [`Graph::index_add`]'s `nodes` -> `label_index` order. A stale id
715    /// (deleted since, bucketed until GC) counts as a scanned non-match,
716    /// the same upper-bound stance [`Graph::label_count`] takes, so the
717    /// extrapolation stays consistent with the label-row level above it.
718    /// The bucket's whole row count rides along as the count's `scan`:
719    /// the unseekable filter pays that scan before any match, the cost
720    /// the compound start estimate (ADR-0474) floors the seed's walk
721    /// with.
722    fn scan_contains_sample(&self, pair: (u32, u32), needle: &str, ts: u64) -> ContainsCount {
723        let (lid, kid) = pair;
724        // (sample, bucket rows): the copy takes at most the bound, and the
725        // bucket's whole size is the extrapolation's denominator base.
726        let (sample, total): (Vec<NodeId>, u64) = match self.indexes.label_index.get(&lid) {
727            Some(bucket) => (
728                bucket.iter().take(CONTAINS_SAMPLE_BOUND).copied().collect(),
729                bucket.len() as u64,
730            ),
731            None => return ContainsCount::SampleScan { rows: 0, scan: 0 },
732        };
733        let scanned = sample.len() as u64;
734        if scanned == 0 {
735            return ContainsCount::SampleScan {
736                rows: 0,
737                scan: total,
738            };
739        }
740        let matches = sample
741            .iter()
742            .filter(|id| {
743                // The raw version's one-slot `CompactProps::get`, not
744                // `node_at`: the sample must not materialize a property
745                // map per node (the profile-hot `to_map` path, ADR-0033),
746                // and the visible version's probe stays inside the one
747                // `nodes` guard it borrows.
748                self.nodes.get(id).is_some_and(|vers| {
749                    visible_version(&vers, ts).is_some_and(|ver| {
750                        ver.live.props.get(kid).is_some_and(|value| {
751                            value.as_string().is_some_and(|s| s.contains(needle))
752                        })
753                    })
754                })
755            })
756            .count() as u64;
757        // The count: exact when the whole bucket was scanned (`scanned ==
758        // total` collapses the formula to `matches`), extrapolated beyond
759        // it. The u128 product keeps a full-bucket match count from
760        // overflowing before the divide. The floor keeps the unseekable
761        // filter from pricing itself below an index-served seed
762        // (`CONTAINS_SAMPLE_FLOOR_DIVISOR` owns the one rationale).
763        let counted =
764            ((matches as u128 * total as u128) / u128::from(scanned)).min(u64::MAX as u128) as u64;
765        ContainsCount::SampleScan {
766            rows: counted.max(total / CONTAINS_SAMPLE_FLOOR_DIVISOR),
767            scan: total,
768        }
769    }
770
771    /// The memo read of the current epoch: `None` on a miss or when the
772    /// epoch moved (the caller rescans and stores under the new epoch).
773    fn contains_memo_hit(&self, ts: u64, pair: (u32, u32), needle: &str) -> Option<ContainsCount> {
774        let memo = self.contains_memo.lock().unwrap();
775        if memo.ts != ts {
776            return None;
777        }
778        memo.entries
779            .get(&pair)?
780            .iter()
781            .find(|(text, _)| text.as_ref() == needle)
782            .map(|(_, count)| *count)
783    }
784
785    /// The memo write: a moved epoch resets first, and a map at the cap
786    /// clears instead of growing (the query-controlled-map bound, see
787    /// [`ContainsMemo`](struct@ContainsMemo)). Concurrent samplers of one
788    /// needle update the slot in place rather than stacking duplicates.
789    fn contains_memo_store(&self, ts: u64, pair: (u32, u32), needle: &str, count: ContainsCount) {
790        let mut memo = self.contains_memo.lock().unwrap();
791        if memo.ts != ts {
792            memo.ts = ts;
793            memo.entries.clear();
794        }
795        if memo.entries.values().map(Vec::len).sum::<usize>() >= CONTAINS_MEMO_CAP {
796            memo.entries.clear();
797        }
798        let bucket = memo.entries.entry(pair).or_default();
799        match bucket.iter_mut().find(|(text, _)| text.as_ref() == needle) {
800            Some(slot) => slot.1 = count,
801            None => bucket.push((Box::from(needle), count)),
802        }
803    }
804
805    /// Record a DDL-named graph catalog name in the namespace its entity
806    /// kind selects (ADR-0363 decision 5): `names` are node labels when
807    /// `relationship` is false, relationship types when true. This is the
808    /// committed twin of the write overlay's scratch facts: an index or
809    /// constraint DDL records its subject through the same catalog sets, so
810    /// a name a transaction mentions stays known after COMMIT publishes it.
811    /// Monotone like the data-write feeds: a later drop never removes a name.
812    pub(crate) fn record_schema_names(
813        &self,
814        relationship: bool,
815        names: impl IntoIterator<Item = String>,
816    ) {
817        let mut catalog = self.catalog.lock().unwrap();
818        for name in names {
819            catalog.record_schema_name(relationship, name);
820        }
821    }
822
823    /// Whether the store catalog knows `label` — the same label set
824    /// `Graph::create_node` / `Graph::add_labels` record on first sight and
825    /// the restore paths (checkpoint rows, WAL redo) record on reload. The
826    /// catalog never removes a label, so a miss proves the label has never
827    /// existed in this store (no false positive for the plan-time warning);
828    /// a hit can outlive the last node carrying it.
829    pub(crate) fn has_label(&self, label: &str) -> bool {
830        self.catalog.lock().unwrap().labels.contains(label)
831    }
832
833    /// Whether the store catalog knows relationship type `rel_type` — the
834    /// one rel-type set `Graph::create_rel` / the restore paths record.
835    /// The same monotone contract as [`Graph::has_label`]: a miss proves
836    /// the type has never existed, a hit may outlive the last relationship.
837    pub(crate) fn has_rel_type(&self, rel_type: &str) -> bool {
838        self.catalog.lock().unwrap().rel_types.contains(rel_type)
839    }
840
841    /// Whether property key `key` has ever been interned by this store —
842    /// a **superset** of the keys `db.propertyKeys` reports.
843    ///
844    /// Every stored property key is interned: `CompactProps::from_parts`
845    /// interns each key a CREATE/SET/MERGE writes, and the checkpoint
846    /// restore and WAL redo paths build their properties through the same
847    /// interner. A key the store has never held is therefore absent, and a
848    /// miss is a true miss. The converse is not true — labels, relationship
849    /// types and the internal relationship `ts` key share the table, and a
850    /// key removed from every entity stays interned — so a hit can only
851    /// suppress a warning, never invent one. That one-sided guarantee is
852    /// what plan-time unknown-key diagnostics need: never warn about a key
853    /// the store holds, at the cost of a false negative for a stale name.
854    pub(crate) fn has_property_key(&self, key: &str) -> bool {
855        self.interner.get_id(key).is_some()
856    }
857}
858
859#[cfg(test)]
860mod tests;