Skip to main content

relate_executor/graph/
index.rs

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