Skip to main content

velesdb_core/
lib.rs

1//! # `VelesDB` Core
2//!
3//! Local-first **tri-engine** database for AI agents, written in Rust:
4//! **vector** (HNSW + SIMD) + **graph** (typed edges, traversal, `MATCH`) +
5//! **columnar** (typed metadata filters), queried together through
6//! **`VelesQL`** — parse with [`velesql::Parser`] and run with
7//! `Database::execute_query`, mixing `NEAR $v`, `WHERE` predicates, and
8//! `MATCH` graph patterns in one statement (see the repository guide
9//! `docs/guides/MULTIMODEL_QUERIES.md` for the full multi-model tour).
10//! Designed for semantic search, agent memory, recommendation, and RAG.
11//!
12//! ## Features
13//!
14//! - **Blazing Fast**: HNSW index with explicit SIMD (4x faster)
15//! - **5 Distance Metrics**: Cosine, Euclidean, Dot Product, Hamming, Jaccard
16//! - **Hybrid Search**: Vector + BM25 full-text with RRF fusion
17//! - **Graph Engine**: typed edges on any collection, BFS/DFS, `MATCH` patterns
18//! - **`VelesQL`**: one SQL-like language across all three engines
19//! - **Quantization**: SQ8 (4x) and Binary (32x) memory compression
20//! - **Persistent Storage**: Memory-mapped files for efficient disk access
21//!
22//! ## Quick Start
23//!
24//! ```rust,no_run
25//! use velesdb_core::{Database, DistanceMetric, Point, StorageMode};
26//! use serde_json::json;
27//!
28//! fn main() -> Result<(), Box<dyn std::error::Error>> {
29//!     // Create a new database
30//!     let db = Database::open("./data")?;
31//!
32//!     // Create a collection (all 5 metrics available)
33//!     db.create_collection("documents", 768, DistanceMetric::Cosine)?;
34//!     // Or with quantization: DistanceMetric::Hamming + StorageMode::Binary
35//!
36//!     let collection = db.get_vector_collection("documents").ok_or("Collection not found")?;
37//!
38//!     // Insert vectors (upsert takes ownership)
39//!     collection.upsert(vec![
40//!         Point::new(1, vec![0.1; 768], Some(json!({"title": "Hello World"}))),
41//!     ])?;
42//!
43//!     // Search for similar vectors
44//!     let query_vector = vec![0.1; 768];
45//!     let results = collection.search(&query_vector, 10)?;
46//!
47//!     // Hybrid search (vector + text)
48//!     let hybrid = collection.hybrid_search(&query_vector, "hello", 5, Some(0.7))?;
49//!     # Ok(())
50//! }
51//! ```
52
53#![warn(missing_docs)]
54// Clippy lints configured in workspace Cargo.toml [workspace.lints.clippy]
55#![cfg_attr(
56    test,
57    allow(
58        clippy::large_stack_arrays,
59        clippy::doc_markdown,
60        clippy::uninlined_format_args,
61        clippy::single_match_else,
62        clippy::cast_lossless,
63        clippy::manual_assert
64    )
65)]
66
67#[cfg(feature = "persistence")]
68pub mod agent;
69pub mod alloc_guard;
70#[cfg(test)]
71mod alloc_guard_tests;
72pub mod api_types;
73pub mod cache;
74// `collection` is declared unconditionally: its `stats` and `query_cost` leaves are
75// persistence-free and feed the `VelesQL` query planner (P1.4). The storage/index-coupled
76// submodules remain individually gated inside `collection/mod.rs`.
77pub mod collection;
78#[cfg(feature = "persistence")]
79pub mod column_store;
80#[cfg(all(test, feature = "persistence"))]
81mod column_store_tests;
82pub mod compression;
83pub mod config;
84pub mod config_quantization;
85#[cfg(test)]
86mod config_tests;
87mod config_validation;
88/// Cross-implementation conformance harness (frozen golden reference vectors).
89pub mod conformance;
90pub mod contiguous_ops;
91mod contiguous_resize;
92pub mod distance;
93#[cfg(test)]
94mod distance_tests;
95pub mod error;
96#[cfg(test)]
97mod error_tests;
98#[cfg(feature = "test-fault-injection")]
99pub mod fault_injection;
100pub mod filter;
101#[cfg(test)]
102mod filter_like_tests;
103#[cfg(test)]
104mod filter_tests;
105pub mod fusion;
106pub mod gpu;
107#[cfg(test)]
108mod gpu_tests;
109#[cfg(feature = "persistence")]
110pub mod guardrails;
111#[cfg(all(test, feature = "persistence"))]
112mod guardrails_tests;
113pub mod half_precision;
114#[cfg(test)]
115mod half_precision_tests;
116#[cfg(feature = "persistence")]
117pub mod index;
118#[cfg(feature = "internal-bench")]
119#[doc(hidden)]
120pub mod internal_bench;
121#[cfg(all(test, feature = "internal-bench"))]
122mod internal_bench_tests;
123pub mod lock_rank;
124pub mod metrics;
125#[cfg(test)]
126mod metrics_tests;
127pub mod perf_optimizations;
128#[cfg(test)]
129mod perf_optimizations_tests;
130pub mod point;
131#[cfg(test)]
132mod point_tests;
133pub mod quantization;
134#[cfg(test)]
135mod quantization_tests;
136pub mod scored_result;
137pub mod simd_dispatch;
138#[cfg(test)]
139mod simd_dispatch_tests;
140#[cfg(test)]
141mod simd_epic073_tests;
142/// Sparse vector types, inverted index, and search -- always compiled (no persistence dependency).
143pub mod sparse_index;
144// simd_explicit removed - consolidated into simd_native (EPIC-075)
145pub mod simd_native;
146#[cfg(test)]
147mod simd_native_tests;
148#[cfg(target_arch = "aarch64")]
149pub mod simd_neon;
150#[cfg(target_arch = "aarch64")]
151pub mod simd_neon_prefetch;
152// simd_ops removed - direct dispatch via simd_native (EPIC-CLEANUP)
153#[cfg(test)]
154mod simd_prefetch_x86_tests;
155#[cfg(test)]
156mod simd_tests;
157#[cfg(feature = "persistence")]
158pub mod storage;
159pub mod sync;
160#[cfg(all(test, feature = "persistence"))]
161mod test_fixtures;
162#[cfg(all(not(target_arch = "wasm32"), feature = "update-check"))]
163pub mod update_check;
164pub mod validation;
165pub mod vector_ref;
166#[cfg(test)]
167mod vector_ref_tests;
168pub mod velesql;
169/// Binary wire formats (VRB1 raw-bulk) — pure, persistence-free, wasm-safe.
170pub mod wire;
171
172#[cfg(all(not(target_arch = "wasm32"), feature = "update-check"))]
173pub use update_check::{check_for_updates, spawn_update_check};
174#[cfg(all(not(target_arch = "wasm32"), feature = "update-check"))]
175pub use update_check::{compute_instance_hash, UpdateCheckConfig};
176
177#[cfg(feature = "persistence")]
178pub use index::{HnswIndex, HnswParams, SearchQuality, VectorIndex};
179
180#[cfg(feature = "persistence")]
181pub use collection::streaming::{BackpressureError, StreamIngester, StreamingConfig};
182#[cfg(feature = "persistence")]
183pub use collection::{
184    // Type-erased collection handle (v2.0.0)
185    AnyCollection,
186    // Diagnostics (US-006: embedded SDK health checks)
187    CollectionDiagnostics,
188    // Public user-facing types — 3 typed collections replace Collection as primary API
189    CollectionType,
190    // Graph API types (user-visible)
191    EdgeType,
192    GraphCollection,
193    GraphEdge,
194    GraphNode,
195    GraphSchema,
196    // Diagnostics (US-006: embedded SDK health checks)
197    IndexHealth,
198    IndexInfo,
199    MetadataCollection,
200    NodeType,
201    // Ordered-index ORDER BY advisor (EPIC-081 phase 3a)
202    OrderByIndexState,
203    OrderByIndexSuggestion,
204    // Scroll cursor (Issue #429)
205    ScrollBatch,
206    TraversalConfig,
207    TraversalPath,
208    TraversalResult,
209    ValueType,
210    VectorCollection,
211    // Durable TTL payload key (shared across all collection types and external crates)
212    EXPIRES_AT_KEY,
213};
214pub use contiguous_ops::pad_to_simd_width;
215pub use distance::{DistanceMetric, CONDITION_TYPE_NAMES, DISTANCE_METRIC_NAMES};
216pub use error::{Error, Result};
217pub use filter::{Condition, Filter};
218pub use lock_rank::{assert_lock_order, LockRank};
219pub use point::{ComponentScores, Point, SearchResult};
220pub use quantization::{
221    cosine_similarity_quantized, cosine_similarity_quantized_simd, dot_product_quantized,
222    dot_product_quantized_simd, euclidean_squared_quantized, euclidean_squared_quantized_simd,
223    BinaryQuantizedVector, QuantizationCodec, QuantizedVector, StorageMode, STORAGE_MODE_NAMES,
224};
225pub use scored_result::ScoredResult;
226pub use validation::{
227    validate_collection_name, validate_dimension, validate_dimension_match,
228    MAX_COLLECTION_NAME_LENGTH, MAX_DIMENSION, MIN_DIMENSION,
229};
230// Canonical cross-engine stable hashing (FNV-1a). Lives in `wire::stable_hash`
231// so persistence-free targets (WASM) can delegate to it. Consumers deriving a
232// numeric ID from a string for persisted or interoperable use MUST call
233// `hash_id` (never a std `DefaultHasher`, which is not stable across runs).
234// `hash_id_bytes` is the bytes-level counterpart, exported so other
235// `VelesDB` crates (velesdb-memory, velesdb-migrate) can delegate their own
236// FNV-1a derivations to this single implementation instead of re-declaring
237// the constants (issue #1542).
238pub use wire::stable_hash::{hash_edge_id, hash_id, hash_id_bytes};
239
240#[cfg(feature = "persistence")]
241pub use column_store::{
242    BatchUpdate, BatchUpdateResult, BatchUpsertResult, ColumnStore, ColumnStoreError, ColumnType,
243    ColumnValue, ExpireResult, StringId, StringTable, TypedColumn, UpsertResult,
244};
245// Observability and guardrail surfaces (audit-2026q2 H2): these were previously
246// reachable only via deep paths (`velesdb_core::metrics::*`,
247// `velesdb_core::guardrails::limits::QueryLimits`), forcing wrapper crates
248// to depend on the internal module layout. Re-exporting at the crate root
249// applies the Facade pattern so the public API can evolve independently
250// of the internal organisation.
251pub use config::{
252    ConfigError, HnswConfig, LimitsConfig, QuantizationConfig, QuantizationType, SearchConfig,
253    SearchMode, VelesConfig,
254};
255#[cfg(feature = "persistence")]
256pub use config::{LoggingConfig, ServerConfig, StorageConfig};
257pub use fusion::{
258    FusionError, FusionStrategy, DEFAULT_WEIGHTED_AVG_WEIGHT, DEFAULT_WEIGHTED_HIT_WEIGHT,
259    DEFAULT_WEIGHTED_MAX_WEIGHT,
260};
261#[cfg(feature = "persistence")]
262pub use guardrails::QueryLimits;
263pub use metrics::{
264    average_metrics, compute_latency_percentiles, hit_rate, mean_average_precision, mrr, ndcg_at_k,
265    precision_at_k, recall_at_k, LatencyStats,
266};
267pub use metrics::{
268    DurationHistogram, GuardRailsMetrics, OperationalMetrics, QueryStats, TraversalMetrics,
269};
270
271#[cfg(feature = "persistence")]
272mod database;
273#[cfg(feature = "persistence")]
274pub mod observer;
275
276#[cfg(feature = "persistence")]
277pub use database::{Database, GatedRead};
278#[cfg(feature = "persistence")]
279pub use observer::DatabaseObserver;
280#[cfg(feature = "persistence")]
281pub use observer::{AccessDecision, AccessScope, QueryAccessContext, QueryOperationKind};
282#[cfg(feature = "persistence")]
283pub use storage::DurabilityMode;