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 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, false)
39 }
40
41 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, false)
50 }
51
52 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, 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 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, 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 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 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 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 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 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 pub fn lookup_graph_nodes_by_label(&self, label: &str) -> Vec<EntityId> {
273 self.resident.lookup_graph_nodes_by_label(label)
274 }
275
276 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 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 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 pub fn get_collection(&self, name: &str) -> Option<Arc<SegmentManager>> {
312 self.resident
313 .get_collection(Self::canonical_collection(name))
314 }
315
316 pub fn context_index(&self) -> &ContextIndex {
318 self.resident.context_index()
319 }
320
321 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 pub fn set_config_tree(&self, prefix: &str, json: &crate::serde_json::Value) -> usize {
343 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 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 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 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 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 pub fn get_config(&self, key: &str) -> Option<reddb_types::Value> {
478 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 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 pub fn set_aux_metadata(&self, bytes: Vec<u8>) {
578 self.resident.set_aux_metadata(bytes)
579 }
580
581 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 pub fn aux_metadata(&self) -> Vec<u8> {
596 self.resident.aux_metadata()
597 }
598
599 pub fn list_collections(&self) -> Vec<String> {
601 self.resident.list_collections()
602 }
603
604 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 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 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 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 if let Some(ref label) = graph_node_label {
702 self.update_graph_label_index(collection, label, id);
703 }
704
705 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 let _ = btree.insert(&key, &value);
730 registry_dirty = root_before != btree.root_page_id();
731 }
732 }
733
734 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 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 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 let _publication = self.vault_publication_lock.lock();
785 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 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 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 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 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 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 for (label, entity_id) in graph_labels.iter().flatten() {
902 self.update_graph_label_index(collection, label, *entity_id);
903 }
904
905 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 let skip_btree = skip_btree_requested && self.pager.is_none();
923 if skip_btree_requested && !skip_btree {
924 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 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 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 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 if let Err(error) = self.finish_paged_write_for_projection(actions, immutable_base) {
994 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 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 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 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 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 self.resident
1063 .context_index
1064 .index_entity(collection, &entity);
1065
1066 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 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 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 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 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 pub fn get(&self, collection: &str, id: EntityId) -> Option<UnifiedEntity> {
1185 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 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 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 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 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 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 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 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 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 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 pub fn get_any(&self, id: EntityId) -> Option<(String, UnifiedEntity)> {
1535 self.resident.get_any(id)
1536 }
1537
1538 pub fn entity_cache_hit_rate(&self) -> Option<f64> {
1544 self.resident.entity_cache_hit_rate()
1545 }
1546
1547 pub fn entity_cache_stats(&self) -> super::super::entity_cache::EntityCacheStats {
1549 self.resident.entity_cache_stats()
1550 }
1551
1552 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 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 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 self.unindex_cross_refs(id)?;
1581
1582 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 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 let _publication = self.vault_publication_lock.lock();
1638
1639 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 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 self.flush_paged_registry()?;
1708 }
1709 Ok(deleted_ids)
1710 }
1711
1712 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 pub fn get_metadata(&self, collection: &str, id: EntityId) -> Option<Metadata> {
1732 self.get_collection(collection)?.get_metadata(id)
1733 }
1734
1735 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 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 pub fn get_refs_from(&self, id: EntityId) -> Vec<(EntityId, RefType, String)> {
1785 self.resident.get_refs_from(id)
1786 }
1787
1788 pub fn get_refs_to(&self, id: EntityId) -> Vec<(EntityId, RefType, String)> {
1790 self.resident.get_refs_to(id)
1791 }
1792
1793 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 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 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 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 pub fn unindex_cross_refs_fast_path_hits(&self) -> u64 {
1873 self.resident.unindex_cross_refs_fast_path_hits()
1874 }
1875
1876 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 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 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 pub fn stats(&self) -> StoreStats {
1906 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 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 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 pub fn pressure_consolidation_tick(&self) -> bool {
1964 let managers: Vec<_> = self.resident.collections.read().values().cloned().collect();
1965 let mut advanced = false;
1968 for manager in &managers {
1969 advanced |= manager.pressure_consolidation_tick();
1970 }
1971 advanced
1972 }
1973}
1974
1975fn 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}