Skip to main content

reddb_server/storage/unified/
manager.rs

1//! Segment Manager
2//!
3//! Manages the lifecycle of unified segments: creation, sealing, consolidation,
4//! and archival. Coordinates writes to growing segments and queries across
5//! all segments.
6//!
7//! # Responsibilities
8//!
9//! - Route writes to the active growing segment
10//! - Auto-seal segments when thresholds are met
11//! - Coordinate queries across multiple segments
12//! - Paced consolidation of sealed segments (ADR 0073 §5)
13//! - Archive old segments to cold storage
14
15mod graph_index_merge;
16
17use parking_lot::RwLock;
18use std::collections::HashMap;
19use std::sync::atomic::{AtomicU64, Ordering};
20use std::sync::{Arc, Weak};
21
22use super::entity::{EntityId, EntityKind, UnifiedEntity};
23use super::metadata::{Metadata, MetadataFilter};
24use super::segment::{
25    GraphEntityKind, GrowingSegment, SegmentConfig, SegmentError, SegmentId, SegmentState,
26    SegmentStats, UnifiedSegment, ZoneColPred, ZoneColPredKind,
27};
28use super::visibility_map::VisibilityMap;
29use crate::runtime::mvcc::{entity_visible_with_context, SnapshotContext};
30
31/// Fraction of a collection's sealed entities that must be tombstoned before
32/// consolidation is worth its cost.
33///
34/// Tunable implementation constant, not a contract: it is surfaced read-only in
35/// `red.stats` so an operator can see what the engine decided, and it may move
36/// between releases without notice.
37pub const CONSOLIDATION_TOMBSTONE_RATIO: f64 = 0.20;
38
39/// Fraction of a collection's sealed bytes that consolidation would return to
40/// the budget (dead entity payloads plus the tombstone sets that bury them)
41/// before consolidation is worth its cost. See [`CONSOLIDATION_TOMBSTONE_RATIO`]
42/// on tunability.
43pub const CONSOLIDATION_FRAGMENTATION_RATIO: f64 = 0.30;
44
45/// Entities copied into the merged segment per maintenance tick.
46///
47/// ADR 0038 §3: consolidation is paced. A tick copies at most this many
48/// entities and returns; the half-built merged segment is carried to the next
49/// tick. No consolidation ever runs to completion in one unbounded pass.
50pub const CONSOLIDATION_ENTITIES_PER_TICK: usize = 4_096;
51
52/// Configuration for the segment manager
53#[derive(Debug, Clone)]
54pub struct ManagerConfig {
55    /// Segment configuration
56    pub segment_config: SegmentConfig,
57    /// Maximum number of sealed segments before consolidation
58    pub max_sealed_segments: usize,
59    /// Idle time (seconds) before auto-sealing
60    pub idle_seal_secs: u64,
61    /// Enable paced sealed-segment consolidation
62    pub enable_consolidation: bool,
63    /// Entities copied per maintenance tick while a consolidation is running
64    pub consolidation_entities_per_tick: usize,
65    /// Enable background archival
66    pub enable_archival: bool,
67    /// Age threshold for archival (seconds)
68    pub archive_age_secs: u64,
69}
70
71impl Default for ManagerConfig {
72    fn default() -> Self {
73        Self {
74            segment_config: SegmentConfig::default(),
75            max_sealed_segments: 10,
76            idle_seal_secs: 300, // 5 minutes
77            enable_consolidation: true,
78            consolidation_entities_per_tick: CONSOLIDATION_ENTITIES_PER_TICK,
79            enable_archival: true,
80            archive_age_secs: 86400 * 7, // 7 days
81        }
82    }
83}
84
85/// Consolidation counters for one collection (ADR 0073 §5).
86///
87/// These replace the `compact_ops` counter, which only ever counted a
88/// do-nothing branch.
89#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
90pub struct ConsolidationStats {
91    /// Consolidations that crossed a threshold and began copying.
92    pub runs_started: u64,
93    /// Consolidations that finished the swap.
94    pub runs_completed: u64,
95    /// Source segments retired by a completed swap.
96    pub segments_merged: u64,
97    /// Tombstones garbage-collected by completed swaps.
98    pub tombstones_reclaimed: u64,
99    /// Logical source-to-merged footprint reduction; readers may retain sources.
100    pub bytes_reclaimed: u64,
101}
102
103/// Manager statistics
104#[derive(Debug, Clone, Default)]
105pub struct ManagerStats {
106    /// Total entities across all segments
107    pub total_entities: usize,
108    /// Number of growing segments
109    pub growing_count: usize,
110    /// Number of sealed segments
111    pub sealed_count: usize,
112    /// Number of archived segments
113    pub archived_count: usize,
114    /// Total memory usage
115    pub total_memory_bytes: usize,
116    /// Number of seal operations
117    pub seal_ops: u64,
118    /// Consolidation counters
119    pub consolidation: ConsolidationStats,
120}
121
122#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
123pub struct SegmentScanStats {
124    pub segments_total: u64,
125    pub segments_scanned: u64,
126    pub segments_pruned: u64,
127}
128
129/// Lifecycle events for monitoring
130#[derive(Debug, Clone)]
131pub enum LifecycleEvent {
132    SegmentCreated(SegmentId),
133    SegmentSealed(SegmentId),
134    SegmentConsolidated {
135        source: Vec<SegmentId>,
136        target: SegmentId,
137    },
138    SegmentArchived(SegmentId),
139    EntityInserted(EntityId, SegmentId),
140    EntityDeleted(EntityId, SegmentId),
141}
142
143/// A consolidation in flight, carried across maintenance ticks.
144///
145/// The merged segment is built off to the side and is invisible to readers
146/// until the swap. Nothing here is durable: sealed segments are the truth (via
147/// the normal checkpoint path), so a crash mid-consolidation simply drops this
148/// state and the next boot starts over.
149struct Consolidation {
150    /// Source segments, frozen when the run started.
151    sources: Vec<SourceProgress>,
152    /// Id reserved for the merged segment.
153    merged_id: SegmentId,
154    /// The half-built merged segment.
155    merged: GrowingSegment,
156    /// Index into `sources` of the segment currently being copied.
157    cursor: usize,
158    /// Live ids of `sources[cursor]`, snapshotted when that source was opened.
159    pending_ids: Vec<EntityId>,
160    /// How many of `pending_ids` have been consumed.
161    pending_cursor: usize,
162    /// Entities copied so far, across every tick of this run.
163    entities_copied: u64,
164}
165
166/// Per-source bookkeeping for a consolidation in flight.
167struct SourceProgress {
168    id: SegmentId,
169    /// Ids copied out of this source into the merged segment.
170    copied: Vec<EntityId>,
171    /// The source's tombstone count when the run opened it, and `None` before
172    /// that. Tombstones only ever grow, so a source whose count is unchanged at
173    /// swap time saw no deletes after we started reading it — and every row we
174    /// copied out of it is still live. Anything else needs a per-row check.
175    ///
176    /// Recording this when the source is *opened*, not when it is drained, is
177    /// what makes the check sound: a row deleted between two copy ticks would
178    /// otherwise be invisible to the swap and get resurrected.
179    tombstones_at_open: Option<usize>,
180}
181
182struct PhysicalRootCacheEntry {
183    segments: Vec<(u64, u64)>,
184    seed: u64,
185    root: u64,
186}
187
188/// Segment manager for a collection
189pub struct SegmentManager {
190    /// Statement-scoped constraint admission. Reentrant because SQL upserts
191    /// invoke the same typed mutation APIs while holding this collection gate.
192    row_constraint_lock: Arc<parking_lot::ReentrantMutex<()>>,
193    /// Collection name
194    collection: String,
195    /// Configuration
196    config: ManagerConfig,
197    /// Next segment ID counter
198    next_segment_id: AtomicU64,
199    /// Next entity ID counter
200    next_entity_id: AtomicU64,
201    /// Per-table auto-increment row ID (1, 2, 3... per collection)
202    next_row_id: AtomicU64,
203    /// Hot-path entity counter — lock-free, updated by every insert/delete.
204    /// Replaces stats.total_entities on the write path to eliminate a lock
205    /// acquisition per row (from 4 lock ops per insert → 2).
206    total_entities_atomic: AtomicU64,
207    /// Currently active growing segment
208    growing: RwLock<Option<Arc<RwLock<GrowingSegment>>>>,
209    /// Sealed segments (immutable, queryable)
210    sealed: RwLock<Vec<Arc<RwLock<GrowingSegment>>>>,
211    /// Retired sources still owned by readers. Weak handles never prolong payload lifetime.
212    retired: RwLock<Vec<Weak<RwLock<GrowingSegment>>>>,
213    /// Archived segment IDs (stored externally)
214    archived: RwLock<Vec<SegmentId>>,
215    /// Entity to segment mapping (for fast lookups by individually-inserted entities).
216    /// Bulk-inserted entities skip this map; their segment is found by sequential scan
217    /// of growing + sealed segments in get()/update()/delete().
218    entity_segment: RwLock<HashMap<EntityId, SegmentId>>,
219    /// Shared column schema: column_name → index in Vec<Value>.
220    /// Populated on first bulk_insert. Enables columnar storage (Vec instead of HashMap per row).
221    column_schema: RwLock<Option<Arc<Vec<String>>>>,
222    /// Statistics (slow path — not updated on every insert).
223    stats: RwLock<ManagerStats>,
224    /// Consolidation in flight, if any. Only `run_maintenance` touches it, so
225    /// at most one consolidation runs per collection at a time.
226    consolidation: RwLock<Option<Consolidation>>,
227    /// Event listeners (simplified - would be channels in production)
228    events: RwLock<Vec<LifecycleEvent>>,
229    /// Visibility map: sealed segment entity ranges marked as all-visible.
230    /// Growing segment is never all-visible (writes are in-flight).
231    /// Used by index-only scan decisions.
232    visibility_map: VisibilityMap,
233    physical_root_cache: parking_lot::Mutex<Option<PhysicalRootCacheEntry>>,
234}
235
236impl SegmentManager {
237    /// Create a new segment manager
238    pub fn new(collection: impl Into<String>) -> Self {
239        Self::with_config(collection, ManagerConfig::default())
240    }
241
242    /// Create with custom configuration
243    pub fn with_config(collection: impl Into<String>, config: ManagerConfig) -> Self {
244        Self {
245            row_constraint_lock: Arc::new(parking_lot::ReentrantMutex::new(())),
246            physical_root_cache: parking_lot::Mutex::new(None),
247            collection: collection.into(),
248            config,
249            next_segment_id: AtomicU64::new(1),
250            next_entity_id: AtomicU64::new(1),
251            next_row_id: AtomicU64::new(1),
252            total_entities_atomic: AtomicU64::new(0),
253            growing: RwLock::new(None),
254            sealed: RwLock::new(Vec::new()),
255            retired: RwLock::new(Vec::new()),
256            archived: RwLock::new(Vec::new()),
257            entity_segment: RwLock::new(HashMap::new()),
258            column_schema: RwLock::new(None),
259            stats: RwLock::new(ManagerStats::default()),
260            consolidation: RwLock::new(None),
261            events: RwLock::new(Vec::new()),
262            visibility_map: VisibilityMap::new(),
263        }
264    }
265
266    pub(crate) fn row_constraint_lock(&self) -> Arc<parking_lot::ReentrantMutex<()>> {
267        Arc::clone(&self.row_constraint_lock)
268    }
269
270    /// Get or create the shared column schema from first row's named fields.
271    pub fn get_or_init_schema(
272        &self,
273        named: &HashMap<String, reddb_types::Value>,
274    ) -> Arc<Vec<String>> {
275        {
276            let schema = self.column_schema.read();
277            if let Some(ref s) = *schema {
278                return Arc::clone(s);
279            }
280        }
281        let cols: Vec<String> = named.keys().cloned().collect();
282        let arc = Arc::new(cols);
283        *self.column_schema.write() = Some(Arc::clone(&arc));
284        arc
285    }
286
287    /// Get the column schema if it exists.
288    pub fn column_schema(&self) -> Option<Arc<Vec<String>>> {
289        self.column_schema.read().clone()
290    }
291
292    pub(crate) fn set_column_schema_if_empty(&self, columns: Vec<String>) {
293        if columns.is_empty() {
294            return;
295        }
296        let mut schema = self.column_schema.write();
297        if schema.is_none() {
298            *schema = Some(Arc::new(columns));
299        }
300    }
301
302    /// Get collection name
303    pub fn collection(&self) -> &str {
304        &self.collection
305    }
306
307    /// Get configuration
308    pub fn config(&self) -> &ManagerConfig {
309        &self.config
310    }
311
312    /// Get statistics. Entity counts cover active segments; memory also covers
313    /// retained sources and unpublished consolidation work.
314    pub fn stats(&self) -> ManagerStats {
315        let mut s = self.stats.read().clone();
316        s.total_entities = self.total_entities_atomic.load(Ordering::Relaxed) as usize;
317        s.total_memory_bytes = self.resident_bytes() as usize;
318        s
319    }
320
321    /// Approximate resident segment memory, including tombstones, retired sources,
322    /// and the in-flight merge and its bookkeeping. This feeds budget admission.
323    pub fn resident_bytes(&self) -> u64 {
324        self.memory_usage().1
325    }
326
327    /// Resident segment payload/directory bytes and consolidation bookkeeping,
328    /// including retired sources. Unlike `resident_bytes`, excludes tombstones.
329    pub fn memory_bytes(&self) -> u64 {
330        self.memory_usage().0
331    }
332
333    /// Sample payload and resident bytes under the publication lock order:
334    /// consolidation, growing, sealed, retired. No entity scan or strong handle
335    /// is retained beyond this call; expired weak entries are pruned in place.
336    fn memory_usage(&self) -> (u64, u64) {
337        let consolidation = self.consolidation.read();
338        let growing = self.growing.read();
339        let sealed = self.sealed.read();
340        let mut retired = self.retired.write();
341        let mut payload = 0u64;
342        let mut resident = 0u64;
343        {
344            let mut add = |segment: &GrowingSegment| {
345                payload = payload.saturating_add(segment.memory_bytes());
346                resident = resident.saturating_add(segment.resident_bytes());
347            };
348            for segment in growing.iter().chain(sealed.iter()) {
349                add(&segment.read());
350            }
351            retired.retain(|source| {
352                if let Some(source) = source.upgrade() {
353                    add(&source.read());
354                    true
355                } else {
356                    false
357                }
358            });
359            if let Some(run) = consolidation.as_ref() {
360                add(&run.merged);
361            }
362        }
363        let mut bookkeeping =
364            (retired.capacity() * std::mem::size_of::<Weak<RwLock<GrowingSegment>>>()) as u64;
365        if let Some(run) = consolidation.as_ref() {
366            bookkeeping = bookkeeping
367                .saturating_add(
368                    (run.sources.capacity() * std::mem::size_of::<SourceProgress>()) as u64,
369                )
370                .saturating_add(
371                    (run.pending_ids.capacity() * std::mem::size_of::<EntityId>()) as u64,
372                );
373            for source in &run.sources {
374                bookkeeping = bookkeeping.saturating_add(
375                    (source.copied.capacity() * std::mem::size_of::<EntityId>()) as u64,
376                );
377            }
378        }
379        (
380            payload.saturating_add(bookkeeping),
381            resident.saturating_add(bookkeeping),
382        )
383    }
384
385    /// Bytes a pressure-triggered consolidation could plausibly return.
386    pub fn reclaimable_bytes(&self) -> u64 {
387        self.sealed
388            .read()
389            .iter()
390            .map(|segment| segment.read().reclaimable_bytes())
391            .fold(0, u64::saturating_add)
392    }
393
394    /// Generate a new entity ID
395    pub fn next_entity_id(&self) -> EntityId {
396        EntityId::new(self.next_entity_id.fetch_add(1, Ordering::SeqCst))
397    }
398
399    /// Generate a per-table sequential row ID (1, 2, 3... per collection)
400    pub fn next_row_id(&self) -> u64 {
401        self.next_row_id.fetch_add(1, Ordering::SeqCst)
402    }
403
404    /// Reserve `n` contiguous per-table row IDs with one atomic
405    /// fetch_add. Caller assigns `row_id = start + i` per entity.
406    /// Saves N-1 atomic RMWs on bulk inserts (25k atomics → 1).
407    pub fn reserve_row_ids(&self, n: u64) -> std::ops::Range<u64> {
408        let start = self.next_row_id.fetch_add(n, Ordering::SeqCst);
409        start..start + n
410    }
411
412    /// Advance the per-table row_id counter to at least `id + 1`.
413    /// Called during load to restore the counter from existing data.
414    pub fn register_row_id(&self, id: u64) {
415        let candidate = id.saturating_add(1);
416        let mut current = self.next_row_id.load(Ordering::SeqCst);
417        while candidate > current {
418            match self.next_row_id.compare_exchange(
419                current,
420                candidate,
421                Ordering::SeqCst,
422                Ordering::SeqCst,
423            ) {
424                Ok(_) => break,
425                Err(updated) => current = updated,
426            }
427        }
428    }
429
430    /// Get or create the active growing segment.
431    ///
432    /// Fast path: read lock only — no write contention when the segment already exists.
433    /// Concurrent writers each clone the `Arc` under a shared read lock, then compete
434    /// on the segment's own write lock. This eliminates the global write-lock serialisation
435    /// that previously throttled concurrent inserts to ~238 ops/s.
436    fn get_or_create_growing(&self) -> Arc<RwLock<GrowingSegment>> {
437        // Common case: segment already exists — shared read lock, zero contention.
438        {
439            let growing = self.growing.read();
440            if let Some(segment) = growing.as_ref() {
441                return Arc::clone(segment);
442            }
443        }
444
445        // Slow path: segment missing — take exclusive write lock to create it.
446        let mut growing = self.growing.write();
447        // Double-check: another thread may have created it between the two lock acquisitions.
448        if let Some(segment) = growing.as_ref() {
449            return Arc::clone(segment);
450        }
451
452        let id = self.next_segment_id.fetch_add(1, Ordering::SeqCst);
453        let segment = GrowingSegment::new(id, &self.collection);
454        let segment_arc = Arc::new(RwLock::new(segment));
455        *growing = Some(Arc::clone(&segment_arc));
456
457        self.emit(LifecycleEvent::SegmentCreated(id));
458
459        // Update growing_count in the slow-path stats struct.
460        // This is the rare segment-creation path — locking is fine here.
461        self.stats.write().growing_count += 1;
462
463        segment_arc
464    }
465
466    /// Insert a new entity
467    pub fn insert(&self, mut entity: UnifiedEntity) -> Result<EntityId, SegmentError> {
468        // Check if we need to seal the current segment first
469        self.maybe_seal_growing()?;
470
471        let segment_arc = self.get_or_create_growing();
472        let mut segment = segment_arc.write();
473
474        // Assign entity ID if not already set
475        if entity.id.raw() == 0 {
476            entity.id = self.next_entity_id();
477        }
478
479        let entity_id = entity.id;
480        let segment_id = segment.id();
481
482        segment.insert(entity)?;
483
484        // Lock-free counter update — eliminates the stats write lock on the hot path.
485        self.total_entities_atomic.fetch_add(1, Ordering::Relaxed);
486
487        // entity_segment map is intentionally NOT updated here.
488        // update() and update_hot() first probe the growing segment directly
489        // (growing.contains(entity.id)) before consulting this map, so entities
490        // that were just inserted are found without entity_segment. The map is
491        // only consulted for entities that may have been moved to sealed segments,
492        // which can't be updated anyway (state().is_writable() == false).
493        // Skipping this write removes one exclusive HashMap lock per insert.
494
495        self.emit(LifecycleEvent::EntityInserted(entity_id, segment_id));
496
497        Ok(entity_id)
498    }
499
500    /// Restore a snapshot image without allocating a new sequence identity.
501    pub(crate) fn restore_snapshot_entity(
502        &self,
503        entity: UnifiedEntity,
504    ) -> Result<EntityId, SegmentError> {
505        self.maybe_seal_growing()?;
506        if self.get(entity.id).is_some() {
507            return Err(SegmentError::AlreadyExists(entity.id));
508        }
509        let segment_arc = self.get_or_create_growing();
510        let mut segment = segment_arc.write();
511        let entity_id = entity.id;
512        let segment_id = segment.id();
513        // Adoption rebuilds derived indexes and advances the allocator past
514        // the stored sequence, including gaps and the legitimate value zero.
515        segment.adopt_entity(entity, None);
516        self.total_entities_atomic.fetch_add(1, Ordering::Relaxed);
517        self.emit(LifecycleEvent::EntityInserted(entity_id, segment_id));
518        Ok(entity_id)
519    }
520
521    /// Insert multiple entities (batch) — sequential, one lock per item.
522    pub fn insert_batch(
523        &self,
524        entities: Vec<UnifiedEntity>,
525    ) -> Result<Vec<EntityId>, SegmentError> {
526        let mut ids = Vec::with_capacity(entities.len());
527        for entity in entities {
528            ids.push(self.insert(entity)?);
529        }
530        Ok(ids)
531    }
532
533    /// Turbo bulk insert — single lock acquisition for the entire batch.
534    /// Skips bloom filter and cross-ref indexing for maximum speed.
535    pub fn bulk_insert(
536        &self,
537        mut entities: Vec<UnifiedEntity>,
538    ) -> Result<Vec<EntityId>, SegmentError> {
539        // Assign IDs and per-table row_ids.
540        for entity in &mut entities {
541            if entity.id.raw() == 0 {
542                entity.id = self.next_entity_id();
543            }
544            if let super::entity::EntityKind::TableRow { ref mut row_id, .. } = entity.kind {
545                if *row_id == 0 {
546                    *row_id = self.next_row_id();
547                } else {
548                    self.register_row_id(*row_id);
549                }
550            }
551        }
552
553        // Convert named HashMap → positional Vec (compact memory representation)
554        // The schema (column order) is shared across all rows in the collection.
555        if let Some(first_row) = entities.first() {
556            if let super::entity::EntityData::Row(ref row) = first_row.data {
557                if let Some(ref named) = row.named {
558                    let schema = self.get_or_init_schema(named);
559                    for entity in &mut entities {
560                        if let super::entity::EntityData::Row(ref mut row) = entity.data {
561                            if let Some(named) = row.named.take() {
562                                let mut cols = Vec::with_capacity(schema.len());
563                                for col_name in schema.iter() {
564                                    cols.push(
565                                        named
566                                            .get(col_name)
567                                            .cloned()
568                                            .unwrap_or(reddb_types::Value::Null),
569                                    );
570                                }
571                                row.columns = cols;
572                                row.schema = Some(Arc::clone(&schema));
573                            }
574                        }
575                    }
576                }
577            }
578        }
579
580        let segment_arc = self.get_or_create_growing();
581        let mut segment = segment_arc.write();
582        let segment_id = segment.id();
583
584        // Single call to GrowingSegment.bulk_insert (one lock, no bloom/cross-refs)
585        let ids = segment.bulk_insert(entities)?;
586
587        // Skip entity-segment mapping for bulk inserts (saves ~56 bytes/entity).
588        // The get() method scans growing+sealed segments directly.
589
590        // Lock-free batch counter update.
591        self.total_entities_atomic
592            .fetch_add(ids.len() as u64, Ordering::Relaxed);
593
594        Ok(ids)
595    }
596
597    /// Get an entity by ID — scans growing then sealed segments.
598    pub fn get(&self, id: EntityId) -> Option<UnifiedEntity> {
599        self.get_with(id, Clone::clone)
600    }
601
602    /// Inspect under the segment lock, for example to bound a payload clone.
603    /// The callback must not re-enter storage or runtime memory admission.
604    pub(crate) fn get_with<T>(
605        &self,
606        id: EntityId,
607        visit: impl FnOnce(&UnifiedEntity) -> T,
608    ) -> Option<T> {
609        // Growing segment first (most likely for recent inserts)
610        if let Some(growing_arc) = self.growing.read().as_ref() {
611            let growing = growing_arc.read();
612            if let Some(entity) = growing.get(id) {
613                return Some(visit(entity));
614            }
615        }
616
617        // Then sealed segments
618        let sealed = self.sealed.read();
619        for segment in sealed.iter() {
620            let seg = segment.read();
621            if let Some(entity) = seg.get(id) {
622                return Some(visit(entity));
623            }
624        }
625
626        None
627    }
628
629    /// Resolve a physical graph node reference without cloning historical payloads.
630    /// This deliberately ignores MVCC: callers must authorize the visible logical
631    /// node separately. The callback bounds every segment probe, including misses.
632    pub(crate) fn graph_node_logical_id(
633        &self,
634        id: EntityId,
635        mut before_segment: impl FnMut() -> bool,
636    ) -> Option<EntityId> {
637        if let Some(growing_arc) = self.growing.read().as_ref() {
638            if !before_segment() {
639                return None;
640            }
641            let growing = growing_arc.read();
642            if let Some(entity) = growing.get(id) {
643                return matches!(entity.kind, EntityKind::GraphNode(_))
644                    .then(|| entity.logical_id());
645            }
646        }
647        let sealed = self.sealed.read();
648        for segment in sealed.iter() {
649            if !before_segment() {
650                return None;
651            }
652            let segment = segment.read();
653            if let Some(entity) = segment.get(id) {
654                return matches!(entity.kind, EntityKind::GraphNode(_))
655                    .then(|| entity.logical_id());
656            }
657        }
658        None
659    }
660
661    /// Pin the source inventory across sealing/consolidation. Consumers hydrate
662    /// IDs through the current manager and run outside all storage locks.
663    /// Admission is also outside storage locks; a growing inventory retries only
664    /// its small handle array. Each indexed candidate buffer has a fixed size.
665    pub(crate) fn visit_graph_index_batches<E>(
666        &self,
667        kind: GraphEntityKind,
668        keys: &[EntityId],
669        mut before_work: impl FnMut() -> bool,
670        mut admit: impl FnMut(usize) -> Result<(), E>,
671        mut consume: impl FnMut(&[EntityId]) -> Result<bool, E>,
672    ) -> Result<bool, E> {
673        use super::segment::{GraphIndexCursor, SCAN_BATCH_SIZE};
674        admit(std::mem::size_of::<[EntityId; SCAN_BATCH_SIZE]>())?;
675        let mut admitted = 0;
676        let sources = loop {
677            let count = {
678                let growing = self.growing.read();
679                let sealed = self.sealed.read();
680                sealed.len() + usize::from(growing.is_some())
681            };
682            let bytes = count.saturating_mul(std::mem::size_of::<(
683                Arc<RwLock<GrowingSegment>>,
684                GraphIndexCursor,
685            )>());
686            admit(bytes.saturating_sub(admitted))?;
687            admitted = admitted.max(bytes);
688            let mut sources = Vec::with_capacity(count);
689            let growing = self.growing.read();
690            let sealed = self.sealed.read();
691            if sealed.len() + usize::from(growing.is_some()) > sources.capacity() {
692                continue;
693            }
694            for segment in growing.iter().chain(sealed.iter()) {
695                if !before_work() {
696                    return Ok(false);
697                }
698                let view = segment.read();
699                if !view.may_contain_graph_kind(kind) {
700                    continue;
701                }
702                let Some(cursor) = view.graph_index_cursor(kind, keys, &mut before_work) else {
703                    return Ok(false);
704                };
705                sources.push((Arc::clone(segment), cursor));
706            }
707            break sources;
708        };
709        let mut ids = [EntityId::new(0); SCAN_BATCH_SIZE];
710        for (source, mut cursor) in sources {
711            while !cursor.finished(keys) {
712                let mut count = 0;
713                {
714                    let segment = source.read();
715                    if !segment.may_contain_graph_kind(kind) {
716                        break;
717                    }
718                    if !segment.graph_index_batch(
719                        kind,
720                        keys,
721                        &mut cursor,
722                        &mut before_work,
723                        &mut |id| {
724                            ids[count] = id;
725                            count += 1;
726                        },
727                    ) {
728                        return Ok(false);
729                    }
730                }
731                if !before_work() || !consume(&ids[..count])? {
732                    return Ok(false);
733                }
734            }
735        }
736        Ok(true)
737    }
738
739    /// Batch-fetch multiple entities by ID in a single lock acquisition per segment.
740    ///
741    /// For indexed-scan result sets (up to ~5000 ids from range/bitmap lookup) this
742    /// is 2-3 lock acquisitions total vs N×3 with individual `get()` calls.
743    pub fn get_many(&self, ids: &[EntityId]) -> Vec<Option<UnifiedEntity>> {
744        let mut out: Vec<Option<UnifiedEntity>> = vec![None; ids.len()];
745        let mut remaining: Vec<usize> = (0..ids.len()).collect(); // indices still unfound
746
747        // Growing segment — one read lock for the entire batch.
748        // Non-blocking first: if a writer is active, fall back to blocking.
749        if let Some(growing_arc) = self.growing.read().as_ref() {
750            let growing = if let Some(g) = growing_arc.try_read() {
751                g
752            } else {
753                growing_arc.read()
754            };
755            remaining.retain(|&i| {
756                if let Some(entity) = growing.get(ids[i]) {
757                    out[i] = Some(entity.clone());
758                    false // remove from remaining
759                } else {
760                    true // keep — not found yet
761                }
762            });
763        }
764
765        if remaining.is_empty() {
766            return out;
767        }
768
769        // Sealed segments — one read lock per segment
770        let sealed = self.sealed.read();
771        for segment in sealed.iter() {
772            if remaining.is_empty() {
773                break;
774            }
775            let seg = segment.read();
776            remaining.retain(|&i| {
777                if let Some(entity) = seg.get(ids[i]) {
778                    out[i] = Some(entity.clone());
779                    false
780                } else {
781                    true
782                }
783            });
784        }
785
786        out
787    }
788
789    /// Visitor-pattern batch fetch. Invokes `f(&UnifiedEntity, usize_index)`
790    /// for each id that resolves, never cloning the entity.
791    ///
792    /// Used by scan hot paths (select_range, select_filtered) that
793    /// materialize each entity into an output record and don't need
794    /// an owned `UnifiedEntity`. Eliminates ~20% of scan CPU spent in
795    /// `UnifiedEntity::clone` when `get_batch` is followed by
796    /// `runtime_table_record_lean(entity)`.
797    ///
798    /// The closure runs while the segment read lock is held, so it
799    /// must be short — avoid doing I/O or taking unrelated locks in
800    /// `f`.
801    pub fn for_each_id<F>(&self, ids: &[EntityId], mut f: F)
802    where
803        F: FnMut(usize, &UnifiedEntity),
804    {
805        // Thread-local scratch buffer for the "pending" index list.
806        // Previous code allocated a fresh `Vec<usize>` of capacity
807        // N on every call — 4200 × 1000 queries / scenario on the
808        // select_range bench path. Take-and-restore pattern (vs
809        // RefCell::borrow_mut) so user closures that recurse into
810        // another `for_each_id` don't panic on a re-borrow; worst
811        // case they allocate a fresh buffer and we lose the caching
812        // win for that nested call.
813        thread_local! {
814            static REMAINING_SCRATCH: std::cell::Cell<Vec<usize>> =
815                const { std::cell::Cell::new(Vec::new()) };
816        }
817
818        let mut remaining: Vec<usize> = REMAINING_SCRATCH.with(|cell| cell.take());
819        remaining.clear();
820
821        if let Some(growing_arc) = self.growing.read().as_ref() {
822            let growing = if let Some(g) = growing_arc.try_read() {
823                g
824            } else {
825                growing_arc.read()
826            };
827            for (i, id) in ids.iter().enumerate() {
828                if let Some(entity) = growing.get(*id) {
829                    f(i, entity);
830                } else {
831                    remaining.push(i);
832                }
833            }
834        } else {
835            remaining.reserve(ids.len());
836            remaining.extend(0..ids.len());
837        }
838
839        if !remaining.is_empty() {
840            let sealed = self.sealed.read();
841            for segment in sealed.iter() {
842                if remaining.is_empty() {
843                    break;
844                }
845                let seg = segment.read();
846                remaining.retain(|&i| {
847                    if let Some(entity) = seg.get(ids[i]) {
848                        f(i, entity);
849                        false
850                    } else {
851                        true
852                    }
853                });
854            }
855        }
856
857        REMAINING_SCRATCH.with(|cell| cell.set(remaining));
858    }
859
860    /// Scan all segments for an entity
861    fn scan_for_entity(&self, id: EntityId) -> Option<UnifiedEntity> {
862        // Check growing
863        if let Some(growing_arc) = self.growing.read().as_ref() {
864            let growing = growing_arc.read();
865            if let Some(entity) = growing.get(id) {
866                return Some(entity.clone());
867            }
868        }
869
870        // Check sealed
871        let sealed = self.sealed.read();
872        for segment in sealed.iter() {
873            if let Some(entity) = segment.get(id) {
874                return Some(entity.clone());
875            }
876        }
877
878        None
879    }
880
881    fn find_sealed_segment_arc(&self, id: EntityId) -> Option<Arc<RwLock<GrowingSegment>>> {
882        let sealed = self.sealed.read();
883        sealed
884            .iter()
885            .find(|segment_arc| segment_arc.read().contains(id))
886            .map(Arc::clone)
887    }
888
889    fn rewrite_sealed_entity_into_growing(
890        &self,
891        entity: UnifiedEntity,
892        metadata: Option<&Metadata>,
893    ) -> Result<(), SegmentError> {
894        let entity_id = entity.id;
895        let sealed_arc = self
896            .find_sealed_segment_arc(entity_id)
897            .ok_or(SegmentError::NotFound(entity_id))?;
898
899        let metadata_to_apply = {
900            let mut sealed = sealed_arc.write();
901            let existing_metadata = sealed.get_metadata(entity_id);
902            if !sealed.force_delete(entity_id) {
903                return Err(SegmentError::NotFound(entity_id));
904            }
905            metadata.cloned().or(existing_metadata)
906        };
907
908        let growing_arc = self.get_or_create_growing();
909        let growing_id = {
910            let mut growing = growing_arc.write();
911            growing.insert(entity)?;
912            if let Some(metadata) = metadata_to_apply {
913                growing.set_metadata(entity_id, metadata)?;
914            }
915            growing.id()
916        };
917
918        self.entity_segment.write().insert(entity_id, growing_id);
919        Ok(())
920    }
921
922    /// Update an entity
923    pub fn update(&self, entity: UnifiedEntity) -> Result<(), SegmentError> {
924        let entity_id = entity.id;
925        let mut entity = Some(entity);
926
927        // Try growing segment directly (covers bulk-inserted entities without entity_segment map)
928        if let Some(growing_arc) = self.growing.read().as_ref() {
929            let mut growing = growing_arc.write();
930            if growing.contains(entity_id) && growing.state().is_writable() {
931                return growing.update(entity.take().expect("entity already moved"));
932            }
933        }
934
935        // Try entity_segment mapping for individually inserted entities
936        let segment_id = self.entity_segment.read().get(&entity_id).copied();
937        if let Some(seg_id) = segment_id {
938            if let Some(growing_arc) = self.growing.read().as_ref() {
939                let mut growing = growing_arc.write();
940                if growing.id() == seg_id && growing.state().is_writable() {
941                    return growing.update(entity.take().expect("entity already moved"));
942                }
943            }
944        }
945
946        if let Some(entity) = entity.take() {
947            return self.rewrite_sealed_entity_into_growing(entity, None);
948        }
949
950        Err(SegmentError::NotFound(entity_id))
951    }
952
953    /// Update an entity and, optionally, replace its metadata while holding
954    /// the segment write lock only once.
955    pub fn update_with_metadata(
956        &self,
957        entity: UnifiedEntity,
958        metadata: Option<&Metadata>,
959    ) -> Result<(), SegmentError> {
960        let entity_id = entity.id;
961        let mut entity = Some(entity);
962
963        // Try growing segment directly (covers bulk-inserted entities without entity_segment map)
964        if let Some(growing_arc) = self.growing.read().as_ref() {
965            let mut growing = growing_arc.write();
966            if growing.contains(entity_id) && growing.state().is_writable() {
967                growing.update(entity.take().expect("entity already moved"))?;
968                if let Some(metadata) = metadata {
969                    growing.set_metadata(entity_id, metadata.clone())?;
970                }
971                return Ok(());
972            }
973        }
974
975        // Try entity_segment mapping for individually inserted entities
976        let segment_id = self.entity_segment.read().get(&entity_id).copied();
977        if let Some(seg_id) = segment_id {
978            if let Some(growing_arc) = self.growing.read().as_ref() {
979                let mut growing = growing_arc.write();
980                if growing.id() == seg_id && growing.state().is_writable() {
981                    growing.update(entity.take().expect("entity already moved"))?;
982                    if let Some(metadata) = metadata {
983                        growing.set_metadata(entity_id, metadata.clone())?;
984                    }
985                    return Ok(());
986                }
987            }
988        }
989
990        if let Some(entity) = entity.take() {
991            return self.rewrite_sealed_entity_into_growing(entity, metadata);
992        }
993
994        Err(SegmentError::NotFound(entity_id))
995    }
996
997    /// HOT-update: like update but skips index work for unchanged columns.
998    /// `modified_columns` is the list of column names actually changed by the
999    /// UPDATE statement — lets us skip pk_index and cross_ref when safe.
1000    pub fn update_hot(
1001        &self,
1002        entity: UnifiedEntity,
1003        modified_columns: &[String],
1004    ) -> Result<(), SegmentError> {
1005        let entity_id = entity.id;
1006        let mut entity = Some(entity);
1007
1008        if let Some(growing_arc) = self.growing.read().as_ref() {
1009            let mut growing = growing_arc.write();
1010            if growing.contains(entity_id) && growing.state().is_writable() {
1011                return growing.update_hot(
1012                    entity.take().expect("entity already moved"),
1013                    modified_columns,
1014                );
1015            }
1016        }
1017
1018        let segment_id = self.entity_segment.read().get(&entity_id).copied();
1019        if let Some(seg_id) = segment_id {
1020            if let Some(growing_arc) = self.growing.read().as_ref() {
1021                let mut growing = growing_arc.write();
1022                if growing.id() == seg_id && growing.state().is_writable() {
1023                    return growing.update_hot(
1024                        entity.take().expect("entity already moved"),
1025                        modified_columns,
1026                    );
1027                }
1028            }
1029        }
1030
1031        if let Some(entity) = entity.take() {
1032            return self.rewrite_sealed_entity_into_growing(entity, None);
1033        }
1034
1035        Err(SegmentError::NotFound(entity_id))
1036    }
1037
1038    /// HOT-update an entity and, optionally, replace its metadata while
1039    /// holding the segment write lock only once.
1040    pub fn update_hot_with_metadata(
1041        &self,
1042        entity: UnifiedEntity,
1043        modified_columns: &[String],
1044        metadata: Option<&Metadata>,
1045    ) -> Result<(), SegmentError> {
1046        let entity_id = entity.id;
1047        let mut entity = Some(entity);
1048
1049        if let Some(growing_arc) = self.growing.read().as_ref() {
1050            let mut growing = growing_arc.write();
1051            if growing.contains(entity_id) && growing.state().is_writable() {
1052                growing.update_hot(
1053                    entity.take().expect("entity already moved"),
1054                    modified_columns,
1055                )?;
1056                if let Some(metadata) = metadata {
1057                    growing.set_metadata(entity_id, metadata.clone())?;
1058                }
1059                return Ok(());
1060            }
1061        }
1062
1063        let segment_id = self.entity_segment.read().get(&entity_id).copied();
1064        if let Some(seg_id) = segment_id {
1065            if let Some(growing_arc) = self.growing.read().as_ref() {
1066                let mut growing = growing_arc.write();
1067                if growing.id() == seg_id && growing.state().is_writable() {
1068                    growing.update_hot(
1069                        entity.take().expect("entity already moved"),
1070                        modified_columns,
1071                    )?;
1072                    if let Some(metadata) = metadata {
1073                        growing.set_metadata(entity_id, metadata.clone())?;
1074                    }
1075                    return Ok(());
1076                }
1077            }
1078        }
1079
1080        if let Some(entity) = entity.take() {
1081            return self.rewrite_sealed_entity_into_growing(entity, metadata);
1082        }
1083
1084        Err(SegmentError::NotFound(entity_id))
1085    }
1086
1087    /// Batch HOT-update multiple entities while holding the growing-segment
1088    /// write lock only once when possible.
1089    pub fn update_hot_batch_with_metadata<'a, I>(&self, items: I) -> Result<(), SegmentError>
1090    where
1091        I: IntoIterator<Item = (&'a UnifiedEntity, &'a [String], Option<&'a Metadata>)>,
1092    {
1093        let items: Vec<(&UnifiedEntity, &[String], Option<&Metadata>)> =
1094            items.into_iter().collect();
1095        if items.is_empty() {
1096            return Ok(());
1097        }
1098
1099        if let Some(growing_arc) = self.growing.read().as_ref() {
1100            let mut growing = growing_arc.write();
1101            if growing.state().is_writable() {
1102                match growing.update_hot_batch_with_metadata(items.iter().copied()) {
1103                    Ok(()) => return Ok(()),
1104                    Err(SegmentError::NotFound(_)) => {}
1105                    Err(other) => return Err(other),
1106                }
1107            }
1108        }
1109
1110        for (entity, modified_columns, metadata) in items {
1111            self.update_hot_with_metadata(entity.clone(), modified_columns, metadata)?;
1112        }
1113        Ok(())
1114    }
1115
1116    /// Delete an entity
1117    pub fn delete(&self, id: EntityId) -> Result<bool, SegmentError> {
1118        // Fast path: probe the growing segment directly — covers entities inserted via
1119        // insert() which no longer writes to entity_segment, and bulk-inserted entities.
1120        if let Some(growing_arc) = self.growing.read().as_ref() {
1121            let mut growing = growing_arc.write();
1122            if growing.contains(id) && growing.state().is_writable() {
1123                let seg_id = growing.id();
1124                let deleted = growing.delete(id)?;
1125                if deleted {
1126                    self.entity_segment.write().remove(&id);
1127                    self.total_entities_atomic.fetch_sub(1, Ordering::Relaxed);
1128                    self.emit(LifecycleEvent::EntityDeleted(id, seg_id));
1129                }
1130                return Ok(deleted);
1131            }
1132        }
1133
1134        // Fallback: check entity_segment map (populated for older insert() paths
1135        // or entities that were in a previous growing segment).
1136        let segment_id = self.entity_segment.read().get(&id).copied();
1137
1138        if let Some(seg_id) = segment_id {
1139            if let Some(growing_arc) = self.growing.read().as_ref() {
1140                let mut growing = growing_arc.write();
1141                if growing.id() == seg_id && growing.state().is_writable() {
1142                    let deleted = growing.delete(id)?;
1143                    if deleted {
1144                        self.entity_segment.write().remove(&id);
1145                        self.total_entities_atomic.fetch_sub(1, Ordering::Relaxed);
1146                        self.emit(LifecycleEvent::EntityDeleted(id, seg_id));
1147                    }
1148                    return Ok(deleted);
1149                }
1150            }
1151        }
1152
1153        // Fallback: entity is in a sealed segment (bulk-inserted, not in entity_segment map).
1154        // Single write-lock per segment to avoid TOCTOU race between contains() and force_delete().
1155        {
1156            let sealed = self.sealed.read();
1157            for segment_arc in sealed.iter() {
1158                let mut seg = segment_arc.write();
1159                let seg_id = seg.id();
1160                if seg.contains(id) {
1161                    let deleted = seg.force_delete(id);
1162                    drop(seg);
1163                    if deleted {
1164                        self.entity_segment.write().remove(&id);
1165                        self.total_entities_atomic.fetch_sub(1, Ordering::Relaxed);
1166                        self.emit(LifecycleEvent::EntityDeleted(id, seg_id));
1167                    }
1168                    return Ok(deleted);
1169                }
1170            }
1171        }
1172
1173        Ok(false)
1174    }
1175
1176    pub fn delete_batch(&self, ids: &[EntityId]) -> Result<Vec<EntityId>, SegmentError> {
1177        if ids.is_empty() {
1178            return Ok(Vec::new());
1179        }
1180
1181        let mut deleted_ids = Vec::with_capacity(ids.len());
1182
1183        if let Some(growing_arc) = self.growing.read().as_ref() {
1184            let mut growing = growing_arc.write();
1185            if growing.state().is_writable() {
1186                let seg_id = growing.id();
1187                let deleted = growing.delete_batch(ids)?;
1188                if !deleted.is_empty() {
1189                    {
1190                        let mut entity_segment = self.entity_segment.write();
1191                        for id in &deleted {
1192                            entity_segment.remove(id);
1193                        }
1194                    }
1195                    self.total_entities_atomic
1196                        .fetch_sub(deleted.len() as u64, Ordering::Relaxed);
1197                    for id in &deleted {
1198                        self.emit(LifecycleEvent::EntityDeleted(*id, seg_id));
1199                    }
1200                    deleted_ids.extend(deleted);
1201                }
1202            }
1203        }
1204
1205        if deleted_ids.len() == ids.len() {
1206            return Ok(deleted_ids);
1207        }
1208
1209        let deleted_set: std::collections::HashSet<EntityId> =
1210            deleted_ids.iter().copied().collect();
1211        for &id in ids {
1212            if deleted_set.contains(&id) {
1213                continue;
1214            }
1215            if self.delete(id)? {
1216                deleted_ids.push(id);
1217            }
1218        }
1219
1220        Ok(deleted_ids)
1221    }
1222
1223    /// Get metadata for an entity
1224    pub fn get_metadata(&self, id: EntityId) -> Option<Metadata> {
1225        // Fast path: probe growing segment directly (no entity_segment needed).
1226        if let Some(growing_arc) = self.growing.read().as_ref() {
1227            let growing = growing_arc.read();
1228            if growing.contains(id) {
1229                return growing.get_metadata(id);
1230            }
1231        }
1232
1233        // Fallback: entity_segment map (for pre-existing or sealed entities)
1234        let segment_id = self.entity_segment.read().get(&id).copied();
1235
1236        if let Some(seg_id) = segment_id {
1237            if let Some(growing_arc) = self.growing.read().as_ref() {
1238                let growing = growing_arc.read();
1239                if growing.id() == seg_id {
1240                    return growing.get_metadata(id);
1241                }
1242            }
1243
1244            let sealed = self.sealed.read();
1245            for segment in sealed.iter() {
1246                if segment.id() == seg_id {
1247                    return segment.get_metadata(id);
1248                }
1249            }
1250        }
1251
1252        if let Some(segment_arc) = self.find_sealed_segment_arc(id) {
1253            return segment_arc.read().get_metadata(id);
1254        }
1255
1256        None
1257    }
1258
1259    /// Set metadata for an entity
1260    pub fn set_metadata(&self, id: EntityId, metadata: Metadata) -> Result<(), SegmentError> {
1261        // Fast path: probe growing segment directly — covers entities inserted via
1262        // insert() which no longer writes to entity_segment.
1263        if let Some(growing_arc) = self.growing.read().as_ref() {
1264            let mut growing = growing_arc.write();
1265            if growing.contains(id) && growing.state().is_writable() {
1266                return growing.set_metadata(id, metadata);
1267            }
1268        }
1269
1270        // Fallback: entity_segment map (sealed or pre-atomic-path entities)
1271        let segment_id = self.entity_segment.read().get(&id).copied();
1272
1273        if let Some(seg_id) = segment_id {
1274            if let Some(growing_arc) = self.growing.read().as_ref() {
1275                let mut growing = growing_arc.write();
1276                if growing.id() == seg_id && growing.state().is_writable() {
1277                    return growing.set_metadata(id, metadata);
1278                }
1279            }
1280        }
1281
1282        if let Some(entity) = self.get(id) {
1283            return self.rewrite_sealed_entity_into_growing(entity, Some(&metadata));
1284        }
1285
1286        Err(SegmentError::NotFound(id))
1287    }
1288
1289    /// Check if growing segment should be sealed
1290    fn maybe_seal_growing(&self) -> Result<(), SegmentError> {
1291        let should_seal = {
1292            let growing_opt = self.growing.read();
1293            if let Some(growing_arc) = growing_opt.as_ref() {
1294                let growing = growing_arc.read();
1295                growing.should_seal(&self.config.segment_config)
1296                    || growing.idle_secs() >= self.config.idle_seal_secs
1297            } else {
1298                false
1299            }
1300        };
1301
1302        if should_seal {
1303            self.seal_current()?;
1304        }
1305
1306        Ok(())
1307    }
1308
1309    /// Seal the current growing segment
1310    pub fn seal_current(&self) -> Result<SegmentId, SegmentError> {
1311        // Keep topology publication atomic for cursors that capture growing
1312        // and sealed under the same lock order: growing, then sealed.
1313        let mut growing_slot = self.growing.write();
1314        if let Some(growing_arc) = growing_slot.take() {
1315            let mut growing = growing_arc.write();
1316            let seg_id = growing.id();
1317            let entity_count = growing.stats().entity_count as u64;
1318
1319            // Seal it
1320            growing.seal()?;
1321
1322            // Move to sealed list (we need to extract it from the Arc)
1323            drop(growing); // Release write lock
1324
1325            // In a real implementation, we'd convert to SealedSegment here
1326            // For now, we keep it as-is since GrowingSegment implements UnifiedSegment
1327            self.sealed.write().push(growing_arc);
1328            drop(growing_slot);
1329
1330            // Mark sealed segment pages all-visible — they're now immutable
1331            self.mark_sealed_pages_visible(entity_count);
1332
1333            // Update stats
1334            {
1335                let mut stats = self.stats.write();
1336                stats.growing_count = stats.growing_count.saturating_sub(1);
1337                stats.sealed_count += 1;
1338                stats.seal_ops += 1;
1339            }
1340
1341            self.emit(LifecycleEvent::SegmentSealed(seg_id));
1342
1343            return Ok(seg_id);
1344        }
1345
1346        Err(SegmentError::InvalidState(SegmentState::Sealed))
1347    }
1348
1349    /// Force seal (for testing/manual control)
1350    pub fn force_seal(&self) -> Result<Option<SegmentId>, SegmentError> {
1351        let has_growing = self.growing.read().is_some();
1352        if has_growing {
1353            Ok(Some(self.seal_current()?))
1354        } else {
1355            Ok(None)
1356        }
1357    }
1358
1359    /// Fraction of "pages" in sealed segments that are marked all-visible.
1360    ///
1361    /// Sealed segments are immutable so all their rows are safe for
1362    /// index-only scans. The growing segment is never counted (writes
1363    /// may be in-flight). Uses `rows_per_page = 256` (matching 8 KB pages
1364    /// with ~32-byte rows).
1365    ///
1366    /// Returns a value in `[0.0, 1.0]`. 1.0 when all sealed rows are
1367    /// visible; 0.0 when there are no sealed segments.
1368    pub fn all_visible_fraction(&self) -> f64 {
1369        const ROWS_PER_PAGE: u32 = 256;
1370        let sealed = self.sealed.read();
1371        if sealed.is_empty() {
1372            return 0.0;
1373        }
1374        let mut total_pages: u64 = 0;
1375        for seg_arc in sealed.iter() {
1376            let seg = seg_arc.read();
1377            let entity_count = seg.stats().entity_count as u64;
1378            let pages = entity_count.div_ceil(ROWS_PER_PAGE as u64);
1379            total_pages += pages;
1380        }
1381        if total_pages == 0 {
1382            return 0.0;
1383        }
1384        let visible = self.visibility_map.all_visible_count();
1385        (visible as f64 / total_pages as f64).min(1.0)
1386    }
1387
1388    /// Mark all pages of newly sealed segments as all-visible in the
1389    /// visibility map. Called internally after `seal_current`.
1390    fn mark_sealed_pages_visible(&self, seg_entity_count: u64) {
1391        const ROWS_PER_PAGE: u32 = 256;
1392        let existing_visible = self.visibility_map.all_visible_count();
1393        // Append pages starting after the last known visible page
1394        let start_page = existing_visible as u32;
1395        let new_pages = seg_entity_count.div_ceil(ROWS_PER_PAGE as u64);
1396        let end_page = start_page + new_pages as u32;
1397        self.visibility_map.mark_range_visible(start_page, end_page);
1398    }
1399
1400    /// Probe a unique-key lookup in each segment under the same entity
1401    /// locks used by scans and writes. Lookup state is rebuilt lazily after
1402    /// recovery, consolidation, or a key-changing mutation.
1403    pub(crate) fn find_unique_key_conflict(
1404        &self,
1405        columns: &[Vec<String>],
1406        key_index: usize,
1407        signatures: &[String],
1408        exclude_id: Option<EntityId>,
1409        reserves_key: &impl Fn(&UnifiedEntity) -> bool,
1410    ) -> Option<EntityId> {
1411        if let Some(growing) = self.growing.read().as_ref() {
1412            if let Some(id) = growing.read().find_unique_key_conflict(
1413                columns,
1414                key_index,
1415                signatures,
1416                exclude_id,
1417                reserves_key,
1418            ) {
1419                return Some(id);
1420            }
1421        }
1422        for segment in self.sealed.read().iter() {
1423            if let Some(id) = segment.read().find_unique_key_conflict(
1424                columns,
1425                key_index,
1426                signatures,
1427                exclude_id,
1428                reserves_key,
1429            ) {
1430                return Some(id);
1431            }
1432        }
1433        None
1434    }
1435
1436    /// Iterate over all entities in-place without collecting into a Vec.
1437    ///
1438    /// The callback receives a reference to each entity. Return `true` to
1439    /// continue iteration, `false` to stop early (e.g. when a LIMIT is reached).
1440    /// This avoids the allocation and cloning overhead of `query_all`.
1441    pub fn for_each_entity<F>(&self, callback: F)
1442    where
1443        F: FnMut(&UnifiedEntity) -> bool,
1444    {
1445        self.for_each_entity_in_segments(|_| true, || true, callback);
1446    }
1447
1448    /// Segment identities and mutation counters, sampled without scanning rows.
1449    pub(crate) fn checkpoint_revisions(&self) -> Vec<(u64, u64)> {
1450        let growing = self.growing.read();
1451        let sealed = self.sealed.read();
1452        growing
1453            .iter()
1454            .chain(sealed.iter())
1455            .map(|segment| {
1456                let segment = segment.read();
1457                (segment.id(), segment.checkpoint_revision())
1458            })
1459            .collect()
1460    }
1461
1462    /// Reuse the derived metadata fingerprint only while its rows and stats match.
1463    pub(crate) fn cached_physical_root(&self, seed: u64, compute: impl FnOnce() -> u64) -> u64 {
1464        let segments = self.checkpoint_revisions();
1465        let mut cache = self.physical_root_cache.lock();
1466        if let Some(previous) = cache.as_ref() {
1467            if previous.seed == seed && previous.segments == segments {
1468                return previous.root;
1469            }
1470        }
1471        let root = compute();
1472        *cache = Some(PhysicalRootCacheEntry {
1473            segments,
1474            seed,
1475            root,
1476        });
1477        root
1478    }
1479
1480    /// Visit borrowed rows with metadata under the same segment read guard.
1481    /// Callbacks must not re-enter this manager while the guard is held.
1482    pub(crate) fn for_each_entity_with_metadata(
1483        &self,
1484        mut callback: impl FnMut(&UnifiedEntity, Option<Metadata>) -> bool,
1485    ) {
1486        if let Some(growing_arc) = self.growing.read().as_ref() {
1487            let growing = growing_arc.read();
1488            if !growing.for_each_fast(|entity| callback(entity, growing.get_metadata(entity.id))) {
1489                return;
1490            }
1491        }
1492        let sealed = self.sealed.read();
1493        for segment_arc in sealed.iter() {
1494            let segment = segment_arc.read();
1495            if !segment.for_each_fast(|entity| callback(entity, segment.get_metadata(entity.id))) {
1496                return;
1497            }
1498        }
1499    }
1500
1501    fn for_each_entity_in_segments<F>(
1502        &self,
1503        segment_filter: impl Fn(&GrowingSegment) -> bool,
1504        mut before_segment: impl FnMut() -> bool,
1505        mut callback: F,
1506    ) where
1507        F: FnMut(&UnifiedEntity) -> bool,
1508    {
1509        // Growing segment — direct iteration (no Box<dyn>)
1510        // Try non-blocking read first; fall back to blocking only when a writer
1511        // is actively holding the write lock (rare in read-heavy workloads).
1512        if let Some(growing_arc) = self.growing.read().as_ref() {
1513            if !before_segment() {
1514                return;
1515            }
1516            let growing = if let Some(g) = growing_arc.try_read() {
1517                g
1518            } else {
1519                growing_arc.read()
1520            };
1521            if segment_filter(&growing) && !growing.for_each_fast(&mut callback) {
1522                return;
1523            }
1524        }
1525
1526        // Sealed segments
1527        let sealed = self.sealed.read();
1528        for segment_arc in sealed.iter() {
1529            if !before_segment() {
1530                return;
1531            }
1532            let segment = segment_arc.read();
1533            if segment_filter(&segment) && !segment.for_each_fast(&mut callback) {
1534                return;
1535            }
1536        }
1537    }
1538
1539    /// Parallel fold across all entities. Each sealed segment is
1540    /// processed on its own rayon task; the growing segment stays on
1541    /// the caller thread (its read lock is briefly held).
1542    ///
1543    /// - `init` builds a fresh accumulator per thread.
1544    /// - `fold` mutates an accumulator with one entity at a time.
1545    /// - `reduce` combines two accumulators into one.
1546    ///
1547    /// The returned value is the reduction of every per-thread
1548    /// accumulator. Use this for aggregate-shape workloads (GROUP BY)
1549    /// where per-thread partial state can be merged cheaply.
1550    ///
1551    /// NOTE: when there are 0 or 1 sealed segments, the parallel path
1552    /// is skipped and the work runs sequentially to avoid rayon
1553    /// overhead on tiny tables.
1554    pub fn fold_entities_parallel<T, FInit, FFold, FReduce>(
1555        &self,
1556        init: FInit,
1557        fold: FFold,
1558        reduce: FReduce,
1559    ) -> T
1560    where
1561        T: Send,
1562        FInit: Fn() -> T + Send + Sync,
1563        FFold: Fn(T, &UnifiedEntity) -> T + Send + Sync,
1564        FReduce: Fn(T, T) -> T + Send + Sync,
1565    {
1566        use rayon::prelude::*;
1567
1568        // Growing segment — always sequential (single writer lock,
1569        // usually small working set).
1570        let mut acc = init();
1571        if let Some(growing_arc) = self.growing.read().as_ref() {
1572            let growing = if let Some(g) = growing_arc.try_read() {
1573                g
1574            } else {
1575                growing_arc.read()
1576            };
1577            growing.for_each_fast(|entity| {
1578                acc = fold(std::mem::replace(&mut acc, init()), entity);
1579                true
1580            });
1581        }
1582
1583        // Sealed segments — snapshot the Arc list under the read lock,
1584        // then drop the lock so rayon workers can fan out without
1585        // blocking writers.
1586        let segments: Vec<_> = {
1587            let sealed = self.sealed.read();
1588            sealed.iter().cloned().collect()
1589        };
1590
1591        if segments.len() <= 1 {
1592            for seg_arc in &segments {
1593                let seg = seg_arc.read();
1594                seg.for_each_fast(|entity| {
1595                    acc = fold(std::mem::replace(&mut acc, init()), entity);
1596                    true
1597                });
1598            }
1599            return acc;
1600        }
1601
1602        let sealed_acc = segments
1603            .into_par_iter()
1604            .map(|seg_arc| {
1605                let mut local = init();
1606                let seg = seg_arc.read();
1607                seg.for_each_fast(|entity| {
1608                    local = fold(std::mem::replace(&mut local, init()), entity);
1609                    true
1610                });
1611                local
1612            })
1613            .reduce(&init, &reduce);
1614
1615        reduce(acc, sealed_acc)
1616    }
1617
1618    /// Zone-map-aware iteration across all segments.
1619    ///
1620    /// Like `for_each_entity`, but checks `zone_preds` against each segment's
1621    /// column zone maps before iterating. Segments where any predicate can
1622    /// definitively prove no rows match are skipped entirely.
1623    ///
1624    /// `zone_preds`: slice of `(column_name, ZoneColPred)` extracted from the WHERE clause.
1625    /// Empty slice → same behaviour as `for_each_entity` (no pruning).
1626    pub fn for_each_entity_zoned<F>(&self, zone_preds: &[(&str, ZoneColPred<'_>)], mut callback: F)
1627    where
1628        F: FnMut(&UnifiedEntity) -> bool,
1629    {
1630        let _ = self.for_each_entity_zoned_with_stats(zone_preds, &mut callback);
1631    }
1632
1633    pub fn for_each_entity_zoned_with_stats<F>(
1634        &self,
1635        zone_preds: &[(&str, ZoneColPred<'_>)],
1636        mut callback: F,
1637    ) -> SegmentScanStats
1638    where
1639        F: FnMut(&UnifiedEntity) -> bool,
1640    {
1641        let mut scan_stats = SegmentScanStats::default();
1642        // Growing segment — never skip (it's receiving writes, zones are partial).
1643        // Try a non-blocking read first: if a writer is currently inserting
1644        // (holding the write lock), try_read() returns None and we fall back to
1645        // the blocking read.  In low-contention workloads (reads far outnumber
1646        // writes) the try_read() almost always succeeds and readers never stall.
1647        if let Some(growing_arc) = self.growing.read().as_ref() {
1648            scan_stats.segments_total += 1;
1649            scan_stats.segments_scanned += 1;
1650            let growing = if let Some(g) = growing_arc.try_read() {
1651                g
1652            } else {
1653                growing_arc.read()
1654            };
1655            if !growing.for_each_fast(&mut callback) {
1656                return scan_stats;
1657            }
1658        }
1659
1660        // Sealed segments — check zone maps before iterating
1661        let sealed = self.sealed.read();
1662        for segment_arc in sealed.iter() {
1663            scan_stats.segments_total += 1;
1664            let segment = segment_arc.read();
1665            if !zone_preds.is_empty() && segment.can_skip_zone_preds(zone_preds) {
1666                scan_stats.segments_pruned += 1;
1667                continue; // entire segment pruned
1668            }
1669            scan_stats.segments_scanned += 1;
1670            if !segment.for_each_fast(&mut callback) {
1671                return scan_stats;
1672            }
1673        }
1674        scan_stats
1675    }
1676
1677    /// Zone-map-aware parallel query.
1678    ///
1679    /// Like `query_all` but applies `zone_preds` on the main thread to
1680    /// prune sealed segments before spawning workers — segments that
1681    /// provably contain no matching rows are skipped entirely.
1682    ///
1683    /// Zone check runs single-threaded (it reads per-segment metadata,
1684    /// not row data), so it's cheap. Surviving segments are then scanned
1685    /// in parallel using `std::thread::scope` when there are > 1 of them.
1686    pub fn query_all_zoned<F>(
1687        &self,
1688        zone_preds: &[(&str, ZoneColPred<'_>)],
1689        filter: F,
1690    ) -> Vec<UnifiedEntity>
1691    where
1692        F: Fn(&UnifiedEntity) -> bool + Sync,
1693    {
1694        self.query_all_zoned_with_stats(zone_preds, filter).0
1695    }
1696
1697    pub fn query_all_zoned_with_stats<F>(
1698        &self,
1699        zone_preds: &[(&str, ZoneColPred<'_>)],
1700        filter: F,
1701    ) -> (Vec<UnifiedEntity>, SegmentScanStats)
1702    where
1703        F: Fn(&UnifiedEntity) -> bool + Sync,
1704    {
1705        let mut results = Vec::new();
1706        let mut scan_stats = SegmentScanStats::default();
1707
1708        // Growing segment — always scan, no zone skip (zones are partial).
1709        // Non-blocking try_read() avoids stalling behind in-progress inserts.
1710        if let Some(growing_arc) = self.growing.read().as_ref() {
1711            scan_stats.segments_total += 1;
1712            scan_stats.segments_scanned += 1;
1713            let growing = if let Some(g) = growing_arc.try_read() {
1714                g
1715            } else {
1716                growing_arc.read()
1717            };
1718            results.extend(growing.iter().filter(|e| filter(e)).cloned());
1719        }
1720
1721        // Sealed segments: zone-prune on main thread, then scan in parallel.
1722        let sealed = self.sealed.read();
1723        // Collect only the segments that survive zone-predicate pruning.
1724        let surviving: Vec<_> = sealed
1725            .iter()
1726            .filter(|seg_arc| {
1727                scan_stats.segments_total += 1;
1728                if zone_preds.is_empty() {
1729                    scan_stats.segments_scanned += 1;
1730                    return true;
1731                }
1732                let seg = seg_arc.read();
1733                if seg.can_skip_zone_preds(zone_preds) {
1734                    scan_stats.segments_pruned += 1;
1735                    false
1736                } else {
1737                    scan_stats.segments_scanned += 1;
1738                    true
1739                }
1740            })
1741            .collect();
1742
1743        let use_parallel = surviving.len() > 1 && crate::runtime::SystemInfo::should_parallelize();
1744
1745        if use_parallel {
1746            let filter_ref = &filter;
1747            let segment_results: Vec<Vec<UnifiedEntity>> = std::thread::scope(|s| {
1748                surviving
1749                    .iter()
1750                    .map(|segment| {
1751                        s.spawn(move || {
1752                            segment
1753                                .read()
1754                                .iter()
1755                                .filter(|e| filter_ref(e))
1756                                .cloned()
1757                                .collect::<Vec<_>>()
1758                        })
1759                    })
1760                    .collect::<Vec<_>>()
1761                    .into_iter()
1762                    .map(|handle| handle.join().unwrap_or_default())
1763                    .collect()
1764            });
1765            for batch in segment_results {
1766                results.extend(batch);
1767            }
1768        } else {
1769            for segment_arc in surviving {
1770                let seg = segment_arc.read();
1771                results.extend(seg.iter().filter(|e| filter(e)).cloned());
1772            }
1773        }
1774
1775        (results, scan_stats)
1776    }
1777
1778    /// Visibility predicate for the `scan_*` family. `Some` delegates to the
1779    /// canonical `entity_visible_with_context`; `None` supports low-level
1780    /// callers that intentionally scan without a statement snapshot and keeps
1781    /// the documented resolver fallback — moderation gate plus hiding
1782    /// superseded physical versions — instead of showing every version.
1783    fn scan_entity_visible(snapshot: Option<&SnapshotContext>, entity: &UnifiedEntity) -> bool {
1784        match snapshot {
1785            Some(ctx) => entity_visible_with_context(Some(ctx), entity),
1786            None => {
1787                !crate::runtime::ai::moderation::entity_moderation_hidden(entity)
1788                    && entity.xmax == 0
1789            }
1790        }
1791    }
1792
1793    /// Scan every segment under an explicit MVCC snapshot.
1794    ///
1795    /// Visibility is evaluated while each segment iterator is active, before
1796    /// the caller's filter. Unlike the raw iteration methods, this entry point
1797    /// does not consult thread-local snapshot state, so it preserves the same
1798    /// view when invoked from a different thread.
1799    pub fn scan<F>(&self, snapshot: Option<&SnapshotContext>, filter: F) -> Vec<UnifiedEntity>
1800    where
1801        F: Fn(&UnifiedEntity) -> bool + Sync,
1802    {
1803        self.query_all(|entity| Self::scan_entity_visible(snapshot, entity) && filter(entity))
1804    }
1805
1806    /// Collect visible graph items, pruning only under the segment read guard.
1807    pub(crate) fn scan_graph_kind(
1808        &self,
1809        snapshot: Option<&SnapshotContext>,
1810        kind: GraphEntityKind,
1811    ) -> Vec<UnifiedEntity> {
1812        self.query_all_in_segments(
1813            |segment| segment.may_contain_graph_kind(kind),
1814            |entity| Self::scan_entity_visible(snapshot, entity) && kind.matches(&entity.kind),
1815        )
1816    }
1817
1818    /// Visit visible candidates in segments that may contain the requested kind.
1819    /// Non-graph items in those segments still reach the callback so work budgets
1820    /// charge every inspected visible candidate. RLS must run outside this callback.
1821    /// `before_segment` runs even for pruned segments; false stops the entire scan.
1822    pub(crate) fn scan_graph_candidates_for_each<F>(
1823        &self,
1824        snapshot: Option<&SnapshotContext>,
1825        kind: GraphEntityKind,
1826        before_segment: impl FnMut() -> bool,
1827        mut callback: F,
1828    ) where
1829        F: FnMut(&UnifiedEntity) -> bool,
1830    {
1831        self.for_each_entity_in_segments(
1832            |segment| segment.may_contain_graph_kind(kind),
1833            before_segment,
1834            |entity| !Self::scan_entity_visible(snapshot, entity) || callback(entity),
1835        );
1836    }
1837
1838    /// Visit every entity visible under an explicit MVCC snapshot.
1839    ///
1840    /// Returning `false` from `callback` stops the scan early. Hidden entities
1841    /// never reach the callback and therefore cannot stop the scan.
1842    pub fn scan_for_each<F>(&self, snapshot: Option<&SnapshotContext>, mut callback: F)
1843    where
1844        F: FnMut(&UnifiedEntity) -> bool,
1845    {
1846        self.for_each_entity(|entity| {
1847            !Self::scan_entity_visible(snapshot, entity) || callback(entity)
1848        });
1849    }
1850
1851    /// Capture segment membership and append boundaries, then hydrate bounded
1852    /// batches. The consumer runs outside topology and segment locks, so scoring
1853    /// and RLS may re-enter storage and writers can progress between batches.
1854    /// Retired sources pin positions only; hydration uses current segments so
1855    /// mutations after consolidation are visible to the snapshot predicate.
1856    pub(crate) fn scan_batches(
1857        &self,
1858        snapshot: Option<&SnapshotContext>,
1859        mut before_work: impl FnMut() -> bool,
1860        mut consume: impl FnMut(&[UnifiedEntity]) -> bool,
1861    ) -> bool {
1862        let segments = {
1863            let growing = self.growing.read();
1864            let sealed = self.sealed.read();
1865            let mut segments = Vec::with_capacity(sealed.len() + usize::from(growing.is_some()));
1866            for segment in growing.iter().chain(sealed.iter()) {
1867                if !before_work() {
1868                    return false;
1869                }
1870                let cursor = segment.read().scan_cursor();
1871                segments.push((Arc::clone(segment), cursor));
1872            }
1873            segments
1874        };
1875        let mut ids = Vec::new();
1876        let mut batch = Vec::new();
1877        for (segment, mut cursor) in segments {
1878            while !cursor.finished() {
1879                ids.clear();
1880                batch.clear();
1881                let batch_size = cursor.remaining().min(super::segment::SCAN_BATCH_SIZE);
1882                ids.reserve_exact(batch_size);
1883                batch.reserve_exact(batch_size);
1884                {
1885                    let segment = segment.read();
1886                    if !segment.scan_batch(&mut cursor, &mut before_work, &mut |id| ids.push(id)) {
1887                        return false;
1888                    }
1889                }
1890                // Sources can retire between batches. Consult authoritative storage
1891                // after releasing the source guard, just as the former ID-list scan did.
1892                if !before_work() {
1893                    return false;
1894                }
1895                self.for_each_id(&ids, |_, entity| {
1896                    if Self::scan_entity_visible(snapshot, entity) {
1897                        batch.push(entity.clone());
1898                    }
1899                });
1900                if !before_work() {
1901                    return false;
1902                }
1903                if !consume(&batch) {
1904                    return false;
1905                }
1906            }
1907        }
1908        true
1909    }
1910
1911    /// Fold entities visible under an explicit MVCC snapshot in parallel.
1912    pub fn scan_fold_parallel<T, FInit, FFold, FReduce>(
1913        &self,
1914        snapshot: Option<&SnapshotContext>,
1915        init: FInit,
1916        fold: FFold,
1917        reduce: FReduce,
1918    ) -> T
1919    where
1920        T: Send,
1921        FInit: Fn() -> T + Send + Sync,
1922        FFold: Fn(T, &UnifiedEntity) -> T + Send + Sync,
1923        FReduce: Fn(T, T) -> T + Send + Sync,
1924    {
1925        self.fold_entities_parallel(
1926            init,
1927            |acc, entity| {
1928                if Self::scan_entity_visible(snapshot, entity) {
1929                    fold(acc, entity)
1930                } else {
1931                    acc
1932                }
1933            },
1934            reduce,
1935        )
1936    }
1937
1938    /// Visit zone-map candidates visible under an explicit MVCC snapshot.
1939    pub fn scan_for_each_zoned_with_stats<F>(
1940        &self,
1941        snapshot: Option<&SnapshotContext>,
1942        zone_preds: &[(&str, ZoneColPred<'_>)],
1943        mut callback: F,
1944    ) -> SegmentScanStats
1945    where
1946        F: FnMut(&UnifiedEntity) -> bool,
1947    {
1948        self.for_each_entity_zoned_with_stats(zone_preds, |entity| {
1949            !Self::scan_entity_visible(snapshot, entity) || callback(entity)
1950        })
1951    }
1952
1953    /// Collect zone-map candidates visible under an explicit MVCC snapshot.
1954    pub fn scan_zoned_with_stats<F>(
1955        &self,
1956        snapshot: Option<&SnapshotContext>,
1957        zone_preds: &[(&str, ZoneColPred<'_>)],
1958        filter: F,
1959    ) -> (Vec<UnifiedEntity>, SegmentScanStats)
1960    where
1961        F: Fn(&UnifiedEntity) -> bool + Sync,
1962    {
1963        self.query_all_zoned_with_stats(zone_preds, |entity| {
1964            Self::scan_entity_visible(snapshot, entity) && filter(entity)
1965        })
1966    }
1967
1968    /// Query across all segments. Uses parallel scanning for sealed segments
1969    /// when more than one sealed segment exists.
1970    pub fn query_all<F>(&self, filter: F) -> Vec<UnifiedEntity>
1971    where
1972        F: Fn(&UnifiedEntity) -> bool + Sync,
1973    {
1974        self.query_all_in_segments(|_| true, filter)
1975    }
1976
1977    fn query_all_in_segments<F>(
1978        &self,
1979        segment_filter: impl Fn(&GrowingSegment) -> bool + Sync,
1980        filter: F,
1981    ) -> Vec<UnifiedEntity>
1982    where
1983        F: Fn(&UnifiedEntity) -> bool + Sync,
1984    {
1985        let mut results = Vec::new();
1986
1987        // Query growing segment — try non-blocking read first (avoids stalling
1988        // behind an in-progress insert; falls back to blocking if writer is active).
1989        if let Some(growing_arc) = self.growing.read().as_ref() {
1990            let growing = if let Some(g) = growing_arc.try_read() {
1991                g
1992            } else {
1993                growing_arc.read()
1994            };
1995            if segment_filter(&growing) {
1996                results.extend(growing.iter().filter(|e| filter(e)).cloned());
1997            }
1998        }
1999
2000        // Query sealed segments — parallel when multiple exist AND multi-core
2001        let sealed = self.sealed.read();
2002        let use_parallel = sealed.len() > 1 && crate::runtime::SystemInfo::should_parallelize();
2003        if use_parallel {
2004            let filter_ref = &filter;
2005            let segment_filter_ref = &segment_filter;
2006            let segment_results: Vec<Vec<UnifiedEntity>> = std::thread::scope(|s| {
2007                sealed
2008                    .iter()
2009                    .map(|segment| {
2010                        s.spawn(move || {
2011                            let segment = segment.read();
2012                            if segment_filter_ref(&segment) {
2013                                segment
2014                                    .iter()
2015                                    .filter(|e| filter_ref(e))
2016                                    .cloned()
2017                                    .collect::<Vec<_>>()
2018                            } else {
2019                                Vec::new()
2020                            }
2021                        })
2022                    })
2023                    .collect::<Vec<_>>()
2024                    .into_iter()
2025                    .map(|handle| handle.join().unwrap_or_default())
2026                    .collect()
2027            });
2028            for batch in segment_results {
2029                results.extend(batch);
2030            }
2031        } else {
2032            for segment in sealed.iter() {
2033                let seg = segment.read();
2034                if segment_filter(&seg) {
2035                    results.extend(seg.iter().filter(|e| filter(e)).cloned());
2036                }
2037            }
2038        }
2039
2040        results
2041    }
2042
2043    /// Probe exact segment membership for a key without materializing matching entities.
2044    ///
2045    /// Returns `false` only when every consulted segment proves absence.
2046    /// Missing segment state is conservative and returns `true`.
2047    pub fn bloom_may_contain_key(&self, key: &[u8]) -> bool {
2048        if let Some(growing_arc) = self.growing.read().as_ref() {
2049            let growing = growing_arc.read();
2050            if growing.may_contain_exact_key(key) {
2051                return true;
2052            }
2053        } else {
2054            return true;
2055        }
2056
2057        let sealed = self.sealed.read();
2058        for segment_arc in sealed.iter() {
2059            let segment = segment_arc.read();
2060            if segment.may_contain_exact_key(key) {
2061                return true;
2062            }
2063        }
2064
2065        false
2066    }
2067
2068    /// Filter by metadata across all segments
2069    pub fn filter_metadata(&self, filters: &[(String, MetadataFilter)]) -> Vec<EntityId> {
2070        let mut results = Vec::new();
2071
2072        // Growing segment
2073        if let Some(growing_arc) = self.growing.read().as_ref() {
2074            let growing = growing_arc.read();
2075            results.extend(growing.filter_metadata(filters));
2076        }
2077
2078        // Sealed segments
2079        let sealed = self.sealed.read();
2080        for segment in sealed.iter() {
2081            results.extend(segment.filter_metadata(filters));
2082        }
2083
2084        results
2085    }
2086
2087    /// Get entities by kind
2088    pub fn get_by_kind(&self, kind: &str) -> Vec<UnifiedEntity> {
2089        let mut results = Vec::new();
2090
2091        // Growing segment
2092        if let Some(growing_arc) = self.growing.read().as_ref() {
2093            let growing = growing_arc.read();
2094            for entity in growing.iter_kind(kind) {
2095                results.push(entity.clone());
2096            }
2097        }
2098
2099        // Sealed segments. Iterate through the read guard, not the
2100        // `Arc<RwLock<GrowingSegment>>` impl of `iter_kind` — that one cannot
2101        // hand out references across the lock, so it returns an empty iterator
2102        // and every sealed entity was silently missing from the result.
2103        let sealed = self.sealed.read();
2104        for segment_arc in sealed.iter() {
2105            let segment = segment_arc.read();
2106            for entity in segment.iter_kind(kind) {
2107                results.push(entity.clone());
2108            }
2109        }
2110
2111        results
2112    }
2113
2114    /// Count entities
2115    pub fn count(&self) -> usize {
2116        self.total_entities_atomic.load(Ordering::Relaxed) as usize
2117    }
2118
2119    /// Get all segment IDs
2120    pub fn segment_ids(&self) -> Vec<SegmentId> {
2121        let mut ids = Vec::new();
2122
2123        if let Some(growing_arc) = self.growing.read().as_ref() {
2124            ids.push(growing_arc.read().id());
2125        }
2126
2127        let sealed = self.sealed.read();
2128        for segment in sealed.iter() {
2129            ids.push(segment.id());
2130        }
2131
2132        ids.extend(self.archived.read().iter().copied());
2133
2134        ids
2135    }
2136
2137    /// Emit a lifecycle event.
2138    ///
2139    /// Perf: this used to push onto a `RwLock<Vec<LifecycleEvent>>`
2140    /// on every insert / delete / seal. Nobody consumes that vec
2141    /// today (no subscription API, `drain_events` has no callers),
2142    /// so the write lock + push was pure tax — and the vec grew
2143    /// unbounded in long-running processes.
2144    ///
2145    /// Current behaviour: no-op. If we ever want the hooks back,
2146    /// replace this with a bounded channel or an actual subscriber
2147    /// registry; the callers (`insert`, `delete`, `maybe_seal_growing`)
2148    /// already pass well-typed events.
2149    #[inline]
2150    #[allow(clippy::unused_self)]
2151    fn emit(&self, _event: LifecycleEvent) {}
2152
2153    /// Drain events. Kept for API compatibility; always returns
2154    /// empty because `emit` no longer buffers.
2155    pub fn drain_events(&self) -> Vec<LifecycleEvent> {
2156        std::mem::take(&mut *self.events.write())
2157    }
2158
2159    /// Run maintenance (would be called periodically in production)
2160    pub fn run_maintenance(&self) -> Result<(), SegmentError> {
2161        // Auto-seal idle segments
2162        self.maybe_seal_growing()?;
2163
2164        if self.config.enable_consolidation {
2165            self.consolidation_tick();
2166        }
2167
2168        Ok(())
2169    }
2170
2171    // ========================================================================
2172    // Consolidation — ADR 0073 §5
2173    // ========================================================================
2174
2175    /// One paced step of sealed-segment consolidation.
2176    ///
2177    /// Starts a run when a threshold has been crossed, copies at most
2178    /// `consolidation_entities_per_tick` live entities into the merged segment,
2179    /// and swaps once every source has been drained. Returns without finishing
2180    /// otherwise — the half-built merged segment waits for the next tick.
2181    fn consolidation_tick(&self) {
2182        // Drop the read guard before `start_consolidation` takes the write
2183        // guard: `parking_lot` locks are not reentrant.
2184        let running = self.consolidation.read().is_some();
2185        if !running && !self.start_consolidation() {
2186            return;
2187        }
2188
2189        // Keep the accounting guard through publication: the merged allocation
2190        // must never disappear between the in-flight and active inventories.
2191        let mut guard = self.consolidation.write();
2192        let Some(run) = guard.as_mut() else {
2193            return;
2194        };
2195        self.copy_bounded(run);
2196        if run.cursor >= run.sources.len() {
2197            if let Some(run) = guard.take() {
2198                self.finish_consolidation(run);
2199            }
2200        }
2201    }
2202
2203    /// Evaluate the trigger and, when it fires, open a consolidation run.
2204    ///
2205    /// Returns `true` when a run was started.
2206    fn start_consolidation(&self) -> bool {
2207        let sources = self.select_candidates();
2208        self.start_consolidation_from_sources(sources)
2209    }
2210
2211    fn start_consolidation_from_sources(&self, sources: Vec<SegmentId>) -> bool {
2212        if sources.len() < 2 && !self.candidates_carry_tombstones(&sources) {
2213            return false;
2214        }
2215
2216        let merged_id = self.next_segment_id.fetch_add(1, Ordering::SeqCst);
2217        let merged = GrowingSegment::new(merged_id, &self.collection);
2218
2219        *self.consolidation.write() = Some(Consolidation {
2220            sources: sources
2221                .into_iter()
2222                .map(|id| SourceProgress {
2223                    id,
2224                    copied: Vec::new(),
2225                    tombstones_at_open: None,
2226                })
2227                .collect(),
2228            merged_id,
2229            merged,
2230            cursor: 0,
2231            pending_ids: Vec::new(),
2232            pending_cursor: 0,
2233            entities_copied: 0,
2234        });
2235
2236        self.stats.write().consolidation.runs_started += 1;
2237        true
2238    }
2239
2240    /// Run one paced consolidation tick because admission pressure needs
2241    /// reclaimable bytes, even if the background thresholds have not fired.
2242    ///
2243    /// Returns true when the call started or advanced a consolidation run.
2244    pub fn pressure_consolidation_tick(&self) -> bool {
2245        if !self.config.enable_consolidation {
2246            return false;
2247        }
2248
2249        let running = self.consolidation.read().is_some();
2250        if !running {
2251            let sources = self.dirty_sealed_segments();
2252            if !self.start_consolidation_from_sources(sources) {
2253                return false;
2254            }
2255        }
2256
2257        self.consolidation_tick();
2258        true
2259    }
2260
2261    /// Which sealed segments this collection should merge, if any.
2262    ///
2263    /// Three thresholds, any of which arms consolidation:
2264    ///
2265    /// * **sealed-segment count** above `max_sealed_segments` — every sealed
2266    ///   segment merges, which is what that knob always claimed to do.
2267    /// * **tombstone ratio** — dead entities over total entities across the
2268    ///   sealed set, past [`CONSOLIDATION_TOMBSTONE_RATIO`].
2269    /// * **fragmentation** — reclaimable bytes over held bytes, past
2270    ///   [`CONSOLIDATION_FRAGMENTATION_RATIO`].
2271    ///
2272    /// The count trigger takes every sealed segment; the two budget triggers
2273    /// take only the segments that actually carry tombstones, so a clean
2274    /// segment is never rewritten for nothing.
2275    fn select_candidates(&self) -> Vec<SegmentId> {
2276        let sealed = self.sealed.read();
2277        if sealed.is_empty() {
2278            return Vec::new();
2279        }
2280
2281        if sealed.len() > self.config.max_sealed_segments {
2282            return sealed.iter().map(|segment| segment.read().id()).collect();
2283        }
2284
2285        let mut live = 0usize;
2286        let mut tombstones = 0usize;
2287        let mut held = 0u64;
2288        let mut reclaimable = 0u64;
2289        let mut dirty = Vec::new();
2290
2291        for segment_arc in sealed.iter() {
2292            let segment = segment_arc.read();
2293            live += segment.live_entity_count();
2294            tombstones += segment.tombstone_count();
2295            held += segment.resident_bytes();
2296            reclaimable += segment.reclaimable_bytes();
2297            if segment.tombstone_count() > 0 {
2298                dirty.push(segment.id());
2299            }
2300        }
2301
2302        let total = live + tombstones;
2303        let tombstone_ratio = if total == 0 {
2304            0.0
2305        } else {
2306            tombstones as f64 / total as f64
2307        };
2308        let fragmentation = if held == 0 {
2309            0.0
2310        } else {
2311            reclaimable as f64 / held as f64
2312        };
2313
2314        if tombstone_ratio >= CONSOLIDATION_TOMBSTONE_RATIO
2315            || fragmentation >= CONSOLIDATION_FRAGMENTATION_RATIO
2316        {
2317            return dirty;
2318        }
2319
2320        Vec::new()
2321    }
2322
2323    fn dirty_sealed_segments(&self) -> Vec<SegmentId> {
2324        self.sealed
2325            .read()
2326            .iter()
2327            .filter_map(|segment_arc| {
2328                let segment = segment_arc.read();
2329                (segment.reclaimable_bytes() > 0).then(|| segment.id())
2330            })
2331            .collect()
2332    }
2333
2334    /// A single candidate is still worth merging when it carries tombstones —
2335    /// the merge drops them. A single clean candidate is not.
2336    fn candidates_carry_tombstones(&self, sources: &[SegmentId]) -> bool {
2337        if sources.is_empty() {
2338            return false;
2339        }
2340        let sealed = self.sealed.read();
2341        sealed.iter().any(|segment_arc| {
2342            let segment = segment_arc.read();
2343            sources.contains(&segment.id()) && segment.tombstone_count() > 0
2344        })
2345    }
2346
2347    fn sealed_segment(&self, id: SegmentId) -> Option<Arc<RwLock<GrowingSegment>>> {
2348        let sealed = self.sealed.read();
2349        sealed
2350            .iter()
2351            .find(|segment| segment.read().id() == id)
2352            .map(Arc::clone)
2353    }
2354
2355    /// Copy at most one tick's worth of live entities into the merged segment.
2356    ///
2357    /// The per-tick bound is the pacing contract: a tick's cost is O(bound),
2358    /// independent of how many entities the run still has to move.
2359    fn copy_bounded(&self, run: &mut Consolidation) {
2360        let mut budget = self.config.consolidation_entities_per_tick;
2361
2362        while budget > 0 && run.cursor < run.sources.len() {
2363            let source_id = run.sources[run.cursor].id;
2364            let Some(source_arc) = self.sealed_segment(source_id) else {
2365                // The source vanished. Only consolidation removes sealed
2366                // segments and it is single-threaded per collection, so this
2367                // cannot happen today — skip it rather than resurrect its rows.
2368                run.cursor += 1;
2369                run.pending_ids.clear();
2370                run.pending_cursor = 0;
2371                continue;
2372            };
2373
2374            if run.sources[run.cursor].tombstones_at_open.is_none() {
2375                let source = source_arc.read();
2376                run.pending_ids = source.live_entity_ids();
2377                run.pending_cursor = 0;
2378                run.sources[run.cursor].tombstones_at_open = Some(source.tombstone_count());
2379            }
2380
2381            {
2382                let source = source_arc.read();
2383                while budget > 0 && run.pending_cursor < run.pending_ids.len() {
2384                    let id = run.pending_ids[run.pending_cursor];
2385                    run.pending_cursor += 1;
2386                    budget -= 1;
2387
2388                    // Tombstoned between the snapshot and now — it must not be
2389                    // resurrected into the merged segment.
2390                    let Some(entity) = source.get(id) else {
2391                        continue;
2392                    };
2393                    let metadata = source.get_metadata(id);
2394                    run.merged.adopt_entity(entity.clone(), metadata);
2395                    run.sources[run.cursor].copied.push(id);
2396                    run.entities_copied += 1;
2397                }
2398            }
2399
2400            if run.pending_cursor >= run.pending_ids.len() {
2401                run.cursor += 1;
2402                run.pending_ids.clear();
2403                run.pending_cursor = 0;
2404            }
2405        }
2406    }
2407
2408    /// Atomically replace the source segments with the merged one.
2409    ///
2410    /// The `sealed` write lock is the boundary: a reader holds the read lock
2411    /// for the whole of its scan, so it observes either the old set or the new
2412    /// set, never a gap and never both copies of a row.
2413    fn finish_consolidation(&self, mut run: Consolidation) {
2414        let mut sealed = self.sealed.write();
2415
2416        let mut positions = Vec::with_capacity(run.sources.len());
2417        for source in &run.sources {
2418            if let Some(index) = sealed
2419                .iter()
2420                .position(|segment| segment.read().id() == source.id)
2421            {
2422                positions.push(index);
2423            }
2424        }
2425        if positions.is_empty() {
2426            return;
2427        }
2428        positions.sort_unstable();
2429
2430        // Rows deleted from a source after we copied them must not come back.
2431        // A source whose tombstone count is unchanged saw no deletes while the
2432        // merge ran, so its copied rows need no per-row check.
2433        let mut stale = Vec::new();
2434        for source in &run.sources {
2435            let Some(source_arc) = sealed
2436                .iter()
2437                .find(|segment| segment.read().id() == source.id)
2438            else {
2439                continue;
2440            };
2441            let segment = source_arc.read();
2442            if source.tombstones_at_open == Some(segment.tombstone_count()) {
2443                continue;
2444            }
2445            stale.extend(
2446                source
2447                    .copied
2448                    .iter()
2449                    .copied()
2450                    .filter(|id| !segment.contains(*id)),
2451            );
2452        }
2453        for id in stale {
2454            run.merged.evict_entity(id);
2455        }
2456
2457        let reclaimed_bytes: u64 = positions
2458            .iter()
2459            .map(|&index| sealed[index].read().resident_bytes())
2460            .sum();
2461        let reclaimed_tombstones: u64 = positions
2462            .iter()
2463            .map(|&index| sealed[index].read().tombstone_count() as u64)
2464            .sum();
2465
2466        if run.merged.seal().is_err() {
2467            return;
2468        }
2469        let merged_bytes = run.merged.resident_bytes();
2470        let merged_arc = Arc::new(RwLock::new(run.merged));
2471
2472        {
2473            let mut retired = self.retired.write();
2474            retired.retain(|source| source.strong_count() > 0);
2475            for &index in positions.iter().rev() {
2476                let source = sealed.remove(index);
2477                if Arc::strong_count(&source) > 1 {
2478                    retired.push(Arc::downgrade(&source));
2479                }
2480            }
2481        }
2482        let insert_at = positions[0].min(sealed.len());
2483        sealed.insert(insert_at, Arc::clone(&merged_arc));
2484        drop(sealed);
2485
2486        // Remap the entity→segment hints that pointed at the retired sources.
2487        let source_ids: Vec<SegmentId> = run.sources.iter().map(|source| source.id).collect();
2488        {
2489            let mut entity_segment = self.entity_segment.write();
2490            for segment_id in entity_segment.values_mut() {
2491                if source_ids.contains(segment_id) {
2492                    *segment_id = run.merged_id;
2493                }
2494            }
2495        }
2496
2497        {
2498            let mut stats = self.stats.write();
2499            stats.sealed_count = stats
2500                .sealed_count
2501                .saturating_sub(positions.len())
2502                .saturating_add(1);
2503            let consolidation = &mut stats.consolidation;
2504            consolidation.runs_completed += 1;
2505            consolidation.segments_merged += positions.len() as u64;
2506            consolidation.tombstones_reclaimed += reclaimed_tombstones;
2507            consolidation.bytes_reclaimed += reclaimed_bytes.saturating_sub(merged_bytes);
2508        }
2509
2510        self.emit(LifecycleEvent::SegmentConsolidated {
2511            source: source_ids,
2512            target: run.merged_id,
2513        });
2514    }
2515
2516    /// Entities copied by the consolidation currently in flight, or `None` when
2517    /// none is running. Exposed for the pacing tests.
2518    #[cfg(test)]
2519    fn consolidation_progress(&self) -> Option<u64> {
2520        self.consolidation
2521            .read()
2522            .as_ref()
2523            .map(|run| run.entities_copied)
2524    }
2525}
2526
2527// Implement the Arc<RwLock<GrowingSegment>> as UnifiedSegment
2528// This is needed because we store growing segments in the sealed list after sealing
2529impl UnifiedSegment for Arc<RwLock<GrowingSegment>> {
2530    fn id(&self) -> SegmentId {
2531        self.read().id()
2532    }
2533
2534    fn state(&self) -> SegmentState {
2535        self.read().state()
2536    }
2537
2538    fn collection(&self) -> &str {
2539        // This is a limitation - we'd need to store collection in the Arc wrapper
2540        "unknown"
2541    }
2542
2543    fn stats(&self) -> SegmentStats {
2544        self.read().stats()
2545    }
2546
2547    fn entity_count(&self) -> usize {
2548        self.read().entity_count()
2549    }
2550
2551    fn contains(&self, id: EntityId) -> bool {
2552        self.read().contains(id)
2553    }
2554
2555    fn get(&self, id: EntityId) -> Option<&UnifiedEntity> {
2556        // This is tricky with RwLock - we can't return a reference
2557        // In production, we'd use a different approach
2558        None
2559    }
2560
2561    fn get_mut(&mut self, _id: EntityId) -> Option<&mut UnifiedEntity> {
2562        None
2563    }
2564
2565    fn insert(&mut self, entity: UnifiedEntity) -> Result<EntityId, SegmentError> {
2566        self.write().insert(entity)
2567    }
2568
2569    fn update(&mut self, entity: UnifiedEntity) -> Result<(), SegmentError> {
2570        self.write().update(entity)
2571    }
2572
2573    fn update_hot(
2574        &mut self,
2575        entity: UnifiedEntity,
2576        modified_columns: &[String],
2577    ) -> Result<(), SegmentError> {
2578        self.write().update_hot(entity, modified_columns)
2579    }
2580
2581    fn delete(&mut self, id: EntityId) -> Result<bool, SegmentError> {
2582        self.write().delete(id)
2583    }
2584
2585    fn get_metadata(&self, id: EntityId) -> Option<Metadata> {
2586        self.read().get_metadata(id)
2587    }
2588
2589    fn set_metadata(&mut self, id: EntityId, metadata: Metadata) -> Result<(), SegmentError> {
2590        self.write().set_metadata(id, metadata)
2591    }
2592
2593    fn seal(&mut self) -> Result<(), SegmentError> {
2594        self.write().seal()
2595    }
2596
2597    fn should_seal(&self, config: &SegmentConfig) -> bool {
2598        self.read().should_seal(config)
2599    }
2600
2601    fn iter(&self) -> Box<dyn Iterator<Item = &UnifiedEntity> + '_> {
2602        // Cannot return iterator with RwLock
2603        Box::new(std::iter::empty())
2604    }
2605
2606    fn iter_kind(&self, _kind_filter: &str) -> Box<dyn Iterator<Item = &UnifiedEntity> + '_> {
2607        Box::new(std::iter::empty())
2608    }
2609
2610    fn filter_metadata(&self, filters: &[(String, MetadataFilter)]) -> Vec<EntityId> {
2611        self.read().filter_metadata(filters)
2612    }
2613}
2614
2615#[cfg(test)]
2616mod tests {
2617    use std::collections::HashSet;
2618
2619    use super::*;
2620    use crate::runtime::mvcc::SnapshotContext;
2621    use crate::storage::transaction::snapshot::{Snapshot, SnapshotManager};
2622    use crate::storage::unified::entity::{EntityData, EntityKind, RowData};
2623    use reddb_types::Value;
2624
2625    #[test]
2626    fn bounded_scan_survives_sealing_consolidation_and_new_writes() {
2627        let manager = SegmentManager::with_config(
2628            "vectors",
2629            ManagerConfig {
2630                max_sealed_segments: 1,
2631                consolidation_entities_per_tick: 10_000,
2632                ..Default::default()
2633            },
2634        );
2635        for part in 0..3 {
2636            manager
2637                .bulk_insert(
2638                    (1..=300)
2639                        .map(|offset| {
2640                            UnifiedEntity::vector(
2641                                EntityId::new(part * 300 + offset),
2642                                "vectors",
2643                                vec![1.0, 0.0],
2644                            )
2645                        })
2646                        .collect(),
2647                )
2648                .expect("batch");
2649            if part < 2 {
2650                manager.force_seal().expect("seal");
2651            }
2652        }
2653        let original_growing = manager.growing.read().as_ref().expect("growing").clone();
2654        let mut changed = false;
2655        let mut seen = Vec::new();
2656        assert!(manager.scan_batches(
2657            None,
2658            || true,
2659            |batch| {
2660                assert!(batch.len() <= super::super::segment::SCAN_BATCH_SIZE);
2661                assert!(
2662                    manager.growing.try_write().is_some(),
2663                    "consumer holds no topology guard"
2664                );
2665                assert!(
2666                    original_growing.try_write().is_some(),
2667                    "consumer holds no segment guard"
2668                );
2669                for entity in batch {
2670                    assert!(manager.get(entity.id).is_some(), "reentrant storage lookup");
2671                    seen.push(entity.id.raw());
2672                }
2673                if !changed {
2674                    changed = true;
2675                    manager.force_seal().expect("seal during scan");
2676                    manager
2677                        .insert(UnifiedEntity::vector(
2678                            EntityId::new(5000),
2679                            "vectors",
2680                            vec![1.0, 0.0],
2681                        ))
2682                        .expect("new write");
2683                    drain_maintenance(&manager);
2684                    assert!(manager.stats().consolidation.runs_completed > 0);
2685                    assert!(manager
2686                        .delete(EntityId::new(1))
2687                        .expect("delete after source retirement"));
2688                    assert!(manager.get(EntityId::new(1)).is_none());
2689                }
2690                true
2691            }
2692        ));
2693        seen.sort_unstable();
2694        assert_eq!(
2695            seen,
2696            (2..=900).collect::<Vec<_>>(),
2697            "no duplicate, missing or late candidates"
2698        );
2699        let mut after = Vec::new();
2700        assert!(manager.scan_batches(
2701            None,
2702            || true,
2703            |batch| {
2704                after.extend(batch.iter().map(|entity| entity.id.raw()));
2705                true
2706            }
2707        ));
2708        after.sort_unstable();
2709        let mut expected: Vec<_> = (2..=900).collect();
2710        expected.push(5000);
2711        assert_eq!(after, expected, "adopted entities have scan positions");
2712    }
2713
2714    #[test]
2715    fn bounded_scan_applies_snapshot_to_relocated_versions() {
2716        for (consolidate, bulk) in [(false, false), (false, true), (true, false), (true, true)] {
2717            let manager = SegmentManager::with_config(
2718                "vectors",
2719                ManagerConfig {
2720                    max_sealed_segments: 1,
2721                    ..Default::default()
2722                },
2723            );
2724            for ids in [[1, 2], [3, 4]] {
2725                let entities = ids.map(|id| {
2726                    let mut entity = UnifiedEntity::vector(EntityId::new(id), "vectors", vec![1.0]);
2727                    entity.set_xmin(3);
2728                    entity
2729                });
2730                if bulk {
2731                    manager
2732                        .bulk_insert(entities.into())
2733                        .expect("initial versions");
2734                } else {
2735                    for entity in entities {
2736                        manager.insert(entity).expect("initial version");
2737                    }
2738                }
2739                manager.force_seal().expect("seal source");
2740            }
2741            let snapshot = SnapshotContext {
2742                snapshot: Snapshot {
2743                    xid: 10,
2744                    in_progress: HashSet::new(),
2745                },
2746                manager: Arc::new(SnapshotManager::new()),
2747                own_xids: HashSet::new(),
2748                requires_index_fallback: false,
2749                serializable_reader: None,
2750            };
2751            let mut changed = false;
2752            let mut seen = Vec::new();
2753            assert!(manager.scan_batches(
2754                Some(&snapshot),
2755                || true,
2756                |batch| {
2757                    seen.extend(batch.iter().map(|entity| entity.id.raw()));
2758                    if !changed {
2759                        changed = true;
2760                        if consolidate {
2761                            drain_maintenance(&manager);
2762                            assert!(manager.stats().consolidation.runs_completed > 0);
2763                        }
2764                        for (id, xmax) in [(3, 8), (4, 12)] {
2765                            let mut entity =
2766                                manager.get(EntityId::new(id)).expect("retained version");
2767                            entity.set_xmax(xmax);
2768                            manager
2769                                .update(entity)
2770                                .expect("update after source retirement");
2771                        }
2772                    }
2773                    true
2774                }
2775            ));
2776            seen.sort_unstable();
2777            assert_eq!(seen, vec![1, 2, 4], "snapshot uses authoritative xmax");
2778            let mut again = Vec::new();
2779            assert!(manager.scan_batches(
2780                Some(&snapshot),
2781                || true,
2782                |batch| {
2783                    again.extend(batch.iter().map(|entity| entity.id.raw()));
2784                    true
2785                }
2786            ));
2787            again.sort_unstable();
2788            assert_eq!(
2789                again,
2790                vec![1, 2, 4],
2791                "old slots do not duplicate relocated versions"
2792            );
2793            let mut current = Vec::new();
2794            assert!(manager.scan_batches(
2795                None,
2796                || true,
2797                |batch| {
2798                    current.extend(batch.iter().map(|entity| entity.id.raw()));
2799                    true
2800                }
2801            ));
2802            current.sort_unstable();
2803            assert_eq!(
2804                current,
2805                vec![1, 2],
2806                "current view excludes both deleted versions"
2807            );
2808        }
2809    }
2810
2811    #[test]
2812    fn bounded_scan_keeps_flat_and_hash_positions_through_mutation() {
2813        let manager = SegmentManager::new("mixed");
2814        let vector = |id| UnifiedEntity::vector(EntityId::new(id), "mixed", vec![1.0]);
2815        manager
2816            .bulk_insert((1..=300).map(vector).collect())
2817            .expect("flat");
2818        manager.insert(vector(500)).expect("hash insert");
2819        manager
2820            .bulk_insert(vec![vector(502), vector(505)])
2821            .expect("gapped bulk");
2822        manager.delete(EntityId::new(2)).expect("flat delete");
2823        manager.delete(EntityId::new(505)).expect("hash delete");
2824        let mut changed = false;
2825        let mut seen = Vec::new();
2826        assert!(manager.scan_batches(
2827            None,
2828            || true,
2829            |batch| {
2830                seen.extend(batch.iter().map(|entity| entity.id.raw()));
2831                if !changed {
2832                    changed = true;
2833                    manager
2834                        .insert(vector(700))
2835                        .expect("append after cursor boundary");
2836                    manager
2837                        .update(UnifiedEntity::graph_node(
2838                            EntityId::new(500),
2839                            "mixed",
2840                            "Node",
2841                            HashMap::new(),
2842                        ))
2843                        .expect("structural update");
2844                }
2845                true
2846            }
2847        ));
2848        seen.sort_unstable();
2849        let mut expected: Vec<_> = (1..=300).filter(|id| *id != 2).collect();
2850        expected.extend([500, 502]);
2851        assert_eq!(seen, expected);
2852    }
2853
2854    #[test]
2855    fn bounded_scan_preserves_snapshot_and_discards_interrupted_batches() {
2856        let manager = SegmentManager::new("vectors");
2857        let mut entities = Vec::new();
2858        for (id, xmin, xmax) in [(1, 3, 12), (2, 12, 0), (3, 3, 0), (4, 3, 4)] {
2859            let mut entity = UnifiedEntity::vector(EntityId::new(id), "vectors", vec![1.0]);
2860            entity.set_xmin(xmin);
2861            entity.set_xmax(xmax);
2862            entities.push(entity);
2863        }
2864        manager.bulk_insert(entities).expect("versions");
2865        manager.force_seal().expect("seal");
2866        let snapshot = SnapshotContext {
2867            snapshot: Snapshot {
2868                xid: 10,
2869                in_progress: HashSet::from([4]),
2870            },
2871            manager: Arc::new(SnapshotManager::new()),
2872            own_xids: HashSet::new(),
2873            requires_index_fallback: false,
2874            serializable_reader: None,
2875        };
2876        let mut work = 0;
2877        let mut callbacks = 0;
2878        assert!(!manager.scan_batches(
2879            Some(&snapshot),
2880            || {
2881                work += 1;
2882                work <= 2
2883            },
2884            |_| {
2885                callbacks += 1;
2886                true
2887            }
2888        ));
2889        assert_eq!(callbacks, 0, "a stopped batch is not consumed");
2890        for (view, expected) in [(Some(&snapshot), vec![1, 3, 4]), (None, vec![2, 3])] {
2891            let mut seen = Vec::new();
2892            assert!(manager.scan_batches(
2893                view,
2894                || true,
2895                |batch| {
2896                    seen.extend(batch.iter().map(|entity| entity.id.raw()));
2897                    true
2898                }
2899            ));
2900            seen.sort_unstable();
2901            assert_eq!(seen, expected);
2902        }
2903    }
2904
2905    #[test]
2906    fn test_manager_basic() {
2907        let manager = SegmentManager::new("test_collection");
2908
2909        let entity = UnifiedEntity::table_row(
2910            manager.next_entity_id(),
2911            "users",
2912            1,
2913            vec![Value::text("Alice".to_string())],
2914        );
2915
2916        let id = manager.insert(entity).unwrap();
2917        assert!(manager.get(id).is_some());
2918        assert_eq!(manager.count(), 1);
2919    }
2920
2921    #[test]
2922    fn graph_pruning_preserves_physical_versions_and_charges_only_selected_segments() {
2923        let manager = Arc::new(SegmentManager::new("mixed"));
2924        manager
2925            .bulk_insert(
2926                (1..=128)
2927                    .map(|id| UnifiedEntity::vector(EntityId::new(id), "mixed", vec![]))
2928                    .collect(),
2929            )
2930            .expect("vector-only segment");
2931        manager.force_seal().expect("seal vectors");
2932        let mut old =
2933            UnifiedEntity::graph_node(EntityId::new(200), "mixed", "person", Default::default());
2934        old.set_xmin(3);
2935        old.set_xmax(12);
2936        let mut new =
2937            UnifiedEntity::graph_node(EntityId::new(201), "mixed", "person", Default::default());
2938        new.set_xmin(12);
2939        let edge = UnifiedEntity::graph_edge(
2940            EntityId::new(202),
2941            "mixed",
2942            "a",
2943            "b",
2944            1.0,
2945            Default::default(),
2946        );
2947        manager
2948            .bulk_insert(vec![old, new, edge])
2949            .expect("physical graph versions");
2950        manager.force_seal().expect("seal graph");
2951        manager
2952            .insert(UnifiedEntity::graph_node(
2953                EntityId::new(203),
2954                "mixed",
2955                "person",
2956                Default::default(),
2957            ))
2958            .expect("growing node");
2959        let snapshot = SnapshotContext {
2960            snapshot: Snapshot {
2961                xid: 10,
2962                in_progress: HashSet::new(),
2963            },
2964            manager: Arc::new(SnapshotManager::new()),
2965            own_xids: HashSet::new(),
2966            requires_index_fallback: false,
2967            serializable_reader: None,
2968        };
2969        std::thread::spawn(move || {
2970            for view in [None, Some(&snapshot)] {
2971                for kind in [GraphEntityKind::Node, GraphEntityKind::Edge] {
2972                    let expected: HashSet<_> = manager
2973                        .scan(view, |item| kind.matches(&item.kind))
2974                        .into_iter()
2975                        .map(|item| item.id)
2976                        .collect();
2977                    let actual: HashSet<_> = manager
2978                        .scan_graph_kind(view, kind)
2979                        .into_iter()
2980                        .map(|item| item.id)
2981                        .collect();
2982                    assert_eq!(actual, expected);
2983                    let mut visited = 0;
2984                    let mut candidates = HashSet::new();
2985                    manager.scan_graph_candidates_for_each(
2986                        view,
2987                        kind,
2988                        || true,
2989                        |item| {
2990                            visited += 1;
2991                            if kind.matches(&item.kind) {
2992                                candidates.insert(item.id);
2993                            }
2994                            true
2995                        },
2996                    );
2997                    assert_eq!(candidates, expected);
2998                    assert_eq!(
2999                        visited,
3000                        if matches!(kind, GraphEntityKind::Node) {
3001                            3
3002                        } else {
3003                            2
3004                        }
3005                    );
3006                }
3007            }
3008            let ids: HashSet<_> = manager
3009                .scan_graph_kind(Some(&snapshot), GraphEntityKind::Node)
3010                .into_iter()
3011                .map(|item| item.id.raw())
3012                .collect();
3013            assert_eq!(ids, HashSet::from([200, 203]));
3014            let ids: HashSet<_> = manager
3015                .scan_graph_kind(None, GraphEntityKind::Node)
3016                .into_iter()
3017                .map(|item| item.id.raw())
3018                .collect();
3019            assert_eq!(ids, HashSet::from([201, 203]));
3020            let mut visits = 0;
3021            manager.scan_graph_candidates_for_each(
3022                None,
3023                GraphEntityKind::Node,
3024                || true,
3025                |_| {
3026                    visits += 1;
3027                    false
3028                },
3029            );
3030            assert_eq!(
3031                visits, 1,
3032                "early termination must also stop subsequent segments"
3033            );
3034        })
3035        .join()
3036        .expect("snapshot worker");
3037    }
3038
3039    #[test]
3040    fn snapshot_scan_applies_table_driven_visibility_on_fresh_thread() {
3041        let manager = Arc::new(SegmentManager::new("accounts"));
3042        let cases = [
3043            ("legacy row", 0, 0, true),
3044            ("committed creator", 3, 0, true),
3045            ("future creator", 11, 0, false),
3046            ("in-progress creator", 4, 0, false),
3047            ("committed deleter", 3, 7, false),
3048            ("future deleter", 3, 11, true),
3049            ("in-progress deleter", 3, 4, true),
3050        ];
3051
3052        for (index, (_, xmin, xmax, _)) in cases.iter().enumerate() {
3053            let row_id = index as u64 + 1;
3054            let mut entity = UnifiedEntity::table_row(
3055                EntityId::new(row_id),
3056                "accounts",
3057                row_id,
3058                vec![Value::Integer(row_id as i64)],
3059            );
3060            entity.set_xmin(*xmin);
3061            entity.set_xmax(*xmax);
3062            manager.insert(entity).unwrap();
3063        }
3064
3065        let snapshot = SnapshotContext {
3066            snapshot: Snapshot {
3067                xid: 10,
3068                in_progress: HashSet::from([4]),
3069            },
3070            manager: Arc::new(SnapshotManager::new()),
3071            own_xids: HashSet::new(),
3072            requires_index_fallback: false,
3073            serializable_reader: None,
3074        };
3075
3076        let raw_visible_row_ids: HashSet<u64> = manager
3077            .query_all(|entity| entity_visible_with_context(Some(&snapshot), entity))
3078            .into_iter()
3079            .filter_map(|entity| match entity.kind {
3080                EntityKind::TableRow { row_id, .. } => Some(row_id),
3081                _ => None,
3082            })
3083            .collect();
3084
3085        let scanned = std::thread::spawn(move || manager.scan(Some(&snapshot), |_| true))
3086            .join()
3087            .unwrap();
3088        let visible_row_ids: HashSet<u64> = scanned
3089            .into_iter()
3090            .filter_map(|entity| match entity.kind {
3091                EntityKind::TableRow { row_id, .. } => Some(row_id),
3092                _ => None,
3093            })
3094            .collect();
3095        assert_eq!(visible_row_ids, raw_visible_row_ids);
3096
3097        for (index, (name, _, _, expected_visible)) in cases.iter().enumerate() {
3098            let row_id = index as u64 + 1;
3099            assert_eq!(
3100                visible_row_ids.contains(&row_id),
3101                *expected_visible,
3102                "{name} visibility mismatch"
3103            );
3104        }
3105    }
3106
3107    #[test]
3108    fn frameless_scan_hides_superseded_versions_and_moderated_rows() {
3109        // A `None` snapshot is the autocommit / prepared-fast-path read: it
3110        // must keep the resolver fallback (xmax == 0), never show every
3111        // version, and never panic (issue #2136 review).
3112        let manager = SegmentManager::new("accounts");
3113        let mut live =
3114            UnifiedEntity::table_row(EntityId::new(1), "accounts", 1, vec![Value::Integer(1)]);
3115        live.set_xmin(2);
3116        live.set_xmax(0);
3117        manager.insert(live).unwrap();
3118
3119        let mut superseded =
3120            UnifiedEntity::table_row(EntityId::new(2), "accounts", 2, vec![Value::Integer(2)]);
3121        superseded.set_xmin(2);
3122        superseded.set_xmax(9);
3123        manager.insert(superseded).unwrap();
3124
3125        let rows: Vec<u64> = manager
3126            .scan(None, |_| true)
3127            .into_iter()
3128            .filter_map(|entity| match entity.kind {
3129                EntityKind::TableRow { row_id, .. } => Some(row_id),
3130                _ => None,
3131            })
3132            .collect();
3133        assert_eq!(
3134            rows,
3135            vec![1],
3136            "frameless scan must hide superseded versions"
3137        );
3138    }
3139
3140    #[test]
3141    fn query_scan_callers_use_snapshot_api_for_visibility() {
3142        let table = include_str!("../../runtime/query_exec/table.rs");
3143        let aggregate = include_str!("../../runtime/query_exec/aggregate.rs");
3144
3145        assert_eq!(
3146            table.matches(".for_each_entity(|entity|").count(),
3147            1,
3148            "only the visibility-independent schema inspection may use the raw table iterator"
3149        );
3150        assert!(!table.contains(".query_all_zoned_with_stats("));
3151        assert!(!table.contains(".for_each_entity_zoned_with_stats("));
3152        assert!(!table.contains("TableRowMvccReadResolver::captured"));
3153
3154        assert!(!aggregate.contains("TableRowMvccReadResolver"));
3155        assert!(!aggregate.contains(".for_each_entity("));
3156        assert!(!aggregate.contains(".fold_entities_parallel("));
3157    }
3158
3159    #[test]
3160    fn remaining_visibility_scan_callers_use_snapshot_api() {
3161        let aggregate_pushdown =
3162            include_str!("../../runtime/query_exec/aggregate_pushdown_dispatch.rs");
3163        let ask = include_str!("../../runtime/ask_pipeline.rs");
3164        let dml = include_str!("../../runtime/impl_dml.rs");
3165        let dml_targets = include_str!("../../runtime/dml_target_scan.rs");
3166        let events = include_str!("../../runtime/impl_events.rs");
3167        let graph_commands = include_str!("../../runtime/impl_graph_commands.rs");
3168        let graph_dsl = include_str!("../../runtime/graph_dsl.rs");
3169        let graph_tvf = include_str!("../../runtime/graph_tvf.rs");
3170        let kv = include_str!("../../runtime/impl_kv.rs");
3171        let queue = include_str!("../../runtime/impl_queue.rs");
3172        let primary_queue = include_str!("../../runtime/primary_queue_store.rs");
3173        let record_search = include_str!("../../runtime/record_search.rs");
3174        let search = include_str!("../../runtime/impl_search.rs");
3175        let vector = include_str!("../../runtime/query_exec/vector.rs");
3176
3177        assert!(!aggregate_pushdown.contains("TableRowMvccReadResolver"));
3178        assert!(!aggregate_pushdown.contains(".for_each_entity("));
3179        assert!(!ask.contains("for entity in manager.query_all(|_| true)"));
3180        assert!(!dml.contains("let entities = manager.query_all(|_| true);"));
3181        // The DML target scan keeps raw iteration on purpose: its
3182        // visibility is kind-conditional (live table rows at the tip
3183        // version, everything else under the snapshot), which the uniform
3184        // scan API cannot express. `candidate_visible` is the single gate.
3185        assert_eq!(
3186            dml_targets
3187                .matches("self.candidate_visible(snapshot.as_ref(), entity)")
3188                .count(),
3189            2,
3190            "both raw DML iterations must route through candidate_visible"
3191        );
3192        // The event-backfill dedup set is deliberately visibility-free:
3193        // it must include consumed messages or backfill re-enqueues them.
3194        assert_eq!(
3195            events.matches("manager.query_all(").count(),
3196            1,
3197            "only the visibility-free backfill dedup may use query_all"
3198        );
3199        assert!(!graph_commands.contains("TableRowMvccReadResolver"));
3200        assert!(!graph_dsl.contains("entity_visible_with_context(snap_ctx.as_ref(), e)"));
3201        assert!(!graph_tvf.contains("entity_visible_with_context(snap_ctx.as_ref(), &entity)"));
3202        assert!(!kv.contains("TableRowMvccReadResolver"));
3203        assert!(!queue.contains("entity_visible_with_context(snap_ctx.as_ref(), entity)"));
3204        assert!(!primary_queue.contains("entity_visible_with_context(snap_ctx.as_ref(), entity)"));
3205        assert!(!record_search.contains("TableRowMvccReadResolver"));
3206        assert!(!search.contains("for entity in manager.query_all(|_| true)"));
3207        assert!(!vector.contains("manager.query_all("));
3208    }
3209
3210    /// Strip `#[cfg(test)] mod … { … }` blocks so the raw-iteration gate
3211    /// only sees production code. Blocks are matched at column zero and
3212    /// closed by brace balance, which is why a file may carry a test
3213    /// module in the middle and still keep production code after it.
3214    fn production_source(src: &str) -> String {
3215        let mut kept: Vec<&str> = Vec::new();
3216        let lines: Vec<&str> = src.lines().collect();
3217        let mut idx = 0;
3218        while idx < lines.len() {
3219            let starts_test_mod = lines[idx].starts_with("#[cfg(test)]")
3220                && lines
3221                    .get(idx + 1)
3222                    .is_some_and(|next| next.starts_with("mod "));
3223            if !starts_test_mod {
3224                kept.push(lines[idx]);
3225                idx += 1;
3226                continue;
3227            }
3228            idx += 1;
3229            let mut depth: isize = 0;
3230            while idx < lines.len() {
3231                depth += lines[idx].matches('{').count() as isize;
3232                depth -= lines[idx].matches('}').count() as isize;
3233                idx += 1;
3234                if depth <= 0 {
3235                    break;
3236                }
3237            }
3238        }
3239        kept.join("\n")
3240    }
3241
3242    /// Count raw (visibility-bypassing) iteration entry points.
3243    fn raw_iteration_sites(src: &str) -> usize {
3244        src.matches("query_all(").count()
3245            + src.matches(".for_each_entity").count()
3246            + src.matches("fold_entities_parallel(").count()
3247    }
3248
3249    #[test]
3250    fn raw_iteration_confined_to_maintenance_allowlist() {
3251        // The query paths migrated by Spec #2107 batches 1 and 2. Inside
3252        // this perimeter raw iteration is maintenance-only: it bypasses
3253        // MVCC visibility entirely, so every remaining site is either an
3254        // internal catalog/bookkeeping read that must observe all physical
3255        // versions, or one of the three exceptions the batch reviews
3256        // documented. A new raw-iteration site changes the count and fails
3257        // this gate — route it through `SegmentManager::scan*` instead.
3258        let allowlist: &[(&str, &str, usize, &str)] = &[
3259            (
3260                "runtime/query_exec/table.rs",
3261                include_str!("../../runtime/query_exec/table.rs"),
3262                1,
3263                "documented exception: schema inspection (does the collection ever \
3264                 observe these fields?) is visibility-independent",
3265            ),
3266            (
3267                "runtime/query_exec/aggregate.rs",
3268                include_str!("../../runtime/query_exec/aggregate.rs"),
3269                0,
3270                "fully migrated by batch 1",
3271            ),
3272            (
3273                "runtime/query_exec/aggregate_pushdown_dispatch.rs",
3274                include_str!("../../runtime/query_exec/aggregate_pushdown_dispatch.rs"),
3275                0,
3276                "fully migrated by batch 1",
3277            ),
3278            (
3279                "runtime/query_exec/vector.rs",
3280                include_str!("../../runtime/query_exec/vector.rs"),
3281                0,
3282                "fully migrated by batch 2",
3283            ),
3284            (
3285                "runtime/ask_pipeline.rs",
3286                include_str!("../../runtime/ask_pipeline.rs"),
3287                0,
3288                "fully migrated by batch 2",
3289            ),
3290            (
3291                "runtime/impl_dml.rs",
3292                include_str!("../../runtime/impl_dml.rs"),
3293                1,
3294                "documented exception: ON CONFLICT resolves a unique key against \
3295                 physical versions on purpose. A snapshot scan cannot see a row an \
3296                 uncommitted concurrent writer already holds the key for, which is \
3297                 exactly the case that must raise a serialization conflict rather \
3298                 than insert a duplicate; the same pass reaps index entries left by \
3299                 aborted writers. \
3300                 TODO(#2263 follow-up): narrow the candidates through the unique \
3301                 index instead of walking the collection",
3302            ),
3303            (
3304                "runtime/dml_target_scan.rs",
3305                include_str!("../../runtime/dml_target_scan.rs"),
3306                2,
3307                "documented exception: kind-conditional visibility the uniform scan \
3308                 API cannot express; both iterations gate on candidate_visible",
3309            ),
3310            (
3311                "runtime/impl_events.rs",
3312                include_str!("../../runtime/impl_events.rs"),
3313                1,
3314                "documented exception: backfill dedup must include consumed messages, \
3315                 so it is deliberately visibility-free",
3316            ),
3317            (
3318                "runtime/impl_graph_commands.rs",
3319                include_str!("../../runtime/impl_graph_commands.rs"),
3320                0,
3321                "native node properties resolve one snapshot-visible, RLS-admitted version",
3322            ),
3323            (
3324                "runtime/graph_dsl.rs",
3325                include_str!("../../runtime/graph_dsl.rs"),
3326                1,
3327                "remaining legacy debt: unused edge-property helper; search expansion \
3328                 now uses snapshot visitors and RLS-gated hydration",
3329            ),
3330            (
3331                "runtime/graph_tvf.rs",
3332                include_str!("../../runtime/graph_tvf.rs"),
3333                0,
3334                "fully migrated by batch 2",
3335            ),
3336            (
3337                "runtime/impl_kv.rs",
3338                include_str!("../../runtime/impl_kv.rs"),
3339                4,
3340                "two non-versioned-collection fallbacks (the versioned arms scan under \
3341                 the captured snapshot). Vault reads use snapshot scans. Offline vault \
3342                 export preserves all \
3343                 physical versions across tenants; restore's emptiness check must reject \
3344                 every physical row, including versions invisible to a snapshot",
3345            ),
3346            (
3347                "runtime/impl_queue.rs",
3348                include_str!("../../runtime/impl_queue.rs"),
3349                10,
3350                "maintenance: red_queue_meta bookkeeping (config, groups, acks, \
3351                 pending, dedup TTL reaper, gauge counts) — queue message bodies are \
3352                 read through scan. \
3353                 TODO(#2138 follow-up): QUEUE PENDING projects meta rows to clients",
3354            ),
3355            (
3356                "runtime/primary_queue_store.rs",
3357                include_str!("../../runtime/primary_queue_store.rs"),
3358                3,
3359                "maintenance: generic red_queue_meta read/delete helpers and the \
3360                 next-position allocator, which must not collide with rows invisible \
3361                 to the writer's snapshot",
3362            ),
3363            (
3364                "runtime/record_search.rs",
3365                include_str!("../../runtime/record_search.rs"),
3366                0,
3367                "fully migrated by batch 2",
3368            ),
3369            (
3370                "runtime/search_graph.rs",
3371                include_str!("../../runtime/search_graph.rs"),
3372                0,
3373                "search graph preparation uses snapshot visitors and gated hydration",
3374            ),
3375            (
3376                "runtime/impl_search.rs",
3377                include_str!("../../runtime/impl_search.rs"),
3378                1,
3379                "maintenance: ask-audit retention sweep must see every physical row",
3380            ),
3381        ];
3382
3383        for (path, src, allowed, reason) in allowlist {
3384            let found = raw_iteration_sites(&production_source(src));
3385            assert_eq!(
3386                found, *allowed,
3387                "{path}: {found} raw-iteration sites, allowlist permits {allowed} \
3388                 ({reason}). Raw iteration bypasses MVCC visibility — use \
3389                 SegmentManager::scan / scan_for_each / scan_fold_parallel / \
3390                 scan_zoned_with_stats, or extend the allowlist with a maintenance \
3391                 justification."
3392            );
3393        }
3394    }
3395
3396    #[test]
3397    fn explicit_snapshot_scan_ignores_ambient_thread_local() {
3398        let manager = Arc::new(SegmentManager::new("accounts"));
3399        // (xmin, xmax) — mix of committed, in-progress and future writers.
3400        let versions = [(0, 0), (3, 0), (11, 0), (4, 0), (3, 7), (3, 11), (3, 4)];
3401        for (index, (xmin, xmax)) in versions.iter().enumerate() {
3402            let row_id = index as u64 + 1;
3403            let mut entity = UnifiedEntity::table_row(
3404                EntityId::new(row_id),
3405                "accounts",
3406                row_id,
3407                vec![Value::Integer(row_id as i64)],
3408            );
3409            entity.set_xmin(*xmin);
3410            entity.set_xmax(*xmax);
3411            manager.insert(entity).unwrap();
3412        }
3413
3414        let explicit = SnapshotContext {
3415            snapshot: Snapshot {
3416                xid: 10,
3417                in_progress: HashSet::from([4]),
3418            },
3419            manager: Arc::new(SnapshotManager::new()),
3420            own_xids: HashSet::new(),
3421            requires_index_fallback: false,
3422            serializable_reader: None,
3423        };
3424        // A decoy statement frame that would hide almost everything if the
3425        // scan ever consulted ambient state instead of its argument.
3426        let decoy = SnapshotContext {
3427            snapshot: Snapshot {
3428                xid: 1,
3429                in_progress: HashSet::new(),
3430            },
3431            manager: Arc::new(SnapshotManager::new()),
3432            own_xids: HashSet::new(),
3433            requires_index_fallback: false,
3434            serializable_reader: None,
3435        };
3436
3437        let row_ids = |entities: Vec<UnifiedEntity>| -> HashSet<u64> {
3438            entities
3439                .into_iter()
3440                .filter_map(|entity| match entity.kind {
3441                    EntityKind::TableRow { row_id, .. } => Some(row_id),
3442                    _ => None,
3443                })
3444                .collect()
3445        };
3446
3447        let guard = crate::runtime::execution_context::CurrentSnapshotGuard::install(decoy);
3448        let on_installing_thread = row_ids(manager.scan(Some(&explicit), |_| true));
3449        drop(guard);
3450
3451        let spawned_manager = Arc::clone(&manager);
3452        let spawned_snapshot = explicit.clone();
3453        let on_fresh_thread = std::thread::spawn(move || {
3454            row_ids(spawned_manager.scan(Some(&spawned_snapshot), |_| true))
3455        })
3456        .join()
3457        .unwrap();
3458
3459        assert_eq!(
3460            on_installing_thread, on_fresh_thread,
3461            "an explicit snapshot must produce the same visible set on any thread"
3462        );
3463        assert_eq!(on_installing_thread, HashSet::from([1, 2, 6, 7]));
3464
3465        // The raw iterators are the maintenance contract: no visibility
3466        // filtering at all, on any thread, regardless of installed frames.
3467        let raw_manager = Arc::clone(&manager);
3468        let raw_count = std::thread::spawn(move || raw_manager.query_all(|_| true).len())
3469            .join()
3470            .unwrap();
3471        assert_eq!(
3472            raw_count,
3473            versions.len(),
3474            "raw iteration must expose every physical version"
3475        );
3476    }
3477
3478    #[test]
3479    fn bloom_may_contain_key_probes_inserted_rid_bytes() {
3480        let manager = SegmentManager::new("test_collection");
3481
3482        let entity = UnifiedEntity::table_row(
3483            manager.next_entity_id(),
3484            "users",
3485            1,
3486            vec![Value::text("Alice".to_string())],
3487        );
3488
3489        let id = manager.insert(entity).unwrap();
3490
3491        assert!(manager.bloom_may_contain_key(&id.raw().to_le_bytes()));
3492        assert!(manager.bloom_may_contain_key(id.raw().to_string().as_bytes()));
3493        assert!(!manager.bloom_may_contain_key(&u64::MAX.to_le_bytes()));
3494
3495        assert!(manager.delete(id).unwrap());
3496        assert!(!manager.bloom_may_contain_key(&id.raw().to_le_bytes()));
3497    }
3498
3499    #[test]
3500    fn zoned_scan_reports_pruned_segments_and_preserves_results() {
3501        let config = ManagerConfig {
3502            segment_config: SegmentConfig {
3503                max_entities: 2,
3504                ..Default::default()
3505            },
3506            ..Default::default()
3507        };
3508        let manager = SegmentManager::with_config("events", config);
3509
3510        for (idx, value) in [10, 20, 100, 110, 200].into_iter().enumerate() {
3511            let row = RowData::with_names(vec![Value::Integer(value)], vec!["ts".to_string()]);
3512            let entity = UnifiedEntity::new(
3513                manager.next_entity_id(),
3514                EntityKind::TableRow {
3515                    table: "events".into(),
3516                    row_id: (idx + 1) as u64,
3517                },
3518                EntityData::Row(row),
3519            );
3520            manager.insert(entity).unwrap();
3521        }
3522
3523        let full = manager.query_all(|entity| match &entity.data {
3524            EntityData::Row(row) => matches!(row.get_field("ts"), Some(Value::Integer(100))),
3525            _ => false,
3526        });
3527        let probe = Value::Integer(100);
3528        let (pruned, stats) =
3529            manager.query_all_zoned_with_stats(&[("ts", ZoneColPred::Eq(&probe))], |entity| {
3530                match &entity.data {
3531                    EntityData::Row(row) => {
3532                        matches!(row.get_field("ts"), Some(Value::Integer(100)))
3533                    }
3534                    _ => false,
3535                }
3536            });
3537
3538        assert_eq!(pruned.len(), full.len());
3539        assert_eq!(pruned[0].id, full[0].id);
3540        assert_eq!(stats.segments_total, 3);
3541        assert_eq!(stats.segments_scanned, 2);
3542        assert_eq!(stats.segments_pruned, 1);
3543    }
3544
3545    #[test]
3546    fn test_manager_auto_seal() {
3547        let config = ManagerConfig {
3548            segment_config: SegmentConfig {
3549                max_entities: 2,
3550                ..Default::default()
3551            },
3552            ..Default::default()
3553        };
3554
3555        let manager = SegmentManager::with_config("test", config);
3556
3557        // Insert first entity
3558        manager
3559            .insert(UnifiedEntity::vector(
3560                manager.next_entity_id(),
3561                "v",
3562                vec![0.1],
3563            ))
3564            .unwrap();
3565
3566        // Insert second entity (triggers seal check)
3567        manager
3568            .insert(UnifiedEntity::vector(
3569                manager.next_entity_id(),
3570                "v",
3571                vec![0.2],
3572            ))
3573            .unwrap();
3574
3575        // Insert third entity (should trigger auto-seal of first segment)
3576        manager
3577            .insert(UnifiedEntity::vector(
3578                manager.next_entity_id(),
3579                "v",
3580                vec![0.3],
3581            ))
3582            .unwrap();
3583
3584        let stats = manager.stats();
3585        assert_eq!(stats.total_entities, 3);
3586    }
3587
3588    #[test]
3589    fn test_manager_delete() {
3590        let manager = SegmentManager::new("test");
3591
3592        let id = manager
3593            .insert(UnifiedEntity::vector(
3594                manager.next_entity_id(),
3595                "v",
3596                vec![0.1],
3597            ))
3598            .unwrap();
3599
3600        assert!(manager.get(id).is_some());
3601        assert!(manager.delete(id).unwrap());
3602        assert!(manager.get(id).is_none());
3603    }
3604
3605    #[test]
3606    fn test_manager_metadata() {
3607        let manager = SegmentManager::new("test");
3608
3609        let id = manager
3610            .insert(UnifiedEntity::table_row(
3611                manager.next_entity_id(),
3612                "hosts",
3613                1,
3614                vec![Value::text("192.168.1.1".to_string())],
3615            ))
3616            .unwrap();
3617
3618        let mut meta = Metadata::new();
3619        meta.set(
3620            "os",
3621            super::super::metadata::MetadataValue::String("linux".to_string()),
3622        );
3623
3624        manager.set_metadata(id, meta).unwrap();
3625
3626        let retrieved = manager.get_metadata(id).unwrap();
3627        assert!(retrieved.has("os"));
3628    }
3629
3630    #[test]
3631    fn test_manager_query_by_kind() {
3632        let manager = SegmentManager::new("test");
3633
3634        manager
3635            .insert(UnifiedEntity::table_row(
3636                manager.next_entity_id(),
3637                "hosts",
3638                1,
3639                vec![],
3640            ))
3641            .unwrap();
3642
3643        manager
3644            .insert(UnifiedEntity::vector(
3645                manager.next_entity_id(),
3646                "embeddings",
3647                vec![0.1],
3648            ))
3649            .unwrap();
3650
3651        manager
3652            .insert(UnifiedEntity::table_row(
3653                manager.next_entity_id(),
3654                "hosts",
3655                2,
3656                vec![],
3657            ))
3658            .unwrap();
3659
3660        let rows = manager.get_by_kind("table");
3661        assert_eq!(rows.len(), 2);
3662
3663        let vectors = manager.get_by_kind("vector");
3664        assert_eq!(vectors.len(), 1);
3665    }
3666
3667    // ========================================================================
3668    // Consolidation — ADR 0073 §5
3669    // ========================================================================
3670
3671    /// A manager whose sealed set never trips the count trigger, so tests can
3672    /// exercise the tombstone/fragmentation triggers in isolation.
3673    fn consolidating_manager(entities_per_tick: usize) -> SegmentManager {
3674        SegmentManager::with_config(
3675            "test",
3676            ManagerConfig {
3677                max_sealed_segments: 1_000,
3678                consolidation_entities_per_tick: entities_per_tick,
3679                ..Default::default()
3680            },
3681        )
3682    }
3683
3684    /// Bulk-load `count` rows into a fresh segment and seal it. Bulk-inserted
3685    /// entities land in flat storage, where a tombstone keeps its payload
3686    /// resident — which is the memory consolidation reclaims.
3687    fn seal_bulk_segment(manager: &SegmentManager, count: usize) -> Vec<EntityId> {
3688        let entities: Vec<UnifiedEntity> = (0..count)
3689            .map(|i| {
3690                UnifiedEntity::table_row(
3691                    manager.next_entity_id(),
3692                    "users",
3693                    i as u64,
3694                    vec![Value::Integer(i as i64), Value::text(format!("row-{i}"))],
3695                )
3696            })
3697            .collect();
3698        let ids = manager.bulk_insert(entities).expect("bulk insert");
3699        manager.force_seal().expect("seal");
3700        ids
3701    }
3702
3703    fn live_ids(manager: &SegmentManager) -> Vec<u64> {
3704        let mut ids: Vec<u64> = manager
3705            .query_all(|_| true)
3706            .into_iter()
3707            .map(|entity| entity.id.raw())
3708            .collect();
3709        ids.sort_unstable();
3710        ids
3711    }
3712
3713    fn drain_maintenance(manager: &SegmentManager) -> usize {
3714        let mut ticks = 0;
3715        while manager.consolidation.read().is_some() || ticks == 0 {
3716            manager.run_maintenance().expect("maintenance");
3717            ticks += 1;
3718            assert!(ticks < 1_000, "consolidation failed to converge");
3719        }
3720        ticks
3721    }
3722
3723    #[test]
3724    fn graph_index_batches_pin_sources_and_hydrate_current_after_consolidation() {
3725        let manager = consolidating_manager(CONSOLIDATION_ENTITIES_PER_TICK);
3726        let ids = manager
3727            .bulk_insert(
3728                (1..=1024)
3729                    .map(|id| {
3730                        UnifiedEntity::graph_edge(
3731                            EntityId::new(id),
3732                            "step",
3733                            "2000",
3734                            "3000",
3735                            1.0,
3736                            HashMap::new(),
3737                        )
3738                    })
3739                    .collect(),
3740            )
3741            .expect("edges");
3742        manager.force_seal().expect("seal");
3743        for id in ids.iter().take(300) {
3744            manager.delete(*id).expect("fragment source");
3745        }
3746        let source = Arc::downgrade(&manager.sealed.read()[0]);
3747        let mut seen = Vec::new();
3748        let mut changed = false;
3749        let mut metadata_bytes = 0;
3750        assert!(manager.visit_graph_index_batches(GraphEntityKind::Edge, &[EntityId::new(2000)],
3751            || true,
3752            |bytes| { metadata_bytes += bytes; Ok::<_, ()>(()) },
3753            |batch| {
3754                assert!(batch.len() <= super::super::segment::SCAN_BATCH_SIZE);
3755                assert!(manager.growing.try_write().is_some(), "no growing topology guard");
3756                assert!(manager.sealed.try_write().is_some(), "no sealed topology guard");
3757                assert!(source.upgrade().expect("source pinned").try_write().is_some(), "no source guard");
3758                if !changed {
3759                    changed = true;
3760                    drain_maintenance(&manager);
3761                    assert!(manager.stats().consolidation.runs_completed > 0);
3762                    assert!(source.upgrade().is_some(), "retired cursor source remains pinned");
3763                    let mut updated = manager.get(EntityId::new(1024)).expect("future edge");
3764                    if let EntityKind::GraphEdge(edge) = &mut updated.kind { edge.weight = 2000; }
3765                    manager.update(updated).expect("update authoritative merged copy");
3766                }
3767                for id in batch {
3768                    let entity = manager.get(*id).expect("hydrate current manager");
3769                    if id.raw() == 1024 {
3770                        assert!(matches!(&entity.kind, EntityKind::GraphEdge(edge) if edge.weight == 2000));
3771                    }
3772                    seen.push(id.raw());
3773                }
3774                Ok(true)
3775            }).expect("cursor"));
3776        assert_eq!(seen, (301..=1024).collect::<Vec<_>>());
3777        assert!(
3778            source.upgrade().is_none(),
3779            "finished cursor releases retired source"
3780        );
3781        assert!(
3782            metadata_bytes < 4096,
3783            "fixed ID buffer plus source handles: {metadata_bytes}"
3784        );
3785    }
3786
3787    #[test]
3788    fn graph_index_batches_propagate_admission_and_cancel_before_partial_delivery() {
3789        let manager = SegmentManager::new("graph");
3790        manager
3791            .bulk_insert(
3792                (1..=1024)
3793                    .map(|id| {
3794                        UnifiedEntity::graph_edge(
3795                            EntityId::new(id),
3796                            "step",
3797                            "2000",
3798                            "3000",
3799                            1.0,
3800                            HashMap::new(),
3801                        )
3802                    })
3803                    .collect(),
3804            )
3805            .expect("edges");
3806        let mut delivered = 0;
3807        let denied = manager.visit_graph_index_batches(
3808            GraphEntityKind::Edge,
3809            &[EntityId::new(2000)],
3810            || true,
3811            |_| Err("out of memory"),
3812            |ids| {
3813                delivered += ids.len();
3814                Ok(true)
3815            },
3816        );
3817        assert_eq!(denied, Err("out of memory"));
3818        assert_eq!(delivered, 0);
3819        let mut work = 0;
3820        assert!(!manager
3821            .visit_graph_index_batches(
3822                GraphEntityKind::Edge,
3823                &[EntityId::new(2000)],
3824                || {
3825                    work += 1;
3826                    work < 100
3827                },
3828                |_| Ok::<_, ()>(()),
3829                |ids| {
3830                    delivered += ids.len();
3831                    Ok(true)
3832                }
3833            )
3834            .expect("cancelled cursor"));
3835        assert_eq!(
3836            delivered, 0,
3837            "cancelled partial batch cannot reach consumer"
3838        );
3839        assert!(!manager
3840            .visit_graph_index_batches(
3841                GraphEntityKind::Edge,
3842                &[EntityId::new(2000)],
3843                || true,
3844                |_| Ok::<_, ()>(()),
3845                |ids| {
3846                    delivered += ids.len();
3847                    Ok(false)
3848                }
3849            )
3850            .expect("consumer stop"));
3851        assert_eq!(delivered, super::super::segment::SCAN_BATCH_SIZE);
3852    }
3853
3854    #[test]
3855    fn retained_memory_tracks_two_readers_until_the_last_cursor_finishes() {
3856        let manager = consolidating_manager(CONSOLIDATION_ENTITIES_PER_TICK);
3857        let ids = seal_bulk_segment(&manager, 100);
3858        for id in ids.iter().take(40) {
3859            manager.delete(*id).expect("delete before scan");
3860        }
3861        let source_bytes = manager.resident_bytes();
3862        let source = Arc::downgrade(&manager.sealed.read()[0]);
3863        std::thread::scope(|scope| {
3864            let (ready, waiting) = std::sync::mpsc::channel();
3865            let (release_first, first_wait) = std::sync::mpsc::channel();
3866            let (release_last, last_wait) = std::sync::mpsc::channel();
3867            let reader = |resume: std::sync::mpsc::Receiver<()>,
3868                          ready: std::sync::mpsc::Sender<()>| {
3869                assert!(manager.scan_batches(
3870                    None,
3871                    || true,
3872                    |_| {
3873                        ready.send(()).expect("signal captured cursor");
3874                        let _ = resume.recv();
3875                        true
3876                    }
3877                ));
3878            };
3879            let ready_first = ready.clone();
3880            let first = scope.spawn(move || reader(first_wait, ready_first));
3881            let last = scope.spawn(move || reader(last_wait, ready));
3882            for _ in 0..2 {
3883                waiting
3884                    .recv_timeout(std::time::Duration::from_secs(10))
3885                    .expect("reader ready");
3886            }
3887            drain_maintenance(&manager);
3888            assert!(
3889                source.upgrade().is_some(),
3890                "both cursors pin the retired source"
3891            );
3892            let active_bytes = manager.sealed.read()[0].read().resident_bytes();
3893            let held = manager.resident_bytes();
3894            assert!(
3895                held >= active_bytes + source_bytes,
3896                "retired source remains resident"
3897            );
3898            release_first.send(()).expect("release first reader");
3899            first.join().expect("first reader");
3900            assert_eq!(
3901                manager.resident_bytes(),
3902                held,
3903                "one reader still pins the source"
3904            );
3905            release_last.send(()).expect("release last reader");
3906            last.join().expect("last reader");
3907            assert!(
3908                source.upgrade().is_none(),
3909                "accounting must not retain payloads"
3910            );
3911            assert_eq!(held - manager.resident_bytes(), source_bytes);
3912            assert_eq!(
3913                manager.stats().total_memory_bytes as u64,
3914                manager.resident_bytes()
3915            );
3916        });
3917    }
3918
3919    #[test]
3920    fn retained_memory_gates_runtime_growth_until_the_cursor_is_cancelled() {
3921        use crate::storage::memory_pools::MemoryPool;
3922        use crate::{RedDBOptions, RedDBRuntime};
3923
3924        let budget = 128 * 1024;
3925        let runtime =
3926            RedDBRuntime::with_options(RedDBOptions::in_memory().with_memory_budget(budget))
3927                .expect("runtime");
3928        runtime
3929            .db()
3930            .store()
3931            .create_collection("test")
3932            .expect("collection");
3933        let manager = runtime
3934            .db()
3935            .store()
3936            .get_collection("test")
3937            .expect("manager");
3938        let ids = seal_bulk_segment(&manager, 100);
3939        for id in ids.iter().take(40) {
3940            manager.delete(*id).expect("delete before scan");
3941        }
3942        let source_bytes = manager.resident_bytes();
3943        let mut growth = 0;
3944        let mut held_used = 0;
3945        assert!(!manager.scan_batches(
3946            None,
3947            || true,
3948            |_| {
3949                drain_maintenance(&manager);
3950                runtime.refresh_memory_accounting();
3951                // Other collections (including the runtime catalog) share this
3952                // arena, so derive headroom from the complete runtime sample.
3953                held_used = runtime.memory_accounting().total_used_bytes();
3954                growth = budget
3955                    .checked_sub(held_used)
3956                    .expect("fixture fits while the cursor is open")
3957                    + source_bytes / 2;
3958                assert!(growth > 0);
3959                assert!(
3960                    runtime
3961                        .admit_non_evictable_growth(
3962                            MemoryPool::SegmentArena,
3963                            "growth with pinned source",
3964                            growth,
3965                        )
3966                        .is_err(),
3967                    "retained source must participate in runtime admission"
3968                );
3969                false
3970            }
3971        ));
3972        runtime.refresh_memory_accounting();
3973        assert_eq!(
3974            held_used - runtime.memory_accounting().total_used_bytes(),
3975            source_bytes
3976        );
3977        let _reservation = runtime
3978            .admit_non_evictable_growth(
3979                MemoryPool::SegmentArena,
3980                "growth after cursor cancellation",
3981                growth,
3982            )
3983            .expect("the same growth fits once the cursor releases its source");
3984    }
3985
3986    #[test]
3987    fn retained_memory_includes_an_inflight_consolidation_copy() {
3988        let manager = consolidating_manager(1);
3989        let ids = seal_bulk_segment(&manager, 100);
3990        for id in ids.iter().take(40) {
3991            manager.delete(*id).expect("delete");
3992        }
3993        let before = manager.resident_bytes();
3994        assert!(manager.pressure_consolidation_tick());
3995        let copied = manager
3996            .consolidation
3997            .read()
3998            .as_ref()
3999            .expect("paced merge")
4000            .merged
4001            .resident_bytes();
4002        assert!(copied > 0);
4003        assert!(
4004            manager.resident_bytes() >= before + copied,
4005            "unpublished copy consumes memory"
4006        );
4007        drain_maintenance(&manager);
4008        assert!(
4009            manager.resident_bytes() < before,
4010            "completed merge releases the old storage"
4011        );
4012    }
4013
4014    #[test]
4015    fn delete_heavy_workload_reclaims_tombstoned_memory_and_counts_it() {
4016        let manager = consolidating_manager(CONSOLIDATION_ENTITIES_PER_TICK);
4017        let ids = seal_bulk_segment(&manager, 100);
4018
4019        let bytes_before_delete = manager.resident_bytes();
4020
4021        // 40% tombstones — past CONSOLIDATION_TOMBSTONE_RATIO.
4022        for id in ids.iter().take(40) {
4023            assert!(manager.delete(*id).expect("delete"));
4024        }
4025
4026        // Tombstones cost memory: the payload stays resident in flat storage
4027        // and the tombstone set grows.
4028        let bytes_with_tombstones = manager.resident_bytes();
4029        assert!(bytes_with_tombstones > bytes_before_delete);
4030
4031        let survivors = live_ids(&manager);
4032        assert_eq!(survivors.len(), 60);
4033
4034        drain_maintenance(&manager);
4035
4036        let stats = manager.stats();
4037        assert_eq!(stats.consolidation.runs_started, 1);
4038        assert_eq!(stats.consolidation.runs_completed, 1);
4039        assert_eq!(stats.consolidation.segments_merged, 1);
4040        assert_eq!(stats.consolidation.tombstones_reclaimed, 40);
4041        assert!(stats.consolidation.bytes_reclaimed > 0);
4042
4043        // The reclaimed memory is at least the tombstoned entities' share.
4044        let bytes_after = manager.resident_bytes();
4045        assert!(
4046            bytes_after <= bytes_before_delete,
4047            "consolidation must return the tombstones' memory: {bytes_after} > {bytes_before_delete}"
4048        );
4049        assert_eq!(
4050            bytes_with_tombstones - bytes_after,
4051            stats.consolidation.bytes_reclaimed
4052        );
4053        assert_eq!(stats.total_memory_bytes, bytes_after as usize);
4054
4055        assert_eq!(live_ids(&manager), survivors);
4056        assert_eq!(manager.sealed.read().len(), 1);
4057        assert_eq!(manager.sealed.read()[0].read().tombstone_count(), 0);
4058    }
4059
4060    #[test]
4061    fn query_results_are_identical_before_during_and_after_consolidation() {
4062        let manager = consolidating_manager(3);
4063        let ids = seal_bulk_segment(&manager, 20);
4064        seal_bulk_segment(&manager, 20);
4065        for id in ids.iter().take(10) {
4066            assert!(manager.delete(*id).expect("delete"));
4067        }
4068
4069        let before = live_ids(&manager);
4070        let survivor = *ids.last().expect("at least one row");
4071        let tombstoned = ids[0];
4072
4073        // Every mid-tick observation matches the pre-consolidation snapshot:
4074        // point reads, full scans, and the kind index (rebuilt by the merge).
4075        let mut mid_tick_observations = 0;
4076        while manager.consolidation.read().is_some() || mid_tick_observations == 0 {
4077            manager.run_maintenance().expect("maintenance");
4078            assert_eq!(live_ids(&manager), before);
4079            assert!(manager.get(survivor).is_some());
4080            assert!(manager.get(tombstoned).is_none());
4081            assert_eq!(manager.get_by_kind("table").len(), before.len());
4082            mid_tick_observations += 1;
4083            assert!(mid_tick_observations < 1_000);
4084        }
4085
4086        assert!(
4087            mid_tick_observations > 2,
4088            "expected the run to span several ticks, saw {mid_tick_observations}"
4089        );
4090        assert_eq!(live_ids(&manager), before);
4091        assert!(manager.get(survivor).is_some());
4092        assert!(manager.get(tombstoned).is_none());
4093        assert_eq!(manager.get_by_kind("table").len(), before.len());
4094    }
4095
4096    #[test]
4097    fn get_by_kind_reaches_sealed_segments() {
4098        let manager = consolidating_manager(CONSOLIDATION_ENTITIES_PER_TICK);
4099        let ids = seal_bulk_segment(&manager, 5);
4100        assert!(manager.delete(ids[0]).expect("delete"));
4101
4102        // The sealed list is walked through the segment read guard; the
4103        // `Arc<RwLock<GrowingSegment>>` impl of `iter_kind` cannot hand out
4104        // references across the lock and yields nothing.
4105        assert_eq!(manager.get_by_kind("table").len(), 4);
4106        assert_eq!(manager.get_by_kind("vector").len(), 0);
4107    }
4108
4109    #[test]
4110    fn consolidation_is_paced_by_the_per_tick_entity_bound() {
4111        const PER_TICK: usize = 4;
4112        let manager = consolidating_manager(PER_TICK);
4113        let ids = seal_bulk_segment(&manager, 60);
4114        for id in ids.iter().take(30) {
4115            assert!(manager.delete(*id).expect("delete"));
4116        }
4117
4118        // First tick opens the run and copies exactly one bound's worth.
4119        manager.run_maintenance().expect("maintenance");
4120        assert_eq!(manager.consolidation_progress(), Some(PER_TICK as u64));
4121
4122        // Each subsequent tick advances by no more than the bound, and the run
4123        // is still in flight — it never completes in one unbounded pass.
4124        let mut previous = PER_TICK as u64;
4125        let mut ticks = 1;
4126        while let Some(copied) = manager.consolidation_progress() {
4127            assert!(
4128                copied - previous <= PER_TICK as u64,
4129                "tick copied {} entities, bound is {PER_TICK}",
4130                copied - previous
4131            );
4132            previous = copied;
4133            manager.run_maintenance().expect("maintenance");
4134            ticks += 1;
4135            assert!(ticks < 100);
4136        }
4137
4138        // 30 survivors at 4 per tick: the run cannot have finished before the
4139        // eighth tick.
4140        assert!(ticks >= 8, "consolidation completed in only {ticks} ticks");
4141        assert_eq!(manager.stats().consolidation.runs_completed, 1);
4142        assert_eq!(live_ids(&manager).len(), 30);
4143    }
4144
4145    #[test]
4146    fn sealed_segment_count_above_the_limit_triggers_a_merge() {
4147        let manager = SegmentManager::with_config(
4148            "test",
4149            ManagerConfig {
4150                max_sealed_segments: 3,
4151                ..Default::default()
4152            },
4153        );
4154        for _ in 0..4 {
4155            seal_bulk_segment(&manager, 5);
4156        }
4157        assert_eq!(manager.sealed.read().len(), 4);
4158
4159        let before = live_ids(&manager);
4160        drain_maintenance(&manager);
4161
4162        // The knob finally does what it claimed: the sealed set collapses even
4163        // though not a single row was deleted.
4164        assert_eq!(manager.sealed.read().len(), 1);
4165        assert_eq!(manager.stats().consolidation.segments_merged, 4);
4166        assert_eq!(manager.stats().consolidation.tombstones_reclaimed, 0);
4167        assert_eq!(live_ids(&manager), before);
4168    }
4169
4170    #[test]
4171    fn a_clean_sealed_set_below_the_limit_is_never_consolidated() {
4172        let manager = consolidating_manager(CONSOLIDATION_ENTITIES_PER_TICK);
4173        seal_bulk_segment(&manager, 10);
4174        seal_bulk_segment(&manager, 10);
4175
4176        for _ in 0..5 {
4177            manager.run_maintenance().expect("maintenance");
4178        }
4179
4180        assert_eq!(manager.stats().consolidation.runs_started, 0);
4181        assert_eq!(manager.sealed.read().len(), 2);
4182    }
4183
4184    #[test]
4185    fn concurrent_readers_never_observe_a_missing_or_duplicated_entity() {
4186        use std::sync::atomic::AtomicBool;
4187
4188        let manager = Arc::new(consolidating_manager(2));
4189        let ids = seal_bulk_segment(&manager, 40);
4190        seal_bulk_segment(&manager, 40);
4191        for id in ids.iter().take(20) {
4192            assert!(manager.delete(*id).expect("delete"));
4193        }
4194
4195        let expected = live_ids(&manager);
4196        let stop = Arc::new(AtomicBool::new(false));
4197
4198        let readers: Vec<_> = (0..4)
4199            .map(|_| {
4200                let manager = Arc::clone(&manager);
4201                let stop = Arc::clone(&stop);
4202                let expected = expected.clone();
4203                std::thread::spawn(move || {
4204                    let mut scans = 0u64;
4205                    // Do-while: every reader scans at least once even when the
4206                    // drain finishes before this thread is first scheduled.
4207                    loop {
4208                        let mut seen: Vec<u64> = manager
4209                            .query_all(|_| true)
4210                            .into_iter()
4211                            .map(|entity| entity.id.raw())
4212                            .collect();
4213                        seen.sort_unstable();
4214                        // Sorting is not enough: a duplicated row would keep
4215                        // the set equal but change the length.
4216                        assert_eq!(seen, expected, "reader saw a torn sealed set");
4217                        scans += 1;
4218                        if stop.load(Ordering::Relaxed) {
4219                            break;
4220                        }
4221                    }
4222                    scans
4223                })
4224            })
4225            .collect();
4226
4227        drain_maintenance(&manager);
4228        stop.store(true, Ordering::Relaxed);
4229
4230        for reader in readers {
4231            let scans = reader.join().expect("reader thread");
4232            assert!(scans > 0, "reader never got to scan");
4233        }
4234
4235        assert_eq!(manager.stats().consolidation.runs_completed, 1);
4236        assert_eq!(live_ids(&manager), expected);
4237    }
4238
4239    #[test]
4240    fn a_row_deleted_mid_consolidation_is_not_resurrected_by_the_swap() {
4241        let manager = consolidating_manager(4);
4242        let ids = seal_bulk_segment(&manager, 20);
4243        for id in ids.iter().take(6) {
4244            assert!(manager.delete(*id).expect("delete"));
4245        }
4246
4247        // Copy the first bound's worth, then delete a row we just copied.
4248        manager.run_maintenance().expect("maintenance");
4249        assert_eq!(manager.consolidation_progress(), Some(4));
4250        let doomed = ids[6];
4251        assert!(manager.delete(doomed).expect("delete"));
4252
4253        let expected = live_ids(&manager);
4254        drain_maintenance(&manager);
4255
4256        assert!(manager.get(doomed).is_none(), "deleted row came back");
4257        assert_eq!(live_ids(&manager), expected);
4258    }
4259
4260    #[test]
4261    fn discarding_an_in_flight_consolidation_leaves_the_data_untouched() {
4262        let manager = consolidating_manager(3);
4263        let ids = seal_bulk_segment(&manager, 30);
4264        for id in ids.iter().take(12) {
4265            assert!(manager.delete(*id).expect("delete"));
4266        }
4267
4268        let before = live_ids(&manager);
4269        let sealed_before: Vec<SegmentId> = manager
4270            .sealed
4271            .read()
4272            .iter()
4273            .map(|segment| segment.read().id())
4274            .collect();
4275
4276        manager.run_maintenance().expect("maintenance");
4277        manager.run_maintenance().expect("maintenance");
4278        assert!(manager.consolidation.read().is_some());
4279
4280        // A crash between ticks drops the half-built merged segment. Sealed
4281        // segments are the durable truth, so nothing was lost — and the run is
4282        // simply started over.
4283        *manager.consolidation.write() = None;
4284
4285        assert_eq!(live_ids(&manager), before);
4286        let sealed_after: Vec<SegmentId> = manager
4287            .sealed
4288            .read()
4289            .iter()
4290            .map(|segment| segment.read().id())
4291            .collect();
4292        assert_eq!(sealed_after, sealed_before);
4293        assert_eq!(manager.stats().consolidation.runs_completed, 0);
4294
4295        drain_maintenance(&manager);
4296        assert_eq!(live_ids(&manager), before);
4297        assert_eq!(manager.stats().consolidation.runs_completed, 1);
4298    }
4299
4300    #[test]
4301    fn consolidation_preserves_entity_payload_metadata_and_sequence() {
4302        let manager = consolidating_manager(CONSOLIDATION_ENTITIES_PER_TICK);
4303
4304        // Metadata must be attached before the seal: `set_metadata` on a sealed
4305        // row rewrites it into the growing segment, which would take it out of
4306        // the segment under test.
4307        let entities: Vec<UnifiedEntity> = (0..10)
4308            .map(|i| {
4309                UnifiedEntity::table_row(
4310                    manager.next_entity_id(),
4311                    "users",
4312                    i as u64,
4313                    vec![Value::Integer(i as i64)],
4314                )
4315            })
4316            .collect();
4317        let ids = manager.bulk_insert(entities).expect("bulk insert");
4318
4319        let mut meta = Metadata::new();
4320        meta.set(
4321            "os",
4322            super::super::metadata::MetadataValue::String("linux".to_string()),
4323        );
4324        manager.set_metadata(ids[9], meta).expect("set metadata");
4325        manager.force_seal().expect("seal");
4326
4327        assert!(manager.delete(ids[0]).expect("delete"));
4328        assert!(manager.delete(ids[1]).expect("delete"));
4329        assert!(manager.delete(ids[2]).expect("delete"));
4330
4331        let before: Vec<UnifiedEntity> = {
4332            let mut entities = manager.query_all(|_| true);
4333            entities.sort_by_key(|entity| entity.id.raw());
4334            entities
4335        };
4336
4337        drain_maintenance(&manager);
4338
4339        let after: Vec<UnifiedEntity> = {
4340            let mut entities = manager.query_all(|_| true);
4341            entities.sort_by_key(|entity| entity.id.raw());
4342            entities
4343        };
4344
4345        let columns = |entity: &UnifiedEntity| match &entity.data {
4346            super::super::entity::EntityData::Row(row) => row.columns.clone(),
4347            _ => Vec::new(),
4348        };
4349
4350        assert_eq!(before.len(), after.len());
4351        for (old, new) in before.iter().zip(after.iter()) {
4352            assert_eq!(old.id, new.id);
4353            assert_eq!(columns(old), columns(new));
4354            assert_eq!(
4355                old.sequence_id, new.sequence_id,
4356                "merge must not re-issue sequence ids"
4357            );
4358        }
4359        assert!(manager
4360            .get_metadata(ids[9])
4361            .expect("metadata survives the merge")
4362            .has("os"));
4363    }
4364
4365    #[test]
4366    #[ignore = "lifecycle events intentionally no-op since the emit-channel refactor; drain_events returns empty — see SegmentManager::emit"]
4367    fn test_lifecycle_events() {
4368        let manager = SegmentManager::new("test");
4369
4370        manager
4371            .insert(UnifiedEntity::vector(
4372                manager.next_entity_id(),
4373                "v",
4374                vec![0.1],
4375            ))
4376            .unwrap();
4377
4378        let events = manager.drain_events();
4379
4380        // Should have: SegmentCreated, EntityInserted
4381        assert!(events
4382            .iter()
4383            .any(|e| matches!(e, LifecycleEvent::SegmentCreated(_))));
4384        assert!(events
4385            .iter()
4386            .any(|e| matches!(e, LifecycleEvent::EntityInserted(_, _))));
4387    }
4388}