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 && !Self::deferred_store_wal_capture_active() {
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_for_projection(
112 [StoreWalAction::BulkUpsertEntityRecords {
113 collection: collection.to_string(),
114 records,
115 }],
116 skip_btree,
117 )?;
118 Ok(())
119 }
120
121 pub(crate) fn persist_entities_to_pager_wal_only(
133 &self,
134 collection: &str,
135 entities: &[UnifiedEntity],
136 ) -> Result<(), StoreError> {
137 self.persist_entities_impl(collection, entities, true)
138 }
139
140 fn persist_entities_impl(
141 &self,
142 collection: &str,
143 entities: &[UnifiedEntity],
144 skip_btree: bool,
145 ) -> Result<(), StoreError> {
146 if entities.is_empty() {
147 return Ok(());
148 }
149
150 if self.pager.is_none() && self.config.embedded_wal_path.is_none() {
151 return Ok(());
152 }
153
154 let fv = self.format_version();
155 let manager = self
156 .get_collection(collection)
157 .ok_or_else(|| StoreError::CollectionNotFound(collection.to_string()))?;
158 let mut serialized: Vec<(Vec<u8>, Vec<u8>)> = entities
159 .iter()
160 .map(|entity| {
161 let metadata = manager.get_metadata(entity.id);
162 (
163 entity.id.raw().to_be_bytes().to_vec(),
164 Self::serialize_entity_record(entity, metadata.as_ref(), fv),
165 )
166 })
167 .collect();
168 serialized.sort_by(|a, b| a.0.cmp(&b.0));
170
171 if !skip_btree && !Self::deferred_store_wal_capture_active() {
172 let Some(pager) = &self.pager else {
173 let records: Vec<Vec<u8>> =
174 serialized.into_iter().map(|(_id, record)| record).collect();
175 self.finish_paged_write([StoreWalAction::BulkUpsertEntityRecords {
176 collection: collection.to_string(),
177 records,
178 }])?;
179 return Ok(());
180 };
181 let mut btree_indices = self.btree_indices.write();
182 let btree = btree_indices
183 .entry(collection.to_string())
184 .or_insert_with(|| Arc::new(BTree::new(Arc::clone(pager))));
185 let root_before = btree.root_page_id();
186
187 btree.upsert_batch_sorted(&serialized).map_err(|e| {
191 StoreError::Io(std::io::Error::other(format!("B-tree upsert error: {}", e)))
192 })?;
193 let root_after = btree.root_page_id();
194 drop(btree_indices);
195 if root_before != root_after {
196 self.mark_paged_registry_dirty();
197 }
198 }
199 let records: Vec<Vec<u8>> = serialized.into_iter().map(|(_id, record)| record).collect();
209 self.finish_paged_write_for_projection(
210 [StoreWalAction::BulkUpsertEntityRecords {
211 collection: collection.to_string(),
212 records,
213 }],
214 skip_btree,
215 )?;
216
217 Ok(())
218 }
219
220 pub(crate) fn update_graph_label_index(
222 &self,
223 collection: &str,
224 label: &str,
225 entity_id: EntityId,
226 ) {
227 let key = (collection.to_string(), label.to_string());
228 let mut idx = self.graph_label_index.write();
229 idx.entry(key).or_default().push(entity_id);
230 }
231
232 pub(crate) fn remove_from_graph_label_index(&self, collection: &str, entity_id: EntityId) {
234 let mut idx = self.graph_label_index.write();
235 for ((col, _), ids) in idx.iter_mut() {
236 if col == collection {
237 ids.retain(|&id| id != entity_id);
238 }
239 }
240 idx.retain(|_, ids| !ids.is_empty());
242 }
243
244 pub(crate) fn remove_from_graph_label_index_batch(
245 &self,
246 collection: &str,
247 entity_ids: &[EntityId],
248 ) {
249 if entity_ids.is_empty() {
250 return;
251 }
252 let id_set: std::collections::HashSet<EntityId> = entity_ids.iter().copied().collect();
253 let mut idx = self.graph_label_index.write();
254 for ((col, _), ids) in idx.iter_mut() {
255 if col == collection {
256 ids.retain(|id| !id_set.contains(id));
257 }
258 }
259 idx.retain(|_, ids| !ids.is_empty());
260 }
261
262 pub fn lookup_graph_nodes_by_label(&self, label: &str) -> Vec<EntityId> {
264 let idx = self.graph_label_index.read();
265 idx.iter()
266 .filter(|((_, l), _)| l == label)
267 .flat_map(|(_, ids)| ids.iter().copied())
268 .collect()
269 }
270
271 pub fn lookup_graph_nodes_by_label_in(&self, collection: &str, label: &str) -> Vec<EntityId> {
273 let idx = self.graph_label_index.read();
274 idx.get(&(collection.to_string(), label.to_string()))
275 .cloned()
276 .unwrap_or_default()
277 }
278
279 pub fn create_collection(&self, name: impl Into<String>) -> Result<(), StoreError> {
280 let name = name.into();
281 let mut collections = self.collections.write();
282
283 if collections.contains_key(&name) {
284 return Err(StoreError::CollectionExists(name));
285 }
286
287 let manager = SegmentManager::with_config(&name, self.config.manager_config.clone());
288 collections.insert(name.clone(), Arc::new(manager));
289 drop(collections);
290
291 let create = match self.prepare_operational_collection_create(&name) {
292 Ok(create) => create,
293 Err(err) => {
294 let mut collections = self.collections.write();
295 collections.remove(&name);
296 return Err(err);
297 }
298 };
299 if let Some(create) = create {
300 if let Err(err) = create.publish().map_err(StoreError::Io) {
301 let mut collections = self.collections.write();
302 collections.remove(&name);
303 return Err(err);
304 }
305 }
306
307 self.mark_paged_registry_dirty();
308 self.finish_paged_write([StoreWalAction::CreateCollection { name }])?;
309
310 Ok(())
311 }
312
313 pub fn get_or_create_collection(&self, name: impl Into<String>) -> Arc<SegmentManager> {
315 let name = name.into();
316 {
318 let collections = self.collections.read();
319 if let Some(manager) = collections.get(&name) {
320 return Arc::clone(manager);
321 }
322 }
323 let mut collections = self.collections.write();
325 if let Some(manager) = collections.get(&name) {
327 return Arc::clone(manager);
328 }
329 let manager = Arc::new(SegmentManager::with_config(
330 &name,
331 self.config.manager_config.clone(),
332 ));
333 collections.insert(name, Arc::clone(&manager));
334 self.mark_paged_registry_dirty();
335 manager
336 }
337
338 pub fn get_collection(&self, name: &str) -> Option<Arc<SegmentManager>> {
340 self.collections.read().get(name).map(Arc::clone)
341 }
342
343 pub fn context_index(&self) -> &ContextIndex {
345 &self.context_index
346 }
347
348 pub fn take_replayed_turbo_inserts(&self, collection: &str) -> Option<Vec<(u64, Vec<f32>)>> {
354 let mut map = self.replayed_turbo_inserts.lock();
355 map.remove(collection)
356 }
357
358 pub(crate) fn take_replayed_probabilistic_deltas(&self) -> Vec<(u8, u8, String, Vec<Vec<u8>>)> {
359 let mut deltas = self.replayed_probabilistic_deltas.lock();
360 std::mem::take(&mut *deltas)
361 }
362
363 pub fn set_config_tree(&self, prefix: &str, json: &crate::serde_json::Value) -> usize {
370 let manager = self.get_or_create_collection("red_config");
371 let mut pairs = Vec::new();
372 flatten_config_json(prefix, json, &mut pairs);
373 let mut previous: HashMap<String, Vec<(EntityId, Option<reddb_types::Value>)>> = pairs
375 .iter()
376 .map(|(key, _)| (key.clone(), Vec::new()))
377 .collect();
378 for entity in manager.query_all(|_| true) {
379 if let EntityData::Row(row) = &entity.data {
380 let Some(named) = row.named.as_ref() else {
381 continue;
382 };
383 if let Some(reddb_types::Value::Text(key)) = named.get("key") {
384 if let Some(rows) = previous.get_mut(key.as_ref()) {
385 rows.push((entity.id, named.get("value").cloned()));
386 }
387 }
388 }
389 }
390 let mut saved = 0;
391 for (key, value) in pairs {
392 let stale = previous.remove(&key).unwrap_or_default();
393 if let [(_, Some(current))] = stale.as_slice() {
397 if *current == value {
398 saved += 1;
399 continue;
400 }
401 }
402 let stale: Vec<EntityId> = stale.into_iter().map(|(id, _)| id).collect();
403 let entity = UnifiedEntity::new(
407 EntityId::new(0),
408 EntityKind::TableRow {
409 table: Arc::from("red_config"),
410 row_id: 0,
411 },
412 EntityData::Row(RowData {
413 columns: Vec::new(),
414 named: Some(
415 [
416 ("key".to_string(), reddb_types::Value::text(key)),
417 ("value".to_string(), value),
418 ]
419 .into_iter()
420 .collect(),
421 ),
422 schema: None,
423 }),
424 );
425 if self.insert_auto("red_config", entity).is_ok() {
426 saved += 1;
427 if !stale.is_empty() {
428 let _ = self.delete_batch("red_config", &stale);
429 }
430 }
431 }
432 saved
433 }
434
435 pub fn get_config(&self, key: &str) -> Option<reddb_types::Value> {
439 let manager = self.get_collection("red_config")?;
440 let mut latest: Option<(u64, reddb_types::Value)> = None;
441 for entity in manager.query_all(|_| true) {
442 if let EntityData::Row(row) = &entity.data {
443 if let Some(named) = &row.named {
444 let key_matches = named
445 .get("key")
446 .and_then(|v| match v {
447 reddb_types::Value::Text(s) => Some(s.as_ref() == key),
448 _ => None,
449 })
450 .unwrap_or(false);
451 if key_matches && latest.as_ref().is_none_or(|(id, _)| entity.id.raw() >= *id) {
452 if let Some(value) = named.get("value") {
453 latest = Some((entity.id.raw(), value.clone()));
454 }
455 }
456 }
457 }
458 }
459 latest.map(|(_, value)| value)
460 }
461
462 pub fn set_aux_metadata(&self, bytes: Vec<u8>) {
467 *self.aux_metadata.write() = bytes;
468 }
469
470 pub fn aux_metadata(&self) -> Vec<u8> {
472 self.aux_metadata.read().clone()
473 }
474
475 pub fn list_collections(&self) -> Vec<String> {
477 self.collections.read().keys().cloned().collect()
478 }
479
480 pub fn drop_collection(&self, name: &str) -> Result<(), StoreError> {
482 let _vault_guard = self.vault_publication_lock.lock();
483 let drop = self.prepare_operational_collection_drop(name)?;
484 let manager = {
485 let mut collections = self.collections.write();
486
487 collections
488 .remove(name)
489 .ok_or_else(|| StoreError::CollectionNotFound(name.to_string()))?
490 };
491
492 let entities = manager.query_all(|_| true);
493 let entity_ids: Vec<EntityId> = entities.iter().map(|entity| entity.id).collect();
494
495 for entity_id in &entity_ids {
496 self.context_index.remove_entity(*entity_id);
497 let _ = self.unindex_cross_refs(*entity_id);
498 }
499
500 if let Some(tree) = self.btree_indices.write().remove(name) {
501 self.retire_btree(tree);
502 }
503
504 self.entity_cache.retain(|entity_id, (collection, _)| {
505 collection != name && !entity_ids.iter().any(|id| id.raw() == entity_id)
506 });
507
508 self.cross_refs.write().retain(|source_id, refs| {
509 refs.retain(|(target_id, _, target_collection)| {
510 target_collection != name && !entity_ids.iter().any(|id| id == target_id)
511 });
512 !entity_ids.iter().any(|id| id == source_id)
513 });
514
515 self.reverse_refs.write().retain(|target_id, refs| {
516 refs.retain(|(source_id, _, source_collection)| {
517 source_collection != name && !entity_ids.iter().any(|id| id == source_id)
518 });
519 !entity_ids.iter().any(|id| id == target_id)
520 });
521
522 self.mark_paged_registry_dirty();
523 self.finish_paged_write([StoreWalAction::DropCollection {
524 name: name.to_string(),
525 }])?;
526 if let Some(drop) = drop {
527 drop.finish().map_err(StoreError::Io)?;
528 }
529
530 Ok(())
531 }
532
533 pub fn insert(&self, collection: &str, entity: UnifiedEntity) -> Result<EntityId, StoreError> {
535 let manager = self
536 .get_collection(collection)
537 .ok_or_else(|| StoreError::CollectionNotFound(collection.to_string()))?;
538
539 let mut entity = entity;
540 if entity.id.raw() == 0 {
541 entity.id = self.next_entity_id();
542 } else {
543 self.register_entity_id(entity.id);
544 }
545 if let EntityKind::TableRow { ref mut row_id, .. } = entity.kind {
547 if *row_id == 0 {
548 *row_id = manager.next_row_id();
549 } else {
550 manager.register_row_id(*row_id);
551 }
552 }
553 entity.ensure_table_logical_id();
554 let graph_node_label: Option<String> = if let EntityKind::GraphNode(ref node) = entity.kind
556 {
557 Some(node.label.clone())
558 } else {
559 None
560 };
561
562 let id = manager.insert(entity)?;
563 self.register_entity_id(id);
564
565 if let Some(ref label) = graph_node_label {
567 self.update_graph_label_index(collection, label, id);
568 }
569
570 let mut registry_dirty = false;
573 if let Some(pager) = self
574 .pager
575 .as_ref()
576 .filter(|_| !Self::deferred_store_wal_capture_active())
577 {
578 if let Some(entity) = manager.get(id) {
579 let mut btree_indices = self.btree_indices.write();
580 let btree = btree_indices
581 .entry(collection.to_string())
582 .or_insert_with(|| Arc::new(BTree::new(Arc::clone(pager))));
583 let root_before = btree.root_page_id();
584
585 let key = id.raw().to_be_bytes();
586 let metadata = manager.get_metadata(id);
587 let value = Self::serialize_entity_record(
588 &entity,
589 metadata.as_ref(),
590 self.format_version(),
591 );
592 let _ = btree.insert(&key, &value);
594 registry_dirty = root_before != btree.root_page_id();
595 }
596 }
597
598 if self.config.auto_index_refs {
600 if let Some(entity) = manager.get(id) {
601 self.index_cross_refs(&entity, collection)?;
602 }
603 }
604
605 if self.pager.is_some() || self.config.embedded_wal_path.is_some() {
609 let actions = manager
610 .get(id)
611 .map(|entity| {
612 let metadata = manager.get_metadata(id);
613 vec![StoreWalAction::upsert_entity(
614 collection,
615 &entity,
616 metadata.as_ref(),
617 self.format_version(),
618 )]
619 })
620 .unwrap_or_default();
621 if registry_dirty {
622 self.mark_paged_registry_dirty();
623 }
624 self.finish_paged_write(actions)?;
625 }
626
627 Ok(id)
628 }
629
630 pub fn bulk_insert(
635 &self,
636 collection: &str,
637 mut entities: Vec<UnifiedEntity>,
638 ) -> Result<Vec<EntityId>, StoreError> {
639 let _publication = self.vault_publication_lock.lock();
642 let trace = matches!(
646 std::env::var("REDDB_BULK_TIMING").ok().as_deref(),
647 Some("1") | Some("true") | Some("on")
648 );
649 let t_start = std::time::Instant::now();
650 let n = entities.len();
651 let manager = self.get_or_create_collection(collection);
652 let t_get_coll = t_start.elapsed();
653
654 let t0 = std::time::Instant::now();
663 let n_missing_entity_ids = entities.iter().filter(|e| e.id.raw() == 0).count() as u64;
664 let n_missing_row_ids = entities
665 .iter()
666 .filter(|e| matches!(e.kind, EntityKind::TableRow { row_id: 0, .. }))
667 .count() as u64;
668 let mut entity_id_range = if n_missing_entity_ids > 0 {
669 self.reserve_entity_ids(n_missing_entity_ids)
670 } else {
671 0..0
672 };
673 let mut row_id_range = if n_missing_row_ids > 0 {
674 manager.reserve_row_ids(n_missing_row_ids)
675 } else {
676 0..0
677 };
678 for entity in &mut entities {
679 if entity.id.raw() == 0 {
680 let next = entity_id_range
681 .next()
682 .expect("reserved entity-id range exhausted");
683 entity.id = EntityId::new(next);
684 } else {
685 self.register_entity_id(entity.id);
686 }
687 if let EntityKind::TableRow { ref mut row_id, .. } = entity.kind {
688 if *row_id == 0 {
689 *row_id = row_id_range
690 .next()
691 .expect("reserved row-id range exhausted");
692 } else {
693 manager.register_row_id(*row_id);
694 }
695 }
696 entity.ensure_table_logical_id();
697 }
698 let t_assign_ids = t0.elapsed();
699
700 let graph_labels: Vec<Option<(String, EntityId)>> = entities
702 .iter()
703 .map(|e| {
704 if let EntityKind::GraphNode(ref node) = e.kind {
705 Some((node.label.clone(), e.id))
706 } else {
707 None
708 }
709 })
710 .collect();
711
712 let t0 = std::time::Instant::now();
719 let serialized: Option<Vec<(Vec<u8>, Vec<u8>)>> =
720 if self.pager.is_some() || self.config.embedded_wal_path.is_some() {
721 let fv = self.format_version();
722 let serial_map = |e: &UnifiedEntity| {
723 (
724 e.id.raw().to_be_bytes().to_vec(),
725 Self::serialize_entity_record(e, None, fv),
726 )
727 };
728 if entities.len() >= 512 {
734 use rayon::prelude::*;
735 Some(entities.par_iter().map(serial_map).collect())
736 } else {
737 Some(entities.iter().map(serial_map).collect())
738 }
739 } else {
740 None
741 };
742 let t_serialize = t0.elapsed();
743
744 let t0 = std::time::Instant::now();
746 let ids = manager.bulk_insert(entities)?;
747 let t_manager = t0.elapsed();
748 for id in &ids {
749 self.register_entity_id(*id);
750 }
751
752 for (label, entity_id) in graph_labels.iter().flatten() {
754 self.update_graph_label_index(collection, label, *entity_id);
755 }
756
757 let skip_btree_requested = matches!(
767 std::env::var("REDDB_BULK_SKIP_PERSIST_UNSAFE")
768 .ok()
769 .as_deref(),
770 Some("1") | Some("true") | Some("on")
771 );
772 let skip_btree = skip_btree_requested && self.pager.is_none();
775 if skip_btree_requested && !skip_btree {
776 static IGNORED: std::sync::OnceLock<()> = std::sync::OnceLock::new();
778 IGNORED.get_or_init(|| {
779 tracing::warn!(
780 "REDDB_BULK_SKIP_PERSIST_UNSAFE set but durable pager is \
781 active — flag ignored; bulk inserts will be persisted normally"
782 );
783 });
784 } else if skip_btree {
785 static WARNED: std::sync::OnceLock<()> = std::sync::OnceLock::new();
787 WARNED.get_or_init(|| {
788 tracing::warn!(
789 "REDDB_BULK_SKIP_PERSIST_UNSAFE set (ephemeral/no-pager mode) — \
790 bulk inserts NOT durable; data will be lost on restart"
791 );
792 });
793 }
794
795 let mut t_btree_lock = std::time::Duration::ZERO;
799 let mut t_btree_insert = std::time::Duration::ZERO;
800 let mut t_flush = std::time::Duration::ZERO;
801 if !skip_btree && !Self::deferred_store_wal_capture_active() {
802 if let (Some(pager), Some(batch)) = (&self.pager, serialized.as_ref()) {
803 let t0 = std::time::Instant::now();
804 let mut btree_indices = self.btree_indices.write();
805 let btree = btree_indices
806 .entry(collection.to_string())
807 .or_insert_with(|| Arc::new(BTree::new(Arc::clone(pager))));
808 let root_before = btree.root_page_id();
809 t_btree_lock = t0.elapsed();
810
811 let t0 = std::time::Instant::now();
812 let _ = btree.bulk_insert_sorted(batch);
813 t_btree_insert = t0.elapsed();
814 let registry_dirty = root_before != btree.root_page_id();
815
816 let t0 = std::time::Instant::now();
817 if registry_dirty {
818 self.mark_paged_registry_dirty();
819 }
820 t_flush = t0.elapsed();
821 }
822 }
823
824 let actions = serialized
830 .map(|batch| {
831 let records: Vec<Vec<u8>> =
832 batch.into_iter().map(|(_key, record)| record).collect();
833 vec![StoreWalAction::BulkUpsertEntityRecords {
834 collection: collection.to_string(),
835 records,
836 }]
837 })
838 .unwrap_or_default();
839 self.finish_paged_write(actions)?;
840
841 if trace {
842 tracing::debug!(
843 n,
844 total = ?t_start.elapsed(),
845 get_coll = ?t_get_coll,
846 assign = ?t_assign_ids,
847 serialize = ?t_serialize,
848 manager = ?t_manager,
849 btree_lock = ?t_btree_lock,
850 btree = ?t_btree_insert,
851 flush = ?t_flush,
852 "bulk_insert timing"
853 );
854 }
855
856 Ok(ids)
857 }
858
859 pub fn insert_auto(
861 &self,
862 collection: &str,
863 entity: UnifiedEntity,
864 ) -> Result<EntityId, StoreError> {
865 let _publication = self.vault_publication_lock.lock();
867 let manager = self.get_or_create_collection(collection);
868 let mut entity = entity;
869 if entity.id.raw() == 0 {
870 entity.id = self.next_entity_id();
871 } else {
872 self.register_entity_id(entity.id);
873 }
874 if let EntityKind::TableRow { ref mut row_id, .. } = entity.kind {
876 if *row_id == 0 {
877 *row_id = manager.next_row_id();
878 } else {
879 manager.register_row_id(*row_id);
880 }
881 }
882 entity.ensure_table_logical_id();
883
884 let graph_node_label: Option<String> = if let EntityKind::GraphNode(ref node) = entity.kind
886 {
887 Some(node.label.clone())
888 } else {
889 None
890 };
891 self.context_index.index_entity(collection, &entity);
893
894 let persist_record = self.pager.is_some() || self.config.embedded_wal_path.is_some();
897 if self.config.auto_index_refs {
898 self.index_cross_refs(&entity, collection)?;
899 }
900
901 let paged_btree = if persist_record && !Self::deferred_store_wal_capture_active() {
908 self.get_or_create_btree(collection)
909 } else {
910 None
911 };
912 let persist_fence = paged_btree
913 .as_ref()
914 .map(|_| self.btree_indices.read_recursive());
915 let before = paged_btree.as_ref().map(|_| manager.checkpoint_revisions());
916 let unversioned = entity.xmin == 0 && entity.xmax == 0;
917
918 let id = manager.insert(entity)?;
919 let serialized_record = if persist_record {
920 Some(
921 manager
922 .get_with(id, |entity| {
923 Self::serialize_entity_record(entity, None, self.format_version())
924 })
925 .ok_or(StoreError::EntityNotFound(id))?,
926 )
927 } else {
928 None
929 };
930 if let Some(ref label) = graph_node_label {
938 self.update_graph_label_index(collection, label, id);
939 }
940
941 let mut registry_dirty = false;
942 if let (Some(btree), Some(record)) = (paged_btree.as_ref(), serialized_record.as_ref()) {
943 let root_before = btree.root_page_id();
944
945 let key = id.raw().to_be_bytes();
946 btree.insert(&key, record).map_err(|e| {
947 StoreError::Io(std::io::Error::other(format!(
948 "B-tree insert error while inserting '{collection}'/{id}: {e}"
949 )))
950 })?;
951 registry_dirty = root_before != btree.root_page_id();
952 }
953 drop(persist_fence);
954
955 if self.pager.is_some() || self.config.embedded_wal_path.is_some() {
959 let actions = serialized_record
960 .map(|record| {
961 vec![StoreWalAction::UpsertEntityRecord {
962 collection: collection.to_string(),
963 record,
964 }]
965 })
966 .unwrap_or_default();
967 if registry_dirty {
968 self.mark_paged_registry_dirty();
969 }
970 if let Some(pending) = self.enqueue_grouped_actions(&actions)? {
971 drop(_publication);
972 self.complete_grouped_actions(&pending, &actions)?;
973 } else {
974 self.finish_paged_write(actions)?;
975 }
976 }
977 if unversioned && !Self::deferred_store_wal_capture_active() {
978 if let Some(before) = before {
979 self.note_paged_insert(collection, &manager, &before, id);
980 }
981 }
982 Ok(id)
983 }
984
985 pub fn get(&self, collection: &str, id: EntityId) -> Option<UnifiedEntity> {
991 if let Some(entity) = self
993 .get_collection(collection)
994 .and_then(|manager| manager.get(id))
995 {
996 return Some(entity);
997 }
998
999 if self.pager.is_some() {
1001 let btree_indices = self.btree_indices.read();
1002 if let Some(btree) = btree_indices.get(collection) {
1003 let key = id.raw().to_be_bytes();
1004 if let Ok(Some(value)) = btree.get(&key) {
1005 if let Ok((entity, _)) =
1006 Self::deserialize_entity_record(&value, self.format_version())
1007 {
1008 return Some(entity);
1009 }
1010 }
1011 }
1012 }
1013
1014 None
1015 }
1016
1017 pub fn get_table_row_by_logical_id(
1023 &self,
1024 collection: &str,
1025 logical_id: EntityId,
1026 ) -> Option<UnifiedEntity> {
1027 if let Some(entity) = self.get(collection, logical_id) {
1028 if matches!(entity.kind, EntityKind::TableRow { .. })
1029 && entity.logical_id() == logical_id
1030 && entity.xmax == 0
1031 {
1032 return Some(entity);
1033 }
1034 }
1035
1036 let manager = self.get_collection(collection)?;
1037 let mut matches = manager.query_all(|entity| {
1038 matches!(entity.kind, EntityKind::TableRow { .. }) && entity.logical_id() == logical_id
1039 });
1040 matches
1041 .iter()
1042 .find(|entity| entity.xmax == 0)
1043 .cloned()
1044 .or_else(|| matches.pop())
1045 }
1046
1047 pub fn table_row_versions_by_logical_id(
1048 &self,
1049 collection: &str,
1050 logical_id: EntityId,
1051 ) -> Vec<UnifiedEntity> {
1052 self.get_collection(collection)
1053 .map(|manager| {
1054 manager.query_all(|entity| {
1055 matches!(entity.kind, EntityKind::TableRow { .. })
1056 && entity.logical_id() == logical_id
1057 })
1058 })
1059 .unwrap_or_default()
1060 }
1061
1062 pub fn vacuum_mvcc_history(
1063 &self,
1064 collection: &str,
1065 cutoff_xid: u64,
1066 ) -> Result<MvccVacuumStats, StoreError> {
1067 let manager = self
1068 .get_collection(collection)
1069 .ok_or_else(|| StoreError::CollectionNotFound(collection.to_string()))?;
1070 let mut logical = HashMap::<EntityId, (bool, u64)>::new();
1071 manager.for_each_entity(|entity| {
1072 if !matches!(entity.kind, EntityKind::TableRow { .. }) {
1073 return true;
1074 }
1075 let entry = logical.entry(entity.logical_id()).or_insert((false, 0));
1076 if entity.xmax == 0 {
1077 entry.0 = true;
1078 }
1079 entry.1 = entry.1.max(entity.xmin);
1080 true
1081 });
1082
1083 let mut stats = MvccVacuumStats::default();
1084 let mut reclaim_ids = Vec::new();
1085 manager.for_each_entity(|entity| {
1086 if !matches!(entity.kind, EntityKind::TableRow { .. }) || entity.xmax == 0 {
1087 return true;
1088 }
1089 stats.scanned_versions += 1;
1090 let (has_live_version, max_xmin) = logical
1091 .get(&entity.logical_id())
1092 .copied()
1093 .unwrap_or((false, entity.xmin));
1094 let is_delete_tombstone = !has_live_version && entity.xmin == max_xmin;
1095 if entity.xmax < cutoff_xid {
1096 stats.reclaimed_versions += 1;
1097 if is_delete_tombstone {
1098 stats.reclaimed_tombstones += 1;
1099 } else {
1100 stats.reclaimed_history_versions += 1;
1101 }
1102 reclaim_ids.push(entity.id);
1103 } else {
1104 stats.retained_versions += 1;
1105 if is_delete_tombstone {
1106 stats.retained_tombstones += 1;
1107 } else {
1108 stats.retained_history_versions += 1;
1109 }
1110 }
1111 true
1112 });
1113
1114 if !reclaim_ids.is_empty() {
1115 self.delete_batch(collection, &reclaim_ids)?;
1116 }
1117 Ok(stats)
1118 }
1119
1120 pub(crate) fn install_versioned_table_row_update(
1121 &self,
1122 collection: &str,
1123 old_version: UnifiedEntity,
1124 mut new_version: UnifiedEntity,
1125 metadata: Option<&Metadata>,
1126 ) -> Result<(), StoreError> {
1127 let manager = self
1128 .get_collection(collection)
1129 .ok_or_else(|| StoreError::CollectionNotFound(collection.to_string()))?;
1130
1131 let old_id = old_version.id;
1132 let new_id = new_version.id;
1133 let inherited_metadata = metadata.cloned().or_else(|| manager.get_metadata(old_id));
1134
1135 self.entity_cache.remove(old_id.raw());
1136 self.entity_cache.remove(new_id.raw());
1137 manager.update(old_version.clone())?;
1138 self.context_index.remove_entity(old_id);
1139
1140 self.register_entity_id(new_version.id);
1141 if let EntityKind::TableRow { ref mut row_id, .. } = new_version.kind {
1142 if *row_id == 0 {
1143 *row_id = manager.next_row_id();
1144 } else {
1145 manager.register_row_id(*row_id);
1146 }
1147 }
1148 new_version.ensure_table_logical_id();
1149 manager.insert(new_version.clone())?;
1150 if let Some(metadata) = inherited_metadata {
1151 manager.set_metadata(new_id, metadata)?;
1152 }
1153 self.context_index.index_entity(collection, &new_version);
1154 if self.config.auto_index_refs {
1155 self.index_cross_refs(&new_version, collection)?;
1156 }
1157
1158 let old_metadata = manager.get_metadata(old_id);
1159 let new_metadata = manager.get_metadata(new_id);
1160 let fv = self.format_version();
1161 let records = vec![
1164 manager
1165 .get_with(old_id, |entity| {
1166 Self::serialize_entity_record(entity, old_metadata.as_ref(), fv)
1167 })
1168 .ok_or(StoreError::EntityNotFound(old_id))?,
1169 manager
1170 .get_with(new_id, |entity| {
1171 Self::serialize_entity_record(entity, new_metadata.as_ref(), fv)
1172 })
1173 .ok_or(StoreError::EntityNotFound(new_id))?,
1174 ];
1175 self.finish_paged_write_for_projection(
1176 [StoreWalAction::BulkUpsertEntityRecords {
1177 collection: collection.to_string(),
1178 records,
1179 }],
1180 true,
1181 )?;
1182
1183 Ok(())
1184 }
1185
1186 pub fn get_batch(&self, collection: &str, ids: &[EntityId]) -> Vec<Option<UnifiedEntity>> {
1192 match self.get_collection(collection) {
1193 Some(manager) => manager.get_many(ids),
1194 None => vec![None; ids.len()],
1195 }
1196 }
1197
1198 pub fn get_any(&self, id: EntityId) -> Option<(String, UnifiedEntity)> {
1200 if let Some(cached) = self.entity_cache.get(id.raw()) {
1204 return Some(cached);
1205 }
1206
1207 let collections = self.collections.read();
1209 for (name, manager) in collections.iter() {
1210 if let Some(entity) = manager.get(id) {
1211 let result = (name.clone(), entity);
1212 drop(collections);
1216 self.entity_cache.insert(id.raw(), result.clone());
1217 return Some(result);
1218 }
1219 }
1220 None
1221 }
1222
1223 pub fn entity_cache_hit_rate(&self) -> Option<f64> {
1229 self.entity_cache.hit_rate()
1230 }
1231
1232 pub fn entity_cache_stats(&self) -> super::super::entity_cache::EntityCacheStats {
1234 self.entity_cache.stats()
1235 }
1236
1237 pub fn delete(&self, collection: &str, id: EntityId) -> Result<bool, StoreError> {
1239 let publication = self.vault_publication_lock.lock();
1240 self.entity_cache.remove(id.raw());
1242 let manager = self
1243 .get_collection(collection)
1244 .ok_or_else(|| StoreError::CollectionNotFound(collection.to_string()))?;
1245
1246 let deleted = manager.delete(id)?;
1247 if !deleted {
1248 return Ok(false);
1249 }
1250
1251 let mut registry_dirty = false;
1253 if self.pager.is_some() {
1254 let btree_indices = self.btree_indices.read();
1255 if let Some(btree) = btree_indices.get(collection) {
1256 let root_before = btree.root_page_id();
1257 let key = id.raw().to_be_bytes();
1258 let _ = btree.delete(&key);
1259 registry_dirty = root_before != btree.root_page_id();
1260 }
1261 }
1262
1263 self.unindex_cross_refs(id)?;
1265
1266 self.remove_from_graph_label_index(collection, id);
1268
1269 if registry_dirty {
1270 self.mark_paged_registry_dirty();
1271 }
1272 let actions = [StoreWalAction::DeleteEntityRecord {
1273 collection: collection.to_string(),
1274 entity_id: id.raw(),
1275 }];
1276 if let Some(pending) = self.enqueue_grouped_actions(&actions)? {
1277 drop(publication);
1278 self.complete_grouped_actions(&pending, &actions)?;
1279 } else {
1280 self.finish_paged_write(actions)?;
1281 }
1282
1283 Ok(true)
1284 }
1285
1286 pub fn delete_batch(
1287 &self,
1288 collection: &str,
1289 ids: &[EntityId],
1290 ) -> Result<Vec<EntityId>, StoreError> {
1291 if ids.is_empty() {
1292 return Ok(Vec::new());
1293 }
1294 let _publication = self.vault_publication_lock.lock();
1297
1298 self.entity_cache.remove_many(ids.iter().map(|id| id.raw()));
1303
1304 let manager = self
1305 .get_collection(collection)
1306 .ok_or_else(|| StoreError::CollectionNotFound(collection.to_string()))?;
1307
1308 let before = self.pager.as_ref().map(|_| manager.checkpoint_revisions());
1309 let deleted_ids = manager.delete_batch(ids)?;
1310 if deleted_ids.is_empty() {
1311 return Ok(deleted_ids);
1312 }
1313
1314 let mut registry_dirty = false;
1315 let mut updated_tree = false;
1316 if self.pager.is_some() {
1317 let btree_indices = self.btree_indices.read();
1318 if let Some(btree) = btree_indices.get(collection) {
1319 updated_tree = true;
1320 let root_before = btree.root_page_id();
1321 for id in &deleted_ids {
1322 let key = id.raw().to_be_bytes();
1323 updated_tree &= matches!(btree.delete(&key), Ok(true));
1324 }
1325 registry_dirty = root_before != btree.root_page_id();
1326 }
1327 }
1328
1329 self.unindex_cross_refs_batch(&deleted_ids)?;
1330 self.remove_from_graph_label_index_batch(collection, &deleted_ids);
1331 if registry_dirty {
1332 self.mark_paged_registry_dirty();
1333 }
1334 let actions = deleted_ids
1335 .iter()
1336 .map(|id| StoreWalAction::DeleteEntityRecord {
1337 collection: collection.to_string(),
1338 entity_id: id.raw(),
1339 })
1340 .collect::<Vec<_>>();
1341 self.finish_paged_write(actions)?;
1342
1343 if updated_tree {
1344 if let Some(before) = before {
1345 self.note_paged_delete(collection, &manager, &before, &deleted_ids);
1346 }
1347 self.flush_paged_registry()?;
1352 }
1353 Ok(deleted_ids)
1354 }
1355
1356 pub fn set_metadata(
1358 &self,
1359 collection: &str,
1360 id: EntityId,
1361 metadata: Metadata,
1362 ) -> Result<(), StoreError> {
1363 let manager = self
1364 .get_collection(collection)
1365 .ok_or_else(|| StoreError::CollectionNotFound(collection.to_string()))?;
1366
1367 manager.set_metadata(id, metadata)?;
1368 if let Some(entity) = manager.get(id) {
1369 self.persist_entities_to_pager(collection, std::slice::from_ref(&entity))?;
1370 }
1371 Ok(())
1372 }
1373
1374 pub fn get_metadata(&self, collection: &str, id: EntityId) -> Option<Metadata> {
1376 self.get_collection(collection)?.get_metadata(id)
1377 }
1378
1379 pub fn add_cross_ref(
1381 &self,
1382 source_collection: &str,
1383 source_id: EntityId,
1384 target_collection: &str,
1385 target_id: EntityId,
1386 ref_type: RefType,
1387 weight: f32,
1388 ) -> Result<(), StoreError> {
1389 let source_manager = self
1391 .get_collection(source_collection)
1392 .ok_or_else(|| StoreError::CollectionNotFound(source_collection.to_string()))?;
1393
1394 if source_manager.get(source_id).is_none() {
1395 return Err(StoreError::EntityNotFound(source_id));
1396 }
1397
1398 let target_manager = self
1400 .get_collection(target_collection)
1401 .ok_or_else(|| StoreError::CollectionNotFound(target_collection.to_string()))?;
1402
1403 if target_manager.get(target_id).is_none() {
1404 return Err(StoreError::EntityNotFound(target_id));
1405 }
1406
1407 let current_refs = self
1409 .cross_refs
1410 .read()
1411 .get(&source_id)
1412 .map_or(0, |v| v.len());
1413
1414 if current_refs >= self.config.max_cross_refs {
1415 return Err(StoreError::TooManyRefs(source_id));
1416 }
1417
1418 let mut registry_dirty = false;
1419 {
1420 let mut forward = self.cross_refs.write();
1421 let refs = forward.entry(source_id).or_default();
1422 let inserted = !refs.iter().any(|(id, kind, coll)| {
1423 *id == target_id && *kind == ref_type && coll == target_collection
1424 });
1425 if inserted {
1426 refs.push((target_id, ref_type, target_collection.to_string()));
1427 registry_dirty = true;
1428 }
1429 }
1430
1431 {
1432 let mut reverse = self.reverse_refs.write();
1433 let refs = reverse.entry(target_id).or_default();
1434 let inserted = !refs.iter().any(|(id, kind, coll)| {
1435 *id == source_id && *kind == ref_type && coll == source_collection
1436 });
1437 if inserted {
1438 refs.push((source_id, ref_type, source_collection.to_string()));
1439 registry_dirty = true;
1440 }
1441 }
1442
1443 if let Some(mut entity) = source_manager.get(source_id) {
1444 if !entity.cross_refs().iter().any(|xref| {
1445 xref.target == target_id
1446 && xref.ref_type == ref_type
1447 && xref.target_collection == target_collection
1448 }) {
1449 let cross_ref = CrossRef::with_weight(
1450 source_id,
1451 target_id,
1452 target_collection,
1453 ref_type,
1454 weight,
1455 );
1456 entity.add_cross_ref(cross_ref);
1457 let _ = source_manager.update(entity.clone());
1458 registry_dirty = true;
1459 self.persist_entities_to_pager(source_collection, std::slice::from_ref(&entity))?;
1460 }
1461 }
1462
1463 if registry_dirty {
1464 self.mark_paged_registry_dirty();
1465 if matches!(
1466 self.config.durability_mode,
1467 crate::api::DurabilityMode::Strict
1468 ) {
1469 self.flush_paged_state()?;
1470 }
1471 }
1472
1473 Ok(())
1474 }
1475
1476 pub fn get_refs_from(&self, id: EntityId) -> Vec<(EntityId, RefType, String)> {
1478 self.cross_refs.read().get(&id).cloned().unwrap_or_default()
1479 }
1480
1481 pub fn get_refs_to(&self, id: EntityId) -> Vec<(EntityId, RefType, String)> {
1483 self.reverse_refs
1484 .read()
1485 .get(&id)
1486 .cloned()
1487 .unwrap_or_default()
1488 }
1489
1490 pub fn expand_refs(
1492 &self,
1493 id: EntityId,
1494 depth: u32,
1495 ref_types: Option<&[RefType]>,
1496 ) -> Vec<(UnifiedEntity, u32, RefType)> {
1497 let mut results = Vec::new();
1498 let mut visited = std::collections::HashSet::new();
1499 visited.insert(id);
1500
1501 self.expand_refs_recursive(id, depth, ref_types, &mut visited, &mut results, 1);
1502
1503 results
1504 }
1505
1506 fn expand_refs_recursive(
1507 &self,
1508 id: EntityId,
1509 max_depth: u32,
1510 ref_types: Option<&[RefType]>,
1511 visited: &mut std::collections::HashSet<EntityId>,
1512 results: &mut Vec<(UnifiedEntity, u32, RefType)>,
1513 current_depth: u32,
1514 ) {
1515 if current_depth > max_depth {
1516 return;
1517 }
1518
1519 for (target_id, ref_type, target_collection) in self.get_refs_from(id) {
1520 if visited.contains(&target_id) {
1521 continue;
1522 }
1523
1524 if let Some(types) = ref_types {
1525 if !types.contains(&ref_type) {
1526 continue;
1527 }
1528 }
1529
1530 visited.insert(target_id);
1531
1532 if let Some(entity) = self.get(&target_collection, target_id) {
1533 results.push((entity, current_depth, ref_type));
1534
1535 self.expand_refs_recursive(
1537 target_id,
1538 max_depth,
1539 ref_types,
1540 visited,
1541 results,
1542 current_depth + 1,
1543 );
1544 }
1545 }
1546 }
1547
1548 pub(crate) fn index_cross_refs(
1550 &self,
1551 entity: &UnifiedEntity,
1552 collection: &str,
1553 ) -> Result<(), StoreError> {
1554 let mut registry_dirty = false;
1555 for cross_ref in entity.cross_refs() {
1556 if cross_ref.target_collection.is_empty() {
1557 continue;
1558 }
1559 {
1560 let mut forward = self.cross_refs.write();
1561 let refs = forward.entry(cross_ref.source).or_default();
1562 let inserted = !refs.iter().any(|(id, kind, coll)| {
1563 *id == cross_ref.target
1564 && *kind == cross_ref.ref_type
1565 && coll == &cross_ref.target_collection
1566 });
1567 if inserted {
1568 refs.push((
1569 cross_ref.target,
1570 cross_ref.ref_type,
1571 cross_ref.target_collection.clone(),
1572 ));
1573 registry_dirty = true;
1574 }
1575 }
1576
1577 {
1578 let mut reverse = self.reverse_refs.write();
1579 let refs = reverse.entry(cross_ref.target).or_default();
1580 let inserted = !refs.iter().any(|(id, kind, coll)| {
1581 *id == cross_ref.source && *kind == cross_ref.ref_type && coll == collection
1582 });
1583 if inserted {
1584 refs.push((cross_ref.source, cross_ref.ref_type, collection.to_string()));
1585 registry_dirty = true;
1586 }
1587 }
1588 }
1589
1590 if registry_dirty {
1591 self.mark_paged_registry_dirty();
1592 }
1593
1594 Ok(())
1595 }
1596
1597 pub(crate) fn unindex_cross_refs(&self, id: EntityId) -> Result<(), StoreError> {
1599 self.cross_refs.write().remove(&id);
1601
1602 let mut reverse = self.reverse_refs.write();
1604 for refs in reverse.values_mut() {
1605 refs.retain(|(source, _, _)| *source != id);
1606 }
1607 reverse.remove(&id);
1608 self.mark_paged_registry_dirty();
1609
1610 Ok(())
1611 }
1612
1613 pub(crate) fn unindex_cross_refs_batch(&self, ids: &[EntityId]) -> Result<(), StoreError> {
1614 if ids.is_empty() {
1615 return Ok(());
1616 }
1617
1618 let id_set: std::collections::HashSet<EntityId> = ids.iter().copied().collect();
1619
1620 let needs_forward_cleanup = {
1634 let forward = self.cross_refs.read();
1635 id_set.iter().any(|id| forward.contains_key(id))
1636 };
1637 let needs_reverse_cleanup = {
1638 let reverse = self.reverse_refs.read();
1639 id_set.iter().any(|id| reverse.contains_key(id))
1640 };
1641
1642 if !needs_forward_cleanup && !needs_reverse_cleanup {
1643 self.unindex_cross_refs_fast_path
1644 .fetch_add(1, Ordering::Relaxed);
1645 return Ok(());
1646 }
1647
1648 if needs_forward_cleanup {
1649 let mut forward = self.cross_refs.write();
1650 for id in &id_set {
1651 forward.remove(id);
1652 }
1653 }
1654
1655 if needs_reverse_cleanup || needs_forward_cleanup {
1656 let mut reverse = self.reverse_refs.write();
1660 if needs_forward_cleanup {
1661 for refs in reverse.values_mut() {
1662 refs.retain(|(source, _, _)| !id_set.contains(source));
1663 }
1664 }
1665 reverse.retain(|target, refs| !id_set.contains(target) && !refs.is_empty());
1666 }
1667 self.mark_paged_registry_dirty();
1668
1669 Ok(())
1670 }
1671
1672 pub fn unindex_cross_refs_fast_path_hits(&self) -> u64 {
1676 self.unindex_cross_refs_fast_path.load(Ordering::Relaxed)
1677 }
1678
1679 pub fn query_all<F>(&self, filter: F) -> Vec<(String, UnifiedEntity)>
1681 where
1682 F: Fn(&UnifiedEntity) -> bool + Clone + Send + Sync,
1683 {
1684 let pairs: Vec<(String, Arc<SegmentManager>)> = {
1695 let collections = self.collections.read();
1696 collections
1697 .iter()
1698 .map(|(name, mgr)| (name.clone(), Arc::clone(mgr)))
1699 .collect()
1700 };
1701
1702 let use_parallel = pairs.len() > 1 && crate::runtime::SystemInfo::should_parallelize();
1703 if !use_parallel {
1704 return pairs
1706 .into_iter()
1707 .flat_map(|(name, mgr)| {
1708 mgr.query_all(filter.clone())
1709 .into_iter()
1710 .map(move |e| (name.clone(), e))
1711 })
1712 .collect();
1713 }
1714
1715 let filter_ref = &filter;
1717 let collection_results: Vec<Vec<(String, UnifiedEntity)>> = std::thread::scope(|s| {
1718 pairs
1719 .iter()
1720 .map(|(name, manager)| {
1721 let name = (*name).clone();
1722 s.spawn(move || {
1723 manager
1724 .query_all(|e| filter_ref(e))
1725 .into_iter()
1726 .map(|e| (name.clone(), e))
1727 .collect::<Vec<_>>()
1728 })
1729 })
1730 .collect::<Vec<_>>()
1731 .into_iter()
1732 .map(|h| h.join().unwrap_or_default())
1733 .collect()
1734 });
1735
1736 collection_results.into_iter().flatten().collect()
1737 }
1738
1739 pub fn scan<F>(
1741 &self,
1742 snapshot: Option<&crate::runtime::impl_core::SnapshotContext>,
1743 filter: F,
1744 ) -> Vec<(String, UnifiedEntity)>
1745 where
1746 F: Fn(&UnifiedEntity) -> bool + Clone + Send + Sync,
1747 {
1748 let pairs: Vec<(String, Arc<SegmentManager>)> = {
1749 let collections = self.collections.read();
1750 collections
1751 .iter()
1752 .map(|(name, manager)| (name.clone(), Arc::clone(manager)))
1753 .collect()
1754 };
1755
1756 let use_parallel = pairs.len() > 1 && crate::runtime::SystemInfo::should_parallelize();
1757 if !use_parallel {
1758 return pairs
1759 .into_iter()
1760 .flat_map(|(name, manager)| {
1761 manager
1762 .scan(snapshot, filter.clone())
1763 .into_iter()
1764 .map(move |entity| (name.clone(), entity))
1765 })
1766 .collect();
1767 }
1768
1769 let filter_ref = &filter;
1770 let collection_results: Vec<Vec<(String, UnifiedEntity)>> = std::thread::scope(|scope| {
1771 pairs
1772 .iter()
1773 .map(|(name, manager)| {
1774 let name = name.clone();
1775 scope.spawn(move || {
1776 manager
1777 .scan(snapshot, |entity| filter_ref(entity))
1778 .into_iter()
1779 .map(|entity| (name.clone(), entity))
1780 .collect::<Vec<_>>()
1781 })
1782 })
1783 .collect::<Vec<_>>()
1784 .into_iter()
1785 .map(|handle| handle.join().unwrap_or_default())
1786 .collect()
1787 });
1788
1789 collection_results.into_iter().flatten().collect()
1790 }
1791
1792 pub fn filter_metadata_all(
1794 &self,
1795 filters: &[(String, MetadataFilter)],
1796 ) -> Vec<(String, EntityId)> {
1797 let mut results = Vec::new();
1798 let collections = self.collections.read();
1799
1800 for (name, manager) in collections.iter() {
1801 for id in manager.filter_metadata(filters) {
1802 results.push((name.clone(), id));
1803 }
1804 }
1805
1806 results
1807 }
1808
1809 pub fn stats(&self) -> StoreStats {
1811 let pairs: Vec<(String, Arc<SegmentManager>)> = {
1817 let collections = self.collections.read();
1818 collections
1819 .iter()
1820 .map(|(name, mgr)| (name.clone(), Arc::clone(mgr)))
1821 .collect()
1822 };
1823
1824 let mut stats = StoreStats {
1825 collection_count: pairs.len(),
1826 ..Default::default()
1827 };
1828
1829 for (name, manager) in &pairs {
1830 let manager_stats = manager.stats();
1831 stats.total_entities += manager_stats.total_entities;
1832 stats.total_memory_bytes += manager_stats.total_memory_bytes;
1833 stats.total_memory_bytes += manager.checkpoint_tracking_bytes();
1834 stats.collections.insert(name.clone(), manager_stats);
1835 }
1836
1837 stats.total_memory_bytes += self.checkpoint_durable_rows.read().memory_bytes();
1838 stats
1839 }
1840
1841 pub fn run_maintenance(&self) -> Result<(), StoreError> {
1843 let collections = self.collections.read();
1844 for manager in collections.values() {
1845 manager.run_maintenance()?;
1846 }
1847 Ok(())
1848 }
1849
1850 pub fn reclaimable_segment_bytes(&self) -> u64 {
1852 let collections = self.collections.read();
1853 collections
1854 .values()
1855 .map(|manager| manager.reclaimable_bytes())
1856 .fold(0, u64::saturating_add)
1857 }
1858
1859 pub fn pressure_consolidation_tick(&self) -> bool {
1862 let managers: Vec<_> = self.collections.read().values().cloned().collect();
1863 let mut advanced = false;
1866 for manager in &managers {
1867 advanced |= manager.pressure_consolidation_tick();
1868 }
1869 advanced
1870 }
1871}
1872
1873fn flatten_config_json(
1875 prefix: &str,
1876 value: &crate::serde_json::Value,
1877 out: &mut Vec<(String, reddb_types::Value)>,
1878) {
1879 use reddb_types::Value;
1880 match value {
1881 crate::serde_json::Value::Object(map) => {
1882 for (k, v) in map {
1883 let key = if prefix.is_empty() {
1884 k.clone()
1885 } else {
1886 format!("{prefix}.{k}")
1887 };
1888 flatten_config_json(&key, v, out);
1889 }
1890 }
1891 crate::serde_json::Value::String(s) => {
1892 out.push((prefix.to_string(), Value::text(s.clone())));
1893 }
1894 crate::serde_json::Value::Integer(n) => {
1895 out.push((prefix.to_string(), Value::Integer(*n)));
1896 }
1897 crate::serde_json::Value::Number(n) => {
1898 if n.fract().abs() < f64::EPSILON {
1899 out.push((prefix.to_string(), Value::UnsignedInteger(*n as u64)));
1900 } else {
1901 out.push((prefix.to_string(), Value::Float(*n)));
1902 }
1903 }
1904 crate::serde_json::Value::Decimal(n) => {
1905 out.push((prefix.to_string(), Value::DecimalText(n.clone())));
1906 }
1907 crate::serde_json::Value::Bool(b) => {
1908 out.push((prefix.to_string(), Value::Boolean(*b)));
1909 }
1910 crate::serde_json::Value::Null => {
1911 out.push((prefix.to_string(), Value::Null));
1912 }
1913 crate::serde_json::Value::Array(arr) => {
1914 let json_str = crate::serde_json::to_string(value).unwrap_or_default();
1915 out.push((prefix.to_string(), Value::text(json_str)));
1916 }
1917 }
1918}