relate-executor 1.5.0

In-memory graph and Cypher physical executor
Documentation
//! The store-level service bundle and its `Graph` accessors; the bundle's
//! contract is documented on [`StoreServices`].

use std::sync::Arc;

use dashmap::DashMap;
use relate_core::{PreviewFeatures, PreviewSources};

use crate::csv::CsvPolicy;
use crate::pattern_engine::PatternEngine;

use super::{DatabasesCatalog, Graph, Procedure};

/// Store-level services shared by every namespace graph of a store
/// (ADR-0116 §10): the procedure registry, the LOAD CSV capability, the
/// store's resolved preview set (ADR-0371, ADR-0378) and the databases
/// catalog (ADR-0276). One bundle lives behind one `Arc`; every namespace
/// graph of the store holds a clone of it (installed via
/// [`Graph::share_services_from`]), so a procedure registered on the store
/// is callable from any namespace session, the CSV policy and the preview
/// set are identical in every namespace, and `ALTER DATABASE` /
/// `SHOW DATABASES` read and write one shared databases table (ADR-0276;
/// ADR-0116 §8 invariants) regardless of the session's namespace. Open
/// installs the preview set once with [`Graph::configure_preview`]; both
/// the catalog and the `CALL` gate read it back through [`Graph::preview`].
///
/// The members split into two kinds. The procedure registry, CSV policy,
/// preview set, advertised serving address (ADR-0729) and pattern-engine
/// switch (ADR-0519) are configuration the
/// store owns and a follower keeps across
/// a reload. The databases catalog is durable state: a checkpoint restores
/// it into the loaded graph's fresh bundle, so the follow reload installs
/// it with [`Graph::install_databases_from`] before adopting the surviving
/// bundle instead of letting that bundle's stale copy win. A third member
/// walks the line: the nested-evaluation budget is plain data in every
/// build (never production configuration beyond its constant
/// initializer, never reloaded by a follower), whose only writer is a
/// `cfg(test)` setter — the budget-bomb seam, absent from every
/// production build's write surface.
#[derive(Debug)]
pub(crate) struct StoreServices {
    /// Registered procedures (TCK / user). Store-level state (ADR-0116 §10).
    pub(crate) procedures: DashMap<String, Procedure>,
    /// LOAD CSV capability (ADR-0081). The policy is store-level
    /// (ADR-0116 §10), so it lives in the shared bundle.
    pub(crate) csv_policy: CsvPolicy,
    /// The store's resolved preview sources (ADR-0371, ADR-0378,
    /// ADR-0719), installed at open and carried on follow reload: the
    /// three additive carriers, kept per-set so the provenance `SHOW
    /// SETTINGS` reports stays answerable. The union every gate reads
    /// derives in [`Graph::preview`], never stored beside its parts.
    pub(crate) preview_sources: PreviewSources,
    /// The address a serving surface advertises for the store (ADR-0729):
    /// the bound `host:port` of the Bolt or HTTP listener the store is
    /// opened for. `None` — the embedded engine, which listens nowhere —
    /// makes `SHOW DATABASES` report a null `address`.
    pub(crate) advertised_address: Option<String>,
    /// The store-level databases catalog (ADR-0276; ADR-0116 §8
    /// invariants): the three fixed
    /// namespaces' settings. One table for the whole store — per-graph
    /// copies diverged when `ALTER DATABASE` wrote the `neo4j` graph's
    /// theater while a `system` session read its own statically seeded one.
    pub(crate) databases: DatabasesCatalog,
    /// The per-allocation expression cap (ADR-0463) every namespace graph
    /// of the store enforces. `None` is the explicit opt-out; the default is
    /// [`crate::memory::EXPRESSION_BUDGET_BYTES`].
    pub(crate) expression_memory_limit: Option<u64>,
    /// The shared memo live-bytes budget (ADR-0657) every statement of the
    /// store enforces, in bytes (the open-time setting is whole MiB).
    /// `0` disables the budgeted memo tables.
    pub(crate) memo_budget_bytes: u64,
    /// The store's diagnostic pattern-engine switch (ADR-0519), resolved
    /// once at open from `RELATE_PATTERN_ENGINE` and read by the
    /// kernel rungs' routing. Configuration the store owns, like the
    /// preview set; the default [`PatternEngine::Auto`] is today's
    /// routing exactly.
    pub(crate) pattern_engine: PatternEngine,
    /// The per-statement nested-evaluation budget (ADR-0395, 1 000 000
    /// since ADR-0670) — plain data in every build, whose only
    /// production initializer is the published constant; the only writer
    /// is the `cfg(test)` `set_nested_eval_budget` (the budget bombs).
    /// The no-knob rule holds by write-path: no production code reads
    /// anything but the default, and no process-global or thread-local
    /// channel exists.
    pub(crate) nested_eval_budget: u64,
}

impl Default for StoreServices {
    fn default() -> Self {
        Self {
            procedures: DashMap::default(),
            csv_policy: CsvPolicy::default(),
            preview_sources: PreviewSources::default(),
            advertised_address: None,
            databases: DatabasesCatalog::default(),
            expression_memory_limit: Some(crate::memory::EXPRESSION_BUDGET_BYTES),
            memo_budget_bytes: crate::memory::memo_budget_bytes(
                crate::memory::DEFAULT_MEMO_BUDGET_MIB,
            ),
            pattern_engine: PatternEngine::Auto,
            nested_eval_budget: crate::memory::NESTED_EVAL_BUDGET,
        }
    }
}

impl Graph {
    /// The store's one `StoreServices` bundle, mutable only before it is
    /// shared with another graph. Both open-time installers
    /// ([`Graph::configure_load_csv`], [`Graph::configure_preview`]) run
    /// through this one accessor, so the pre-share contract and its panic
    /// are stated once: after [`Graph::share_services_from`] the bundle's
    /// `Arc` identity is the store's one-bundle invariant (ADR-0116 §10),
    /// and rebuilding it would silently detach this graph from every other
    /// namespace.
    fn services_mut(&mut self) -> &mut StoreServices {
        Arc::get_mut(&mut self.services).expect(
            "the StoreServices bundle must be configured before \
             share_services_from: it is already shared (ADR-0116 §10)",
        )
    }

    /// Install the per-allocation expression cap (ADR-0463) before the
    /// services bundle is shared. `None` disables the cap; the default is
    /// [`crate::memory::EXPRESSION_BUDGET_BYTES`].
    #[doc(hidden)]
    pub fn configure_expression_memory_limit(&mut self, limit: Option<u64>) {
        self.services_mut().expression_memory_limit = limit;
    }

    /// Install the shared memo budget (ADR-0657), in whole MiB, before the
    /// services bundle is shared. `0` disables the budgeted memo tables.
    #[doc(hidden)]
    pub fn configure_expression_memo_budget(&mut self, mib: u64) {
        self.services_mut().memo_budget_bytes = crate::memory::memo_budget_bytes(mib);
    }

    /// The configured shared memo budget in bytes (ADR-0657).
    pub(crate) fn memo_budget_bytes(&self) -> u64 {
        self.services.memo_budget_bytes
    }

    /// The configured per-allocation expression cap (`None` = no cap).
    pub(crate) fn expression_memory_limit(&self) -> Option<u64> {
        self.services.expression_memory_limit
    }

    /// Install a validated local CSV capability before sharing the graph with connections.
    ///
    /// Mutates the store's single `StoreServices` bundle in place; panics
    /// if the bundle is already shared via [`Graph::share_services_from`]
    /// (see `Graph::services_mut`).
    #[doc(hidden)]
    pub fn configure_load_csv(&mut self, policy: CsvPolicy) {
        self.services_mut().csv_policy = policy;
    }

    /// Install the databases catalog a checkpoint loaded on `loaded` into
    /// this graph's store-level bundle (ADR-0276), so a replacement graph
    /// can then adopt that bundle without losing durable state.
    ///
    /// The catalog is the one durable member of [`StoreServices`]: the
    /// store's configuration (procedure registry, CSV policy, preview set)
    /// belongs to the surviving bundle, while `open_store_readonly` restores
    /// this table into the fresh graph's own bundle through
    /// [`Graph::restore_checkpoint_theater`]. The follow reload
    /// (`follow::reload`) calls this before [`Graph::share_services_from`];
    /// the catalog's interior mutability lets it write through `&Graph`
    /// without rebuilding the bundle's `Arc`. Not public API.
    #[doc(hidden)]
    pub fn install_databases_from(&self, loaded: &Graph) {
        self.databases().install(loaded.databases().snapshot());
    }

    /// Point this graph at the store-level service bundle of `other`
    /// (ADR-0116 §10), so every namespace of a store shares one procedure
    /// registry, one LOAD CSV policy, one resolved preview set, one advertised
    /// address and one databases catalog. Called when the store creates or swaps a
    /// namespace slot, and by the follow reload (`follow::reload`). The
    /// bundle mixes configuration the store owns (procedure registry, CSV
    /// policy, preview set, advertised address) with durable state restored from a checkpoint
    /// (the databases catalog, ADR-0276), so a caller that loaded this graph
    /// from disk must first install its catalog into `other` with
    /// [`Graph::install_databases_from`]; a plain share replaces the loaded
    /// bundle wholesale and would discard the checkpoint's catalog. Not
    /// public API.
    #[doc(hidden)]
    pub fn share_services_from(&mut self, other: &Graph) {
        self.services = Arc::clone(&other.services);
    }

    /// Look up a registered procedure in the store's shared registry
    /// (ADR-0116 §10). Read-only: the registry itself is interior-mutable,
    /// so lookups never touch the bundle's `Arc` identity.
    #[doc(hidden)]
    pub fn procedure(&self, name: &str) -> Option<Procedure> {
        self.services.procedures.get(name).map(|p| p.clone())
    }

    /// Whether `name` is registered in the store's shared procedure
    /// registry (ADR-0116 §10).
    #[doc(hidden)]
    pub fn has_procedure(&self, name: &str) -> bool {
        self.services.procedures.contains_key(name)
    }

    /// Register a procedure into the store's shared registry (ADR-0116
    /// §10), visible to every namespace graph of the store. Interior
    /// mutation only; the bundle's `Arc` identity is untouched.
    #[doc(hidden)]
    pub fn register_procedure(&self, proc: Procedure) {
        self.services.procedures.insert(proc.name.clone(), proc);
    }

    /// The store-level LOAD CSV policy (ADR-0081, ADR-0116 §10), read-only.
    pub(crate) fn csv_policy(&self) -> &CsvPolicy {
        &self.services.csv_policy
    }

    /// Install the store's resolved preview sources (ADR-0371,
    /// ADR-0378, ADR-0719) on the one bundle; same pre-share contract
    /// as [`Graph::configure_load_csv`]. The parts are the stored
    /// fact; the union derives in [`Graph::preview`].
    #[doc(hidden)]
    pub fn configure_preview(&mut self, sources: PreviewSources) {
        self.services_mut().preview_sources = sources;
    }

    /// Install the address a serving surface advertises (ADR-0729) on the
    /// one bundle; same pre-share contract as [`Graph::configure_preview`].
    #[doc(hidden)]
    pub fn configure_advertised_address(&mut self, address: Option<String>) {
        self.services_mut().advertised_address = address;
    }

    /// The store's advertised serving address (ADR-0729); `None` when the
    /// store is embedded and no surface serves it.
    pub(crate) fn advertised_address(&self) -> Option<&str> {
        self.services.advertised_address.as_deref()
    }

    /// The store-level preview set (ADR-0371, ADR-0378) the `SHOW
    /// PROCEDURES` catalog and the `CALL` gate read — the sources'
    /// derived union.
    #[doc(hidden)]
    pub fn preview(&self) -> PreviewFeatures {
        self.services.preview_sources.union()
    }

    /// The store's resolved preview sources (ADR-0719 decision 6) —
    /// the parts behind the derived union, for the provenance `SHOW
    /// SETTINGS` reports.
    pub(crate) fn preview_sources(&self) -> PreviewSources {
        self.services.preview_sources
    }

    /// Install the store's resolved pattern-engine switch (ADR-0519) on
    /// the one bundle; same pre-share contract as
    /// [`Graph::configure_preview`]. The open path resolves
    /// `RELATE_PATTERN_ENGINE` once (the `RELATE_PARSER`
    /// precedent's resolution site) and installs it here; a follower
    /// keeps it across a reload with the rest of the store's
    /// configuration.
    #[doc(hidden)]
    pub fn configure_pattern_engine(&mut self, engine: PatternEngine) {
        self.services_mut().pattern_engine = engine;
    }

    /// The store's nested-evaluation budget (ADR-0395/ADR-0670) — the
    /// field's contract is stated once, at the field.
    pub(crate) fn nested_eval_budget(&self) -> u64 {
        self.services.nested_eval_budget
    }

    /// The budget field's only writer (`cfg(test)` only): the budget
    /// bombs lower their own store's budget. See the field's contract
    /// for the no-knob rule it preserves.
    #[cfg(test)]
    pub(crate) fn set_nested_eval_budget(&mut self, budget: u64) {
        self.services_mut().nested_eval_budget = budget;
    }

    /// The store-level pattern-engine switch (ADR-0519) the kernel
    /// rungs' routing reads: [`PatternEngine::Auto`] on every store
    /// opened without the diagnostic variable. Public since LABS-1117:
    /// the EXPLAIN tree stamps it on every `MATCH` operator, so the one
    /// static rung fact travels with the plan.
    pub fn pattern_engine(&self) -> PatternEngine {
        self.services.pattern_engine
    }

    /// The store-level databases catalog (ADR-0276; ADR-0116 §8
    /// invariants), shared by every namespace graph of the store.
    pub(crate) fn databases(&self) -> &DatabasesCatalog {
        &self.services.databases
    }
}