Skip to main content

relate_executor/graph/
services.rs

1//! The store-level service bundle and its `Graph` accessors; the bundle's
2//! contract is documented on [`StoreServices`].
3
4use std::sync::Arc;
5
6use dashmap::DashMap;
7use relate_core::{PreviewFeatures, PreviewSources};
8
9use crate::csv::CsvPolicy;
10use crate::pattern_engine::PatternEngine;
11
12use super::{DatabasesCatalog, Graph, Procedure};
13
14/// Store-level services shared by every namespace graph of a store
15/// (ADR-0116 §10): the procedure registry, the LOAD CSV capability, the
16/// store's resolved preview set (ADR-0371, ADR-0378) and the databases
17/// catalog (ADR-0276). One bundle lives behind one `Arc`; every namespace
18/// graph of the store holds a clone of it (installed via
19/// [`Graph::share_services_from`]), so a procedure registered on the store
20/// is callable from any namespace session, the CSV policy and the preview
21/// set are identical in every namespace, and `ALTER DATABASE` /
22/// `SHOW DATABASES` read and write one shared databases table (ADR-0276;
23/// ADR-0116 §8 invariants) regardless of the session's namespace. Open
24/// installs the preview set once with [`Graph::configure_preview`]; both
25/// the catalog and the `CALL` gate read it back through [`Graph::preview`].
26///
27/// The members split into two kinds. The procedure registry, CSV policy,
28/// preview set, advertised serving address (ADR-0729) and pattern-engine
29/// switch (ADR-0519) are configuration the
30/// store owns and a follower keeps across
31/// a reload. The databases catalog is durable state: a checkpoint restores
32/// it into the loaded graph's fresh bundle, so the follow reload installs
33/// it with [`Graph::install_databases_from`] before adopting the surviving
34/// bundle instead of letting that bundle's stale copy win. A third member
35/// walks the line: the nested-evaluation budget is plain data in every
36/// build (never production configuration beyond its constant
37/// initializer, never reloaded by a follower), whose only writer is a
38/// `cfg(test)` setter — the budget-bomb seam, absent from every
39/// production build's write surface.
40#[derive(Debug)]
41pub(crate) struct StoreServices {
42    /// Registered procedures (TCK / user). Store-level state (ADR-0116 §10).
43    pub(crate) procedures: DashMap<String, Procedure>,
44    /// LOAD CSV capability (ADR-0081). The policy is store-level
45    /// (ADR-0116 §10), so it lives in the shared bundle.
46    pub(crate) csv_policy: CsvPolicy,
47    /// The store's resolved preview sources (ADR-0371, ADR-0378,
48    /// ADR-0719), installed at open and carried on follow reload: the
49    /// three additive carriers, kept per-set so the provenance `SHOW
50    /// SETTINGS` reports stays answerable. The union every gate reads
51    /// derives in [`Graph::preview`], never stored beside its parts.
52    pub(crate) preview_sources: PreviewSources,
53    /// The address a serving surface advertises for the store (ADR-0729):
54    /// the bound `host:port` of the Bolt or HTTP listener the store is
55    /// opened for. `None` — the embedded engine, which listens nowhere —
56    /// makes `SHOW DATABASES` report a null `address`.
57    pub(crate) advertised_address: Option<String>,
58    /// The store-level databases catalog (ADR-0276; ADR-0116 §8
59    /// invariants): the three fixed
60    /// namespaces' settings. One table for the whole store — per-graph
61    /// copies diverged when `ALTER DATABASE` wrote the `neo4j` graph's
62    /// theater while a `system` session read its own statically seeded one.
63    pub(crate) databases: DatabasesCatalog,
64    /// The per-allocation expression cap (ADR-0463) every namespace graph
65    /// of the store enforces. `None` is the explicit opt-out; the default is
66    /// [`crate::memory::EXPRESSION_BUDGET_BYTES`].
67    pub(crate) expression_memory_limit: Option<u64>,
68    /// The shared memo live-bytes budget (ADR-0657) every statement of the
69    /// store enforces, in bytes (the open-time setting is whole MiB).
70    /// `0` disables the budgeted memo tables.
71    pub(crate) memo_budget_bytes: u64,
72    /// The store's diagnostic pattern-engine switch (ADR-0519), resolved
73    /// once at open from `RELATE_PATTERN_ENGINE` and read by the
74    /// kernel rungs' routing. Configuration the store owns, like the
75    /// preview set; the default [`PatternEngine::Auto`] is today's
76    /// routing exactly.
77    pub(crate) pattern_engine: PatternEngine,
78    /// The per-statement nested-evaluation budget (ADR-0395, 1 000 000
79    /// since ADR-0670) — plain data in every build, whose only
80    /// production initializer is the published constant; the only writer
81    /// is the `cfg(test)` `set_nested_eval_budget` (the budget bombs).
82    /// The no-knob rule holds by write-path: no production code reads
83    /// anything but the default, and no process-global or thread-local
84    /// channel exists.
85    pub(crate) nested_eval_budget: u64,
86}
87
88impl Default for StoreServices {
89    fn default() -> Self {
90        Self {
91            procedures: DashMap::default(),
92            csv_policy: CsvPolicy::default(),
93            preview_sources: PreviewSources::default(),
94            advertised_address: None,
95            databases: DatabasesCatalog::default(),
96            expression_memory_limit: Some(crate::memory::EXPRESSION_BUDGET_BYTES),
97            memo_budget_bytes: crate::memory::memo_budget_bytes(
98                crate::memory::DEFAULT_MEMO_BUDGET_MIB,
99            ),
100            pattern_engine: PatternEngine::Auto,
101            nested_eval_budget: crate::memory::NESTED_EVAL_BUDGET,
102        }
103    }
104}
105
106impl Graph {
107    /// The store's one `StoreServices` bundle, mutable only before it is
108    /// shared with another graph. Both open-time installers
109    /// ([`Graph::configure_load_csv`], [`Graph::configure_preview`]) run
110    /// through this one accessor, so the pre-share contract and its panic
111    /// are stated once: after [`Graph::share_services_from`] the bundle's
112    /// `Arc` identity is the store's one-bundle invariant (ADR-0116 §10),
113    /// and rebuilding it would silently detach this graph from every other
114    /// namespace.
115    fn services_mut(&mut self) -> &mut StoreServices {
116        Arc::get_mut(&mut self.services).expect(
117            "the StoreServices bundle must be configured before \
118             share_services_from: it is already shared (ADR-0116 §10)",
119        )
120    }
121
122    /// Install the per-allocation expression cap (ADR-0463) before the
123    /// services bundle is shared. `None` disables the cap; the default is
124    /// [`crate::memory::EXPRESSION_BUDGET_BYTES`].
125    #[doc(hidden)]
126    pub fn configure_expression_memory_limit(&mut self, limit: Option<u64>) {
127        self.services_mut().expression_memory_limit = limit;
128    }
129
130    /// Install the shared memo budget (ADR-0657), in whole MiB, before the
131    /// services bundle is shared. `0` disables the budgeted memo tables.
132    #[doc(hidden)]
133    pub fn configure_expression_memo_budget(&mut self, mib: u64) {
134        self.services_mut().memo_budget_bytes = crate::memory::memo_budget_bytes(mib);
135    }
136
137    /// The configured shared memo budget in bytes (ADR-0657).
138    pub(crate) fn memo_budget_bytes(&self) -> u64 {
139        self.services.memo_budget_bytes
140    }
141
142    /// The configured per-allocation expression cap (`None` = no cap).
143    pub(crate) fn expression_memory_limit(&self) -> Option<u64> {
144        self.services.expression_memory_limit
145    }
146
147    /// Install a validated local CSV capability before sharing the graph with connections.
148    ///
149    /// Mutates the store's single `StoreServices` bundle in place; panics
150    /// if the bundle is already shared via [`Graph::share_services_from`]
151    /// (see `Graph::services_mut`).
152    #[doc(hidden)]
153    pub fn configure_load_csv(&mut self, policy: CsvPolicy) {
154        self.services_mut().csv_policy = policy;
155    }
156
157    /// Install the databases catalog a checkpoint loaded on `loaded` into
158    /// this graph's store-level bundle (ADR-0276), so a replacement graph
159    /// can then adopt that bundle without losing durable state.
160    ///
161    /// The catalog is the one durable member of [`StoreServices`]: the
162    /// store's configuration (procedure registry, CSV policy, preview set)
163    /// belongs to the surviving bundle, while `open_store_readonly` restores
164    /// this table into the fresh graph's own bundle through
165    /// [`Graph::restore_checkpoint_theater`]. The follow reload
166    /// (`follow::reload`) calls this before [`Graph::share_services_from`];
167    /// the catalog's interior mutability lets it write through `&Graph`
168    /// without rebuilding the bundle's `Arc`. Not public API.
169    #[doc(hidden)]
170    pub fn install_databases_from(&self, loaded: &Graph) {
171        self.databases().install(loaded.databases().snapshot());
172    }
173
174    /// Point this graph at the store-level service bundle of `other`
175    /// (ADR-0116 §10), so every namespace of a store shares one procedure
176    /// registry, one LOAD CSV policy, one resolved preview set, one advertised
177    /// address and one databases catalog. Called when the store creates or swaps a
178    /// namespace slot, and by the follow reload (`follow::reload`). The
179    /// bundle mixes configuration the store owns (procedure registry, CSV
180    /// policy, preview set, advertised address) with durable state restored from a checkpoint
181    /// (the databases catalog, ADR-0276), so a caller that loaded this graph
182    /// from disk must first install its catalog into `other` with
183    /// [`Graph::install_databases_from`]; a plain share replaces the loaded
184    /// bundle wholesale and would discard the checkpoint's catalog. Not
185    /// public API.
186    #[doc(hidden)]
187    pub fn share_services_from(&mut self, other: &Graph) {
188        self.services = Arc::clone(&other.services);
189    }
190
191    /// Look up a registered procedure in the store's shared registry
192    /// (ADR-0116 §10). Read-only: the registry itself is interior-mutable,
193    /// so lookups never touch the bundle's `Arc` identity.
194    #[doc(hidden)]
195    pub fn procedure(&self, name: &str) -> Option<Procedure> {
196        self.services.procedures.get(name).map(|p| p.clone())
197    }
198
199    /// Whether `name` is registered in the store's shared procedure
200    /// registry (ADR-0116 §10).
201    #[doc(hidden)]
202    pub fn has_procedure(&self, name: &str) -> bool {
203        self.services.procedures.contains_key(name)
204    }
205
206    /// Register a procedure into the store's shared registry (ADR-0116
207    /// §10), visible to every namespace graph of the store. Interior
208    /// mutation only; the bundle's `Arc` identity is untouched.
209    #[doc(hidden)]
210    pub fn register_procedure(&self, proc: Procedure) {
211        self.services.procedures.insert(proc.name.clone(), proc);
212    }
213
214    /// The store-level LOAD CSV policy (ADR-0081, ADR-0116 §10), read-only.
215    pub(crate) fn csv_policy(&self) -> &CsvPolicy {
216        &self.services.csv_policy
217    }
218
219    /// Install the store's resolved preview sources (ADR-0371,
220    /// ADR-0378, ADR-0719) on the one bundle; same pre-share contract
221    /// as [`Graph::configure_load_csv`]. The parts are the stored
222    /// fact; the union derives in [`Graph::preview`].
223    #[doc(hidden)]
224    pub fn configure_preview(&mut self, sources: PreviewSources) {
225        self.services_mut().preview_sources = sources;
226    }
227
228    /// Install the address a serving surface advertises (ADR-0729) on the
229    /// one bundle; same pre-share contract as [`Graph::configure_preview`].
230    #[doc(hidden)]
231    pub fn configure_advertised_address(&mut self, address: Option<String>) {
232        self.services_mut().advertised_address = address;
233    }
234
235    /// The store's advertised serving address (ADR-0729); `None` when the
236    /// store is embedded and no surface serves it.
237    pub(crate) fn advertised_address(&self) -> Option<&str> {
238        self.services.advertised_address.as_deref()
239    }
240
241    /// The store-level preview set (ADR-0371, ADR-0378) the `SHOW
242    /// PROCEDURES` catalog and the `CALL` gate read — the sources'
243    /// derived union.
244    #[doc(hidden)]
245    pub fn preview(&self) -> PreviewFeatures {
246        self.services.preview_sources.union()
247    }
248
249    /// The store's resolved preview sources (ADR-0719 decision 6) —
250    /// the parts behind the derived union, for the provenance `SHOW
251    /// SETTINGS` reports.
252    pub(crate) fn preview_sources(&self) -> PreviewSources {
253        self.services.preview_sources
254    }
255
256    /// Install the store's resolved pattern-engine switch (ADR-0519) on
257    /// the one bundle; same pre-share contract as
258    /// [`Graph::configure_preview`]. The open path resolves
259    /// `RELATE_PATTERN_ENGINE` once (the `RELATE_PARSER`
260    /// precedent's resolution site) and installs it here; a follower
261    /// keeps it across a reload with the rest of the store's
262    /// configuration.
263    #[doc(hidden)]
264    pub fn configure_pattern_engine(&mut self, engine: PatternEngine) {
265        self.services_mut().pattern_engine = engine;
266    }
267
268    /// The store's nested-evaluation budget (ADR-0395/ADR-0670) — the
269    /// field's contract is stated once, at the field.
270    pub(crate) fn nested_eval_budget(&self) -> u64 {
271        self.services.nested_eval_budget
272    }
273
274    /// The budget field's only writer (`cfg(test)` only): the budget
275    /// bombs lower their own store's budget. See the field's contract
276    /// for the no-knob rule it preserves.
277    #[cfg(test)]
278    pub(crate) fn set_nested_eval_budget(&mut self, budget: u64) {
279        self.services_mut().nested_eval_budget = budget;
280    }
281
282    /// The store-level pattern-engine switch (ADR-0519) the kernel
283    /// rungs' routing reads: [`PatternEngine::Auto`] on every store
284    /// opened without the diagnostic variable. Public since LABS-1117:
285    /// the EXPLAIN tree stamps it on every `MATCH` operator, so the one
286    /// static rung fact travels with the plan.
287    pub fn pattern_engine(&self) -> PatternEngine {
288        self.services.pattern_engine
289    }
290
291    /// The store-level databases catalog (ADR-0276; ADR-0116 §8
292    /// invariants), shared by every namespace graph of the store.
293    pub(crate) fn databases(&self) -> &DatabasesCatalog {
294        &self.services.databases
295    }
296}