Skip to main content

reddb_server/storage/unified/store/
impl_entities.rs

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