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