Skip to main content

reddb_server/storage/unified/store/
impl_entities.rs

1use super::*;
2
3impl UnifiedStore {
4    /// Vault versions are WAL-backed in memory until a committed checkpoint.
5    /// Preparing a commit must not dirty pager pages: eviction or an auth
6    /// flush could otherwise persist a version before its WAL batch exists.
7    pub(crate) fn insert_vault_version(
8        &self,
9        collection: &str,
10        entity: UnifiedEntity,
11        metadata: Metadata,
12    ) -> Result<(), StoreError> {
13        assert!(matches!(entity.data, EntityData::Row(_)));
14        let manager = self
15            .get_collection(collection)
16            .ok_or_else(|| StoreError::CollectionNotFound(collection.into()))?;
17        self.pending_vault_versions.write().insert(entity.id);
18        let id = manager.insert(entity)?;
19        self.register_entity_id(id);
20        if !metadata.fields.is_empty() {
21            manager.set_metadata(id, metadata)?;
22        }
23        let entity = manager
24            .get(id)
25            .expect("inserted vault version remains in memory");
26        self.persist_entities_to_pager_wal_only(collection, &[entity])
27    }
28
29    pub(crate) fn persist_entities_to_pager(
30        &self,
31        collection: &str,
32        entities: &[UnifiedEntity],
33    ) -> Result<(), StoreError> {
34        self.persist_entities_impl(collection, entities, /* skip_btree= */ false)
35    }
36
37    /// Same as `persist_entities_to_pager` but takes `&[&UnifiedEntity]` so
38    /// callers that already hold references (SQL UPDATE fast path) don't
39    /// have to clone a `Vec<UnifiedEntity>` just to satisfy the signature.
40    pub(crate) fn persist_entity_refs_to_pager(
41        &self,
42        collection: &str,
43        entities: &[&UnifiedEntity],
44    ) -> Result<(), StoreError> {
45        self.persist_entity_refs_impl(collection, entities, /* skip_btree= */ false)
46    }
47
48    /// Reference-taking WAL-only variant — see
49    /// `persist_entities_to_pager_wal_only` for semantics.
50    pub(crate) fn persist_entity_refs_to_pager_wal_only(
51        &self,
52        collection: &str,
53        entities: &[&UnifiedEntity],
54    ) -> Result<(), StoreError> {
55        self.persist_entity_refs_impl(collection, entities, /* skip_btree= */ true)
56    }
57
58    fn persist_entity_refs_impl(
59        &self,
60        collection: &str,
61        entities: &[&UnifiedEntity],
62        skip_btree: bool,
63    ) -> Result<(), StoreError> {
64        if entities.is_empty() {
65            return Ok(());
66        }
67        if self.pager.is_none() && self.config.embedded_wal_path.is_none() {
68            return Ok(());
69        }
70        let fv = self.format_version();
71        let manager = self
72            .get_collection(collection)
73            .ok_or_else(|| StoreError::CollectionNotFound(collection.to_string()))?;
74        let mut serialized: Vec<(Vec<u8>, Vec<u8>)> = entities
75            .iter()
76            .map(|entity| {
77                let metadata = manager.get_metadata(entity.id);
78                (
79                    entity.id.raw().to_be_bytes().to_vec(),
80                    Self::serialize_entity_record(entity, metadata.as_ref(), fv),
81                )
82            })
83            .collect();
84        serialized.sort_by(|a, b| a.0.cmp(&b.0));
85
86        if !skip_btree {
87            let Some(pager) = &self.pager else {
88                let records: Vec<Vec<u8>> =
89                    serialized.into_iter().map(|(_id, record)| record).collect();
90                self.finish_paged_write([StoreWalAction::BulkUpsertEntityRecords {
91                    collection: collection.to_string(),
92                    records,
93                }])?;
94                return Ok(());
95            };
96            let mut btree_indices = self.btree_indices.write();
97            let btree = btree_indices
98                .entry(collection.to_string())
99                .or_insert_with(|| Arc::new(BTree::new(Arc::clone(pager))));
100            let root_before = btree.root_page_id();
101            btree.upsert_batch_sorted(&serialized).map_err(|e| {
102                StoreError::Io(std::io::Error::other(format!("B-tree upsert error: {}", e)))
103            })?;
104            let root_after = btree.root_page_id();
105            drop(btree_indices);
106            if root_before != root_after {
107                self.mark_paged_registry_dirty();
108            }
109        }
110        let records: Vec<Vec<u8>> = serialized.into_iter().map(|(_id, record)| record).collect();
111        self.finish_paged_write([StoreWalAction::BulkUpsertEntityRecords {
112            collection: collection.to_string(),
113            records,
114        }])?;
115        Ok(())
116    }
117
118    /// PG-HOT-like UPDATE persist: emit the WAL record so the update
119    /// survives a crash, but skip the in-line B-tree upsert. Reads
120    /// continue to see the new entity because `manager.get()` prefers
121    /// the segment over the B-tree; WAL replay re-applies the upsert
122    /// to the B-tree on recovery so the two views converge before
123    /// any stale B-tree page can be surfaced.
124    ///
125    /// Safe to use only when the caller has already updated the
126    /// segment in-place (so live reads see the new value). Cuts out
127    /// the dominant cost of single-row UPDATEs: per-entity serialize
128    /// + leaf descent + page decompress / compress / write_page.
129    pub(crate) fn persist_entities_to_pager_wal_only(
130        &self,
131        collection: &str,
132        entities: &[UnifiedEntity],
133    ) -> Result<(), StoreError> {
134        self.persist_entities_impl(collection, entities, /* skip_btree= */ true)
135    }
136
137    fn persist_entities_impl(
138        &self,
139        collection: &str,
140        entities: &[UnifiedEntity],
141        skip_btree: bool,
142    ) -> Result<(), StoreError> {
143        if entities.is_empty() {
144            return Ok(());
145        }
146
147        if self.pager.is_none() && self.config.embedded_wal_path.is_none() {
148            return Ok(());
149        }
150
151        let fv = self.format_version();
152        let manager = self
153            .get_collection(collection)
154            .ok_or_else(|| StoreError::CollectionNotFound(collection.to_string()))?;
155        let mut serialized: Vec<(Vec<u8>, Vec<u8>)> = entities
156            .iter()
157            .map(|entity| {
158                let metadata = manager.get_metadata(entity.id);
159                (
160                    entity.id.raw().to_be_bytes().to_vec(),
161                    Self::serialize_entity_record(entity, metadata.as_ref(), fv),
162                )
163            })
164            .collect();
165        // u64 IDs encoded as big-endian — lex order = numeric order.
166        serialized.sort_by(|a, b| a.0.cmp(&b.0));
167
168        if !skip_btree {
169            let Some(pager) = &self.pager else {
170                let records: Vec<Vec<u8>> =
171                    serialized.into_iter().map(|(_id, record)| record).collect();
172                self.finish_paged_write([StoreWalAction::BulkUpsertEntityRecords {
173                    collection: collection.to_string(),
174                    records,
175                }])?;
176                return Ok(());
177            };
178            let mut btree_indices = self.btree_indices.write();
179            let btree = btree_indices
180                .entry(collection.to_string())
181                .or_insert_with(|| Arc::new(BTree::new(Arc::clone(pager))));
182            let root_before = btree.root_page_id();
183
184            // Walks each distinct leaf once, applies all in-place overwrites
185            // that belong there under one read+write. Keys that miss or grow
186            // fall back to the per-key `upsert` path internally.
187            btree.upsert_batch_sorted(&serialized).map_err(|e| {
188                StoreError::Io(std::io::Error::other(format!("B-tree upsert error: {}", e)))
189            })?;
190            let root_after = btree.root_page_id();
191            drop(btree_indices);
192            if root_before != root_after {
193                self.mark_paged_registry_dirty();
194            }
195        }
196        // One WAL action covering the whole bulk. Previously each entity
197        // produced its own `UpsertEntityRecord` action, which then became
198        // its own `WalRecord::PageWrite` triple inside
199        // `StoreCommitCoordinator::append_actions` — N WAL records per
200        // bulk. The batched variant is one WAL record per bulk.
201        //
202        // WAL is emitted even in the `skip_btree` variant — recovery
203        // replay reapplies the upsert to the B-tree, so durability
204        // is unchanged.
205        let records: Vec<Vec<u8>> = serialized.into_iter().map(|(_id, record)| record).collect();
206        self.finish_paged_write([StoreWalAction::BulkUpsertEntityRecords {
207            collection: collection.to_string(),
208            records,
209        }])?;
210
211        Ok(())
212    }
213
214    /// Insert a label→entity_id mapping into the graph label index.
215    pub(crate) fn update_graph_label_index(
216        &self,
217        collection: &str,
218        label: &str,
219        entity_id: EntityId,
220    ) {
221        let key = (collection.to_string(), label.to_string());
222        let mut idx = self.graph_label_index.write();
223        idx.entry(key).or_default().push(entity_id);
224    }
225
226    /// Remove a specific entity_id from the graph label index (called on delete).
227    pub(crate) fn remove_from_graph_label_index(&self, collection: &str, entity_id: EntityId) {
228        let mut idx = self.graph_label_index.write();
229        for ((col, _), ids) in idx.iter_mut() {
230            if col == collection {
231                ids.retain(|&id| id != entity_id);
232            }
233        }
234        // Prune empty entries to keep the index compact
235        idx.retain(|_, ids| !ids.is_empty());
236    }
237
238    pub(crate) fn remove_from_graph_label_index_batch(
239        &self,
240        collection: &str,
241        entity_ids: &[EntityId],
242    ) {
243        if entity_ids.is_empty() {
244            return;
245        }
246        let id_set: std::collections::HashSet<EntityId> = entity_ids.iter().copied().collect();
247        let mut idx = self.graph_label_index.write();
248        for ((col, _), ids) in idx.iter_mut() {
249            if col == collection {
250                ids.retain(|id| !id_set.contains(id));
251            }
252        }
253        idx.retain(|_, ids| !ids.is_empty());
254    }
255
256    /// Look up entity IDs for a graph node label across all collections.
257    pub fn lookup_graph_nodes_by_label(&self, label: &str) -> Vec<EntityId> {
258        let idx = self.graph_label_index.read();
259        idx.iter()
260            .filter(|((_, l), _)| l == label)
261            .flat_map(|(_, ids)| ids.iter().copied())
262            .collect()
263    }
264
265    /// Look up entity IDs for a graph node label scoped to a single collection.
266    pub fn lookup_graph_nodes_by_label_in(&self, collection: &str, label: &str) -> Vec<EntityId> {
267        let idx = self.graph_label_index.read();
268        idx.get(&(collection.to_string(), label.to_string()))
269            .cloned()
270            .unwrap_or_default()
271    }
272
273    pub fn create_collection(&self, name: impl Into<String>) -> Result<(), StoreError> {
274        let name = name.into();
275        let mut collections = self.collections.write();
276
277        if collections.contains_key(&name) {
278            return Err(StoreError::CollectionExists(name));
279        }
280
281        let manager = SegmentManager::with_config(&name, self.config.manager_config.clone());
282        collections.insert(name.clone(), Arc::new(manager));
283        drop(collections);
284
285        let create = match self.prepare_operational_collection_create(&name) {
286            Ok(create) => create,
287            Err(err) => {
288                let mut collections = self.collections.write();
289                collections.remove(&name);
290                return Err(err);
291            }
292        };
293        if let Some(create) = create {
294            if let Err(err) = create.publish().map_err(StoreError::Io) {
295                let mut collections = self.collections.write();
296                collections.remove(&name);
297                return Err(err);
298            }
299        }
300
301        self.mark_paged_registry_dirty();
302        self.finish_paged_write([StoreWalAction::CreateCollection { name }])?;
303
304        Ok(())
305    }
306
307    /// Get or create a collection
308    pub fn get_or_create_collection(&self, name: impl Into<String>) -> Arc<SegmentManager> {
309        let name = name.into();
310        // Fast path: shared read lock — zero contention for existing collections
311        {
312            let collections = self.collections.read();
313            if let Some(manager) = collections.get(&name) {
314                return Arc::clone(manager);
315            }
316        }
317        // Slow path: exclusive write lock — only when collection is missing
318        let mut collections = self.collections.write();
319        // Double-check after acquiring write lock (another thread may have created it)
320        if let Some(manager) = collections.get(&name) {
321            return Arc::clone(manager);
322        }
323        let manager = Arc::new(SegmentManager::with_config(
324            &name,
325            self.config.manager_config.clone(),
326        ));
327        collections.insert(name, Arc::clone(&manager));
328        self.mark_paged_registry_dirty();
329        manager
330    }
331
332    /// Get a collection
333    pub fn get_collection(&self, name: &str) -> Option<Arc<SegmentManager>> {
334        self.collections.read().get(name).map(Arc::clone)
335    }
336
337    /// Get the context index for cross-structure search.
338    pub fn context_index(&self) -> &ContextIndex {
339        &self.context_index
340    }
341
342    /// Drain WAL-replayed `VectorInsert` records for `collection`
343    /// (issue #694). Returns `None` when nothing was captured at open
344    /// time (in-memory mode, fresh database, or non-turbo collection).
345    /// One-shot: the caller owns the records after this call, the
346    /// store's internal buffer is cleared for that collection.
347    pub fn take_replayed_turbo_inserts(&self, collection: &str) -> Option<Vec<(u64, Vec<f32>)>> {
348        let mut map = self.replayed_turbo_inserts.lock();
349        map.remove(collection)
350    }
351
352    pub(crate) fn take_replayed_probabilistic_deltas(&self) -> Vec<(u8, u8, String, Vec<Vec<u8>>)> {
353        let mut deltas = self.replayed_probabilistic_deltas.lock();
354        std::mem::take(&mut *deltas)
355    }
356
357    /// Set multiple config KV pairs at once from a JSON tree.
358    /// Keys are flattened with dot-notation: `{"a":{"b":1}}` → `a.b = 1`.
359    ///
360    /// `red_config` is last-writer-wins (ADR 0014): each write replaces the
361    /// key's earlier rows. Appending instead grew the store on every boot,
362    /// since boot re-seeds keys such as `red.system.*`.
363    pub fn set_config_tree(&self, prefix: &str, json: &crate::serde_json::Value) -> usize {
364        let manager = self.get_or_create_collection("red_config");
365        let mut pairs = Vec::new();
366        flatten_config_json(prefix, json, &mut pairs);
367        // Existing rows per key, with the value each one holds.
368        let mut previous: HashMap<String, Vec<(EntityId, Option<reddb_types::Value>)>> = pairs
369            .iter()
370            .map(|(key, _)| (key.clone(), Vec::new()))
371            .collect();
372        for entity in manager.query_all(|_| true) {
373            if let EntityData::Row(row) = &entity.data {
374                let Some(named) = row.named.as_ref() else {
375                    continue;
376                };
377                if let Some(reddb_types::Value::Text(key)) = named.get("key") {
378                    if let Some(rows) = previous.get_mut(key.as_ref()) {
379                        rows.push((entity.id, named.get("value").cloned()));
380                    }
381                }
382            }
383        }
384        let mut saved = 0;
385        for (key, value) in pairs {
386            let stale = previous.remove(&key).unwrap_or_default();
387            // Rewriting a key with the value it already holds is a no-op.
388            // Boot re-seeds the same config every time, and each write is a
389            // durable WAL append with its own fsync.
390            if let [(_, Some(current))] = stale.as_slice() {
391                if *current == value {
392                    saved += 1;
393                    continue;
394                }
395            }
396            let stale: Vec<EntityId> = stale.into_iter().map(|(id, _)| id).collect();
397            // Insert before removing the old rows: a failure in between
398            // leaves a duplicate that readers resolve to the newest row,
399            // never a missing key.
400            let entity = UnifiedEntity::new(
401                EntityId::new(0),
402                EntityKind::TableRow {
403                    table: Arc::from("red_config"),
404                    row_id: 0,
405                },
406                EntityData::Row(RowData {
407                    columns: Vec::new(),
408                    named: Some(
409                        [
410                            ("key".to_string(), reddb_types::Value::text(key)),
411                            ("value".to_string(), value),
412                        ]
413                        .into_iter()
414                        .collect(),
415                    ),
416                    schema: None,
417                }),
418            );
419            if self.insert_auto("red_config", entity).is_ok() {
420                saved += 1;
421                if !stale.is_empty() {
422                    let _ = self.delete_batch("red_config", &stale);
423                }
424            }
425        }
426        saved
427    }
428
429    /// Read a single config value from `red_config` by dot-notation key.
430    /// When a key has several rows the newest one wins, like every other
431    /// `red_config` reader.
432    pub fn get_config(&self, key: &str) -> Option<reddb_types::Value> {
433        let manager = self.get_collection("red_config")?;
434        let mut latest: Option<(u64, reddb_types::Value)> = None;
435        for entity in manager.query_all(|_| true) {
436            if let EntityData::Row(row) = &entity.data {
437                if let Some(named) = &row.named {
438                    let key_matches = named
439                        .get("key")
440                        .and_then(|v| match v {
441                            reddb_types::Value::Text(s) => Some(s.as_ref() == key),
442                            _ => None,
443                        })
444                        .unwrap_or(false);
445                    if key_matches && latest.as_ref().is_none_or(|(id, _)| entity.id.raw() >= *id) {
446                        if let Some(value) = named.get("value") {
447                            latest = Some((entity.id.raw(), value.clone()));
448                        }
449                    }
450                }
451            }
452        }
453        latest.map(|(_, value)| value)
454    }
455
456    /// Replace the opaque store-level auxiliary metadata blob. Persisted
457    /// inside the binary dump (store format V10+); see the `aux_metadata`
458    /// field. RedDB uses it to carry collection contracts through the
459    /// single-file artifact.
460    pub fn set_aux_metadata(&self, bytes: Vec<u8>) {
461        *self.aux_metadata.write() = bytes;
462    }
463
464    /// Read the opaque store-level auxiliary metadata blob. Empty when unset.
465    pub fn aux_metadata(&self) -> Vec<u8> {
466        self.aux_metadata.read().clone()
467    }
468
469    /// List all collections
470    pub fn list_collections(&self) -> Vec<String> {
471        self.collections.read().keys().cloned().collect()
472    }
473
474    /// Drop a collection
475    pub fn drop_collection(&self, name: &str) -> Result<(), StoreError> {
476        let drop = self.prepare_operational_collection_drop(name)?;
477        let manager = {
478            let mut collections = self.collections.write();
479
480            collections
481                .remove(name)
482                .ok_or_else(|| StoreError::CollectionNotFound(name.to_string()))?
483        };
484
485        let entities = manager.query_all(|_| true);
486        let entity_ids: Vec<EntityId> = entities.iter().map(|entity| entity.id).collect();
487
488        for entity_id in &entity_ids {
489            self.context_index.remove_entity(*entity_id);
490            let _ = self.unindex_cross_refs(*entity_id);
491        }
492
493        self.btree_indices.write().remove(name);
494
495        self.entity_cache.retain(|entity_id, (collection, _)| {
496            collection != name && !entity_ids.iter().any(|id| id.raw() == entity_id)
497        });
498
499        self.cross_refs.write().retain(|source_id, refs| {
500            refs.retain(|(target_id, _, target_collection)| {
501                target_collection != name && !entity_ids.iter().any(|id| id == target_id)
502            });
503            !entity_ids.iter().any(|id| id == source_id)
504        });
505
506        self.reverse_refs.write().retain(|target_id, refs| {
507            refs.retain(|(source_id, _, source_collection)| {
508                source_collection != name && !entity_ids.iter().any(|id| id == source_id)
509            });
510            !entity_ids.iter().any(|id| id == target_id)
511        });
512
513        self.mark_paged_registry_dirty();
514        self.finish_paged_write([StoreWalAction::DropCollection {
515            name: name.to_string(),
516        }])?;
517        if let Some(drop) = drop {
518            drop.finish().map_err(StoreError::Io)?;
519        }
520
521        Ok(())
522    }
523
524    /// Insert an entity into a collection
525    pub fn insert(&self, collection: &str, entity: UnifiedEntity) -> Result<EntityId, StoreError> {
526        let manager = self
527            .get_collection(collection)
528            .ok_or_else(|| StoreError::CollectionNotFound(collection.to_string()))?;
529
530        let mut entity = entity;
531        if entity.id.raw() == 0 {
532            entity.id = self.next_entity_id();
533        } else {
534            self.register_entity_id(entity.id);
535        }
536        // Assign per-table sequential row_id if not set
537        if let EntityKind::TableRow { ref mut row_id, .. } = entity.kind {
538            if *row_id == 0 {
539                *row_id = manager.next_row_id();
540            } else {
541                manager.register_row_id(*row_id);
542            }
543        }
544        entity.ensure_table_logical_id();
545        // Capture graph node label before entity is moved into the manager
546        let graph_node_label: Option<String> = if let EntityKind::GraphNode(ref node) = entity.kind
547        {
548            Some(node.label.clone())
549        } else {
550            None
551        };
552
553        let id = manager.insert(entity)?;
554        self.register_entity_id(id);
555
556        // Update graph label index for GraphNode entities
557        if let Some(ref label) = graph_node_label {
558            self.update_graph_label_index(collection, label, id);
559        }
560
561        // Also insert into B-tree index if pager is active
562        let mut registry_dirty = false;
563        if let Some(pager) = &self.pager {
564            if let Some(entity) = manager.get(id) {
565                let mut btree_indices = self.btree_indices.write();
566                let btree = btree_indices
567                    .entry(collection.to_string())
568                    .or_insert_with(|| Arc::new(BTree::new(Arc::clone(pager))));
569                let root_before = btree.root_page_id();
570
571                let key = id.raw().to_be_bytes();
572                let metadata = manager.get_metadata(id);
573                let value = Self::serialize_entity_record(
574                    &entity,
575                    metadata.as_ref(),
576                    self.format_version(),
577                );
578                // Ignore duplicate key errors (update scenario)
579                let _ = btree.insert(&key, &value);
580                registry_dirty = root_before != btree.root_page_id();
581            }
582        }
583
584        // Index cross-references if enabled
585        if self.config.auto_index_refs {
586            if let Some(entity) = manager.get(id) {
587                self.index_cross_refs(&entity, collection)?;
588            }
589        }
590
591        // Perf: skip WAL-action construction when the store is
592        // pagerless. For in-memory benchmarks this saved another
593        // `manager.get(id)` + `serialize_entity_record` per call.
594        if self.pager.is_some() || self.config.embedded_wal_path.is_some() {
595            let actions = manager
596                .get(id)
597                .map(|entity| {
598                    let metadata = manager.get_metadata(id);
599                    vec![StoreWalAction::upsert_entity(
600                        collection,
601                        &entity,
602                        metadata.as_ref(),
603                        self.format_version(),
604                    )]
605                })
606                .unwrap_or_default();
607            if registry_dirty {
608                self.mark_paged_registry_dirty();
609            }
610            self.finish_paged_write(actions)?;
611        }
612
613        Ok(id)
614    }
615
616    /// Turbo bulk insert — optimized fast path.
617    ///
618    /// Single lock for the entire batch. Skips bloom filter,
619    /// context index, and cross-ref indexing. B-tree writes are batched.
620    pub fn bulk_insert(
621        &self,
622        collection: &str,
623        mut entities: Vec<UnifiedEntity>,
624    ) -> Result<Vec<EntityId>, StoreError> {
625        // REDDB_BULK_TIMING=1 prints a per-call breakdown of the bulk
626        // insert path to stderr. Off by default — used by the reddb
627        // benchmark harness to locate ingest bottlenecks.
628        let trace = matches!(
629            std::env::var("REDDB_BULK_TIMING").ok().as_deref(),
630            Some("1") | Some("true") | Some("on")
631        );
632        let t_start = std::time::Instant::now();
633        let n = entities.len();
634        let manager = self.get_or_create_collection(collection);
635        let t_get_coll = t_start.elapsed();
636
637        // Assign IDs and per-table row_ids before serialization. Bulk
638        // insert must follow the same global ID semantics as
639        // insert()/insert_auto(). Reserve ID ranges in single fetch_add
640        // calls instead of one-per-entity. The overwhelming common case
641        // is "every entity comes in with id==0 and kind==TableRow with
642        // row_id==0" (the wire bulk insert path). Any entity that
643        // already carries an id or row_id falls back to the individual
644        // register_* path to preserve those semantics exactly.
645        let t0 = std::time::Instant::now();
646        let n_missing_entity_ids = entities.iter().filter(|e| e.id.raw() == 0).count() as u64;
647        let n_missing_row_ids = entities
648            .iter()
649            .filter(|e| matches!(e.kind, EntityKind::TableRow { row_id: 0, .. }))
650            .count() as u64;
651        let mut entity_id_range = if n_missing_entity_ids > 0 {
652            self.reserve_entity_ids(n_missing_entity_ids)
653        } else {
654            0..0
655        };
656        let mut row_id_range = if n_missing_row_ids > 0 {
657            manager.reserve_row_ids(n_missing_row_ids)
658        } else {
659            0..0
660        };
661        for entity in &mut entities {
662            if entity.id.raw() == 0 {
663                let next = entity_id_range
664                    .next()
665                    .expect("reserved entity-id range exhausted");
666                entity.id = EntityId::new(next);
667            } else {
668                self.register_entity_id(entity.id);
669            }
670            if let EntityKind::TableRow { ref mut row_id, .. } = entity.kind {
671                if *row_id == 0 {
672                    *row_id = row_id_range
673                        .next()
674                        .expect("reserved row-id range exhausted");
675                } else {
676                    manager.register_row_id(*row_id);
677                }
678            }
679            entity.ensure_table_logical_id();
680        }
681        let t_assign_ids = t0.elapsed();
682
683        // Capture graph node labels before entities are moved into the segment manager
684        let graph_labels: Vec<Option<(String, EntityId)>> = entities
685            .iter()
686            .map(|e| {
687                if let EntityKind::GraphNode(ref node) = e.kind {
688                    Some((node.label.clone(), e.id))
689                } else {
690                    None
691                }
692            })
693            .collect();
694
695        // Pre-serialize for B-tree while we still have references.
696        // `serialize_entity_record` is pure; with `n >= 1024` the
697        // rayon dispatch cost is amortised and the 16-core serialize
698        // fan-out becomes the biggest single win on insert_bulk. For
699        // smaller batches, stay serial — micro-batches pay more in
700        // work-stealing overhead than they save.
701        let t0 = std::time::Instant::now();
702        let serialized: Option<Vec<(Vec<u8>, Vec<u8>)>> =
703            if self.pager.is_some() || self.config.embedded_wal_path.is_some() {
704                let fv = self.format_version();
705                let serial_map = |e: &UnifiedEntity| {
706                    (
707                        e.id.raw().to_be_bytes().to_vec(),
708                        Self::serialize_entity_record(e, None, fv),
709                    )
710                };
711                // Gate chosen to match the bench's `BULK_BATCH_SIZE=1000`.
712                // Rayon's dispatch overhead is ~30µs/batch — on a 15-col
713                // row serializing for ~40µs the break-even is around
714                // 200-300 rows on a 16-core host. Keep a safety margin
715                // at 512.
716                if entities.len() >= 512 {
717                    use rayon::prelude::*;
718                    Some(entities.par_iter().map(serial_map).collect())
719                } else {
720                    Some(entities.iter().map(serial_map).collect())
721                }
722            } else {
723                None
724            };
725        let t_serialize = t0.elapsed();
726
727        // Move entities into segment
728        let t0 = std::time::Instant::now();
729        let ids = manager.bulk_insert(entities)?;
730        let t_manager = t0.elapsed();
731        for id in &ids {
732            self.register_entity_id(*id);
733        }
734
735        // Update graph label index for bulk-inserted GraphNode entities
736        for (label, entity_id) in graph_labels.iter().flatten() {
737            self.update_graph_label_index(collection, label, *entity_id);
738        }
739
740        // REDDB_BULK_SKIP_PERSIST_UNSAFE=1 skips the persistent B-tree index
741        // during bulk ingest.
742        //
743        // UNSAFE: for ephemeral benchmark containers ONLY.
744        // This flag is silently ignored when a pager (durable storage) is active.
745        // In persistent mode, bulk inserts ALWAYS write to the B-tree so the data
746        // survives a cold restart without any manual rebuild step.
747        //
748        // The flag is only honoured when self.pager is None (in-memory / ephemeral).
749        let skip_btree_requested = matches!(
750            std::env::var("REDDB_BULK_SKIP_PERSIST_UNSAFE")
751                .ok()
752                .as_deref(),
753            Some("1") | Some("true") | Some("on")
754        );
755        // Honour the flag only when there is no durable pager.
756        // If a pager exists we are in persistent mode → always persist.
757        let skip_btree = skip_btree_requested && self.pager.is_none();
758        if skip_btree_requested && !skip_btree {
759            // Flag was set but we ignored it because we have a real pager.
760            static IGNORED: std::sync::OnceLock<()> = std::sync::OnceLock::new();
761            IGNORED.get_or_init(|| {
762                tracing::warn!(
763                    "REDDB_BULK_SKIP_PERSIST_UNSAFE set but durable pager is \
764                     active — flag ignored; bulk inserts will be persisted normally"
765                );
766            });
767        } else if skip_btree {
768            // Ephemeral mode and flag is active — warn once.
769            static WARNED: std::sync::OnceLock<()> = std::sync::OnceLock::new();
770            WARNED.get_or_init(|| {
771                tracing::warn!(
772                    "REDDB_BULK_SKIP_PERSIST_UNSAFE set (ephemeral/no-pager mode) — \
773                     bulk inserts NOT durable; data will be lost on restart"
774                );
775            });
776        }
777
778        // Batch B-tree write from pre-serialized data.
779        // Uses sorted bulk insert: walks to a leaf once, appends many entries,
780        // writes each leaf exactly once per batch — O(N) instead of O(N²).
781        let mut t_btree_lock = std::time::Duration::ZERO;
782        let mut t_btree_insert = std::time::Duration::ZERO;
783        let mut t_flush = std::time::Duration::ZERO;
784        if !skip_btree {
785            if let (Some(pager), Some(batch)) = (&self.pager, serialized.as_ref()) {
786                let t0 = std::time::Instant::now();
787                let mut btree_indices = self.btree_indices.write();
788                let btree = btree_indices
789                    .entry(collection.to_string())
790                    .or_insert_with(|| Arc::new(BTree::new(Arc::clone(pager))));
791                let root_before = btree.root_page_id();
792                t_btree_lock = t0.elapsed();
793
794                let t0 = std::time::Instant::now();
795                let _ = btree.bulk_insert_sorted(batch);
796                t_btree_insert = t0.elapsed();
797                let registry_dirty = root_before != btree.root_page_id();
798
799                let t0 = std::time::Instant::now();
800                if registry_dirty {
801                    self.mark_paged_registry_dirty();
802                }
803                t_flush = t0.elapsed();
804            }
805        }
806
807        // Fold 25k per-entity `UpsertEntityRecord` actions into one
808        // `BulkUpsertEntityRecords` — same on-disk semantics (replay
809        // applies each record by id), one `WalRecord::PageWrite`
810        // instead of N, and `record.clone()` drops out because we
811        // consume `serialized`.
812        let actions = serialized
813            .map(|batch| {
814                let records: Vec<Vec<u8>> =
815                    batch.into_iter().map(|(_key, record)| record).collect();
816                vec![StoreWalAction::BulkUpsertEntityRecords {
817                    collection: collection.to_string(),
818                    records,
819                }]
820            })
821            .unwrap_or_default();
822        self.finish_paged_write(actions)?;
823
824        if trace {
825            tracing::debug!(
826                n,
827                total = ?t_start.elapsed(),
828                get_coll = ?t_get_coll,
829                assign = ?t_assign_ids,
830                serialize = ?t_serialize,
831                manager = ?t_manager,
832                btree_lock = ?t_btree_lock,
833                btree = ?t_btree_insert,
834                flush = ?t_flush,
835                "bulk_insert timing"
836            );
837        }
838
839        Ok(ids)
840    }
841
842    /// Insert an entity, creating collection if needed
843    pub fn insert_auto(
844        &self,
845        collection: &str,
846        entity: UnifiedEntity,
847    ) -> Result<EntityId, StoreError> {
848        // Include the WAL append in the checkpoint publication fence.
849        let _publication = self.vault_publication_lock.lock();
850        let manager = self.get_or_create_collection(collection);
851        let mut entity = entity;
852        if entity.id.raw() == 0 {
853            entity.id = self.next_entity_id();
854        } else {
855            self.register_entity_id(entity.id);
856        }
857        // Assign per-table sequential row_id if not set
858        if let EntityKind::TableRow { ref mut row_id, .. } = entity.kind {
859            if *row_id == 0 {
860                *row_id = manager.next_row_id();
861            } else {
862                manager.register_row_id(*row_id);
863            }
864        }
865        entity.ensure_table_logical_id();
866
867        // Capture graph node label before entity is moved into the manager
868        let graph_node_label: Option<String> = if let EntityKind::GraphNode(ref node) = entity.kind
869        {
870            Some(node.label.clone())
871        } else {
872            None
873        };
874        // Index into context index before consuming the entity
875        self.context_index.index_entity(collection, &entity);
876
877        // Serialize the canonical segment image after insertion: the segment
878        // assigns its sequence identity. Borrow it instead of cloning payloads.
879        let persist_record = self.pager.is_some() || self.config.embedded_wal_path.is_some();
880        if self.config.auto_index_refs {
881            self.index_cross_refs(&entity, collection)?;
882        }
883
884        // #2376: `persist()` rebuilds every collection B-tree from the
885        // manager under `btree_indices.write()`. Hold the read side from the
886        // manager insert through the B-tree insert so a rebuild observes
887        // both or neither. Otherwise the rebuild re-inserts this row from the
888        // manager and one of the two B-tree inserts fails on a duplicate key,
889        // or lands mid-rebuild and tears the tree.
890        let paged_btree = if persist_record {
891            self.get_or_create_btree(collection)
892        } else {
893            None
894        };
895        let persist_fence = paged_btree
896            .as_ref()
897            .map(|_| self.btree_indices.read_recursive());
898        let before = paged_btree.as_ref().map(|_| manager.checkpoint_revisions());
899        let unversioned = entity.xmin == 0 && entity.xmax == 0;
900
901        let id = manager.insert(entity)?;
902        let serialized_record = if persist_record {
903            Some(
904                manager
905                    .get_with(id, |entity| {
906                        Self::serialize_entity_record(entity, None, self.format_version())
907                    })
908                    .ok_or(StoreError::EntityNotFound(id))?,
909            )
910        } else {
911            None
912        };
913        // `register_entity_id` already advances the atomic counter on
914        // the allocation path above (`self.next_entity_id()`), so the
915        // second call here is a no-op CAS loop on the hot path. Only
916        // needed for the caller-supplied-id branch which happens via
917        // the `register_entity_id` call on line 573.
918
919        // Update graph label index for GraphNode entities
920        if let Some(ref label) = graph_node_label {
921            self.update_graph_label_index(collection, label, id);
922        }
923
924        let mut registry_dirty = false;
925        if let (Some(btree), Some(record)) = (paged_btree.as_ref(), serialized_record.as_ref()) {
926            let root_before = btree.root_page_id();
927
928            let key = id.raw().to_be_bytes();
929            btree.insert(&key, record).map_err(|e| {
930                StoreError::Io(std::io::Error::other(format!(
931                    "B-tree insert error while inserting '{collection}'/{id}: {e}"
932                )))
933            })?;
934            registry_dirty = root_before != btree.root_page_id();
935        }
936        drop(persist_fence);
937
938        // Perf: pagerless → skip WAL-action construction (saves a
939        // third manager.get + entity serialize per insert). For
940        // in-memory runtimes finish_paged_write is a no-op.
941        if self.pager.is_some() || self.config.embedded_wal_path.is_some() {
942            let actions = serialized_record
943                .map(|record| {
944                    vec![StoreWalAction::UpsertEntityRecord {
945                        collection: collection.to_string(),
946                        record,
947                    }]
948                })
949                .unwrap_or_default();
950            if registry_dirty {
951                self.mark_paged_registry_dirty();
952            }
953            self.finish_paged_write(actions)?;
954        }
955        if unversioned && !Self::deferred_store_wal_capture_active() {
956            if let Some(before) = before {
957                self.note_paged_insert(collection, &manager, &before, id);
958            }
959        }
960        Ok(id)
961    }
962
963    /// Get an entity from a collection
964    ///
965    /// Prefers the live SegmentManager view so reads after update/delete observe
966    /// the current in-memory state even when the paged B-tree image has not been
967    /// refreshed yet. Falls back to the B-tree image for recovery-oriented reads.
968    pub fn get(&self, collection: &str, id: EntityId) -> Option<UnifiedEntity> {
969        // Prefer the live manager state to avoid stale reads after manager.update().
970        if let Some(entity) = self
971            .get_collection(collection)
972            .and_then(|manager| manager.get(id))
973        {
974            return Some(entity);
975        }
976
977        // Fall back to the paged B-tree image if the manager does not currently hold the row.
978        if self.pager.is_some() {
979            let btree_indices = self.btree_indices.read();
980            if let Some(btree) = btree_indices.get(collection) {
981                let key = id.raw().to_be_bytes();
982                if let Ok(Some(value)) = btree.get(&key) {
983                    if let Ok((entity, _)) =
984                        Self::deserialize_entity_record(&value, self.format_version())
985                    {
986                        return Some(entity);
987                    }
988                }
989            }
990        }
991
992        None
993    }
994
995    /// Resolve a table row by stable logical identity.
996    ///
997    /// Legacy rows use `logical_id == id`, so the physical-id lookup remains
998    /// the fast path. Versioned rows may have a different physical id and fall
999    /// back to a scan until the history-store/index slices add a dedicated map.
1000    pub fn get_table_row_by_logical_id(
1001        &self,
1002        collection: &str,
1003        logical_id: EntityId,
1004    ) -> Option<UnifiedEntity> {
1005        if let Some(entity) = self.get(collection, logical_id) {
1006            if matches!(entity.kind, EntityKind::TableRow { .. })
1007                && entity.logical_id() == logical_id
1008                && entity.xmax == 0
1009            {
1010                return Some(entity);
1011            }
1012        }
1013
1014        let manager = self.get_collection(collection)?;
1015        let mut matches = manager.query_all(|entity| {
1016            matches!(entity.kind, EntityKind::TableRow { .. }) && entity.logical_id() == logical_id
1017        });
1018        matches
1019            .iter()
1020            .find(|entity| entity.xmax == 0)
1021            .cloned()
1022            .or_else(|| matches.pop())
1023    }
1024
1025    pub fn table_row_versions_by_logical_id(
1026        &self,
1027        collection: &str,
1028        logical_id: EntityId,
1029    ) -> Vec<UnifiedEntity> {
1030        self.get_collection(collection)
1031            .map(|manager| {
1032                manager.query_all(|entity| {
1033                    matches!(entity.kind, EntityKind::TableRow { .. })
1034                        && entity.logical_id() == logical_id
1035                })
1036            })
1037            .unwrap_or_default()
1038    }
1039
1040    pub fn vacuum_mvcc_history(
1041        &self,
1042        collection: &str,
1043        cutoff_xid: u64,
1044    ) -> Result<MvccVacuumStats, StoreError> {
1045        let manager = self
1046            .get_collection(collection)
1047            .ok_or_else(|| StoreError::CollectionNotFound(collection.to_string()))?;
1048        let entities =
1049            manager.query_all(|entity| matches!(entity.kind, EntityKind::TableRow { .. }));
1050        let mut logical = HashMap::<EntityId, (bool, u64)>::new();
1051        for entity in &entities {
1052            let entry = logical.entry(entity.logical_id()).or_insert((false, 0));
1053            if entity.xmax == 0 {
1054                entry.0 = true;
1055            }
1056            entry.1 = entry.1.max(entity.xmin);
1057        }
1058
1059        let mut stats = MvccVacuumStats::default();
1060        let mut reclaim_ids = Vec::new();
1061        for entity in entities {
1062            if entity.xmax == 0 {
1063                continue;
1064            }
1065            stats.scanned_versions += 1;
1066            let (has_live_version, max_xmin) = logical
1067                .get(&entity.logical_id())
1068                .copied()
1069                .unwrap_or((false, entity.xmin));
1070            let is_delete_tombstone = !has_live_version && entity.xmin == max_xmin;
1071            if entity.xmax < cutoff_xid {
1072                stats.reclaimed_versions += 1;
1073                if is_delete_tombstone {
1074                    stats.reclaimed_tombstones += 1;
1075                } else {
1076                    stats.reclaimed_history_versions += 1;
1077                }
1078                reclaim_ids.push(entity.id);
1079            } else {
1080                stats.retained_versions += 1;
1081                if is_delete_tombstone {
1082                    stats.retained_tombstones += 1;
1083                } else {
1084                    stats.retained_history_versions += 1;
1085                }
1086            }
1087        }
1088
1089        if !reclaim_ids.is_empty() {
1090            self.delete_batch(collection, &reclaim_ids)?;
1091        }
1092        Ok(stats)
1093    }
1094
1095    pub(crate) fn install_versioned_table_row_update(
1096        &self,
1097        collection: &str,
1098        old_version: UnifiedEntity,
1099        mut new_version: UnifiedEntity,
1100        metadata: Option<&Metadata>,
1101    ) -> Result<(), StoreError> {
1102        let manager = self
1103            .get_collection(collection)
1104            .ok_or_else(|| StoreError::CollectionNotFound(collection.to_string()))?;
1105
1106        let old_id = old_version.id;
1107        let new_id = new_version.id;
1108        let inherited_metadata = metadata.cloned().or_else(|| manager.get_metadata(old_id));
1109
1110        self.entity_cache.remove(old_id.raw());
1111        self.entity_cache.remove(new_id.raw());
1112        manager.update(old_version.clone())?;
1113        self.context_index.remove_entity(old_id);
1114
1115        self.register_entity_id(new_version.id);
1116        if let EntityKind::TableRow { ref mut row_id, .. } = new_version.kind {
1117            if *row_id == 0 {
1118                *row_id = manager.next_row_id();
1119            } else {
1120                manager.register_row_id(*row_id);
1121            }
1122        }
1123        new_version.ensure_table_logical_id();
1124        manager.insert(new_version.clone())?;
1125        if let Some(metadata) = inherited_metadata {
1126            manager.set_metadata(new_id, metadata)?;
1127        }
1128        self.context_index.index_entity(collection, &new_version);
1129        if self.config.auto_index_refs {
1130            self.index_cross_refs(&new_version, collection)?;
1131        }
1132
1133        let old_metadata = manager.get_metadata(old_id);
1134        let new_metadata = manager.get_metadata(new_id);
1135        let fv = self.format_version();
1136        let records = vec![
1137            Self::serialize_entity_record(&old_version, old_metadata.as_ref(), fv),
1138            Self::serialize_entity_record(&new_version, new_metadata.as_ref(), fv),
1139        ];
1140        self.finish_paged_write([StoreWalAction::BulkUpsertEntityRecords {
1141            collection: collection.to_string(),
1142            records,
1143        }])?;
1144
1145        Ok(())
1146    }
1147
1148    /// Batch-fetch multiple entities from the same collection in minimal lock acquisitions.
1149    ///
1150    /// Preferred over N individual `get()` calls in indexed-scan loops (sorted index,
1151    /// bitmap, hash). Reduces lock acquisitions from N×3 to 2-3 total.
1152    /// Preserves input order: `result[i]` corresponds to `ids[i]`.
1153    pub fn get_batch(&self, collection: &str, ids: &[EntityId]) -> Vec<Option<UnifiedEntity>> {
1154        match self.get_collection(collection) {
1155            Some(manager) => manager.get_many(ids),
1156            None => vec![None; ids.len()],
1157        }
1158    }
1159
1160    /// Get an entity from any collection
1161    pub fn get_any(&self, id: EntityId) -> Option<(String, UnifiedEntity)> {
1162        // Sharded LRU probe: hits / misses are counted by `EntityCache::get`,
1163        // so external observers can read `entity_cache_hit_rate()` without
1164        // any extra wiring on the call site.
1165        if let Some(cached) = self.entity_cache.get(id.raw()) {
1166            return Some(cached);
1167        }
1168
1169        // Cache miss — fall back to the full collection scan, then memoise.
1170        let collections = self.collections.read();
1171        for (name, manager) in collections.iter() {
1172            if let Some(entity) = manager.get(id) {
1173                let result = (name.clone(), entity);
1174                // Drop the collections read guard before taking any cache
1175                // lock — the cache shards are independent, but releasing
1176                // here keeps `collections` contention low.
1177                drop(collections);
1178                self.entity_cache.insert(id.raw(), result.clone());
1179                return Some(result);
1180            }
1181        }
1182        None
1183    }
1184
1185    /// Hit rate of the store's entity cache (`get_any` lookups).
1186    ///
1187    /// Returns `None` until the cache has served at least one lookup.
1188    /// Exposed for observability — e.g. dashboards distinguishing graph
1189    /// workloads (high hit rate) from OLTP DML (≈ 0 % hit rate).
1190    pub fn entity_cache_hit_rate(&self) -> Option<f64> {
1191        self.entity_cache.hit_rate()
1192    }
1193
1194    /// Snapshot of cache hit / miss / eviction counters and current size.
1195    pub fn entity_cache_stats(&self) -> super::super::entity_cache::EntityCacheStats {
1196        self.entity_cache.stats()
1197    }
1198
1199    /// Delete an entity
1200    pub fn delete(&self, collection: &str, id: EntityId) -> Result<bool, StoreError> {
1201        // Invalidate entity cache (read-lock probe; no write lock when cold).
1202        self.entity_cache.remove(id.raw());
1203        let manager = self
1204            .get_collection(collection)
1205            .ok_or_else(|| StoreError::CollectionNotFound(collection.to_string()))?;
1206
1207        let deleted = manager.delete(id)?;
1208        if !deleted {
1209            return Ok(false);
1210        }
1211
1212        // Remove from B-tree index if active
1213        let mut registry_dirty = false;
1214        if self.pager.is_some() {
1215            let btree_indices = self.btree_indices.read();
1216            if let Some(btree) = btree_indices.get(collection) {
1217                let root_before = btree.root_page_id();
1218                let key = id.raw().to_be_bytes();
1219                let _ = btree.delete(&key);
1220                registry_dirty = root_before != btree.root_page_id();
1221            }
1222        }
1223
1224        // Remove cross-references
1225        self.unindex_cross_refs(id)?;
1226
1227        // Remove from graph label index
1228        self.remove_from_graph_label_index(collection, id);
1229
1230        if registry_dirty {
1231            self.mark_paged_registry_dirty();
1232        }
1233        self.finish_paged_write([StoreWalAction::DeleteEntityRecord {
1234            collection: collection.to_string(),
1235            entity_id: id.raw(),
1236        }])?;
1237
1238        Ok(true)
1239    }
1240
1241    pub fn delete_batch(
1242        &self,
1243        collection: &str,
1244        ids: &[EntityId],
1245    ) -> Result<Vec<EntityId>, StoreError> {
1246        if ids.is_empty() {
1247            return Ok(Vec::new());
1248        }
1249
1250        // Sharded invalidation. The bounded LRU's shard write lock is
1251        // only acquired when the shard actually carries one of these ids,
1252        // so the bench-typical zero-hit `delete_sequential` workload never
1253        // takes a write lock here at all.
1254        self.entity_cache.remove_many(ids.iter().map(|id| id.raw()));
1255
1256        let manager = self
1257            .get_collection(collection)
1258            .ok_or_else(|| StoreError::CollectionNotFound(collection.to_string()))?;
1259
1260        let deleted_ids = manager.delete_batch(ids)?;
1261        if deleted_ids.is_empty() {
1262            return Ok(deleted_ids);
1263        }
1264
1265        let mut registry_dirty = false;
1266        if self.pager.is_some() {
1267            let btree_indices = self.btree_indices.read();
1268            if let Some(btree) = btree_indices.get(collection) {
1269                let root_before = btree.root_page_id();
1270                for id in &deleted_ids {
1271                    let key = id.raw().to_be_bytes();
1272                    let _ = btree.delete(&key);
1273                }
1274                registry_dirty = root_before != btree.root_page_id();
1275            }
1276        }
1277
1278        self.unindex_cross_refs_batch(&deleted_ids)?;
1279        self.remove_from_graph_label_index_batch(collection, &deleted_ids);
1280        if registry_dirty {
1281            self.mark_paged_registry_dirty();
1282        }
1283        let actions = deleted_ids
1284            .iter()
1285            .map(|id| StoreWalAction::DeleteEntityRecord {
1286                collection: collection.to_string(),
1287                entity_id: id.raw(),
1288            })
1289            .collect::<Vec<_>>();
1290        self.finish_paged_write(actions)?;
1291
1292        Ok(deleted_ids)
1293    }
1294
1295    /// Set metadata for an entity
1296    pub fn set_metadata(
1297        &self,
1298        collection: &str,
1299        id: EntityId,
1300        metadata: Metadata,
1301    ) -> Result<(), StoreError> {
1302        let manager = self
1303            .get_collection(collection)
1304            .ok_or_else(|| StoreError::CollectionNotFound(collection.to_string()))?;
1305
1306        manager.set_metadata(id, metadata)?;
1307        if let Some(entity) = manager.get(id) {
1308            self.persist_entities_to_pager(collection, std::slice::from_ref(&entity))?;
1309        }
1310        Ok(())
1311    }
1312
1313    /// Get metadata for an entity
1314    pub fn get_metadata(&self, collection: &str, id: EntityId) -> Option<Metadata> {
1315        self.get_collection(collection)?.get_metadata(id)
1316    }
1317
1318    /// Add a cross-reference between entities
1319    pub fn add_cross_ref(
1320        &self,
1321        source_collection: &str,
1322        source_id: EntityId,
1323        target_collection: &str,
1324        target_id: EntityId,
1325        ref_type: RefType,
1326        weight: f32,
1327    ) -> Result<(), StoreError> {
1328        // Check source exists
1329        let source_manager = self
1330            .get_collection(source_collection)
1331            .ok_or_else(|| StoreError::CollectionNotFound(source_collection.to_string()))?;
1332
1333        if source_manager.get(source_id).is_none() {
1334            return Err(StoreError::EntityNotFound(source_id));
1335        }
1336
1337        // Check target exists
1338        let target_manager = self
1339            .get_collection(target_collection)
1340            .ok_or_else(|| StoreError::CollectionNotFound(target_collection.to_string()))?;
1341
1342        if target_manager.get(target_id).is_none() {
1343            return Err(StoreError::EntityNotFound(target_id));
1344        }
1345
1346        // Check limits
1347        let current_refs = self
1348            .cross_refs
1349            .read()
1350            .get(&source_id)
1351            .map_or(0, |v| v.len());
1352
1353        if current_refs >= self.config.max_cross_refs {
1354            return Err(StoreError::TooManyRefs(source_id));
1355        }
1356
1357        let mut registry_dirty = false;
1358        {
1359            let mut forward = self.cross_refs.write();
1360            let refs = forward.entry(source_id).or_default();
1361            let inserted = !refs.iter().any(|(id, kind, coll)| {
1362                *id == target_id && *kind == ref_type && coll == target_collection
1363            });
1364            if inserted {
1365                refs.push((target_id, ref_type, target_collection.to_string()));
1366                registry_dirty = true;
1367            }
1368        }
1369
1370        {
1371            let mut reverse = self.reverse_refs.write();
1372            let refs = reverse.entry(target_id).or_default();
1373            let inserted = !refs.iter().any(|(id, kind, coll)| {
1374                *id == source_id && *kind == ref_type && coll == source_collection
1375            });
1376            if inserted {
1377                refs.push((source_id, ref_type, source_collection.to_string()));
1378                registry_dirty = true;
1379            }
1380        }
1381
1382        if let Some(mut entity) = source_manager.get(source_id) {
1383            if !entity.cross_refs().iter().any(|xref| {
1384                xref.target == target_id
1385                    && xref.ref_type == ref_type
1386                    && xref.target_collection == target_collection
1387            }) {
1388                let cross_ref = CrossRef::with_weight(
1389                    source_id,
1390                    target_id,
1391                    target_collection,
1392                    ref_type,
1393                    weight,
1394                );
1395                entity.add_cross_ref(cross_ref);
1396                let _ = source_manager.update(entity.clone());
1397                registry_dirty = true;
1398                self.persist_entities_to_pager(source_collection, std::slice::from_ref(&entity))?;
1399            }
1400        }
1401
1402        if registry_dirty {
1403            self.mark_paged_registry_dirty();
1404            if matches!(
1405                self.config.durability_mode,
1406                crate::api::DurabilityMode::Strict
1407            ) {
1408                self.flush_paged_state()?;
1409            }
1410        }
1411
1412        Ok(())
1413    }
1414
1415    /// Get cross-references from an entity
1416    pub fn get_refs_from(&self, id: EntityId) -> Vec<(EntityId, RefType, String)> {
1417        self.cross_refs.read().get(&id).cloned().unwrap_or_default()
1418    }
1419
1420    /// Get cross-references to an entity
1421    pub fn get_refs_to(&self, id: EntityId) -> Vec<(EntityId, RefType, String)> {
1422        self.reverse_refs
1423            .read()
1424            .get(&id)
1425            .cloned()
1426            .unwrap_or_default()
1427    }
1428
1429    /// Expand cross-references to get related entities
1430    pub fn expand_refs(
1431        &self,
1432        id: EntityId,
1433        depth: u32,
1434        ref_types: Option<&[RefType]>,
1435    ) -> Vec<(UnifiedEntity, u32, RefType)> {
1436        let mut results = Vec::new();
1437        let mut visited = std::collections::HashSet::new();
1438        visited.insert(id);
1439
1440        self.expand_refs_recursive(id, depth, ref_types, &mut visited, &mut results, 1);
1441
1442        results
1443    }
1444
1445    fn expand_refs_recursive(
1446        &self,
1447        id: EntityId,
1448        max_depth: u32,
1449        ref_types: Option<&[RefType]>,
1450        visited: &mut std::collections::HashSet<EntityId>,
1451        results: &mut Vec<(UnifiedEntity, u32, RefType)>,
1452        current_depth: u32,
1453    ) {
1454        if current_depth > max_depth {
1455            return;
1456        }
1457
1458        for (target_id, ref_type, target_collection) in self.get_refs_from(id) {
1459            if visited.contains(&target_id) {
1460                continue;
1461            }
1462
1463            if let Some(types) = ref_types {
1464                if !types.contains(&ref_type) {
1465                    continue;
1466                }
1467            }
1468
1469            visited.insert(target_id);
1470
1471            if let Some(entity) = self.get(&target_collection, target_id) {
1472                results.push((entity, current_depth, ref_type));
1473
1474                // Recurse
1475                self.expand_refs_recursive(
1476                    target_id,
1477                    max_depth,
1478                    ref_types,
1479                    visited,
1480                    results,
1481                    current_depth + 1,
1482                );
1483            }
1484        }
1485    }
1486
1487    /// Index cross-references from an entity
1488    pub(crate) fn index_cross_refs(
1489        &self,
1490        entity: &UnifiedEntity,
1491        collection: &str,
1492    ) -> Result<(), StoreError> {
1493        let mut registry_dirty = false;
1494        for cross_ref in entity.cross_refs() {
1495            if cross_ref.target_collection.is_empty() {
1496                continue;
1497            }
1498            {
1499                let mut forward = self.cross_refs.write();
1500                let refs = forward.entry(cross_ref.source).or_default();
1501                let inserted = !refs.iter().any(|(id, kind, coll)| {
1502                    *id == cross_ref.target
1503                        && *kind == cross_ref.ref_type
1504                        && coll == &cross_ref.target_collection
1505                });
1506                if inserted {
1507                    refs.push((
1508                        cross_ref.target,
1509                        cross_ref.ref_type,
1510                        cross_ref.target_collection.clone(),
1511                    ));
1512                    registry_dirty = true;
1513                }
1514            }
1515
1516            {
1517                let mut reverse = self.reverse_refs.write();
1518                let refs = reverse.entry(cross_ref.target).or_default();
1519                let inserted = !refs.iter().any(|(id, kind, coll)| {
1520                    *id == cross_ref.source && *kind == cross_ref.ref_type && coll == collection
1521                });
1522                if inserted {
1523                    refs.push((cross_ref.source, cross_ref.ref_type, collection.to_string()));
1524                    registry_dirty = true;
1525                }
1526            }
1527        }
1528
1529        if registry_dirty {
1530            self.mark_paged_registry_dirty();
1531        }
1532
1533        Ok(())
1534    }
1535
1536    /// Remove cross-references for an entity
1537    pub(crate) fn unindex_cross_refs(&self, id: EntityId) -> Result<(), StoreError> {
1538        // Remove forward refs
1539        self.cross_refs.write().remove(&id);
1540
1541        // Remove from reverse refs (scan all)
1542        let mut reverse = self.reverse_refs.write();
1543        for refs in reverse.values_mut() {
1544            refs.retain(|(source, _, _)| *source != id);
1545        }
1546        reverse.remove(&id);
1547        self.mark_paged_registry_dirty();
1548
1549        Ok(())
1550    }
1551
1552    pub(crate) fn unindex_cross_refs_batch(&self, ids: &[EntityId]) -> Result<(), StoreError> {
1553        if ids.is_empty() {
1554            return Ok(());
1555        }
1556
1557        let id_set: std::collections::HashSet<EntityId> = ids.iter().copied().collect();
1558
1559        // Read-only probe: under steady-state delete workloads most rows have
1560        // no cross-refs at all, so both maps are entirely cold for the batch.
1561        // Acquiring the write lock to scan `reverse_refs.values_mut()` over an
1562        // unrelated dictionary was the dominant cost in #85's `delete_sequential`
1563        // profile. The read-lock probe below is O(|ids|) hashmap lookups against
1564        // each map, vs. O(|reverse_refs|) for the write-path scan it replaces.
1565        //
1566        // Decision: skip the write path iff
1567        //   - no deleted id is a key in `cross_refs`  (no outbound refs to drop,
1568        //     and so no `(deleted_id, _, _)` source entry exists anywhere in
1569        //     `reverse_refs.values()` either — the two maps are kept in sync by
1570        //     `add_cross_ref`), AND
1571        //   - no deleted id is a key in `reverse_refs` (no inbound refs to drop).
1572        let needs_forward_cleanup = {
1573            let forward = self.cross_refs.read();
1574            id_set.iter().any(|id| forward.contains_key(id))
1575        };
1576        let needs_reverse_cleanup = {
1577            let reverse = self.reverse_refs.read();
1578            id_set.iter().any(|id| reverse.contains_key(id))
1579        };
1580
1581        if !needs_forward_cleanup && !needs_reverse_cleanup {
1582            self.unindex_cross_refs_fast_path
1583                .fetch_add(1, Ordering::Relaxed);
1584            return Ok(());
1585        }
1586
1587        if needs_forward_cleanup {
1588            let mut forward = self.cross_refs.write();
1589            for id in &id_set {
1590                forward.remove(id);
1591            }
1592        }
1593
1594        if needs_reverse_cleanup || needs_forward_cleanup {
1595            // The inner `values_mut()` scan is only needed when at least one
1596            // deleted id was a *source* somewhere — which, by the invariant
1597            // above, can only happen when it had outbound forward refs.
1598            let mut reverse = self.reverse_refs.write();
1599            if needs_forward_cleanup {
1600                for refs in reverse.values_mut() {
1601                    refs.retain(|(source, _, _)| !id_set.contains(source));
1602                }
1603            }
1604            reverse.retain(|target, refs| !id_set.contains(target) && !refs.is_empty());
1605        }
1606        self.mark_paged_registry_dirty();
1607
1608        Ok(())
1609    }
1610
1611    /// Test/observability hook: number of times `unindex_cross_refs_batch`
1612    /// took the read-only fast path. Used to pin the early-exit in tests
1613    /// and as a cheap signal in delete-heavy benchmarks.
1614    pub fn unindex_cross_refs_fast_path_hits(&self) -> u64 {
1615        self.unindex_cross_refs_fast_path.load(Ordering::Relaxed)
1616    }
1617
1618    /// Query across all collections with a filter
1619    pub fn query_all<F>(&self, filter: F) -> Vec<(String, UnifiedEntity)>
1620    where
1621        F: Fn(&UnifiedEntity) -> bool + Clone + Send + Sync,
1622    {
1623        // Issue #815 — snapshot the (name, manager) handles under a brief
1624        // read lock, then release the `collections` lock *before* the
1625        // potentially long per-collection scan. Holding `collections.read()`
1626        // across a full-store scan let a large `/catalog` snapshot block (and
1627        // be blocked by) the replica apply loop's collection-creation writes:
1628        // under parking_lot a writer waiting behind the long read parks every
1629        // subsequent reader, so `/catalog` and readiness wedged during a big
1630        // WAL re-apply. The managers are `Arc`-shared with their own internal
1631        // locks, so scanning them off the map lock is safe and keeps the HTTP
1632        // surface responsive.
1633        let pairs: Vec<(String, Arc<SegmentManager>)> = {
1634            let collections = self.collections.read();
1635            collections
1636                .iter()
1637                .map(|(name, mgr)| (name.clone(), Arc::clone(mgr)))
1638                .collect()
1639        };
1640
1641        let use_parallel = pairs.len() > 1 && crate::runtime::SystemInfo::should_parallelize();
1642        if !use_parallel {
1643            // Single collection — no parallelism overhead
1644            return pairs
1645                .into_iter()
1646                .flat_map(|(name, mgr)| {
1647                    mgr.query_all(filter.clone())
1648                        .into_iter()
1649                        .map(move |e| (name.clone(), e))
1650                })
1651                .collect();
1652        }
1653
1654        // Multiple collections — scan in parallel
1655        let filter_ref = &filter;
1656        let collection_results: Vec<Vec<(String, UnifiedEntity)>> = std::thread::scope(|s| {
1657            pairs
1658                .iter()
1659                .map(|(name, manager)| {
1660                    let name = (*name).clone();
1661                    s.spawn(move || {
1662                        manager
1663                            .query_all(|e| filter_ref(e))
1664                            .into_iter()
1665                            .map(|e| (name.clone(), e))
1666                            .collect::<Vec<_>>()
1667                    })
1668                })
1669                .collect::<Vec<_>>()
1670                .into_iter()
1671                .map(|h| h.join().unwrap_or_default())
1672                .collect()
1673        });
1674
1675        collection_results.into_iter().flatten().collect()
1676    }
1677
1678    /// Scan every collection under an explicit MVCC snapshot.
1679    pub fn scan<F>(
1680        &self,
1681        snapshot: Option<&crate::runtime::impl_core::SnapshotContext>,
1682        filter: F,
1683    ) -> Vec<(String, UnifiedEntity)>
1684    where
1685        F: Fn(&UnifiedEntity) -> bool + Clone + Send + Sync,
1686    {
1687        let pairs: Vec<(String, Arc<SegmentManager>)> = {
1688            let collections = self.collections.read();
1689            collections
1690                .iter()
1691                .map(|(name, manager)| (name.clone(), Arc::clone(manager)))
1692                .collect()
1693        };
1694
1695        let use_parallel = pairs.len() > 1 && crate::runtime::SystemInfo::should_parallelize();
1696        if !use_parallel {
1697            return pairs
1698                .into_iter()
1699                .flat_map(|(name, manager)| {
1700                    manager
1701                        .scan(snapshot, filter.clone())
1702                        .into_iter()
1703                        .map(move |entity| (name.clone(), entity))
1704                })
1705                .collect();
1706        }
1707
1708        let filter_ref = &filter;
1709        let collection_results: Vec<Vec<(String, UnifiedEntity)>> = std::thread::scope(|scope| {
1710            pairs
1711                .iter()
1712                .map(|(name, manager)| {
1713                    let name = name.clone();
1714                    scope.spawn(move || {
1715                        manager
1716                            .scan(snapshot, |entity| filter_ref(entity))
1717                            .into_iter()
1718                            .map(|entity| (name.clone(), entity))
1719                            .collect::<Vec<_>>()
1720                    })
1721                })
1722                .collect::<Vec<_>>()
1723                .into_iter()
1724                .map(|handle| handle.join().unwrap_or_default())
1725                .collect()
1726        });
1727
1728        collection_results.into_iter().flatten().collect()
1729    }
1730
1731    /// Filter by metadata across all collections
1732    pub fn filter_metadata_all(
1733        &self,
1734        filters: &[(String, MetadataFilter)],
1735    ) -> Vec<(String, EntityId)> {
1736        let mut results = Vec::new();
1737        let collections = self.collections.read();
1738
1739        for (name, manager) in collections.iter() {
1740            for id in manager.filter_metadata(filters) {
1741                results.push((name.clone(), id));
1742            }
1743        }
1744
1745        results
1746    }
1747
1748    /// Get statistics
1749    pub fn stats(&self) -> StoreStats {
1750        // Issue #815 — snapshot the manager handles, drop the `collections`
1751        // read lock, then gather per-collection stats off the map lock. The
1752        // readiness probe (via `health()`) walks `stats()`, so holding the
1753        // store lock across a full-store stats scan was part of the same
1754        // wedge that froze `/catalog` during a large replica re-apply.
1755        let pairs: Vec<(String, Arc<SegmentManager>)> = {
1756            let collections = self.collections.read();
1757            collections
1758                .iter()
1759                .map(|(name, mgr)| (name.clone(), Arc::clone(mgr)))
1760                .collect()
1761        };
1762
1763        let mut stats = StoreStats {
1764            collection_count: pairs.len(),
1765            ..Default::default()
1766        };
1767
1768        for (name, manager) in &pairs {
1769            let manager_stats = manager.stats();
1770            stats.total_entities += manager_stats.total_entities;
1771            stats.total_memory_bytes += manager_stats.total_memory_bytes;
1772            stats.collections.insert(name.clone(), manager_stats);
1773        }
1774
1775        stats
1776    }
1777
1778    /// Run maintenance on all collections
1779    pub fn run_maintenance(&self) -> Result<(), StoreError> {
1780        let collections = self.collections.read();
1781        for manager in collections.values() {
1782            manager.run_maintenance()?;
1783        }
1784        Ok(())
1785    }
1786
1787    /// Bytes pressure consolidation could plausibly return across collections.
1788    pub fn reclaimable_segment_bytes(&self) -> u64 {
1789        let collections = self.collections.read();
1790        collections
1791            .values()
1792            .map(|manager| manager.reclaimable_bytes())
1793            .fold(0, u64::saturating_add)
1794    }
1795
1796    /// Advance pressure-triggered consolidation by one paced tick per
1797    /// collection. Returns true if any collection started or advanced a run.
1798    pub fn pressure_consolidation_tick(&self) -> bool {
1799        let managers: Vec<_> = self.collections.read().values().cloned().collect();
1800        // A plain loop, not `any()`: every collection must receive its tick —
1801        // short-circuiting on the first advanced run would starve the rest.
1802        let mut advanced = false;
1803        for manager in &managers {
1804            advanced |= manager.pressure_consolidation_tick();
1805        }
1806        advanced
1807    }
1808}
1809
1810/// Flatten a JSON value into dot-notation key-value pairs for red_config.
1811fn flatten_config_json(
1812    prefix: &str,
1813    value: &crate::serde_json::Value,
1814    out: &mut Vec<(String, reddb_types::Value)>,
1815) {
1816    use reddb_types::Value;
1817    match value {
1818        crate::serde_json::Value::Object(map) => {
1819            for (k, v) in map {
1820                let key = if prefix.is_empty() {
1821                    k.clone()
1822                } else {
1823                    format!("{prefix}.{k}")
1824                };
1825                flatten_config_json(&key, v, out);
1826            }
1827        }
1828        crate::serde_json::Value::String(s) => {
1829            out.push((prefix.to_string(), Value::text(s.clone())));
1830        }
1831        crate::serde_json::Value::Integer(n) => {
1832            out.push((prefix.to_string(), Value::Integer(*n)));
1833        }
1834        crate::serde_json::Value::Number(n) => {
1835            if n.fract().abs() < f64::EPSILON {
1836                out.push((prefix.to_string(), Value::UnsignedInteger(*n as u64)));
1837            } else {
1838                out.push((prefix.to_string(), Value::Float(*n)));
1839            }
1840        }
1841        crate::serde_json::Value::Decimal(n) => {
1842            out.push((prefix.to_string(), Value::DecimalText(n.clone())));
1843        }
1844        crate::serde_json::Value::Bool(b) => {
1845            out.push((prefix.to_string(), Value::Boolean(*b)));
1846        }
1847        crate::serde_json::Value::Null => {
1848            out.push((prefix.to_string(), Value::Null));
1849        }
1850        crate::serde_json::Value::Array(arr) => {
1851            let json_str = crate::serde_json::to_string(value).unwrap_or_default();
1852            out.push((prefix.to_string(), Value::text(json_str)));
1853        }
1854    }
1855}