1use super::*;
2
3impl UnifiedStore {
4 pub(crate) fn insert_vault_version(
8 &self,
9 collection: &str,
10 entity: UnifiedEntity,
11 metadata: Metadata,
12 ) -> Result<(), StoreError> {
13 assert!(matches!(entity.data, EntityData::Row(_)));
14 let manager = self
15 .get_collection(collection)
16 .ok_or_else(|| StoreError::CollectionNotFound(collection.into()))?;
17 self.pending_vault_versions.write().insert(entity.id);
18 let id = manager.insert(entity)?;
19 self.register_entity_id(id);
20 if !metadata.fields.is_empty() {
21 manager.set_metadata(id, metadata)?;
22 }
23 let entity = manager
24 .get(id)
25 .expect("inserted vault version remains in memory");
26 self.persist_entities_to_pager_wal_only(collection, &[entity])
27 }
28
29 pub(crate) fn persist_entities_to_pager(
30 &self,
31 collection: &str,
32 entities: &[UnifiedEntity],
33 ) -> Result<(), StoreError> {
34 self.persist_entities_impl(collection, entities, false)
35 }
36
37 pub(crate) fn persist_entity_refs_to_pager(
41 &self,
42 collection: &str,
43 entities: &[&UnifiedEntity],
44 ) -> Result<(), StoreError> {
45 self.persist_entity_refs_impl(collection, entities, false)
46 }
47
48 pub(crate) fn persist_entity_refs_to_pager_wal_only(
51 &self,
52 collection: &str,
53 entities: &[&UnifiedEntity],
54 ) -> Result<(), StoreError> {
55 self.persist_entity_refs_impl(collection, entities, true)
56 }
57
58 fn persist_entity_refs_impl(
59 &self,
60 collection: &str,
61 entities: &[&UnifiedEntity],
62 skip_btree: bool,
63 ) -> Result<(), StoreError> {
64 if entities.is_empty() {
65 return Ok(());
66 }
67 if self.pager.is_none() && self.config.embedded_wal_path.is_none() {
68 return Ok(());
69 }
70 let fv = self.format_version();
71 let manager = self
72 .get_collection(collection)
73 .ok_or_else(|| StoreError::CollectionNotFound(collection.to_string()))?;
74 let mut serialized: Vec<(Vec<u8>, Vec<u8>)> = entities
75 .iter()
76 .map(|entity| {
77 let metadata = manager.get_metadata(entity.id);
78 (
79 entity.id.raw().to_be_bytes().to_vec(),
80 Self::serialize_entity_record(entity, metadata.as_ref(), fv),
81 )
82 })
83 .collect();
84 serialized.sort_by(|a, b| a.0.cmp(&b.0));
85
86 if !skip_btree {
87 let Some(pager) = &self.pager else {
88 let records: Vec<Vec<u8>> =
89 serialized.into_iter().map(|(_id, record)| record).collect();
90 self.finish_paged_write([StoreWalAction::BulkUpsertEntityRecords {
91 collection: collection.to_string(),
92 records,
93 }])?;
94 return Ok(());
95 };
96 let mut btree_indices = self.btree_indices.write();
97 let btree = btree_indices
98 .entry(collection.to_string())
99 .or_insert_with(|| Arc::new(BTree::new(Arc::clone(pager))));
100 let root_before = btree.root_page_id();
101 btree.upsert_batch_sorted(&serialized).map_err(|e| {
102 StoreError::Io(std::io::Error::other(format!("B-tree upsert error: {}", e)))
103 })?;
104 let root_after = btree.root_page_id();
105 drop(btree_indices);
106 if root_before != root_after {
107 self.mark_paged_registry_dirty();
108 }
109 }
110 let records: Vec<Vec<u8>> = serialized.into_iter().map(|(_id, record)| record).collect();
111 self.finish_paged_write([StoreWalAction::BulkUpsertEntityRecords {
112 collection: collection.to_string(),
113 records,
114 }])?;
115 Ok(())
116 }
117
118 pub(crate) fn persist_entities_to_pager_wal_only(
130 &self,
131 collection: &str,
132 entities: &[UnifiedEntity],
133 ) -> Result<(), StoreError> {
134 self.persist_entities_impl(collection, entities, true)
135 }
136
137 fn persist_entities_impl(
138 &self,
139 collection: &str,
140 entities: &[UnifiedEntity],
141 skip_btree: bool,
142 ) -> Result<(), StoreError> {
143 if entities.is_empty() {
144 return Ok(());
145 }
146
147 if self.pager.is_none() && self.config.embedded_wal_path.is_none() {
148 return Ok(());
149 }
150
151 let fv = self.format_version();
152 let manager = self
153 .get_collection(collection)
154 .ok_or_else(|| StoreError::CollectionNotFound(collection.to_string()))?;
155 let mut serialized: Vec<(Vec<u8>, Vec<u8>)> = entities
156 .iter()
157 .map(|entity| {
158 let metadata = manager.get_metadata(entity.id);
159 (
160 entity.id.raw().to_be_bytes().to_vec(),
161 Self::serialize_entity_record(entity, metadata.as_ref(), fv),
162 )
163 })
164 .collect();
165 serialized.sort_by(|a, b| a.0.cmp(&b.0));
167
168 if !skip_btree {
169 let Some(pager) = &self.pager else {
170 let records: Vec<Vec<u8>> =
171 serialized.into_iter().map(|(_id, record)| record).collect();
172 self.finish_paged_write([StoreWalAction::BulkUpsertEntityRecords {
173 collection: collection.to_string(),
174 records,
175 }])?;
176 return Ok(());
177 };
178 let mut btree_indices = self.btree_indices.write();
179 let btree = btree_indices
180 .entry(collection.to_string())
181 .or_insert_with(|| Arc::new(BTree::new(Arc::clone(pager))));
182 let root_before = btree.root_page_id();
183
184 btree.upsert_batch_sorted(&serialized).map_err(|e| {
188 StoreError::Io(std::io::Error::other(format!("B-tree upsert error: {}", e)))
189 })?;
190 let root_after = btree.root_page_id();
191 drop(btree_indices);
192 if root_before != root_after {
193 self.mark_paged_registry_dirty();
194 }
195 }
196 let records: Vec<Vec<u8>> = serialized.into_iter().map(|(_id, record)| record).collect();
206 self.finish_paged_write([StoreWalAction::BulkUpsertEntityRecords {
207 collection: collection.to_string(),
208 records,
209 }])?;
210
211 Ok(())
212 }
213
214 pub(crate) fn update_graph_label_index(
216 &self,
217 collection: &str,
218 label: &str,
219 entity_id: EntityId,
220 ) {
221 let key = (collection.to_string(), label.to_string());
222 let mut idx = self.graph_label_index.write();
223 idx.entry(key).or_default().push(entity_id);
224 }
225
226 pub(crate) fn remove_from_graph_label_index(&self, collection: &str, entity_id: EntityId) {
228 let mut idx = self.graph_label_index.write();
229 for ((col, _), ids) in idx.iter_mut() {
230 if col == collection {
231 ids.retain(|&id| id != entity_id);
232 }
233 }
234 idx.retain(|_, ids| !ids.is_empty());
236 }
237
238 pub(crate) fn remove_from_graph_label_index_batch(
239 &self,
240 collection: &str,
241 entity_ids: &[EntityId],
242 ) {
243 if entity_ids.is_empty() {
244 return;
245 }
246 let id_set: std::collections::HashSet<EntityId> = entity_ids.iter().copied().collect();
247 let mut idx = self.graph_label_index.write();
248 for ((col, _), ids) in idx.iter_mut() {
249 if col == collection {
250 ids.retain(|id| !id_set.contains(id));
251 }
252 }
253 idx.retain(|_, ids| !ids.is_empty());
254 }
255
256 pub fn lookup_graph_nodes_by_label(&self, label: &str) -> Vec<EntityId> {
258 let idx = self.graph_label_index.read();
259 idx.iter()
260 .filter(|((_, l), _)| l == label)
261 .flat_map(|(_, ids)| ids.iter().copied())
262 .collect()
263 }
264
265 pub fn lookup_graph_nodes_by_label_in(&self, collection: &str, label: &str) -> Vec<EntityId> {
267 let idx = self.graph_label_index.read();
268 idx.get(&(collection.to_string(), label.to_string()))
269 .cloned()
270 .unwrap_or_default()
271 }
272
273 pub fn create_collection(&self, name: impl Into<String>) -> Result<(), StoreError> {
274 let name = name.into();
275 let mut collections = self.collections.write();
276
277 if collections.contains_key(&name) {
278 return Err(StoreError::CollectionExists(name));
279 }
280
281 let manager = SegmentManager::with_config(&name, self.config.manager_config.clone());
282 collections.insert(name.clone(), Arc::new(manager));
283 drop(collections);
284
285 let create = match self.prepare_operational_collection_create(&name) {
286 Ok(create) => create,
287 Err(err) => {
288 let mut collections = self.collections.write();
289 collections.remove(&name);
290 return Err(err);
291 }
292 };
293 if let Some(create) = create {
294 if let Err(err) = create.publish().map_err(StoreError::Io) {
295 let mut collections = self.collections.write();
296 collections.remove(&name);
297 return Err(err);
298 }
299 }
300
301 self.mark_paged_registry_dirty();
302 self.finish_paged_write([StoreWalAction::CreateCollection { name }])?;
303
304 Ok(())
305 }
306
307 pub fn get_or_create_collection(&self, name: impl Into<String>) -> Arc<SegmentManager> {
309 let name = name.into();
310 {
312 let collections = self.collections.read();
313 if let Some(manager) = collections.get(&name) {
314 return Arc::clone(manager);
315 }
316 }
317 let mut collections = self.collections.write();
319 if let Some(manager) = collections.get(&name) {
321 return Arc::clone(manager);
322 }
323 let manager = Arc::new(SegmentManager::with_config(
324 &name,
325 self.config.manager_config.clone(),
326 ));
327 collections.insert(name, Arc::clone(&manager));
328 self.mark_paged_registry_dirty();
329 manager
330 }
331
332 pub fn get_collection(&self, name: &str) -> Option<Arc<SegmentManager>> {
334 self.collections.read().get(name).map(Arc::clone)
335 }
336
337 pub fn context_index(&self) -> &ContextIndex {
339 &self.context_index
340 }
341
342 pub fn take_replayed_turbo_inserts(&self, collection: &str) -> Option<Vec<(u64, Vec<f32>)>> {
348 let mut map = self.replayed_turbo_inserts.lock();
349 map.remove(collection)
350 }
351
352 pub(crate) fn take_replayed_probabilistic_deltas(&self) -> Vec<(u8, u8, String, Vec<Vec<u8>>)> {
353 let mut deltas = self.replayed_probabilistic_deltas.lock();
354 std::mem::take(&mut *deltas)
355 }
356
357 pub fn set_config_tree(&self, prefix: &str, json: &crate::serde_json::Value) -> usize {
364 let manager = self.get_or_create_collection("red_config");
365 let mut pairs = Vec::new();
366 flatten_config_json(prefix, json, &mut pairs);
367 let mut previous: HashMap<String, Vec<(EntityId, Option<reddb_types::Value>)>> = pairs
369 .iter()
370 .map(|(key, _)| (key.clone(), Vec::new()))
371 .collect();
372 for entity in manager.query_all(|_| true) {
373 if let EntityData::Row(row) = &entity.data {
374 let Some(named) = row.named.as_ref() else {
375 continue;
376 };
377 if let Some(reddb_types::Value::Text(key)) = named.get("key") {
378 if let Some(rows) = previous.get_mut(key.as_ref()) {
379 rows.push((entity.id, named.get("value").cloned()));
380 }
381 }
382 }
383 }
384 let mut saved = 0;
385 for (key, value) in pairs {
386 let stale = previous.remove(&key).unwrap_or_default();
387 if let [(_, Some(current))] = stale.as_slice() {
391 if *current == value {
392 saved += 1;
393 continue;
394 }
395 }
396 let stale: Vec<EntityId> = stale.into_iter().map(|(id, _)| id).collect();
397 let entity = UnifiedEntity::new(
401 EntityId::new(0),
402 EntityKind::TableRow {
403 table: Arc::from("red_config"),
404 row_id: 0,
405 },
406 EntityData::Row(RowData {
407 columns: Vec::new(),
408 named: Some(
409 [
410 ("key".to_string(), reddb_types::Value::text(key)),
411 ("value".to_string(), value),
412 ]
413 .into_iter()
414 .collect(),
415 ),
416 schema: None,
417 }),
418 );
419 if self.insert_auto("red_config", entity).is_ok() {
420 saved += 1;
421 if !stale.is_empty() {
422 let _ = self.delete_batch("red_config", &stale);
423 }
424 }
425 }
426 saved
427 }
428
429 pub fn get_config(&self, key: &str) -> Option<reddb_types::Value> {
433 let manager = self.get_collection("red_config")?;
434 let mut latest: Option<(u64, reddb_types::Value)> = None;
435 for entity in manager.query_all(|_| true) {
436 if let EntityData::Row(row) = &entity.data {
437 if let Some(named) = &row.named {
438 let key_matches = named
439 .get("key")
440 .and_then(|v| match v {
441 reddb_types::Value::Text(s) => Some(s.as_ref() == key),
442 _ => None,
443 })
444 .unwrap_or(false);
445 if key_matches && latest.as_ref().is_none_or(|(id, _)| entity.id.raw() >= *id) {
446 if let Some(value) = named.get("value") {
447 latest = Some((entity.id.raw(), value.clone()));
448 }
449 }
450 }
451 }
452 }
453 latest.map(|(_, value)| value)
454 }
455
456 pub fn set_aux_metadata(&self, bytes: Vec<u8>) {
461 *self.aux_metadata.write() = bytes;
462 }
463
464 pub fn aux_metadata(&self) -> Vec<u8> {
466 self.aux_metadata.read().clone()
467 }
468
469 pub fn list_collections(&self) -> Vec<String> {
471 self.collections.read().keys().cloned().collect()
472 }
473
474 pub fn drop_collection(&self, name: &str) -> Result<(), StoreError> {
476 let _vault_guard = self.vault_publication_lock.lock();
477 let drop = self.prepare_operational_collection_drop(name)?;
478 let manager = {
479 let mut collections = self.collections.write();
480
481 collections
482 .remove(name)
483 .ok_or_else(|| StoreError::CollectionNotFound(name.to_string()))?
484 };
485
486 let entities = manager.query_all(|_| true);
487 let entity_ids: Vec<EntityId> = entities.iter().map(|entity| entity.id).collect();
488
489 for entity_id in &entity_ids {
490 self.context_index.remove_entity(*entity_id);
491 let _ = self.unindex_cross_refs(*entity_id);
492 }
493
494 if let Some(tree) = self.btree_indices.write().remove(name) {
495 self.retire_btree(tree);
496 }
497
498 self.entity_cache.retain(|entity_id, (collection, _)| {
499 collection != name && !entity_ids.iter().any(|id| id.raw() == entity_id)
500 });
501
502 self.cross_refs.write().retain(|source_id, refs| {
503 refs.retain(|(target_id, _, target_collection)| {
504 target_collection != name && !entity_ids.iter().any(|id| id == target_id)
505 });
506 !entity_ids.iter().any(|id| id == source_id)
507 });
508
509 self.reverse_refs.write().retain(|target_id, refs| {
510 refs.retain(|(source_id, _, source_collection)| {
511 source_collection != name && !entity_ids.iter().any(|id| id == source_id)
512 });
513 !entity_ids.iter().any(|id| id == target_id)
514 });
515
516 self.mark_paged_registry_dirty();
517 self.finish_paged_write([StoreWalAction::DropCollection {
518 name: name.to_string(),
519 }])?;
520 if let Some(drop) = drop {
521 drop.finish().map_err(StoreError::Io)?;
522 }
523
524 Ok(())
525 }
526
527 pub fn insert(&self, collection: &str, entity: UnifiedEntity) -> Result<EntityId, StoreError> {
529 let manager = self
530 .get_collection(collection)
531 .ok_or_else(|| StoreError::CollectionNotFound(collection.to_string()))?;
532
533 let mut entity = entity;
534 if entity.id.raw() == 0 {
535 entity.id = self.next_entity_id();
536 } else {
537 self.register_entity_id(entity.id);
538 }
539 if let EntityKind::TableRow { ref mut row_id, .. } = entity.kind {
541 if *row_id == 0 {
542 *row_id = manager.next_row_id();
543 } else {
544 manager.register_row_id(*row_id);
545 }
546 }
547 entity.ensure_table_logical_id();
548 let graph_node_label: Option<String> = if let EntityKind::GraphNode(ref node) = entity.kind
550 {
551 Some(node.label.clone())
552 } else {
553 None
554 };
555
556 let id = manager.insert(entity)?;
557 self.register_entity_id(id);
558
559 if let Some(ref label) = graph_node_label {
561 self.update_graph_label_index(collection, label, id);
562 }
563
564 let mut registry_dirty = false;
566 if let Some(pager) = &self.pager {
567 if let Some(entity) = manager.get(id) {
568 let mut btree_indices = self.btree_indices.write();
569 let btree = btree_indices
570 .entry(collection.to_string())
571 .or_insert_with(|| Arc::new(BTree::new(Arc::clone(pager))));
572 let root_before = btree.root_page_id();
573
574 let key = id.raw().to_be_bytes();
575 let metadata = manager.get_metadata(id);
576 let value = Self::serialize_entity_record(
577 &entity,
578 metadata.as_ref(),
579 self.format_version(),
580 );
581 let _ = btree.insert(&key, &value);
583 registry_dirty = root_before != btree.root_page_id();
584 }
585 }
586
587 if self.config.auto_index_refs {
589 if let Some(entity) = manager.get(id) {
590 self.index_cross_refs(&entity, collection)?;
591 }
592 }
593
594 if self.pager.is_some() || self.config.embedded_wal_path.is_some() {
598 let actions = manager
599 .get(id)
600 .map(|entity| {
601 let metadata = manager.get_metadata(id);
602 vec![StoreWalAction::upsert_entity(
603 collection,
604 &entity,
605 metadata.as_ref(),
606 self.format_version(),
607 )]
608 })
609 .unwrap_or_default();
610 if registry_dirty {
611 self.mark_paged_registry_dirty();
612 }
613 self.finish_paged_write(actions)?;
614 }
615
616 Ok(id)
617 }
618
619 pub fn bulk_insert(
624 &self,
625 collection: &str,
626 mut entities: Vec<UnifiedEntity>,
627 ) -> Result<Vec<EntityId>, StoreError> {
628 let trace = matches!(
632 std::env::var("REDDB_BULK_TIMING").ok().as_deref(),
633 Some("1") | Some("true") | Some("on")
634 );
635 let t_start = std::time::Instant::now();
636 let n = entities.len();
637 let manager = self.get_or_create_collection(collection);
638 let t_get_coll = t_start.elapsed();
639
640 let t0 = std::time::Instant::now();
649 let n_missing_entity_ids = entities.iter().filter(|e| e.id.raw() == 0).count() as u64;
650 let n_missing_row_ids = entities
651 .iter()
652 .filter(|e| matches!(e.kind, EntityKind::TableRow { row_id: 0, .. }))
653 .count() as u64;
654 let mut entity_id_range = if n_missing_entity_ids > 0 {
655 self.reserve_entity_ids(n_missing_entity_ids)
656 } else {
657 0..0
658 };
659 let mut row_id_range = if n_missing_row_ids > 0 {
660 manager.reserve_row_ids(n_missing_row_ids)
661 } else {
662 0..0
663 };
664 for entity in &mut entities {
665 if entity.id.raw() == 0 {
666 let next = entity_id_range
667 .next()
668 .expect("reserved entity-id range exhausted");
669 entity.id = EntityId::new(next);
670 } else {
671 self.register_entity_id(entity.id);
672 }
673 if let EntityKind::TableRow { ref mut row_id, .. } = entity.kind {
674 if *row_id == 0 {
675 *row_id = row_id_range
676 .next()
677 .expect("reserved row-id range exhausted");
678 } else {
679 manager.register_row_id(*row_id);
680 }
681 }
682 entity.ensure_table_logical_id();
683 }
684 let t_assign_ids = t0.elapsed();
685
686 let graph_labels: Vec<Option<(String, EntityId)>> = entities
688 .iter()
689 .map(|e| {
690 if let EntityKind::GraphNode(ref node) = e.kind {
691 Some((node.label.clone(), e.id))
692 } else {
693 None
694 }
695 })
696 .collect();
697
698 let t0 = std::time::Instant::now();
705 let serialized: Option<Vec<(Vec<u8>, Vec<u8>)>> =
706 if self.pager.is_some() || self.config.embedded_wal_path.is_some() {
707 let fv = self.format_version();
708 let serial_map = |e: &UnifiedEntity| {
709 (
710 e.id.raw().to_be_bytes().to_vec(),
711 Self::serialize_entity_record(e, None, fv),
712 )
713 };
714 if entities.len() >= 512 {
720 use rayon::prelude::*;
721 Some(entities.par_iter().map(serial_map).collect())
722 } else {
723 Some(entities.iter().map(serial_map).collect())
724 }
725 } else {
726 None
727 };
728 let t_serialize = t0.elapsed();
729
730 let t0 = std::time::Instant::now();
732 let ids = manager.bulk_insert(entities)?;
733 let t_manager = t0.elapsed();
734 for id in &ids {
735 self.register_entity_id(*id);
736 }
737
738 for (label, entity_id) in graph_labels.iter().flatten() {
740 self.update_graph_label_index(collection, label, *entity_id);
741 }
742
743 let skip_btree_requested = matches!(
753 std::env::var("REDDB_BULK_SKIP_PERSIST_UNSAFE")
754 .ok()
755 .as_deref(),
756 Some("1") | Some("true") | Some("on")
757 );
758 let skip_btree = skip_btree_requested && self.pager.is_none();
761 if skip_btree_requested && !skip_btree {
762 static IGNORED: std::sync::OnceLock<()> = std::sync::OnceLock::new();
764 IGNORED.get_or_init(|| {
765 tracing::warn!(
766 "REDDB_BULK_SKIP_PERSIST_UNSAFE set but durable pager is \
767 active — flag ignored; bulk inserts will be persisted normally"
768 );
769 });
770 } else if skip_btree {
771 static WARNED: std::sync::OnceLock<()> = std::sync::OnceLock::new();
773 WARNED.get_or_init(|| {
774 tracing::warn!(
775 "REDDB_BULK_SKIP_PERSIST_UNSAFE set (ephemeral/no-pager mode) — \
776 bulk inserts NOT durable; data will be lost on restart"
777 );
778 });
779 }
780
781 let mut t_btree_lock = std::time::Duration::ZERO;
785 let mut t_btree_insert = std::time::Duration::ZERO;
786 let mut t_flush = std::time::Duration::ZERO;
787 if !skip_btree {
788 if let (Some(pager), Some(batch)) = (&self.pager, serialized.as_ref()) {
789 let t0 = std::time::Instant::now();
790 let mut btree_indices = self.btree_indices.write();
791 let btree = btree_indices
792 .entry(collection.to_string())
793 .or_insert_with(|| Arc::new(BTree::new(Arc::clone(pager))));
794 let root_before = btree.root_page_id();
795 t_btree_lock = t0.elapsed();
796
797 let t0 = std::time::Instant::now();
798 let _ = btree.bulk_insert_sorted(batch);
799 t_btree_insert = t0.elapsed();
800 let registry_dirty = root_before != btree.root_page_id();
801
802 let t0 = std::time::Instant::now();
803 if registry_dirty {
804 self.mark_paged_registry_dirty();
805 }
806 t_flush = t0.elapsed();
807 }
808 }
809
810 let actions = serialized
816 .map(|batch| {
817 let records: Vec<Vec<u8>> =
818 batch.into_iter().map(|(_key, record)| record).collect();
819 vec![StoreWalAction::BulkUpsertEntityRecords {
820 collection: collection.to_string(),
821 records,
822 }]
823 })
824 .unwrap_or_default();
825 self.finish_paged_write(actions)?;
826
827 if trace {
828 tracing::debug!(
829 n,
830 total = ?t_start.elapsed(),
831 get_coll = ?t_get_coll,
832 assign = ?t_assign_ids,
833 serialize = ?t_serialize,
834 manager = ?t_manager,
835 btree_lock = ?t_btree_lock,
836 btree = ?t_btree_insert,
837 flush = ?t_flush,
838 "bulk_insert timing"
839 );
840 }
841
842 Ok(ids)
843 }
844
845 pub fn insert_auto(
847 &self,
848 collection: &str,
849 entity: UnifiedEntity,
850 ) -> Result<EntityId, StoreError> {
851 let _publication = self.vault_publication_lock.lock();
853 let manager = self.get_or_create_collection(collection);
854 let mut entity = entity;
855 if entity.id.raw() == 0 {
856 entity.id = self.next_entity_id();
857 } else {
858 self.register_entity_id(entity.id);
859 }
860 if let EntityKind::TableRow { ref mut row_id, .. } = entity.kind {
862 if *row_id == 0 {
863 *row_id = manager.next_row_id();
864 } else {
865 manager.register_row_id(*row_id);
866 }
867 }
868 entity.ensure_table_logical_id();
869
870 let graph_node_label: Option<String> = if let EntityKind::GraphNode(ref node) = entity.kind
872 {
873 Some(node.label.clone())
874 } else {
875 None
876 };
877 self.context_index.index_entity(collection, &entity);
879
880 let persist_record = self.pager.is_some() || self.config.embedded_wal_path.is_some();
883 if self.config.auto_index_refs {
884 self.index_cross_refs(&entity, collection)?;
885 }
886
887 let paged_btree = if persist_record {
894 self.get_or_create_btree(collection)
895 } else {
896 None
897 };
898 let persist_fence = paged_btree
899 .as_ref()
900 .map(|_| self.btree_indices.read_recursive());
901 let before = paged_btree.as_ref().map(|_| manager.checkpoint_revisions());
902 let unversioned = entity.xmin == 0 && entity.xmax == 0;
903
904 let id = manager.insert(entity)?;
905 let serialized_record = if persist_record {
906 Some(
907 manager
908 .get_with(id, |entity| {
909 Self::serialize_entity_record(entity, None, self.format_version())
910 })
911 .ok_or(StoreError::EntityNotFound(id))?,
912 )
913 } else {
914 None
915 };
916 if let Some(ref label) = graph_node_label {
924 self.update_graph_label_index(collection, label, id);
925 }
926
927 let mut registry_dirty = false;
928 if let (Some(btree), Some(record)) = (paged_btree.as_ref(), serialized_record.as_ref()) {
929 let root_before = btree.root_page_id();
930
931 let key = id.raw().to_be_bytes();
932 btree.insert(&key, record).map_err(|e| {
933 StoreError::Io(std::io::Error::other(format!(
934 "B-tree insert error while inserting '{collection}'/{id}: {e}"
935 )))
936 })?;
937 registry_dirty = root_before != btree.root_page_id();
938 }
939 drop(persist_fence);
940
941 if self.pager.is_some() || self.config.embedded_wal_path.is_some() {
945 let actions = serialized_record
946 .map(|record| {
947 vec![StoreWalAction::UpsertEntityRecord {
948 collection: collection.to_string(),
949 record,
950 }]
951 })
952 .unwrap_or_default();
953 if registry_dirty {
954 self.mark_paged_registry_dirty();
955 }
956 if let Some(pending) = self.enqueue_grouped_actions(&actions)? {
957 drop(_publication);
958 self.complete_grouped_actions(&pending, &actions)?;
959 } else {
960 self.finish_paged_write(actions)?;
961 }
962 }
963 if unversioned && !Self::deferred_store_wal_capture_active() {
964 if let Some(before) = before {
965 self.note_paged_insert(collection, &manager, &before, id);
966 }
967 }
968 Ok(id)
969 }
970
971 pub fn get(&self, collection: &str, id: EntityId) -> Option<UnifiedEntity> {
977 if let Some(entity) = self
979 .get_collection(collection)
980 .and_then(|manager| manager.get(id))
981 {
982 return Some(entity);
983 }
984
985 if self.pager.is_some() {
987 let btree_indices = self.btree_indices.read();
988 if let Some(btree) = btree_indices.get(collection) {
989 let key = id.raw().to_be_bytes();
990 if let Ok(Some(value)) = btree.get(&key) {
991 if let Ok((entity, _)) =
992 Self::deserialize_entity_record(&value, self.format_version())
993 {
994 return Some(entity);
995 }
996 }
997 }
998 }
999
1000 None
1001 }
1002
1003 pub fn get_table_row_by_logical_id(
1009 &self,
1010 collection: &str,
1011 logical_id: EntityId,
1012 ) -> Option<UnifiedEntity> {
1013 if let Some(entity) = self.get(collection, logical_id) {
1014 if matches!(entity.kind, EntityKind::TableRow { .. })
1015 && entity.logical_id() == logical_id
1016 && entity.xmax == 0
1017 {
1018 return Some(entity);
1019 }
1020 }
1021
1022 let manager = self.get_collection(collection)?;
1023 let mut matches = manager.query_all(|entity| {
1024 matches!(entity.kind, EntityKind::TableRow { .. }) && entity.logical_id() == logical_id
1025 });
1026 matches
1027 .iter()
1028 .find(|entity| entity.xmax == 0)
1029 .cloned()
1030 .or_else(|| matches.pop())
1031 }
1032
1033 pub fn table_row_versions_by_logical_id(
1034 &self,
1035 collection: &str,
1036 logical_id: EntityId,
1037 ) -> Vec<UnifiedEntity> {
1038 self.get_collection(collection)
1039 .map(|manager| {
1040 manager.query_all(|entity| {
1041 matches!(entity.kind, EntityKind::TableRow { .. })
1042 && entity.logical_id() == logical_id
1043 })
1044 })
1045 .unwrap_or_default()
1046 }
1047
1048 pub fn vacuum_mvcc_history(
1049 &self,
1050 collection: &str,
1051 cutoff_xid: u64,
1052 ) -> Result<MvccVacuumStats, StoreError> {
1053 let manager = self
1054 .get_collection(collection)
1055 .ok_or_else(|| StoreError::CollectionNotFound(collection.to_string()))?;
1056 let entities =
1057 manager.query_all(|entity| matches!(entity.kind, EntityKind::TableRow { .. }));
1058 let mut logical = HashMap::<EntityId, (bool, u64)>::new();
1059 for entity in &entities {
1060 let entry = logical.entry(entity.logical_id()).or_insert((false, 0));
1061 if entity.xmax == 0 {
1062 entry.0 = true;
1063 }
1064 entry.1 = entry.1.max(entity.xmin);
1065 }
1066
1067 let mut stats = MvccVacuumStats::default();
1068 let mut reclaim_ids = Vec::new();
1069 for entity in entities {
1070 if entity.xmax == 0 {
1071 continue;
1072 }
1073 stats.scanned_versions += 1;
1074 let (has_live_version, max_xmin) = logical
1075 .get(&entity.logical_id())
1076 .copied()
1077 .unwrap_or((false, entity.xmin));
1078 let is_delete_tombstone = !has_live_version && entity.xmin == max_xmin;
1079 if entity.xmax < cutoff_xid {
1080 stats.reclaimed_versions += 1;
1081 if is_delete_tombstone {
1082 stats.reclaimed_tombstones += 1;
1083 } else {
1084 stats.reclaimed_history_versions += 1;
1085 }
1086 reclaim_ids.push(entity.id);
1087 } else {
1088 stats.retained_versions += 1;
1089 if is_delete_tombstone {
1090 stats.retained_tombstones += 1;
1091 } else {
1092 stats.retained_history_versions += 1;
1093 }
1094 }
1095 }
1096
1097 if !reclaim_ids.is_empty() {
1098 self.delete_batch(collection, &reclaim_ids)?;
1099 }
1100 Ok(stats)
1101 }
1102
1103 pub(crate) fn install_versioned_table_row_update(
1104 &self,
1105 collection: &str,
1106 old_version: UnifiedEntity,
1107 mut new_version: UnifiedEntity,
1108 metadata: Option<&Metadata>,
1109 ) -> Result<(), StoreError> {
1110 let manager = self
1111 .get_collection(collection)
1112 .ok_or_else(|| StoreError::CollectionNotFound(collection.to_string()))?;
1113
1114 let old_id = old_version.id;
1115 let new_id = new_version.id;
1116 let inherited_metadata = metadata.cloned().or_else(|| manager.get_metadata(old_id));
1117
1118 self.entity_cache.remove(old_id.raw());
1119 self.entity_cache.remove(new_id.raw());
1120 manager.update(old_version.clone())?;
1121 self.context_index.remove_entity(old_id);
1122
1123 self.register_entity_id(new_version.id);
1124 if let EntityKind::TableRow { ref mut row_id, .. } = new_version.kind {
1125 if *row_id == 0 {
1126 *row_id = manager.next_row_id();
1127 } else {
1128 manager.register_row_id(*row_id);
1129 }
1130 }
1131 new_version.ensure_table_logical_id();
1132 manager.insert(new_version.clone())?;
1133 if let Some(metadata) = inherited_metadata {
1134 manager.set_metadata(new_id, metadata)?;
1135 }
1136 self.context_index.index_entity(collection, &new_version);
1137 if self.config.auto_index_refs {
1138 self.index_cross_refs(&new_version, collection)?;
1139 }
1140
1141 let old_metadata = manager.get_metadata(old_id);
1142 let new_metadata = manager.get_metadata(new_id);
1143 let fv = self.format_version();
1144 let records = vec![
1145 Self::serialize_entity_record(&old_version, old_metadata.as_ref(), fv),
1146 Self::serialize_entity_record(&new_version, new_metadata.as_ref(), fv),
1147 ];
1148 self.finish_paged_write([StoreWalAction::BulkUpsertEntityRecords {
1149 collection: collection.to_string(),
1150 records,
1151 }])?;
1152
1153 Ok(())
1154 }
1155
1156 pub fn get_batch(&self, collection: &str, ids: &[EntityId]) -> Vec<Option<UnifiedEntity>> {
1162 match self.get_collection(collection) {
1163 Some(manager) => manager.get_many(ids),
1164 None => vec![None; ids.len()],
1165 }
1166 }
1167
1168 pub fn get_any(&self, id: EntityId) -> Option<(String, UnifiedEntity)> {
1170 if let Some(cached) = self.entity_cache.get(id.raw()) {
1174 return Some(cached);
1175 }
1176
1177 let collections = self.collections.read();
1179 for (name, manager) in collections.iter() {
1180 if let Some(entity) = manager.get(id) {
1181 let result = (name.clone(), entity);
1182 drop(collections);
1186 self.entity_cache.insert(id.raw(), result.clone());
1187 return Some(result);
1188 }
1189 }
1190 None
1191 }
1192
1193 pub fn entity_cache_hit_rate(&self) -> Option<f64> {
1199 self.entity_cache.hit_rate()
1200 }
1201
1202 pub fn entity_cache_stats(&self) -> super::super::entity_cache::EntityCacheStats {
1204 self.entity_cache.stats()
1205 }
1206
1207 pub fn delete(&self, collection: &str, id: EntityId) -> Result<bool, StoreError> {
1209 let publication = self.vault_publication_lock.lock();
1210 self.entity_cache.remove(id.raw());
1212 let manager = self
1213 .get_collection(collection)
1214 .ok_or_else(|| StoreError::CollectionNotFound(collection.to_string()))?;
1215
1216 let deleted = manager.delete(id)?;
1217 if !deleted {
1218 return Ok(false);
1219 }
1220
1221 let mut registry_dirty = false;
1223 if self.pager.is_some() {
1224 let btree_indices = self.btree_indices.read();
1225 if let Some(btree) = btree_indices.get(collection) {
1226 let root_before = btree.root_page_id();
1227 let key = id.raw().to_be_bytes();
1228 let _ = btree.delete(&key);
1229 registry_dirty = root_before != btree.root_page_id();
1230 }
1231 }
1232
1233 self.unindex_cross_refs(id)?;
1235
1236 self.remove_from_graph_label_index(collection, id);
1238
1239 if registry_dirty {
1240 self.mark_paged_registry_dirty();
1241 }
1242 let actions = [StoreWalAction::DeleteEntityRecord {
1243 collection: collection.to_string(),
1244 entity_id: id.raw(),
1245 }];
1246 if let Some(pending) = self.enqueue_grouped_actions(&actions)? {
1247 drop(publication);
1248 self.complete_grouped_actions(&pending, &actions)?;
1249 } else {
1250 self.finish_paged_write(actions)?;
1251 }
1252
1253 Ok(true)
1254 }
1255
1256 pub fn delete_batch(
1257 &self,
1258 collection: &str,
1259 ids: &[EntityId],
1260 ) -> Result<Vec<EntityId>, StoreError> {
1261 if ids.is_empty() {
1262 return Ok(Vec::new());
1263 }
1264
1265 self.entity_cache.remove_many(ids.iter().map(|id| id.raw()));
1270
1271 let manager = self
1272 .get_collection(collection)
1273 .ok_or_else(|| StoreError::CollectionNotFound(collection.to_string()))?;
1274
1275 let deleted_ids = manager.delete_batch(ids)?;
1276 if deleted_ids.is_empty() {
1277 return Ok(deleted_ids);
1278 }
1279
1280 let mut registry_dirty = false;
1281 if self.pager.is_some() {
1282 let btree_indices = self.btree_indices.read();
1283 if let Some(btree) = btree_indices.get(collection) {
1284 let root_before = btree.root_page_id();
1285 for id in &deleted_ids {
1286 let key = id.raw().to_be_bytes();
1287 let _ = btree.delete(&key);
1288 }
1289 registry_dirty = root_before != btree.root_page_id();
1290 }
1291 }
1292
1293 self.unindex_cross_refs_batch(&deleted_ids)?;
1294 self.remove_from_graph_label_index_batch(collection, &deleted_ids);
1295 if registry_dirty {
1296 self.mark_paged_registry_dirty();
1297 }
1298 let actions = deleted_ids
1299 .iter()
1300 .map(|id| StoreWalAction::DeleteEntityRecord {
1301 collection: collection.to_string(),
1302 entity_id: id.raw(),
1303 })
1304 .collect::<Vec<_>>();
1305 self.finish_paged_write(actions)?;
1306
1307 Ok(deleted_ids)
1308 }
1309
1310 pub fn set_metadata(
1312 &self,
1313 collection: &str,
1314 id: EntityId,
1315 metadata: Metadata,
1316 ) -> Result<(), StoreError> {
1317 let manager = self
1318 .get_collection(collection)
1319 .ok_or_else(|| StoreError::CollectionNotFound(collection.to_string()))?;
1320
1321 manager.set_metadata(id, metadata)?;
1322 if let Some(entity) = manager.get(id) {
1323 self.persist_entities_to_pager(collection, std::slice::from_ref(&entity))?;
1324 }
1325 Ok(())
1326 }
1327
1328 pub fn get_metadata(&self, collection: &str, id: EntityId) -> Option<Metadata> {
1330 self.get_collection(collection)?.get_metadata(id)
1331 }
1332
1333 pub fn add_cross_ref(
1335 &self,
1336 source_collection: &str,
1337 source_id: EntityId,
1338 target_collection: &str,
1339 target_id: EntityId,
1340 ref_type: RefType,
1341 weight: f32,
1342 ) -> Result<(), StoreError> {
1343 let source_manager = self
1345 .get_collection(source_collection)
1346 .ok_or_else(|| StoreError::CollectionNotFound(source_collection.to_string()))?;
1347
1348 if source_manager.get(source_id).is_none() {
1349 return Err(StoreError::EntityNotFound(source_id));
1350 }
1351
1352 let target_manager = self
1354 .get_collection(target_collection)
1355 .ok_or_else(|| StoreError::CollectionNotFound(target_collection.to_string()))?;
1356
1357 if target_manager.get(target_id).is_none() {
1358 return Err(StoreError::EntityNotFound(target_id));
1359 }
1360
1361 let current_refs = self
1363 .cross_refs
1364 .read()
1365 .get(&source_id)
1366 .map_or(0, |v| v.len());
1367
1368 if current_refs >= self.config.max_cross_refs {
1369 return Err(StoreError::TooManyRefs(source_id));
1370 }
1371
1372 let mut registry_dirty = false;
1373 {
1374 let mut forward = self.cross_refs.write();
1375 let refs = forward.entry(source_id).or_default();
1376 let inserted = !refs.iter().any(|(id, kind, coll)| {
1377 *id == target_id && *kind == ref_type && coll == target_collection
1378 });
1379 if inserted {
1380 refs.push((target_id, ref_type, target_collection.to_string()));
1381 registry_dirty = true;
1382 }
1383 }
1384
1385 {
1386 let mut reverse = self.reverse_refs.write();
1387 let refs = reverse.entry(target_id).or_default();
1388 let inserted = !refs.iter().any(|(id, kind, coll)| {
1389 *id == source_id && *kind == ref_type && coll == source_collection
1390 });
1391 if inserted {
1392 refs.push((source_id, ref_type, source_collection.to_string()));
1393 registry_dirty = true;
1394 }
1395 }
1396
1397 if let Some(mut entity) = source_manager.get(source_id) {
1398 if !entity.cross_refs().iter().any(|xref| {
1399 xref.target == target_id
1400 && xref.ref_type == ref_type
1401 && xref.target_collection == target_collection
1402 }) {
1403 let cross_ref = CrossRef::with_weight(
1404 source_id,
1405 target_id,
1406 target_collection,
1407 ref_type,
1408 weight,
1409 );
1410 entity.add_cross_ref(cross_ref);
1411 let _ = source_manager.update(entity.clone());
1412 registry_dirty = true;
1413 self.persist_entities_to_pager(source_collection, std::slice::from_ref(&entity))?;
1414 }
1415 }
1416
1417 if registry_dirty {
1418 self.mark_paged_registry_dirty();
1419 if matches!(
1420 self.config.durability_mode,
1421 crate::api::DurabilityMode::Strict
1422 ) {
1423 self.flush_paged_state()?;
1424 }
1425 }
1426
1427 Ok(())
1428 }
1429
1430 pub fn get_refs_from(&self, id: EntityId) -> Vec<(EntityId, RefType, String)> {
1432 self.cross_refs.read().get(&id).cloned().unwrap_or_default()
1433 }
1434
1435 pub fn get_refs_to(&self, id: EntityId) -> Vec<(EntityId, RefType, String)> {
1437 self.reverse_refs
1438 .read()
1439 .get(&id)
1440 .cloned()
1441 .unwrap_or_default()
1442 }
1443
1444 pub fn expand_refs(
1446 &self,
1447 id: EntityId,
1448 depth: u32,
1449 ref_types: Option<&[RefType]>,
1450 ) -> Vec<(UnifiedEntity, u32, RefType)> {
1451 let mut results = Vec::new();
1452 let mut visited = std::collections::HashSet::new();
1453 visited.insert(id);
1454
1455 self.expand_refs_recursive(id, depth, ref_types, &mut visited, &mut results, 1);
1456
1457 results
1458 }
1459
1460 fn expand_refs_recursive(
1461 &self,
1462 id: EntityId,
1463 max_depth: u32,
1464 ref_types: Option<&[RefType]>,
1465 visited: &mut std::collections::HashSet<EntityId>,
1466 results: &mut Vec<(UnifiedEntity, u32, RefType)>,
1467 current_depth: u32,
1468 ) {
1469 if current_depth > max_depth {
1470 return;
1471 }
1472
1473 for (target_id, ref_type, target_collection) in self.get_refs_from(id) {
1474 if visited.contains(&target_id) {
1475 continue;
1476 }
1477
1478 if let Some(types) = ref_types {
1479 if !types.contains(&ref_type) {
1480 continue;
1481 }
1482 }
1483
1484 visited.insert(target_id);
1485
1486 if let Some(entity) = self.get(&target_collection, target_id) {
1487 results.push((entity, current_depth, ref_type));
1488
1489 self.expand_refs_recursive(
1491 target_id,
1492 max_depth,
1493 ref_types,
1494 visited,
1495 results,
1496 current_depth + 1,
1497 );
1498 }
1499 }
1500 }
1501
1502 pub(crate) fn index_cross_refs(
1504 &self,
1505 entity: &UnifiedEntity,
1506 collection: &str,
1507 ) -> Result<(), StoreError> {
1508 let mut registry_dirty = false;
1509 for cross_ref in entity.cross_refs() {
1510 if cross_ref.target_collection.is_empty() {
1511 continue;
1512 }
1513 {
1514 let mut forward = self.cross_refs.write();
1515 let refs = forward.entry(cross_ref.source).or_default();
1516 let inserted = !refs.iter().any(|(id, kind, coll)| {
1517 *id == cross_ref.target
1518 && *kind == cross_ref.ref_type
1519 && coll == &cross_ref.target_collection
1520 });
1521 if inserted {
1522 refs.push((
1523 cross_ref.target,
1524 cross_ref.ref_type,
1525 cross_ref.target_collection.clone(),
1526 ));
1527 registry_dirty = true;
1528 }
1529 }
1530
1531 {
1532 let mut reverse = self.reverse_refs.write();
1533 let refs = reverse.entry(cross_ref.target).or_default();
1534 let inserted = !refs.iter().any(|(id, kind, coll)| {
1535 *id == cross_ref.source && *kind == cross_ref.ref_type && coll == collection
1536 });
1537 if inserted {
1538 refs.push((cross_ref.source, cross_ref.ref_type, collection.to_string()));
1539 registry_dirty = true;
1540 }
1541 }
1542 }
1543
1544 if registry_dirty {
1545 self.mark_paged_registry_dirty();
1546 }
1547
1548 Ok(())
1549 }
1550
1551 pub(crate) fn unindex_cross_refs(&self, id: EntityId) -> Result<(), StoreError> {
1553 self.cross_refs.write().remove(&id);
1555
1556 let mut reverse = self.reverse_refs.write();
1558 for refs in reverse.values_mut() {
1559 refs.retain(|(source, _, _)| *source != id);
1560 }
1561 reverse.remove(&id);
1562 self.mark_paged_registry_dirty();
1563
1564 Ok(())
1565 }
1566
1567 pub(crate) fn unindex_cross_refs_batch(&self, ids: &[EntityId]) -> Result<(), StoreError> {
1568 if ids.is_empty() {
1569 return Ok(());
1570 }
1571
1572 let id_set: std::collections::HashSet<EntityId> = ids.iter().copied().collect();
1573
1574 let needs_forward_cleanup = {
1588 let forward = self.cross_refs.read();
1589 id_set.iter().any(|id| forward.contains_key(id))
1590 };
1591 let needs_reverse_cleanup = {
1592 let reverse = self.reverse_refs.read();
1593 id_set.iter().any(|id| reverse.contains_key(id))
1594 };
1595
1596 if !needs_forward_cleanup && !needs_reverse_cleanup {
1597 self.unindex_cross_refs_fast_path
1598 .fetch_add(1, Ordering::Relaxed);
1599 return Ok(());
1600 }
1601
1602 if needs_forward_cleanup {
1603 let mut forward = self.cross_refs.write();
1604 for id in &id_set {
1605 forward.remove(id);
1606 }
1607 }
1608
1609 if needs_reverse_cleanup || needs_forward_cleanup {
1610 let mut reverse = self.reverse_refs.write();
1614 if needs_forward_cleanup {
1615 for refs in reverse.values_mut() {
1616 refs.retain(|(source, _, _)| !id_set.contains(source));
1617 }
1618 }
1619 reverse.retain(|target, refs| !id_set.contains(target) && !refs.is_empty());
1620 }
1621 self.mark_paged_registry_dirty();
1622
1623 Ok(())
1624 }
1625
1626 pub fn unindex_cross_refs_fast_path_hits(&self) -> u64 {
1630 self.unindex_cross_refs_fast_path.load(Ordering::Relaxed)
1631 }
1632
1633 pub fn query_all<F>(&self, filter: F) -> Vec<(String, UnifiedEntity)>
1635 where
1636 F: Fn(&UnifiedEntity) -> bool + Clone + Send + Sync,
1637 {
1638 let pairs: Vec<(String, Arc<SegmentManager>)> = {
1649 let collections = self.collections.read();
1650 collections
1651 .iter()
1652 .map(|(name, mgr)| (name.clone(), Arc::clone(mgr)))
1653 .collect()
1654 };
1655
1656 let use_parallel = pairs.len() > 1 && crate::runtime::SystemInfo::should_parallelize();
1657 if !use_parallel {
1658 return pairs
1660 .into_iter()
1661 .flat_map(|(name, mgr)| {
1662 mgr.query_all(filter.clone())
1663 .into_iter()
1664 .map(move |e| (name.clone(), e))
1665 })
1666 .collect();
1667 }
1668
1669 let filter_ref = &filter;
1671 let collection_results: Vec<Vec<(String, UnifiedEntity)>> = std::thread::scope(|s| {
1672 pairs
1673 .iter()
1674 .map(|(name, manager)| {
1675 let name = (*name).clone();
1676 s.spawn(move || {
1677 manager
1678 .query_all(|e| filter_ref(e))
1679 .into_iter()
1680 .map(|e| (name.clone(), e))
1681 .collect::<Vec<_>>()
1682 })
1683 })
1684 .collect::<Vec<_>>()
1685 .into_iter()
1686 .map(|h| h.join().unwrap_or_default())
1687 .collect()
1688 });
1689
1690 collection_results.into_iter().flatten().collect()
1691 }
1692
1693 pub fn scan<F>(
1695 &self,
1696 snapshot: Option<&crate::runtime::impl_core::SnapshotContext>,
1697 filter: F,
1698 ) -> Vec<(String, UnifiedEntity)>
1699 where
1700 F: Fn(&UnifiedEntity) -> bool + Clone + Send + Sync,
1701 {
1702 let pairs: Vec<(String, Arc<SegmentManager>)> = {
1703 let collections = self.collections.read();
1704 collections
1705 .iter()
1706 .map(|(name, manager)| (name.clone(), Arc::clone(manager)))
1707 .collect()
1708 };
1709
1710 let use_parallel = pairs.len() > 1 && crate::runtime::SystemInfo::should_parallelize();
1711 if !use_parallel {
1712 return pairs
1713 .into_iter()
1714 .flat_map(|(name, manager)| {
1715 manager
1716 .scan(snapshot, filter.clone())
1717 .into_iter()
1718 .map(move |entity| (name.clone(), entity))
1719 })
1720 .collect();
1721 }
1722
1723 let filter_ref = &filter;
1724 let collection_results: Vec<Vec<(String, UnifiedEntity)>> = std::thread::scope(|scope| {
1725 pairs
1726 .iter()
1727 .map(|(name, manager)| {
1728 let name = name.clone();
1729 scope.spawn(move || {
1730 manager
1731 .scan(snapshot, |entity| filter_ref(entity))
1732 .into_iter()
1733 .map(|entity| (name.clone(), entity))
1734 .collect::<Vec<_>>()
1735 })
1736 })
1737 .collect::<Vec<_>>()
1738 .into_iter()
1739 .map(|handle| handle.join().unwrap_or_default())
1740 .collect()
1741 });
1742
1743 collection_results.into_iter().flatten().collect()
1744 }
1745
1746 pub fn filter_metadata_all(
1748 &self,
1749 filters: &[(String, MetadataFilter)],
1750 ) -> Vec<(String, EntityId)> {
1751 let mut results = Vec::new();
1752 let collections = self.collections.read();
1753
1754 for (name, manager) in collections.iter() {
1755 for id in manager.filter_metadata(filters) {
1756 results.push((name.clone(), id));
1757 }
1758 }
1759
1760 results
1761 }
1762
1763 pub fn stats(&self) -> StoreStats {
1765 let pairs: Vec<(String, Arc<SegmentManager>)> = {
1771 let collections = self.collections.read();
1772 collections
1773 .iter()
1774 .map(|(name, mgr)| (name.clone(), Arc::clone(mgr)))
1775 .collect()
1776 };
1777
1778 let mut stats = StoreStats {
1779 collection_count: pairs.len(),
1780 ..Default::default()
1781 };
1782
1783 for (name, manager) in &pairs {
1784 let manager_stats = manager.stats();
1785 stats.total_entities += manager_stats.total_entities;
1786 stats.total_memory_bytes += manager_stats.total_memory_bytes;
1787 stats.collections.insert(name.clone(), manager_stats);
1788 }
1789
1790 stats
1791 }
1792
1793 pub fn run_maintenance(&self) -> Result<(), StoreError> {
1795 let collections = self.collections.read();
1796 for manager in collections.values() {
1797 manager.run_maintenance()?;
1798 }
1799 Ok(())
1800 }
1801
1802 pub fn reclaimable_segment_bytes(&self) -> u64 {
1804 let collections = self.collections.read();
1805 collections
1806 .values()
1807 .map(|manager| manager.reclaimable_bytes())
1808 .fold(0, u64::saturating_add)
1809 }
1810
1811 pub fn pressure_consolidation_tick(&self) -> bool {
1814 let managers: Vec<_> = self.collections.read().values().cloned().collect();
1815 let mut advanced = false;
1818 for manager in &managers {
1819 advanced |= manager.pressure_consolidation_tick();
1820 }
1821 advanced
1822 }
1823}
1824
1825fn flatten_config_json(
1827 prefix: &str,
1828 value: &crate::serde_json::Value,
1829 out: &mut Vec<(String, reddb_types::Value)>,
1830) {
1831 use reddb_types::Value;
1832 match value {
1833 crate::serde_json::Value::Object(map) => {
1834 for (k, v) in map {
1835 let key = if prefix.is_empty() {
1836 k.clone()
1837 } else {
1838 format!("{prefix}.{k}")
1839 };
1840 flatten_config_json(&key, v, out);
1841 }
1842 }
1843 crate::serde_json::Value::String(s) => {
1844 out.push((prefix.to_string(), Value::text(s.clone())));
1845 }
1846 crate::serde_json::Value::Integer(n) => {
1847 out.push((prefix.to_string(), Value::Integer(*n)));
1848 }
1849 crate::serde_json::Value::Number(n) => {
1850 if n.fract().abs() < f64::EPSILON {
1851 out.push((prefix.to_string(), Value::UnsignedInteger(*n as u64)));
1852 } else {
1853 out.push((prefix.to_string(), Value::Float(*n)));
1854 }
1855 }
1856 crate::serde_json::Value::Decimal(n) => {
1857 out.push((prefix.to_string(), Value::DecimalText(n.clone())));
1858 }
1859 crate::serde_json::Value::Bool(b) => {
1860 out.push((prefix.to_string(), Value::Boolean(*b)));
1861 }
1862 crate::serde_json::Value::Null => {
1863 out.push((prefix.to_string(), Value::Null));
1864 }
1865 crate::serde_json::Value::Array(arr) => {
1866 let json_str = crate::serde_json::to_string(value).unwrap_or_default();
1867 out.push((prefix.to_string(), Value::text(json_str)));
1868 }
1869 }
1870}