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