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::{AtomicU32, Ordering};
26use std::sync::Arc;
27
28use parking_lot::RwLock;
29
30use super::context_index::ContextIndex;
31use super::entity::{
32    CrossRef, EmbeddingSlot, EntityData, EntityId, EntityKind, RefType, RowData,
33    TimeSeriesPointKind, UnifiedEntity,
34};
35use super::manager::{ManagerConfig, ManagerStats, SegmentManager};
36use super::metadata::{Metadata, MetadataFilter, MetadataValue};
37use crate::api::{DurabilityMode, GroupCommitOptions};
38use crate::physical::{ManifestEvent, ManifestEventKind};
39use crate::storage::engine::pager::PagerError;
40use crate::storage::engine::{BTree, BTreeError, Pager, PagerConfig, PhysicalFileHeader};
41use crate::storage::primitives::encoding::read_varu64;
42use reddb_types::types::Value;
43
44pub use reddb_file::{
45    is_supported_store_version, NativeCatalogCollectionSummary, NativeCatalogSummary,
46    NativeExportSummary, NativeManifestEntrySummary, NativeManifestSummary,
47    NativeMetadataStateSummary, NativeRecoverySummary, NativeRegistryIndexSummary,
48    NativeRegistryJobSummary, NativeRegistryProjectionSummary, NativeRegistrySummary,
49    NativeSnapshotSummary, NativeVectorArtifactPageSummary, NativeVectorArtifactSummary,
50    ENTITY_RECORD_MAGIC, METADATA_MAGIC, METADATA_OVERFLOW_MAGIC, NATIVE_BLOB_MAGIC,
51    NATIVE_CATALOG_MAGIC, NATIVE_COLLECTION_ROOTS_MAGIC, NATIVE_MANIFEST_MAGIC,
52    NATIVE_MANIFEST_SAMPLE_LIMIT, NATIVE_METADATA_STATE_MAGIC, NATIVE_RECOVERY_MAGIC,
53    NATIVE_REGISTRY_MAGIC, NATIVE_VECTOR_ARTIFACT_MAGIC, STORE_MAGIC, STORE_VERSION_CURRENT,
54    STORE_VERSION_V1, STORE_VERSION_V11, STORE_VERSION_V12, STORE_VERSION_V2, STORE_VERSION_V3,
55    STORE_VERSION_V4, STORE_VERSION_V5, STORE_VERSION_V6, STORE_VERSION_V7, STORE_VERSION_V8,
56    STORE_VERSION_V9,
57};
58
59#[derive(Debug, Clone, Default, PartialEq, Eq)]
60pub struct MvccVacuumStats {
61    pub scanned_versions: u64,
62    pub retained_versions: u64,
63    pub reclaimed_versions: u64,
64    pub retained_history_versions: u64,
65    pub reclaimed_history_versions: u64,
66    pub retained_tombstones: u64,
67    pub reclaimed_tombstones: u64,
68}
69
70impl MvccVacuumStats {
71    pub fn add(&mut self, other: &Self) {
72        self.scanned_versions += other.scanned_versions;
73        self.retained_versions += other.retained_versions;
74        self.reclaimed_versions += other.reclaimed_versions;
75        self.retained_history_versions += other.retained_history_versions;
76        self.reclaimed_history_versions += other.reclaimed_history_versions;
77        self.retained_tombstones += other.retained_tombstones;
78        self.reclaimed_tombstones += other.reclaimed_tombstones;
79    }
80}
81
82#[derive(Debug, Clone)]
83pub struct NativePhysicalState {
84    pub header: PhysicalFileHeader,
85    pub collection_roots: BTreeMap<String, u64>,
86    pub manifest: Option<NativeManifestSummary>,
87    pub registry: Option<NativeRegistrySummary>,
88    pub recovery: Option<NativeRecoverySummary>,
89    pub catalog: Option<NativeCatalogSummary>,
90    pub metadata_state: Option<NativeMetadataStateSummary>,
91    pub vector_artifact_pages: Option<Vec<NativeVectorArtifactPageSummary>>,
92}
93
94// ============================================================================
95// Configuration
96// ============================================================================
97
98/// Configuration for UnifiedStore
99#[derive(Debug, Clone)]
100pub struct UnifiedStoreConfig {
101    /// Configuration for segment managers
102    pub manager_config: ManagerConfig,
103    /// Automatically index cross-references on insert
104    pub auto_index_refs: bool,
105    /// Automatically build a HASH index on a user `id` column the first
106    /// time a row carrying that column is inserted into a collection.
107    /// Mirrors PostgreSQL's implicit primary-key index and Mongo's `_id`
108    /// default index — without it, `WHERE id = N` falls through to a
109    /// full segment scan because RedDB has no concept of an automatic
110    /// primary-key index on user-declared columns. See `docs/perf/
111    /// delete-sequential-2026-05-06.md` for the perf rationale.
112    /// Defaults to `true`; set to `false` to opt out per workload.
113    pub auto_index_id: bool,
114    /// Maximum cross-references per entity
115    pub max_cross_refs: usize,
116    /// Enable write-ahead logging
117    pub enable_wal: bool,
118    /// Durability profile for paged writes.
119    pub durability_mode: DurabilityMode,
120    /// Group-commit batching knobs when using grouped durability.
121    pub group_commit: GroupCommitOptions,
122    /// Data directory path
123    pub data_dir: Option<std::path::PathBuf>,
124    /// Embedded single-file artifact used for the internal WAL stream.
125    pub embedded_wal_path: Option<std::path::PathBuf>,
126    /// Preallocated page-cache slot count (ADR 0073 §2). `None` leaves the
127    /// pager on its own structural default; the promoted boot path always
128    /// supplies a count derived from the page-cache budget share, so the
129    /// default is reached only by direct library callers.
130    pub page_cache_slots: Option<usize>,
131}
132
133impl Default for UnifiedStoreConfig {
134    fn default() -> Self {
135        Self {
136            manager_config: ManagerConfig::default(),
137            auto_index_refs: true,
138            auto_index_id: true,
139            max_cross_refs: 1000,
140            enable_wal: false,
141            // Mirrors `RedDBOptions::default().durability_mode` — see
142            // `src/api.rs` for the rationale.
143            durability_mode: DurabilityMode::WalDurableGrouped,
144            group_commit: GroupCommitOptions::default(),
145            data_dir: None,
146            embedded_wal_path: None,
147            page_cache_slots: None,
148        }
149    }
150}
151
152impl UnifiedStoreConfig {
153    /// Create config with data directory
154    pub fn with_data_dir(mut self, path: impl Into<std::path::PathBuf>) -> Self {
155        self.data_dir = Some(path.into());
156        self
157    }
158
159    /// Enable WAL
160    pub fn with_wal(mut self) -> Self {
161        self.enable_wal = true;
162        self
163    }
164
165    pub fn with_durability_mode(mut self, mode: DurabilityMode) -> Self {
166        self.durability_mode = mode;
167        self
168    }
169
170    pub fn with_group_commit(mut self, options: GroupCommitOptions) -> Self {
171        self.group_commit = options;
172        self
173    }
174
175    pub fn with_embedded_wal_path(mut self, path: impl Into<std::path::PathBuf>) -> Self {
176        self.embedded_wal_path = Some(path.into());
177        self
178    }
179
180    /// Pre-size the page cache from its budget share (ADR 0073 §2).
181    pub fn with_page_cache_slots(mut self, slots: usize) -> Self {
182        self.page_cache_slots = Some(slots);
183        self
184    }
185
186    /// Set max cross-references
187    pub fn with_max_refs(mut self, max: usize) -> Self {
188        self.max_cross_refs = max;
189        self
190    }
191}
192
193// ============================================================================
194// Error Types
195// ============================================================================
196
197pub use reddb_engine::storage::error::StoreError;
198
199// ============================================================================
200// Statistics
201// ============================================================================
202
203/// Statistics for UnifiedStore
204#[derive(Debug, Clone, Default)]
205pub struct StoreStats {
206    /// Number of collections
207    pub collection_count: usize,
208    /// Total entities across all collections
209    pub total_entities: usize,
210    /// Total memory usage in bytes
211    pub total_memory_bytes: usize,
212    /// Per-collection statistics
213    pub collections: HashMap<String, ManagerStats>,
214    /// Total cross-references
215    pub cross_ref_count: usize,
216}
217
218impl StoreStats {
219    /// Get average entities per collection
220    pub fn avg_entities_per_collection(&self) -> f64 {
221        if self.collection_count == 0 {
222            0.0
223        } else {
224            self.total_entities as f64 / self.collection_count as f64
225        }
226    }
227
228    /// Get memory in MB
229    pub fn memory_mb(&self) -> f64 {
230        self.total_memory_bytes as f64 / (1024.0 * 1024.0)
231    }
232}
233
234// ============================================================================
235// UnifiedStore - The Main API
236// ============================================================================
237
238struct CheckpointVersion {
239    manager: std::sync::Weak<SegmentManager>,
240    segments: Vec<(u64, u64)>,
241    visibility_revision: u64,
242    untracked_visibility_revision: u64,
243    excluded_xids: Arc<std::collections::HashSet<u64>>,
244    pending_vault: Arc<std::collections::HashSet<EntityId>>,
245    format_version: u32,
246    /// Raw rows omitted or normalized in the durable image. None retains the
247    /// full validation path when more than 1,024 such rows are outstanding.
248    /// Also carries bounded unprojected IDs across completed inline GC batches.
249    deferred_rows: Option<Arc<Vec<EntityId>>>,
250    /// Inline GC advanced the segment proof past rows still awaiting projection.
251    has_unprojected_rows: bool,
252}
253
254impl CheckpointVersion {
255    fn remember_deferred_row(&mut self, id: EntityId) {
256        let Some(rows) = self.deferred_rows.as_mut() else {
257            return;
258        };
259        if rows.len() == 1024 {
260            self.deferred_rows = None;
261        } else {
262            Arc::make_mut(rows).push(id);
263        }
264    }
265}
266
267/// Unified storage for tables, graphs, and vectors
268///
269/// UnifiedStore provides a single coherent interface for all data types:
270/// - **Tables**: Row-based data with columns
271/// - **Graphs**: Nodes and edges with labels
272/// - **Vectors**: Embeddings for similarity search
273///
274/// # Features
275///
276/// - Multi-collection management
277/// - Cross-collection queries
278/// - Cross-reference tracking between entities
279/// - Automatic ID generation
280/// - Segment-based storage with growing/sealed lifecycle
281///
282/// # Example
283///
284/// ```ignore
285/// use reddb::storage::{Entity, Store};
286///
287/// let store = Store::new();
288///
289/// // Create a collection
290/// store.create_collection("hosts")?;
291///
292/// // Insert an entity
293/// let entity = Entity::table_row(1, "hosts", 1, vec![]);
294/// let id = store.insert("hosts", entity)?;
295///
296/// // Query
297/// let found = store.get("hosts", id);
298/// ```
299pub struct UnifiedStore {
300    /// Canonical resident state; native fields below retain durability policy.
301    resident: reddb_engine::storage::resident_store::ResidentStore,
302    /// Store configuration
303    config: UnifiedStoreConfig,
304    /// File format version for serialization
305    format_version: AtomicU32,
306    /// Optional page-based storage via Pager
307    pager: Option<Arc<Pager>>,
308    /// Database file path (for paged mode)
309    db_path: Option<PathBuf>,
310    /// B-tree indices for O(log n) entity lookups by ID (per collection).
311    /// Stored as `Arc<BTree>` so hot-path callers can clone the handle out
312    /// under a read lock and release the map-level lock before doing the
313    /// actual insert — previously the outer RwLock was held for the whole
314    /// btree mutation, serialising every concurrent insert across every
315    /// collection into one global write lock.
316    btree_indices: RwLock<HashMap<String, Arc<BTree>>>,
317    /// Reuse only a successfully published generation with the same live rows.
318    checkpoint_versions: RwLock<HashMap<String, CheckpointVersion>>,
319    checkpoint_durable_rows: RwLock<checkpoint_delta::DurableRows>,
320    /// The immediately previous published trees and any older reader-pinned
321    /// trees. Root identities are persisted with the paged catalog.
322    retired_btrees: parking_lot::Mutex<Vec<RetiredBTree>>,
323    /// Detached artifact pages stay unavailable until native metadata is durable.
324    detached_native_blob_pages: parking_lot::Mutex<std::collections::BTreeSet<u32>>,
325    /// Logical store WAL / grouped durability coordinator for paged mode.
326    commit: Option<Arc<StoreCommitCoordinator>>,
327    /// WAL-replayed `VectorInsert` records, captured at open time and
328    /// drained per-collection on first `vector.turbo` access (issue
329    /// #694). Boot-time recovery: the in-memory TurboQuant index is
330    /// rebuilt by replaying these FP32 vectors in WAL order, so the
331    /// rebuilt state is byte-deterministic against the pre-restart
332    /// state under a fixed codec seed.
333    pub(crate) replayed_turbo_inserts: parking_lot::Mutex<HashMap<String, Vec<(u64, Vec<f32>)>>>,
334    /// WAL-replayed probabilistic mutation deltas captured at open time.
335    /// Runtime recovery drains these after loading the latest full
336    /// probabilistic snapshot from store state.
337    pub(crate) replayed_probabilistic_deltas:
338        parking_lot::Mutex<Vec<(u8, u8, String, Vec<Vec<u8>>)>>,
339    /// Serialize vault publication with snapshot capture and WAL truncation.
340    /// Physical metadata and native header publication take it too (#2376).
341    /// Reentrant because embedded checkpoint calls the snapshot encoder while
342    /// holding the barrier, and storage maintenance may nest those calls.
343    pub(crate) vault_publication_lock: parking_lot::ReentrantMutex<()>,
344    /// Live-only vault rows excluded from a reentrant WAL-full compaction.
345    pub(crate) pending_vault_versions: RwLock<std::collections::HashSet<EntityId>>,
346    /// Retain transaction outcomes through embedded snapshot-on-drop. Without
347    /// this, aborted physical versions are reopened as committed rows.
348    pub(crate) snapshot_manager:
349        std::sync::OnceLock<Arc<crate::storage::transaction::snapshot::SnapshotManager>>,
350    embedded_commit_session: std::sync::OnceLock<crate::storage::embedded::EmbeddedCommitSession>,
351}
352
353struct RetiredBTree {
354    tree: Arc<BTree>,
355    published: bool,
356}
357
358mod builder;
359mod checkpoint_delta;
360mod checkpoint_wal;
361mod commit;
362mod impl_entities;
363mod impl_file;
364mod impl_native_a;
365mod impl_native_b;
366mod impl_native_c;
367mod impl_pages;
368mod impl_vault_import;
369mod keyed_write;
370mod mvcc_reclaim;
371pub(crate) use mvcc_reclaim::MvccReclaimCursor;
372mod native_helpers;
373
374pub use self::builder::EntityBuilder;
375pub(crate) use self::commit::DeferredStoreWalActions;
376use self::commit::{StoreCommitCoordinator, StoreWalAction};
377use self::native_helpers::*;
378
379#[cfg(test)]
380mod shared_state_tests {
381    use super::*;
382
383    #[test]
384    fn native_mutations_and_shared_reads_use_one_resident_state() {
385        let store = UnifiedStore::new();
386        let resident: &reddb_engine::storage::resident_store::ResidentStore = &store.resident;
387        store.create_collection("nodes").expect("collection");
388        let native = store.get_collection("nodes").expect("native manager");
389        let shared = resident.get_collection("nodes").expect("shared manager");
390        assert!(
391            Arc::ptr_eq(&native, &shared),
392            "one canonical collection owner"
393        );
394        let id = store
395            .insert_auto(
396                "nodes",
397                UnifiedEntity::graph_node(EntityId::new(0), "Person", "person", HashMap::new()),
398            )
399            .expect("native mutation");
400        assert_eq!(id.raw(), 1);
401        assert_eq!(
402            resident.get_any(id).expect("shared read").1.kind,
403            store.get("nodes", id).expect("native read").kind
404        );
405        assert_eq!(
406            resident.lookup_graph_nodes_by_label_in("nodes", "Person"),
407            [id]
408        );
409        assert_eq!(resident.entity_cache_stats().entries, 1);
410        assert!(store.delete("nodes", id).expect("native delete"));
411        assert!(resident.get_any(id).is_none());
412        assert!(resident.lookup_graph_nodes_by_label("Person").is_empty());
413        assert_eq!(resident.entity_cache_stats().entries, 0);
414        store.set_aux_metadata(b"catalog".to_vec());
415        assert_eq!(resident.aux_metadata(), b"catalog");
416        assert_eq!(
417            store.next_entity_id().raw(),
418            2,
419            "native allocator is the shared allocator"
420        );
421    }
422}