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