Skip to main content

velesdb_core/
lib.rs

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