Skip to main content

reddb_server/storage/unified/
store.rs

1//! Unified Store
2//!
3//! High-level API for the unified storage layer that combines tables, graphs,
4//! and vectors into a single coherent interface.
5//!
6//! # Features
7//!
8//! - Multi-collection management
9//! - Cross-collection queries
10//! - Unified entity access
11//! - Automatic ID generation
12//! - Cross-reference management
13//! - **Binary persistence** with pages, indices, and efficient encoding
14//! - **Page-based storage** via Pager for ACID durability
15//!
16//! # Persistence Modes
17//!
18//! 1. **File Mode** (`save_to_file`/`load_from_file`): Simple binary dump
19//! 2. **Paged Mode** (`open`/`persist`): Full page-based storage with B-tree indices
20
21use std::collections::{BTreeMap, HashMap};
22use std::fs::File;
23use std::io::{BufReader, Read};
24use std::path::{Path, PathBuf};
25use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering};
26use std::sync::Arc;
27
28use parking_lot::RwLock;
29
30use super::context_index::ContextIndex;
31use super::entity::{
32    CrossRef, EdgeData, EmbeddingSlot, EntityData, EntityId, EntityKind, GraphEdgeKind,
33    GraphNodeKind, NodeData, RefType, RowData, TimeSeriesPointKind, UnifiedEntity, VectorData,
34};
35use super::entity_cache::EntityCache;
36use super::manager::{ManagerConfig, ManagerStats, SegmentManager};
37use super::metadata::{Metadata, MetadataFilter, MetadataValue};
38use super::segment::SegmentError;
39use crate::api::{DurabilityMode, GroupCommitOptions};
40use crate::physical::{ManifestEvent, ManifestEventKind};
41use crate::storage::engine::pager::PagerError;
42use crate::storage::engine::{BTree, BTreeError, Pager, PagerConfig, PhysicalFileHeader};
43use crate::storage::primitives::encoding::{read_varu32, read_varu64, write_varu32, write_varu64};
44use crate::storage::schema::types::Value;
45
46pub use reddb_file::{
47    is_supported_store_version, NativeCatalogCollectionSummary, NativeCatalogSummary,
48    NativeExportSummary, NativeManifestEntrySummary, NativeManifestSummary,
49    NativeMetadataStateSummary, NativeRecoverySummary, NativeRegistryIndexSummary,
50    NativeRegistryJobSummary, NativeRegistryProjectionSummary, NativeRegistrySummary,
51    NativeSnapshotSummary, NativeVectorArtifactPageSummary, NativeVectorArtifactSummary,
52    ENTITY_RECORD_MAGIC, METADATA_MAGIC, METADATA_OVERFLOW_MAGIC, NATIVE_BLOB_MAGIC,
53    NATIVE_CATALOG_MAGIC, NATIVE_COLLECTION_ROOTS_MAGIC, NATIVE_MANIFEST_MAGIC,
54    NATIVE_MANIFEST_SAMPLE_LIMIT, NATIVE_METADATA_STATE_MAGIC, NATIVE_RECOVERY_MAGIC,
55    NATIVE_REGISTRY_MAGIC, NATIVE_VECTOR_ARTIFACT_MAGIC, STORE_MAGIC, STORE_VERSION_CURRENT,
56    STORE_VERSION_V1, STORE_VERSION_V11, STORE_VERSION_V2, STORE_VERSION_V3, STORE_VERSION_V4,
57    STORE_VERSION_V5, STORE_VERSION_V6, STORE_VERSION_V7, STORE_VERSION_V8, STORE_VERSION_V9,
58};
59
60#[derive(Debug, Clone, Default, PartialEq, Eq)]
61pub struct MvccVacuumStats {
62    pub scanned_versions: u64,
63    pub retained_versions: u64,
64    pub reclaimed_versions: u64,
65    pub retained_history_versions: u64,
66    pub reclaimed_history_versions: u64,
67    pub retained_tombstones: u64,
68    pub reclaimed_tombstones: u64,
69}
70
71impl MvccVacuumStats {
72    pub fn add(&mut self, other: &Self) {
73        self.scanned_versions += other.scanned_versions;
74        self.retained_versions += other.retained_versions;
75        self.reclaimed_versions += other.reclaimed_versions;
76        self.retained_history_versions += other.retained_history_versions;
77        self.reclaimed_history_versions += other.reclaimed_history_versions;
78        self.retained_tombstones += other.retained_tombstones;
79        self.reclaimed_tombstones += other.reclaimed_tombstones;
80    }
81}
82
83#[derive(Debug, Clone)]
84pub struct NativePhysicalState {
85    pub header: PhysicalFileHeader,
86    pub collection_roots: BTreeMap<String, u64>,
87    pub manifest: Option<NativeManifestSummary>,
88    pub registry: Option<NativeRegistrySummary>,
89    pub recovery: Option<NativeRecoverySummary>,
90    pub catalog: Option<NativeCatalogSummary>,
91    pub metadata_state: Option<NativeMetadataStateSummary>,
92    pub vector_artifact_pages: Option<Vec<NativeVectorArtifactPageSummary>>,
93}
94
95// ============================================================================
96// Configuration
97// ============================================================================
98
99/// Configuration for UnifiedStore
100#[derive(Debug, Clone)]
101pub struct UnifiedStoreConfig {
102    /// Configuration for segment managers
103    pub manager_config: ManagerConfig,
104    /// Automatically index cross-references on insert
105    pub auto_index_refs: bool,
106    /// Automatically build a HASH index on a user `id` column the first
107    /// time a row carrying that column is inserted into a collection.
108    /// Mirrors PostgreSQL's implicit primary-key index and Mongo's `_id`
109    /// default index — without it, `WHERE id = N` falls through to a
110    /// full segment scan because RedDB has no concept of an automatic
111    /// primary-key index on user-declared columns. See `docs/perf/
112    /// delete-sequential-2026-05-06.md` for the perf rationale.
113    /// Defaults to `true`; set to `false` to opt out per workload.
114    pub auto_index_id: bool,
115    /// Maximum cross-references per entity
116    pub max_cross_refs: usize,
117    /// Enable write-ahead logging
118    pub enable_wal: bool,
119    /// Durability profile for paged writes.
120    pub durability_mode: DurabilityMode,
121    /// Group-commit batching knobs when using grouped durability.
122    pub group_commit: GroupCommitOptions,
123    /// Data directory path
124    pub data_dir: Option<std::path::PathBuf>,
125    /// Embedded single-file artifact used for the internal WAL stream.
126    pub embedded_wal_path: Option<std::path::PathBuf>,
127    /// Preallocated page-cache slot count (ADR 0073 §2). `None` leaves the
128    /// pager on its own structural default; the promoted boot path always
129    /// supplies a count derived from the page-cache budget share, so the
130    /// default is reached only by direct library callers.
131    pub page_cache_slots: Option<usize>,
132}
133
134impl Default for UnifiedStoreConfig {
135    fn default() -> Self {
136        Self {
137            manager_config: ManagerConfig::default(),
138            auto_index_refs: true,
139            auto_index_id: true,
140            max_cross_refs: 1000,
141            enable_wal: false,
142            // Mirrors `RedDBOptions::default().durability_mode` — see
143            // `src/api.rs` for the rationale.
144            durability_mode: DurabilityMode::WalDurableGrouped,
145            group_commit: GroupCommitOptions::default(),
146            data_dir: None,
147            embedded_wal_path: None,
148            page_cache_slots: None,
149        }
150    }
151}
152
153impl UnifiedStoreConfig {
154    /// Create config with data directory
155    pub fn with_data_dir(mut self, path: impl Into<std::path::PathBuf>) -> Self {
156        self.data_dir = Some(path.into());
157        self
158    }
159
160    /// Enable WAL
161    pub fn with_wal(mut self) -> Self {
162        self.enable_wal = true;
163        self
164    }
165
166    pub fn with_durability_mode(mut self, mode: DurabilityMode) -> Self {
167        self.durability_mode = mode;
168        self
169    }
170
171    pub fn with_group_commit(mut self, options: GroupCommitOptions) -> Self {
172        self.group_commit = options;
173        self
174    }
175
176    pub fn with_embedded_wal_path(mut self, path: impl Into<std::path::PathBuf>) -> Self {
177        self.embedded_wal_path = Some(path.into());
178        self
179    }
180
181    /// Pre-size the page cache from its budget share (ADR 0073 §2).
182    pub fn with_page_cache_slots(mut self, slots: usize) -> Self {
183        self.page_cache_slots = Some(slots);
184        self
185    }
186
187    /// Set max cross-references
188    pub fn with_max_refs(mut self, max: usize) -> Self {
189        self.max_cross_refs = max;
190        self
191    }
192}
193
194// ============================================================================
195// Error Types
196// ============================================================================
197
198/// Errors from UnifiedStore operations
199#[derive(Debug)]
200pub enum StoreError {
201    /// Collection already exists
202    CollectionExists(String),
203    /// Collection not found
204    CollectionNotFound(String),
205    /// Entity not found
206    EntityNotFound(EntityId),
207    /// Too many cross-references
208    TooManyRefs(EntityId),
209    /// Segment error
210    Segment(SegmentError),
211    /// I/O error
212    Io(std::io::Error),
213    /// Checksummed storage bytes failed validation.
214    StorageIntegrity(crate::api::StorageIntegrityError),
215    /// Serialization error
216    Serialization(String),
217    /// Internal error (lock poisoning, invariant violation)
218    Internal(String),
219}
220
221impl std::fmt::Display for StoreError {
222    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
223        match self {
224            Self::CollectionExists(name) => write!(f, "Collection already exists: {}", name),
225            Self::CollectionNotFound(name) => write!(f, "Collection not found: {}", name),
226            Self::EntityNotFound(id) => write!(f, "Entity not found: {}", id),
227            Self::TooManyRefs(id) => write!(f, "Too many cross-references for entity: {}", id),
228            Self::Segment(e) => write!(f, "Segment error: {:?}", e),
229            Self::Io(e) => write!(f, "I/O error: {}", e),
230            Self::StorageIntegrity(e) => write!(f, "{e}"),
231            Self::Serialization(msg) => write!(f, "Serialization error: {}", msg),
232            Self::Internal(msg) => write!(f, "Internal error: {}", msg),
233        }
234    }
235}
236
237impl std::error::Error for StoreError {}
238
239impl From<SegmentError> for StoreError {
240    fn from(e: SegmentError) -> Self {
241        Self::Segment(e)
242    }
243}
244
245impl From<std::io::Error> for StoreError {
246    fn from(e: std::io::Error) -> Self {
247        Self::Io(e)
248    }
249}
250
251// ============================================================================
252// Statistics
253// ============================================================================
254
255/// Statistics for UnifiedStore
256#[derive(Debug, Clone, Default)]
257pub struct StoreStats {
258    /// Number of collections
259    pub collection_count: usize,
260    /// Total entities across all collections
261    pub total_entities: usize,
262    /// Total memory usage in bytes
263    pub total_memory_bytes: usize,
264    /// Per-collection statistics
265    pub collections: HashMap<String, ManagerStats>,
266    /// Total cross-references
267    pub cross_ref_count: usize,
268}
269
270impl StoreStats {
271    /// Get average entities per collection
272    pub fn avg_entities_per_collection(&self) -> f64 {
273        if self.collection_count == 0 {
274            0.0
275        } else {
276            self.total_entities as f64 / self.collection_count as f64
277        }
278    }
279
280    /// Get memory in MB
281    pub fn memory_mb(&self) -> f64 {
282        self.total_memory_bytes as f64 / (1024.0 * 1024.0)
283    }
284}
285
286// ============================================================================
287// UnifiedStore - The Main API
288// ============================================================================
289
290/// Unified storage for tables, graphs, and vectors
291///
292/// UnifiedStore provides a single coherent interface for all data types:
293/// - **Tables**: Row-based data with columns
294/// - **Graphs**: Nodes and edges with labels
295/// - **Vectors**: Embeddings for similarity search
296///
297/// # Features
298///
299/// - Multi-collection management
300/// - Cross-collection queries
301/// - Cross-reference tracking between entities
302/// - Automatic ID generation
303/// - Segment-based storage with growing/sealed lifecycle
304///
305/// # Example
306///
307/// ```ignore
308/// use reddb::storage::{Entity, Store};
309///
310/// let store = Store::new();
311///
312/// // Create a collection
313/// store.create_collection("hosts")?;
314///
315/// // Insert an entity
316/// let entity = Entity::table_row(1, "hosts", 1, vec![]);
317/// let id = store.insert("hosts", entity)?;
318///
319/// // Query
320/// let found = store.get("hosts", id);
321/// ```
322pub struct UnifiedStore {
323    /// Store configuration
324    config: UnifiedStoreConfig,
325    /// File format version for serialization
326    format_version: AtomicU32,
327    /// Global entity ID counter
328    next_entity_id: AtomicU64,
329    /// Collections by name
330    collections: RwLock<HashMap<String, Arc<SegmentManager>>>,
331    /// Forward cross-references: source_id → [(target_id, ref_type, target_collection)]
332    cross_refs: RwLock<HashMap<EntityId, Vec<(EntityId, RefType, String)>>>,
333    /// Reverse cross-references: target_id → [(source_id, ref_type, source_collection)]
334    reverse_refs: RwLock<HashMap<EntityId, Vec<(EntityId, RefType, String)>>>,
335    /// Optional page-based storage via Pager
336    pager: Option<Arc<Pager>>,
337    /// Database file path (for paged mode)
338    db_path: Option<PathBuf>,
339    /// B-tree indices for O(log n) entity lookups by ID (per collection).
340    /// Stored as `Arc<BTree>` so hot-path callers can clone the handle out
341    /// under a read lock and release the map-level lock before doing the
342    /// actual insert — previously the outer RwLock was held for the whole
343    /// btree mutation, serialising every concurrent insert across every
344    /// collection into one global write lock.
345    btree_indices: RwLock<HashMap<String, Arc<BTree>>>,
346    /// Cross-structure context index for unified search
347    context_index: ContextIndex,
348    /// Hot entity cache — sharded bounded LRU for `get_any` lookups.
349    /// See `entity_cache.rs` for the rationale; this replaced a single
350    /// `RwLock<HashMap>` that serialised every `delete_batch` invalidation.
351    entity_cache: EntityCache,
352    /// Graph node label index: (collection, label) → Vec<EntityId>.
353    /// O(1) lookup for MATCH (n:Label) graph patterns — avoids full collection scan.
354    graph_label_index: RwLock<HashMap<(String, String), Vec<EntityId>>>,
355    /// Whether the paged registry on page 1 must be rewritten before the next flush.
356    paged_registry_dirty: AtomicBool,
357    /// Logical store WAL / grouped durability coordinator for paged mode.
358    commit: Option<Arc<StoreCommitCoordinator>>,
359    /// Counts how often `unindex_cross_refs_batch` took the read-only fast
360    /// path (no inbound refs, no outbound refs for any deleted id) and so
361    /// avoided acquiring the `cross_refs` / `reverse_refs` write locks.
362    /// Used by tests to pin the early-exit; cheap relaxed counter otherwise.
363    unindex_cross_refs_fast_path: AtomicU64,
364    /// WAL-replayed `VectorInsert` records, captured at open time and
365    /// drained per-collection on first `vector.turbo` access (issue
366    /// #694). Boot-time recovery: the in-memory TurboQuant index is
367    /// rebuilt by replaying these FP32 vectors in WAL order, so the
368    /// rebuilt state is byte-deterministic against the pre-restart
369    /// state under a fixed codec seed.
370    pub(crate) replayed_turbo_inserts: parking_lot::Mutex<HashMap<String, Vec<(u64, Vec<f32>)>>>,
371    /// WAL-replayed probabilistic mutation deltas captured at open time.
372    /// Runtime recovery drains these after loading the latest full
373    /// probabilistic snapshot from store state.
374    pub(crate) replayed_probabilistic_deltas:
375        parking_lot::Mutex<Vec<(u8, u8, String, Vec<Vec<u8>>)>>,
376    /// Opaque store-level auxiliary metadata persisted inside the binary dump
377    /// (store format V10+). RedDB uses this to carry collection contracts
378    /// through the single-file artifact so a collection's `declared_model`
379    /// (e.g. `kv`) survives a restart instead of being re-inferred as a table.
380    /// The store treats the bytes as opaque; only RedDB interprets them.
381    pub(crate) aux_metadata: RwLock<Vec<u8>>,
382}
383
384mod builder;
385mod commit;
386mod impl_entities;
387mod impl_file;
388mod impl_native_a;
389mod impl_native_b;
390mod impl_native_c;
391mod impl_pages;
392mod native_helpers;
393
394pub use self::builder::EntityBuilder;
395pub(crate) use self::commit::DeferredStoreWalActions;
396use self::commit::{StoreCommitCoordinator, StoreWalAction};
397use self::native_helpers::*;