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