Skip to main content

velesdb_core/database/
mod.rs

1//! Database facade and orchestration layer for collection lifecycle and query routing.
2//!
3//! This module is split into focused submodules:
4//!
5//! - [`collection_ops`] — Collection CRUD dispatcher (create, delete, list, get)
6//! - [`vector_ops`] — Vector collection create/get
7//! - [`graph_ops`] — Graph collection create/get
8//! - [`metadata_ops`] — Metadata-only collection create/get
9//! - [`query_engine`] — `VelesQL` query execution, plan caching, DML dispatch
10//! - [`query_join`] — JOIN execution strategies (lookup, filtered, condition pushdown)
11//! - [`dml_executor`] — DML mutations (INSERT EDGE, DELETE, DELETE EDGE, SELECT EDGES, INSERT NODE)
12//! - [`persistence`] — Loading collections from disk at startup
13//! - [`training`] — `TRAIN QUANTIZER` statement execution
14//! - [`stats`] — Collection statistics (analyze, cache)
15//! - [`database_helpers`] — DML value conversion and JOIN column store helpers
16
17use crate::collection::{GraphCollection, MetadataCollection, VectorCollection};
18use crate::observer::DatabaseObserver;
19use crate::simd_dispatch;
20use crate::{ColumnStore, Error, Result};
21
22/// Shared out-cell for the executed filter strategy, threaded from the
23/// EXPLAIN ANALYZE counted path down to the base collection's query pipeline.
24pub(crate) type StrategyProbeSlot = std::sync::Arc<crate::guardrails::ExecutedStrategyCell>;
25
26mod admin_executor;
27mod collection_ops;
28mod cross_collection;
29mod ddl_executor;
30mod dml_executor;
31mod gated_search;
32mod graph_ops;
33mod introspection_executor;
34mod join_pushdown;
35mod metadata_ops;
36mod persistence;
37mod query_engine;
38mod query_engine_agg;
39mod query_engine_dml;
40mod query_join;
41mod stats;
42mod subquery_resolver;
43mod training;
44mod vector_ops;
45
46#[cfg(feature = "persistence")]
47mod database_helpers;
48
49#[cfg(all(test, feature = "persistence"))]
50mod collection_ops_tests;
51#[cfg(all(test, feature = "persistence"))]
52mod database_helpers_tests;
53#[cfg(all(test, feature = "persistence"))]
54mod database_tests;
55#[cfg(all(test, feature = "persistence"))]
56mod ddl_executor_tests;
57#[cfg(all(test, feature = "persistence"))]
58mod graph_ops_tests;
59#[cfg(all(test, feature = "persistence"))]
60mod query_engine_tests;
61#[cfg(all(test, feature = "persistence"))]
62mod query_join_tests;
63#[cfg(all(test, feature = "persistence"))]
64mod stats_tests;
65
66pub use gated_search::GatedRead;
67
68/// Database instance managing collections and storage.
69///
70/// # Lifecycle
71///
72/// `Database::open()` automatically loads all previously created collections from disk.
73/// There is no need to call `load_collections()` separately.
74///
75/// # Extension (Premium)
76///
77/// Use [`Database::open_with_observer`] to inject a [`DatabaseObserver`] implementation
78/// from `velesdb-premium` without modifying this crate.
79#[cfg(feature = "persistence")]
80pub struct Database {
81    /// Path to the data directory
82    data_dir: std::path::PathBuf,
83    /// Exclusive file lock preventing multi-process corruption.
84    ///
85    /// The lock is held for the lifetime of the `Database` and released on `Drop`.
86    /// The `_` prefix signals this field is kept for its RAII side effect.
87    _lock_file: std::fs::File,
88    /// Root configuration applied to every subsystem.
89    ///
90    /// Stored as an `Arc` so `Database::config()` can hand out cheap,
91    /// cloneable references without forcing the whole struct onto the
92    /// heap or locking. The value is populated at construction time
93    /// (`open`, `open_with_observer`, or `open_with_config`) and is
94    /// immutable for the life of the `Database` — Wave 3 never needs
95    /// to mutate the root config at runtime, and making it immutable
96    /// rules out a large class of surprising behaviours.
97    config: std::sync::Arc<crate::config::VelesConfig>,
98    /// Typed registry: vector collections.
99    vector_colls: parking_lot::RwLock<std::collections::HashMap<String, VectorCollection>>,
100    /// Typed registry: graph collections.
101    graph_colls: parking_lot::RwLock<std::collections::HashMap<String, GraphCollection>>,
102    /// Typed registry: metadata-only collections.
103    metadata_colls: parking_lot::RwLock<std::collections::HashMap<String, MetadataCollection>>,
104    /// Cached collection statistics for CBO planning.
105    collection_stats: parking_lot::RwLock<
106        std::collections::HashMap<String, crate::collection::stats::CollectionStats>,
107    >,
108    /// Optional lifecycle observer (used by velesdb-premium for RBAC, audit, multi-tenant).
109    observer: Option<std::sync::Arc<dyn DatabaseObserver>>,
110    /// Monotonic DDL schema version counter (CACHE-01).
111    ///
112    /// Incremented on every create/drop collection operation.
113    /// Used by `CompiledPlanCache` to invalidate cached query plans.
114    schema_version: std::sync::atomic::AtomicU64,
115    /// Compiled query plan cache (CACHE-02).
116    ///
117    /// Stores recently compiled `QueryPlan` instances keyed by `PlanKey`.
118    /// Default sizing: L1 = 1K hot entries, L2 = 10K LRU entries.
119    compiled_plan_cache: crate::cache::CompiledPlanCache,
120    /// JOIN-side `ColumnStore` cache keyed by collection name (CACHE-03).
121    ///
122    /// An entry is valid only while its `(schema_version, write_generation)`
123    /// stamp matches the live counters, so any mutation — or a drop/recreate
124    /// under the same name — forces a rebuild. Entries are also purged
125    /// eagerly on `delete_collection`. Collections carrying TTL points are
126    /// never cached (expiry does not bump `write_generation`).
127    join_store_cache:
128        parking_lot::RwLock<std::collections::HashMap<String, query_join::JoinStoreEntry>>,
129}
130
131#[cfg(feature = "persistence")]
132impl Database {
133    /// Opens or creates a database, **automatically loading all existing collections**.
134    ///
135    /// This replaces the previous `open()` + `load_collections()` two-step pattern.
136    /// The new `open()` is a strict auto-load: all `config.json` directories under
137    /// `path` are loaded on startup.
138    ///
139    /// Uses the default [`VelesConfig`](crate::config::VelesConfig) — every
140    /// subsystem behaves identically to the pre-Wave-3 version of this
141    /// function, so existing callers keep their exact behaviour. Users
142    /// that need to customise subsystem limits or WAL batching should
143    /// call [`Database::open_with_config`] instead.
144    ///
145    /// # Errors
146    ///
147    /// Returns an error if the directory cannot be created or accessed.
148    pub fn open<P: AsRef<std::path::Path>>(path: P) -> Result<Self> {
149        Self::open_impl(path, None, None)
150    }
151
152    /// Opens a database with an explicit [`VelesConfig`](crate::config::VelesConfig).
153    ///
154    /// Every subsystem that honours a config field (HNSW defaults, WAL
155    /// batching, runtime limits, search quality) reads from the passed
156    /// instance. A clone is stored inside the `Database` and retained
157    /// for the lifetime of the handle so sub-systems can consult it
158    /// without re-parsing a TOML file.
159    ///
160    /// # Errors
161    ///
162    /// Returns an error if the directory cannot be created, the lock
163    /// cannot be acquired, or any already-present collection exceeds
164    /// the limits declared in `config.limits` (see
165    /// [`Database::open`] for the default-limit behaviour).
166    pub fn open_with_config<P: AsRef<std::path::Path>>(
167        path: P,
168        config: crate::config::VelesConfig,
169    ) -> Result<Self> {
170        Self::open_impl(path, None, Some(config))
171    }
172
173    /// Opens a database with a [`DatabaseObserver`] (used by velesdb-premium).
174    ///
175    /// The observer receives lifecycle hooks for every collection operation,
176    /// enabling RBAC, audit logging, multi-tenant routing, etc.
177    ///
178    /// Equivalent to [`Database::open`] plus the observer injection —
179    /// applies the default [`VelesConfig`](crate::config::VelesConfig).
180    ///
181    /// # Errors
182    ///
183    /// Returns an error if the directory cannot be created or accessed.
184    pub fn open_with_observer<P: AsRef<std::path::Path>>(
185        path: P,
186        observer: std::sync::Arc<dyn DatabaseObserver>,
187    ) -> Result<Self> {
188        Self::open_impl(path, Some(observer), None)
189    }
190
191    /// Opens a database with both an explicit [`crate::VelesConfig`] and a
192    /// [`crate::DatabaseObserver`]. Used by the premium shell that layers
193    /// RBAC/audit on top of a tenant-specific config file.
194    ///
195    /// # Errors
196    ///
197    /// Same as [`Database::open_with_config`].
198    pub fn open_with_observer_and_config<P: AsRef<std::path::Path>>(
199        path: P,
200        observer: std::sync::Arc<dyn DatabaseObserver>,
201        config: crate::config::VelesConfig,
202    ) -> Result<Self> {
203        Self::open_impl(path, Some(observer), Some(config))
204    }
205
206    fn open_impl<P: AsRef<std::path::Path>>(
207        path: P,
208        observer: Option<std::sync::Arc<dyn DatabaseObserver>>,
209        config: Option<crate::config::VelesConfig>,
210    ) -> Result<Self> {
211        // Validate at the consumption boundary: a `VelesConfig` built
212        // programmatically (not through a loader) never passes through
213        // `validate()`, so an out-of-range field would otherwise reach the
214        // engine unchecked. Loaders already validate, but re-validating here
215        // is cheap and closes the bypass for direct API callers.
216        let config = config.unwrap_or_default();
217        config
218            .validate()
219            .map_err(|e| Error::Config(e.to_string()))?;
220
221        let data_dir = path.as_ref().to_path_buf();
222        std::fs::create_dir_all(&data_dir)?;
223
224        // Acquire exclusive file lock to prevent multi-process corruption
225        let lock_path = data_dir.join("velesdb.lock");
226        let lock_file = std::fs::File::create(&lock_path)?;
227        fs2::FileExt::try_lock_exclusive(&lock_file)
228            .map_err(|_| Error::DatabaseLocked(data_dir.display().to_string()))?;
229
230        // Log SIMD features detected at startup
231        let features = simd_dispatch::simd_features_info();
232        tracing::info!(
233            avx512 = features.avx512f,
234            avx2 = features.avx2,
235            "SIMD features detected - direct dispatch enabled"
236        );
237
238        let db = Self {
239            data_dir,
240            _lock_file: lock_file,
241            config: std::sync::Arc::new(config),
242            vector_colls: parking_lot::RwLock::new(std::collections::HashMap::new()),
243            graph_colls: parking_lot::RwLock::new(std::collections::HashMap::new()),
244            metadata_colls: parking_lot::RwLock::new(std::collections::HashMap::new()),
245            collection_stats: parking_lot::RwLock::new(std::collections::HashMap::new()),
246            observer,
247            schema_version: std::sync::atomic::AtomicU64::new(0),
248            compiled_plan_cache: crate::cache::CompiledPlanCache::new(1_000, 10_000),
249            join_store_cache: parking_lot::RwLock::new(std::collections::HashMap::new()),
250        };
251
252        // Auto-load all existing collections from disk (replaces manual load_collections()).
253        db.load_collections()?;
254
255        Ok(db)
256    }
257
258    /// Returns a reference to the root [`VelesConfig`](crate::config::VelesConfig)
259    /// that was supplied at construction (or the default if the database
260    /// was opened via [`Database::open`]).
261    ///
262    /// Sub-systems (`vector_ops`, `query_engine`, `stats`, …) consult this
263    /// through `database.config()` when they need to honour a user-supplied
264    /// limit or toggle — the shared `Arc` makes the call free of locks
265    /// and cheap to propagate to background threads.
266    #[must_use]
267    pub fn config(&self) -> &crate::config::VelesConfig {
268        &self.config
269    }
270
271    /// Returns a cheap, cloneable handle to the root config.
272    ///
273    /// Use this when you need to move the config into a thread or
274    /// long-lived closure that outlives the current `&self` borrow.
275    #[must_use]
276    pub fn config_arc(&self) -> std::sync::Arc<crate::config::VelesConfig> {
277        std::sync::Arc::clone(&self.config)
278    }
279
280    /// Returns the path to the data directory.
281    #[must_use]
282    pub fn data_dir(&self) -> &std::path::Path {
283        &self.data_dir
284    }
285
286    /// Returns the current DDL schema version counter.
287    #[must_use]
288    pub fn schema_version(&self) -> u64 {
289        self.schema_version
290            .load(std::sync::atomic::Ordering::Relaxed)
291    }
292
293    /// Returns a reference to the compiled query plan cache.
294    #[must_use]
295    pub fn plan_cache(&self) -> &crate::cache::CompiledPlanCache {
296        &self.compiled_plan_cache
297    }
298
299    // =========================================================================
300    // Observer notification helpers (called by server handlers after operations)
301    // =========================================================================
302
303    /// Fires the `on_upsert` telemetry hook once for a completed upsert write.
304    ///
305    /// Called by the core use-case DML entry points (INSERT/UPSERT and UPDATE
306    /// in [`query_engine_dml`]) after the data-plane write completes, so a
307    /// single completed operation results in exactly one `on_upsert`
308    /// invocation (Requirement 2.1, 2.3, 2.5). This is the internal replacement
309    /// for the deprecated [`Database::notify_upsert`] shim — it is invoked by
310    /// core itself rather than by callers, and is a single pointer check when
311    /// no observer is present (Requirement 2.4).
312    pub(super) fn fire_on_upsert(&self, collection: &str, point_count: usize) {
313        if let Some(ref obs) = self.observer {
314            obs.on_upsert(collection, point_count);
315        }
316    }
317
318    /// Notifies the observer that points were upserted into a collection.
319    ///
320    /// **Caller contract**: this method is NOT called automatically by
321    /// [`Database`] internals. HTTP handlers and SDK bindings are responsible
322    /// for calling it after a successful upsert, passing the number of points
323    /// written. Forgetting to call it means the observer receives no upsert
324    /// events for that operation.
325    ///
326    /// No-op when no observer is registered.
327    #[deprecated(
328        since = "3.9.0",
329        note = "Telemetry is now invoked inside the core use-case layer. \
330                This shim is retained for backward compatibility and will be \
331                removed in a future major version. Callers should stop invoking \
332                it to avoid double-counting once they upgrade."
333    )]
334    pub fn notify_upsert(&self, collection: &str, point_count: usize) {
335        if let Some(ref obs) = self.observer {
336            obs.on_upsert(collection, point_count);
337        }
338    }
339
340    /// Notifies the observer that a query was executed, with its duration.
341    ///
342    /// **Caller contract**: this method is NOT called automatically by
343    /// [`Database::execute_query`]. Callers must measure the wall-clock
344    /// duration themselves (e.g. `std::time::Instant::now()` before the call)
345    /// and invoke this method afterwards with the elapsed microseconds.
346    ///
347    /// No-op when no observer is registered.
348    #[deprecated(
349        since = "3.9.0",
350        note = "See notify_upsert deprecation note. Telemetry is now invoked \
351                inside the core use-case layer; callers should stop invoking \
352                this shim to avoid double-counting once they upgrade."
353    )]
354    pub fn notify_query(&self, collection: &str, duration_us: u64) {
355        if let Some(ref obs) = self.observer {
356            obs.on_query(collection, duration_us);
357        }
358    }
359}