Skip to main content

relate_executor/graph/
index.rs

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