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 rows in the same stable ID order as sorting `query_all`, without
1481    /// cloning their payloads. The caller fences mutations while fingerprinting.
1482    /// Pin source segments, but hold only one segment guard during each visit.
1483    /// Callbacks must not re-enter storage while that guard is held.
1484    pub(crate) fn for_each_entity_in_id_order(
1485        &self,
1486        mut visit: impl FnMut(&UnifiedEntity) -> bool,
1487    ) {
1488        let segments: Vec<_> = {
1489            let growing = self.growing.read();
1490            let sealed = self.sealed.read();
1491            growing.iter().chain(sealed.iter()).cloned().collect()
1492        };
1493        let mut order = Vec::new();
1494        for (source, segment) in segments.iter().enumerate() {
1495            segment.read().for_each_fast(|entity| {
1496                order.push((entity.id, source));
1497                true
1498            });
1499        }
1500        order.sort_by_key(|(id, _)| id.raw());
1501        for (id, source) in order {
1502            let segment = segments[source].read();
1503            if let Some(entity) = segment.get(id) {
1504                if !visit(entity) {
1505                    break;
1506                }
1507            }
1508        }
1509    }
1510
1511    /// Visit borrowed rows with metadata under the same segment read guard.
1512    /// Callbacks must not re-enter this manager while the guard is held.
1513    pub(crate) fn for_each_entity_with_metadata(
1514        &self,
1515        mut callback: impl FnMut(&UnifiedEntity, Option<Metadata>) -> bool,
1516    ) {
1517        if let Some(growing_arc) = self.growing.read().as_ref() {
1518            let growing = growing_arc.read();
1519            if !growing.for_each_fast(|entity| callback(entity, growing.get_metadata(entity.id))) {
1520                return;
1521            }
1522        }
1523        let sealed = self.sealed.read();
1524        for segment_arc in sealed.iter() {
1525            let segment = segment_arc.read();
1526            if !segment.for_each_fast(|entity| callback(entity, segment.get_metadata(entity.id))) {
1527                return;
1528            }
1529        }
1530    }
1531
1532    fn for_each_entity_in_segments<F>(
1533        &self,
1534        segment_filter: impl Fn(&GrowingSegment) -> bool,
1535        mut before_segment: impl FnMut() -> bool,
1536        mut callback: F,
1537    ) where
1538        F: FnMut(&UnifiedEntity) -> bool,
1539    {
1540        // Growing segment — direct iteration (no Box<dyn>)
1541        // Try non-blocking read first; fall back to blocking only when a writer
1542        // is actively holding the write lock (rare in read-heavy workloads).
1543        if let Some(growing_arc) = self.growing.read().as_ref() {
1544            if !before_segment() {
1545                return;
1546            }
1547            let growing = if let Some(g) = growing_arc.try_read() {
1548                g
1549            } else {
1550                growing_arc.read()
1551            };
1552            if segment_filter(&growing) && !growing.for_each_fast(&mut callback) {
1553                return;
1554            }
1555        }
1556
1557        // Sealed segments
1558        let sealed = self.sealed.read();
1559        for segment_arc in sealed.iter() {
1560            if !before_segment() {
1561                return;
1562            }
1563            let segment = segment_arc.read();
1564            if segment_filter(&segment) && !segment.for_each_fast(&mut callback) {
1565                return;
1566            }
1567        }
1568    }
1569
1570    /// Parallel fold across all entities. Each sealed segment is
1571    /// processed on its own rayon task; the growing segment stays on
1572    /// the caller thread (its read lock is briefly held).
1573    ///
1574    /// - `init` builds a fresh accumulator per thread.
1575    /// - `fold` mutates an accumulator with one entity at a time.
1576    /// - `reduce` combines two accumulators into one.
1577    ///
1578    /// The returned value is the reduction of every per-thread
1579    /// accumulator. Use this for aggregate-shape workloads (GROUP BY)
1580    /// where per-thread partial state can be merged cheaply.
1581    ///
1582    /// NOTE: when there are 0 or 1 sealed segments, the parallel path
1583    /// is skipped and the work runs sequentially to avoid rayon
1584    /// overhead on tiny tables.
1585    pub fn fold_entities_parallel<T, FInit, FFold, FReduce>(
1586        &self,
1587        init: FInit,
1588        fold: FFold,
1589        reduce: FReduce,
1590    ) -> T
1591    where
1592        T: Send,
1593        FInit: Fn() -> T + Send + Sync,
1594        FFold: Fn(T, &UnifiedEntity) -> T + Send + Sync,
1595        FReduce: Fn(T, T) -> T + Send + Sync,
1596    {
1597        use rayon::prelude::*;
1598
1599        // Growing segment — always sequential (single writer lock,
1600        // usually small working set).
1601        let mut acc = init();
1602        if let Some(growing_arc) = self.growing.read().as_ref() {
1603            let growing = if let Some(g) = growing_arc.try_read() {
1604                g
1605            } else {
1606                growing_arc.read()
1607            };
1608            growing.for_each_fast(|entity| {
1609                acc = fold(std::mem::replace(&mut acc, init()), entity);
1610                true
1611            });
1612        }
1613
1614        // Sealed segments — snapshot the Arc list under the read lock,
1615        // then drop the lock so rayon workers can fan out without
1616        // blocking writers.
1617        let segments: Vec<_> = {
1618            let sealed = self.sealed.read();
1619            sealed.iter().cloned().collect()
1620        };
1621
1622        if segments.len() <= 1 {
1623            for seg_arc in &segments {
1624                let seg = seg_arc.read();
1625                seg.for_each_fast(|entity| {
1626                    acc = fold(std::mem::replace(&mut acc, init()), entity);
1627                    true
1628                });
1629            }
1630            return acc;
1631        }
1632
1633        let sealed_acc = segments
1634            .into_par_iter()
1635            .map(|seg_arc| {
1636                let mut local = init();
1637                let seg = seg_arc.read();
1638                seg.for_each_fast(|entity| {
1639                    local = fold(std::mem::replace(&mut local, init()), entity);
1640                    true
1641                });
1642                local
1643            })
1644            .reduce(&init, &reduce);
1645
1646        reduce(acc, sealed_acc)
1647    }
1648
1649    /// Zone-map-aware iteration across all segments.
1650    ///
1651    /// Like `for_each_entity`, but checks `zone_preds` against each segment's
1652    /// column zone maps before iterating. Segments where any predicate can
1653    /// definitively prove no rows match are skipped entirely.
1654    ///
1655    /// `zone_preds`: slice of `(column_name, ZoneColPred)` extracted from the WHERE clause.
1656    /// Empty slice → same behaviour as `for_each_entity` (no pruning).
1657    pub fn for_each_entity_zoned<F>(&self, zone_preds: &[(&str, ZoneColPred<'_>)], mut callback: F)
1658    where
1659        F: FnMut(&UnifiedEntity) -> bool,
1660    {
1661        let _ = self.for_each_entity_zoned_with_stats(zone_preds, &mut callback);
1662    }
1663
1664    pub fn for_each_entity_zoned_with_stats<F>(
1665        &self,
1666        zone_preds: &[(&str, ZoneColPred<'_>)],
1667        mut callback: F,
1668    ) -> SegmentScanStats
1669    where
1670        F: FnMut(&UnifiedEntity) -> bool,
1671    {
1672        let mut scan_stats = SegmentScanStats::default();
1673        // Growing segment — never skip (it's receiving writes, zones are partial).
1674        // Try a non-blocking read first: if a writer is currently inserting
1675        // (holding the write lock), try_read() returns None and we fall back to
1676        // the blocking read.  In low-contention workloads (reads far outnumber
1677        // writes) the try_read() almost always succeeds and readers never stall.
1678        if let Some(growing_arc) = self.growing.read().as_ref() {
1679            scan_stats.segments_total += 1;
1680            scan_stats.segments_scanned += 1;
1681            let growing = if let Some(g) = growing_arc.try_read() {
1682                g
1683            } else {
1684                growing_arc.read()
1685            };
1686            if !growing.for_each_fast(&mut callback) {
1687                return scan_stats;
1688            }
1689        }
1690
1691        // Sealed segments — check zone maps before iterating
1692        let sealed = self.sealed.read();
1693        for segment_arc in sealed.iter() {
1694            scan_stats.segments_total += 1;
1695            let segment = segment_arc.read();
1696            if !zone_preds.is_empty() && segment.can_skip_zone_preds(zone_preds) {
1697                scan_stats.segments_pruned += 1;
1698                continue; // entire segment pruned
1699            }
1700            scan_stats.segments_scanned += 1;
1701            if !segment.for_each_fast(&mut callback) {
1702                return scan_stats;
1703            }
1704        }
1705        scan_stats
1706    }
1707
1708    /// Zone-map-aware parallel query.
1709    ///
1710    /// Like `query_all` but applies `zone_preds` on the main thread to
1711    /// prune sealed segments before spawning workers — segments that
1712    /// provably contain no matching rows are skipped entirely.
1713    ///
1714    /// Zone check runs single-threaded (it reads per-segment metadata,
1715    /// not row data), so it's cheap. Surviving segments are then scanned
1716    /// in parallel using `std::thread::scope` when there are > 1 of them.
1717    pub fn query_all_zoned<F>(
1718        &self,
1719        zone_preds: &[(&str, ZoneColPred<'_>)],
1720        filter: F,
1721    ) -> Vec<UnifiedEntity>
1722    where
1723        F: Fn(&UnifiedEntity) -> bool + Sync,
1724    {
1725        self.query_all_zoned_with_stats(zone_preds, filter).0
1726    }
1727
1728    pub fn query_all_zoned_with_stats<F>(
1729        &self,
1730        zone_preds: &[(&str, ZoneColPred<'_>)],
1731        filter: F,
1732    ) -> (Vec<UnifiedEntity>, SegmentScanStats)
1733    where
1734        F: Fn(&UnifiedEntity) -> bool + Sync,
1735    {
1736        let mut results = Vec::new();
1737        let mut scan_stats = SegmentScanStats::default();
1738
1739        // Growing segment — always scan, no zone skip (zones are partial).
1740        // Non-blocking try_read() avoids stalling behind in-progress inserts.
1741        if let Some(growing_arc) = self.growing.read().as_ref() {
1742            scan_stats.segments_total += 1;
1743            scan_stats.segments_scanned += 1;
1744            let growing = if let Some(g) = growing_arc.try_read() {
1745                g
1746            } else {
1747                growing_arc.read()
1748            };
1749            results.extend(growing.iter().filter(|e| filter(e)).cloned());
1750        }
1751
1752        // Sealed segments: zone-prune on main thread, then scan in parallel.
1753        let sealed = self.sealed.read();
1754        // Collect only the segments that survive zone-predicate pruning.
1755        let surviving: Vec<_> = sealed
1756            .iter()
1757            .filter(|seg_arc| {
1758                scan_stats.segments_total += 1;
1759                if zone_preds.is_empty() {
1760                    scan_stats.segments_scanned += 1;
1761                    return true;
1762                }
1763                let seg = seg_arc.read();
1764                if seg.can_skip_zone_preds(zone_preds) {
1765                    scan_stats.segments_pruned += 1;
1766                    false
1767                } else {
1768                    scan_stats.segments_scanned += 1;
1769                    true
1770                }
1771            })
1772            .collect();
1773
1774        let use_parallel = surviving.len() > 1 && crate::runtime::SystemInfo::should_parallelize();
1775
1776        if use_parallel {
1777            let filter_ref = &filter;
1778            let segment_results: Vec<Vec<UnifiedEntity>> = std::thread::scope(|s| {
1779                surviving
1780                    .iter()
1781                    .map(|segment| {
1782                        s.spawn(move || {
1783                            segment
1784                                .read()
1785                                .iter()
1786                                .filter(|e| filter_ref(e))
1787                                .cloned()
1788                                .collect::<Vec<_>>()
1789                        })
1790                    })
1791                    .collect::<Vec<_>>()
1792                    .into_iter()
1793                    .map(|handle| handle.join().unwrap_or_default())
1794                    .collect()
1795            });
1796            for batch in segment_results {
1797                results.extend(batch);
1798            }
1799        } else {
1800            for segment_arc in surviving {
1801                let seg = segment_arc.read();
1802                results.extend(seg.iter().filter(|e| filter(e)).cloned());
1803            }
1804        }
1805
1806        (results, scan_stats)
1807    }
1808
1809    /// Visibility predicate for the `scan_*` family. `Some` delegates to the
1810    /// canonical `entity_visible_with_context`; `None` supports low-level
1811    /// callers that intentionally scan without a statement snapshot and keeps
1812    /// the documented resolver fallback — moderation gate plus hiding
1813    /// superseded physical versions — instead of showing every version.
1814    fn scan_entity_visible(snapshot: Option<&SnapshotContext>, entity: &UnifiedEntity) -> bool {
1815        match snapshot {
1816            Some(ctx) => entity_visible_with_context(Some(ctx), entity),
1817            None => {
1818                !crate::runtime::ai::moderation::entity_moderation_hidden(entity)
1819                    && entity.xmax == 0
1820            }
1821        }
1822    }
1823
1824    /// Scan every segment under an explicit MVCC snapshot.
1825    ///
1826    /// Visibility is evaluated while each segment iterator is active, before
1827    /// the caller's filter. Unlike the raw iteration methods, this entry point
1828    /// does not consult thread-local snapshot state, so it preserves the same
1829    /// view when invoked from a different thread.
1830    pub fn scan<F>(&self, snapshot: Option<&SnapshotContext>, filter: F) -> Vec<UnifiedEntity>
1831    where
1832        F: Fn(&UnifiedEntity) -> bool + Sync,
1833    {
1834        self.query_all(|entity| Self::scan_entity_visible(snapshot, entity) && filter(entity))
1835    }
1836
1837    /// Collect visible graph items, pruning only under the segment read guard.
1838    pub(crate) fn scan_graph_kind(
1839        &self,
1840        snapshot: Option<&SnapshotContext>,
1841        kind: GraphEntityKind,
1842    ) -> Vec<UnifiedEntity> {
1843        self.query_all_in_segments(
1844            |segment| segment.may_contain_graph_kind(kind),
1845            |entity| Self::scan_entity_visible(snapshot, entity) && kind.matches(&entity.kind),
1846        )
1847    }
1848
1849    /// Visit visible candidates in segments that may contain the requested kind.
1850    /// Non-graph items in those segments still reach the callback so work budgets
1851    /// charge every inspected visible candidate. RLS must run outside this callback.
1852    /// `before_segment` runs even for pruned segments; false stops the entire scan.
1853    pub(crate) fn scan_graph_candidates_for_each<F>(
1854        &self,
1855        snapshot: Option<&SnapshotContext>,
1856        kind: GraphEntityKind,
1857        before_segment: impl FnMut() -> bool,
1858        mut callback: F,
1859    ) where
1860        F: FnMut(&UnifiedEntity) -> bool,
1861    {
1862        self.for_each_entity_in_segments(
1863            |segment| segment.may_contain_graph_kind(kind),
1864            before_segment,
1865            |entity| !Self::scan_entity_visible(snapshot, entity) || callback(entity),
1866        );
1867    }
1868
1869    /// Visit every entity visible under an explicit MVCC snapshot.
1870    ///
1871    /// Returning `false` from `callback` stops the scan early. Hidden entities
1872    /// never reach the callback and therefore cannot stop the scan.
1873    pub fn scan_for_each<F>(&self, snapshot: Option<&SnapshotContext>, mut callback: F)
1874    where
1875        F: FnMut(&UnifiedEntity) -> bool,
1876    {
1877        self.for_each_entity(|entity| {
1878            !Self::scan_entity_visible(snapshot, entity) || callback(entity)
1879        });
1880    }
1881
1882    /// Capture segment membership and append boundaries, then hydrate bounded
1883    /// batches. The consumer runs outside topology and segment locks, so scoring
1884    /// and RLS may re-enter storage and writers can progress between batches.
1885    /// Retired sources pin positions only; hydration uses current segments so
1886    /// mutations after consolidation are visible to the snapshot predicate.
1887    pub(crate) fn scan_batches(
1888        &self,
1889        snapshot: Option<&SnapshotContext>,
1890        mut before_work: impl FnMut() -> bool,
1891        mut consume: impl FnMut(&[UnifiedEntity]) -> bool,
1892    ) -> bool {
1893        let segments = {
1894            let growing = self.growing.read();
1895            let sealed = self.sealed.read();
1896            let mut segments = Vec::with_capacity(sealed.len() + usize::from(growing.is_some()));
1897            for segment in growing.iter().chain(sealed.iter()) {
1898                if !before_work() {
1899                    return false;
1900                }
1901                let cursor = segment.read().scan_cursor();
1902                segments.push((Arc::clone(segment), cursor));
1903            }
1904            segments
1905        };
1906        let mut ids = Vec::new();
1907        let mut batch = Vec::new();
1908        for (segment, mut cursor) in segments {
1909            while !cursor.finished() {
1910                ids.clear();
1911                batch.clear();
1912                let batch_size = cursor.remaining().min(super::segment::SCAN_BATCH_SIZE);
1913                ids.reserve_exact(batch_size);
1914                batch.reserve_exact(batch_size);
1915                {
1916                    let segment = segment.read();
1917                    if !segment.scan_batch(&mut cursor, &mut before_work, &mut |id| ids.push(id)) {
1918                        return false;
1919                    }
1920                }
1921                // Sources can retire between batches. Consult authoritative storage
1922                // after releasing the source guard, just as the former ID-list scan did.
1923                if !before_work() {
1924                    return false;
1925                }
1926                self.for_each_id(&ids, |_, entity| {
1927                    if Self::scan_entity_visible(snapshot, entity) {
1928                        batch.push(entity.clone());
1929                    }
1930                });
1931                if !before_work() {
1932                    return false;
1933                }
1934                if !consume(&batch) {
1935                    return false;
1936                }
1937            }
1938        }
1939        true
1940    }
1941
1942    /// Fold entities visible under an explicit MVCC snapshot in parallel.
1943    pub fn scan_fold_parallel<T, FInit, FFold, FReduce>(
1944        &self,
1945        snapshot: Option<&SnapshotContext>,
1946        init: FInit,
1947        fold: FFold,
1948        reduce: FReduce,
1949    ) -> T
1950    where
1951        T: Send,
1952        FInit: Fn() -> T + Send + Sync,
1953        FFold: Fn(T, &UnifiedEntity) -> T + Send + Sync,
1954        FReduce: Fn(T, T) -> T + Send + Sync,
1955    {
1956        self.fold_entities_parallel(
1957            init,
1958            |acc, entity| {
1959                if Self::scan_entity_visible(snapshot, entity) {
1960                    fold(acc, entity)
1961                } else {
1962                    acc
1963                }
1964            },
1965            reduce,
1966        )
1967    }
1968
1969    /// Visit zone-map candidates visible under an explicit MVCC snapshot.
1970    pub fn scan_for_each_zoned_with_stats<F>(
1971        &self,
1972        snapshot: Option<&SnapshotContext>,
1973        zone_preds: &[(&str, ZoneColPred<'_>)],
1974        mut callback: F,
1975    ) -> SegmentScanStats
1976    where
1977        F: FnMut(&UnifiedEntity) -> bool,
1978    {
1979        self.for_each_entity_zoned_with_stats(zone_preds, |entity| {
1980            !Self::scan_entity_visible(snapshot, entity) || callback(entity)
1981        })
1982    }
1983
1984    /// Collect zone-map candidates visible under an explicit MVCC snapshot.
1985    pub fn scan_zoned_with_stats<F>(
1986        &self,
1987        snapshot: Option<&SnapshotContext>,
1988        zone_preds: &[(&str, ZoneColPred<'_>)],
1989        filter: F,
1990    ) -> (Vec<UnifiedEntity>, SegmentScanStats)
1991    where
1992        F: Fn(&UnifiedEntity) -> bool + Sync,
1993    {
1994        self.query_all_zoned_with_stats(zone_preds, |entity| {
1995            Self::scan_entity_visible(snapshot, entity) && filter(entity)
1996        })
1997    }
1998
1999    /// Query across all segments. Uses parallel scanning for sealed segments
2000    /// when more than one sealed segment exists.
2001    pub fn query_all<F>(&self, filter: F) -> Vec<UnifiedEntity>
2002    where
2003        F: Fn(&UnifiedEntity) -> bool + Sync,
2004    {
2005        self.query_all_in_segments(|_| true, filter)
2006    }
2007
2008    fn query_all_in_segments<F>(
2009        &self,
2010        segment_filter: impl Fn(&GrowingSegment) -> bool + Sync,
2011        filter: F,
2012    ) -> Vec<UnifiedEntity>
2013    where
2014        F: Fn(&UnifiedEntity) -> bool + Sync,
2015    {
2016        let mut results = Vec::new();
2017
2018        // Query growing segment — try non-blocking read first (avoids stalling
2019        // behind an in-progress insert; falls back to blocking if writer is active).
2020        if let Some(growing_arc) = self.growing.read().as_ref() {
2021            let growing = if let Some(g) = growing_arc.try_read() {
2022                g
2023            } else {
2024                growing_arc.read()
2025            };
2026            if segment_filter(&growing) {
2027                results.extend(growing.iter().filter(|e| filter(e)).cloned());
2028            }
2029        }
2030
2031        // Query sealed segments — parallel when multiple exist AND multi-core
2032        let sealed = self.sealed.read();
2033        let use_parallel = sealed.len() > 1 && crate::runtime::SystemInfo::should_parallelize();
2034        if use_parallel {
2035            let filter_ref = &filter;
2036            let segment_filter_ref = &segment_filter;
2037            let segment_results: Vec<Vec<UnifiedEntity>> = std::thread::scope(|s| {
2038                sealed
2039                    .iter()
2040                    .map(|segment| {
2041                        s.spawn(move || {
2042                            let segment = segment.read();
2043                            if segment_filter_ref(&segment) {
2044                                segment
2045                                    .iter()
2046                                    .filter(|e| filter_ref(e))
2047                                    .cloned()
2048                                    .collect::<Vec<_>>()
2049                            } else {
2050                                Vec::new()
2051                            }
2052                        })
2053                    })
2054                    .collect::<Vec<_>>()
2055                    .into_iter()
2056                    .map(|handle| handle.join().unwrap_or_default())
2057                    .collect()
2058            });
2059            for batch in segment_results {
2060                results.extend(batch);
2061            }
2062        } else {
2063            for segment in sealed.iter() {
2064                let seg = segment.read();
2065                if segment_filter(&seg) {
2066                    results.extend(seg.iter().filter(|e| filter(e)).cloned());
2067                }
2068            }
2069        }
2070
2071        results
2072    }
2073
2074    /// Probe exact segment membership for a key without materializing matching entities.
2075    ///
2076    /// Returns `false` only when every consulted segment proves absence.
2077    /// Missing segment state is conservative and returns `true`.
2078    pub fn bloom_may_contain_key(&self, key: &[u8]) -> bool {
2079        if let Some(growing_arc) = self.growing.read().as_ref() {
2080            let growing = growing_arc.read();
2081            if growing.may_contain_exact_key(key) {
2082                return true;
2083            }
2084        } else {
2085            return true;
2086        }
2087
2088        let sealed = self.sealed.read();
2089        for segment_arc in sealed.iter() {
2090            let segment = segment_arc.read();
2091            if segment.may_contain_exact_key(key) {
2092                return true;
2093            }
2094        }
2095
2096        false
2097    }
2098
2099    /// Filter by metadata across all segments
2100    pub fn filter_metadata(&self, filters: &[(String, MetadataFilter)]) -> Vec<EntityId> {
2101        let mut results = Vec::new();
2102
2103        // Growing segment
2104        if let Some(growing_arc) = self.growing.read().as_ref() {
2105            let growing = growing_arc.read();
2106            results.extend(growing.filter_metadata(filters));
2107        }
2108
2109        // Sealed segments
2110        let sealed = self.sealed.read();
2111        for segment in sealed.iter() {
2112            results.extend(segment.filter_metadata(filters));
2113        }
2114
2115        results
2116    }
2117
2118    /// Get entities by kind
2119    pub fn get_by_kind(&self, kind: &str) -> Vec<UnifiedEntity> {
2120        let mut results = Vec::new();
2121
2122        // Growing segment
2123        if let Some(growing_arc) = self.growing.read().as_ref() {
2124            let growing = growing_arc.read();
2125            for entity in growing.iter_kind(kind) {
2126                results.push(entity.clone());
2127            }
2128        }
2129
2130        // Sealed segments. Iterate through the read guard, not the
2131        // `Arc<RwLock<GrowingSegment>>` impl of `iter_kind` — that one cannot
2132        // hand out references across the lock, so it returns an empty iterator
2133        // and every sealed entity was silently missing from the result.
2134        let sealed = self.sealed.read();
2135        for segment_arc in sealed.iter() {
2136            let segment = segment_arc.read();
2137            for entity in segment.iter_kind(kind) {
2138                results.push(entity.clone());
2139            }
2140        }
2141
2142        results
2143    }
2144
2145    /// Count entities
2146    pub fn count(&self) -> usize {
2147        self.total_entities_atomic.load(Ordering::Relaxed) as usize
2148    }
2149
2150    /// Get all segment IDs
2151    pub fn segment_ids(&self) -> Vec<SegmentId> {
2152        let mut ids = Vec::new();
2153
2154        if let Some(growing_arc) = self.growing.read().as_ref() {
2155            ids.push(growing_arc.read().id());
2156        }
2157
2158        let sealed = self.sealed.read();
2159        for segment in sealed.iter() {
2160            ids.push(segment.id());
2161        }
2162
2163        ids.extend(self.archived.read().iter().copied());
2164
2165        ids
2166    }
2167
2168    /// Emit a lifecycle event.
2169    ///
2170    /// Perf: this used to push onto a `RwLock<Vec<LifecycleEvent>>`
2171    /// on every insert / delete / seal. Nobody consumes that vec
2172    /// today (no subscription API, `drain_events` has no callers),
2173    /// so the write lock + push was pure tax — and the vec grew
2174    /// unbounded in long-running processes.
2175    ///
2176    /// Current behaviour: no-op. If we ever want the hooks back,
2177    /// replace this with a bounded channel or an actual subscriber
2178    /// registry; the callers (`insert`, `delete`, `maybe_seal_growing`)
2179    /// already pass well-typed events.
2180    #[inline]
2181    #[allow(clippy::unused_self)]
2182    fn emit(&self, _event: LifecycleEvent) {}
2183
2184    /// Drain events. Kept for API compatibility; always returns
2185    /// empty because `emit` no longer buffers.
2186    pub fn drain_events(&self) -> Vec<LifecycleEvent> {
2187        std::mem::take(&mut *self.events.write())
2188    }
2189
2190    /// Run maintenance (would be called periodically in production)
2191    pub fn run_maintenance(&self) -> Result<(), SegmentError> {
2192        // Auto-seal idle segments
2193        self.maybe_seal_growing()?;
2194
2195        if self.config.enable_consolidation {
2196            self.consolidation_tick();
2197        }
2198
2199        Ok(())
2200    }
2201
2202    // ========================================================================
2203    // Consolidation — ADR 0073 §5
2204    // ========================================================================
2205
2206    /// One paced step of sealed-segment consolidation.
2207    ///
2208    /// Starts a run when a threshold has been crossed, copies at most
2209    /// `consolidation_entities_per_tick` live entities into the merged segment,
2210    /// and swaps once every source has been drained. Returns without finishing
2211    /// otherwise — the half-built merged segment waits for the next tick.
2212    fn consolidation_tick(&self) {
2213        // Drop the read guard before `start_consolidation` takes the write
2214        // guard: `parking_lot` locks are not reentrant.
2215        let running = self.consolidation.read().is_some();
2216        if !running && !self.start_consolidation() {
2217            return;
2218        }
2219
2220        // Keep the accounting guard through publication: the merged allocation
2221        // must never disappear between the in-flight and active inventories.
2222        let mut guard = self.consolidation.write();
2223        let Some(run) = guard.as_mut() else {
2224            return;
2225        };
2226        self.copy_bounded(run);
2227        if run.cursor >= run.sources.len() {
2228            if let Some(run) = guard.take() {
2229                self.finish_consolidation(run);
2230            }
2231        }
2232    }
2233
2234    /// Evaluate the trigger and, when it fires, open a consolidation run.
2235    ///
2236    /// Returns `true` when a run was started.
2237    fn start_consolidation(&self) -> bool {
2238        let sources = self.select_candidates();
2239        self.start_consolidation_from_sources(sources)
2240    }
2241
2242    fn start_consolidation_from_sources(&self, sources: Vec<SegmentId>) -> bool {
2243        if sources.len() < 2 && !self.candidates_carry_tombstones(&sources) {
2244            return false;
2245        }
2246
2247        let merged_id = self.next_segment_id.fetch_add(1, Ordering::SeqCst);
2248        let merged = GrowingSegment::new(merged_id, &self.collection);
2249
2250        *self.consolidation.write() = Some(Consolidation {
2251            sources: sources
2252                .into_iter()
2253                .map(|id| SourceProgress {
2254                    id,
2255                    copied: Vec::new(),
2256                    tombstones_at_open: None,
2257                })
2258                .collect(),
2259            merged_id,
2260            merged,
2261            cursor: 0,
2262            pending_ids: Vec::new(),
2263            pending_cursor: 0,
2264            entities_copied: 0,
2265        });
2266
2267        self.stats.write().consolidation.runs_started += 1;
2268        true
2269    }
2270
2271    /// Run one paced consolidation tick because admission pressure needs
2272    /// reclaimable bytes, even if the background thresholds have not fired.
2273    ///
2274    /// Returns true when the call started or advanced a consolidation run.
2275    pub fn pressure_consolidation_tick(&self) -> bool {
2276        if !self.config.enable_consolidation {
2277            return false;
2278        }
2279
2280        let running = self.consolidation.read().is_some();
2281        if !running {
2282            let sources = self.dirty_sealed_segments();
2283            if !self.start_consolidation_from_sources(sources) {
2284                return false;
2285            }
2286        }
2287
2288        self.consolidation_tick();
2289        true
2290    }
2291
2292    /// Which sealed segments this collection should merge, if any.
2293    ///
2294    /// Three thresholds, any of which arms consolidation:
2295    ///
2296    /// * **sealed-segment count** above `max_sealed_segments` — every sealed
2297    ///   segment merges, which is what that knob always claimed to do.
2298    /// * **tombstone ratio** — dead entities over total entities across the
2299    ///   sealed set, past [`CONSOLIDATION_TOMBSTONE_RATIO`].
2300    /// * **fragmentation** — reclaimable bytes over held bytes, past
2301    ///   [`CONSOLIDATION_FRAGMENTATION_RATIO`].
2302    ///
2303    /// The count trigger takes every sealed segment; the two budget triggers
2304    /// take only the segments that actually carry tombstones, so a clean
2305    /// segment is never rewritten for nothing.
2306    fn select_candidates(&self) -> Vec<SegmentId> {
2307        let sealed = self.sealed.read();
2308        if sealed.is_empty() {
2309            return Vec::new();
2310        }
2311
2312        if sealed.len() > self.config.max_sealed_segments {
2313            return sealed.iter().map(|segment| segment.read().id()).collect();
2314        }
2315
2316        let mut live = 0usize;
2317        let mut tombstones = 0usize;
2318        let mut held = 0u64;
2319        let mut reclaimable = 0u64;
2320        let mut dirty = Vec::new();
2321
2322        for segment_arc in sealed.iter() {
2323            let segment = segment_arc.read();
2324            live += segment.live_entity_count();
2325            tombstones += segment.tombstone_count();
2326            held += segment.resident_bytes();
2327            reclaimable += segment.reclaimable_bytes();
2328            if segment.tombstone_count() > 0 {
2329                dirty.push(segment.id());
2330            }
2331        }
2332
2333        let total = live + tombstones;
2334        let tombstone_ratio = if total == 0 {
2335            0.0
2336        } else {
2337            tombstones as f64 / total as f64
2338        };
2339        let fragmentation = if held == 0 {
2340            0.0
2341        } else {
2342            reclaimable as f64 / held as f64
2343        };
2344
2345        if tombstone_ratio >= CONSOLIDATION_TOMBSTONE_RATIO
2346            || fragmentation >= CONSOLIDATION_FRAGMENTATION_RATIO
2347        {
2348            return dirty;
2349        }
2350
2351        Vec::new()
2352    }
2353
2354    fn dirty_sealed_segments(&self) -> Vec<SegmentId> {
2355        self.sealed
2356            .read()
2357            .iter()
2358            .filter_map(|segment_arc| {
2359                let segment = segment_arc.read();
2360                (segment.reclaimable_bytes() > 0).then(|| segment.id())
2361            })
2362            .collect()
2363    }
2364
2365    /// A single candidate is still worth merging when it carries tombstones —
2366    /// the merge drops them. A single clean candidate is not.
2367    fn candidates_carry_tombstones(&self, sources: &[SegmentId]) -> bool {
2368        if sources.is_empty() {
2369            return false;
2370        }
2371        let sealed = self.sealed.read();
2372        sealed.iter().any(|segment_arc| {
2373            let segment = segment_arc.read();
2374            sources.contains(&segment.id()) && segment.tombstone_count() > 0
2375        })
2376    }
2377
2378    fn sealed_segment(&self, id: SegmentId) -> Option<Arc<RwLock<GrowingSegment>>> {
2379        let sealed = self.sealed.read();
2380        sealed
2381            .iter()
2382            .find(|segment| segment.read().id() == id)
2383            .map(Arc::clone)
2384    }
2385
2386    /// Copy at most one tick's worth of live entities into the merged segment.
2387    ///
2388    /// The per-tick bound is the pacing contract: a tick's cost is O(bound),
2389    /// independent of how many entities the run still has to move.
2390    fn copy_bounded(&self, run: &mut Consolidation) {
2391        let mut budget = self.config.consolidation_entities_per_tick;
2392
2393        while budget > 0 && run.cursor < run.sources.len() {
2394            let source_id = run.sources[run.cursor].id;
2395            let Some(source_arc) = self.sealed_segment(source_id) else {
2396                // The source vanished. Only consolidation removes sealed
2397                // segments and it is single-threaded per collection, so this
2398                // cannot happen today — skip it rather than resurrect its rows.
2399                run.cursor += 1;
2400                run.pending_ids.clear();
2401                run.pending_cursor = 0;
2402                continue;
2403            };
2404
2405            if run.sources[run.cursor].tombstones_at_open.is_none() {
2406                let source = source_arc.read();
2407                run.pending_ids = source.live_entity_ids();
2408                run.pending_cursor = 0;
2409                run.sources[run.cursor].tombstones_at_open = Some(source.tombstone_count());
2410            }
2411
2412            {
2413                let source = source_arc.read();
2414                while budget > 0 && run.pending_cursor < run.pending_ids.len() {
2415                    let id = run.pending_ids[run.pending_cursor];
2416                    run.pending_cursor += 1;
2417                    budget -= 1;
2418
2419                    // Tombstoned between the snapshot and now — it must not be
2420                    // resurrected into the merged segment.
2421                    let Some(entity) = source.get(id) else {
2422                        continue;
2423                    };
2424                    let metadata = source.get_metadata(id);
2425                    run.merged.adopt_entity(entity.clone(), metadata);
2426                    run.sources[run.cursor].copied.push(id);
2427                    run.entities_copied += 1;
2428                }
2429            }
2430
2431            if run.pending_cursor >= run.pending_ids.len() {
2432                run.cursor += 1;
2433                run.pending_ids.clear();
2434                run.pending_cursor = 0;
2435            }
2436        }
2437    }
2438
2439    /// Atomically replace the source segments with the merged one.
2440    ///
2441    /// The `sealed` write lock is the boundary: a reader holds the read lock
2442    /// for the whole of its scan, so it observes either the old set or the new
2443    /// set, never a gap and never both copies of a row.
2444    fn finish_consolidation(&self, mut run: Consolidation) {
2445        let mut sealed = self.sealed.write();
2446
2447        let mut positions = Vec::with_capacity(run.sources.len());
2448        for source in &run.sources {
2449            if let Some(index) = sealed
2450                .iter()
2451                .position(|segment| segment.read().id() == source.id)
2452            {
2453                positions.push(index);
2454            }
2455        }
2456        if positions.is_empty() {
2457            return;
2458        }
2459        positions.sort_unstable();
2460
2461        // Rows deleted from a source after we copied them must not come back.
2462        // A source whose tombstone count is unchanged saw no deletes while the
2463        // merge ran, so its copied rows need no per-row check.
2464        let mut stale = Vec::new();
2465        for source in &run.sources {
2466            let Some(source_arc) = sealed
2467                .iter()
2468                .find(|segment| segment.read().id() == source.id)
2469            else {
2470                continue;
2471            };
2472            let segment = source_arc.read();
2473            if source.tombstones_at_open == Some(segment.tombstone_count()) {
2474                continue;
2475            }
2476            stale.extend(
2477                source
2478                    .copied
2479                    .iter()
2480                    .copied()
2481                    .filter(|id| !segment.contains(*id)),
2482            );
2483        }
2484        for id in stale {
2485            run.merged.evict_entity(id);
2486        }
2487
2488        let reclaimed_bytes: u64 = positions
2489            .iter()
2490            .map(|&index| sealed[index].read().resident_bytes())
2491            .sum();
2492        let reclaimed_tombstones: u64 = positions
2493            .iter()
2494            .map(|&index| sealed[index].read().tombstone_count() as u64)
2495            .sum();
2496
2497        if run.merged.seal().is_err() {
2498            return;
2499        }
2500        let merged_bytes = run.merged.resident_bytes();
2501        let merged_arc = Arc::new(RwLock::new(run.merged));
2502
2503        {
2504            let mut retired = self.retired.write();
2505            retired.retain(|source| source.strong_count() > 0);
2506            for &index in positions.iter().rev() {
2507                let source = sealed.remove(index);
2508                if Arc::strong_count(&source) > 1 {
2509                    retired.push(Arc::downgrade(&source));
2510                }
2511            }
2512        }
2513        let insert_at = positions[0].min(sealed.len());
2514        sealed.insert(insert_at, Arc::clone(&merged_arc));
2515        drop(sealed);
2516
2517        // Remap the entity→segment hints that pointed at the retired sources.
2518        let source_ids: Vec<SegmentId> = run.sources.iter().map(|source| source.id).collect();
2519        {
2520            let mut entity_segment = self.entity_segment.write();
2521            for segment_id in entity_segment.values_mut() {
2522                if source_ids.contains(segment_id) {
2523                    *segment_id = run.merged_id;
2524                }
2525            }
2526        }
2527
2528        {
2529            let mut stats = self.stats.write();
2530            stats.sealed_count = stats
2531                .sealed_count
2532                .saturating_sub(positions.len())
2533                .saturating_add(1);
2534            let consolidation = &mut stats.consolidation;
2535            consolidation.runs_completed += 1;
2536            consolidation.segments_merged += positions.len() as u64;
2537            consolidation.tombstones_reclaimed += reclaimed_tombstones;
2538            consolidation.bytes_reclaimed += reclaimed_bytes.saturating_sub(merged_bytes);
2539        }
2540
2541        self.emit(LifecycleEvent::SegmentConsolidated {
2542            source: source_ids,
2543            target: run.merged_id,
2544        });
2545    }
2546
2547    /// Entities copied by the consolidation currently in flight, or `None` when
2548    /// none is running. Exposed for the pacing tests.
2549    #[cfg(test)]
2550    fn consolidation_progress(&self) -> Option<u64> {
2551        self.consolidation
2552            .read()
2553            .as_ref()
2554            .map(|run| run.entities_copied)
2555    }
2556}
2557
2558// Implement the Arc<RwLock<GrowingSegment>> as UnifiedSegment
2559// This is needed because we store growing segments in the sealed list after sealing
2560impl UnifiedSegment for Arc<RwLock<GrowingSegment>> {
2561    fn id(&self) -> SegmentId {
2562        self.read().id()
2563    }
2564
2565    fn state(&self) -> SegmentState {
2566        self.read().state()
2567    }
2568
2569    fn collection(&self) -> &str {
2570        // This is a limitation - we'd need to store collection in the Arc wrapper
2571        "unknown"
2572    }
2573
2574    fn stats(&self) -> SegmentStats {
2575        self.read().stats()
2576    }
2577
2578    fn entity_count(&self) -> usize {
2579        self.read().entity_count()
2580    }
2581
2582    fn contains(&self, id: EntityId) -> bool {
2583        self.read().contains(id)
2584    }
2585
2586    fn get(&self, id: EntityId) -> Option<&UnifiedEntity> {
2587        // This is tricky with RwLock - we can't return a reference
2588        // In production, we'd use a different approach
2589        None
2590    }
2591
2592    fn get_mut(&mut self, _id: EntityId) -> Option<&mut UnifiedEntity> {
2593        None
2594    }
2595
2596    fn insert(&mut self, entity: UnifiedEntity) -> Result<EntityId, SegmentError> {
2597        self.write().insert(entity)
2598    }
2599
2600    fn update(&mut self, entity: UnifiedEntity) -> Result<(), SegmentError> {
2601        self.write().update(entity)
2602    }
2603
2604    fn update_hot(
2605        &mut self,
2606        entity: UnifiedEntity,
2607        modified_columns: &[String],
2608    ) -> Result<(), SegmentError> {
2609        self.write().update_hot(entity, modified_columns)
2610    }
2611
2612    fn delete(&mut self, id: EntityId) -> Result<bool, SegmentError> {
2613        self.write().delete(id)
2614    }
2615
2616    fn get_metadata(&self, id: EntityId) -> Option<Metadata> {
2617        self.read().get_metadata(id)
2618    }
2619
2620    fn set_metadata(&mut self, id: EntityId, metadata: Metadata) -> Result<(), SegmentError> {
2621        self.write().set_metadata(id, metadata)
2622    }
2623
2624    fn seal(&mut self) -> Result<(), SegmentError> {
2625        self.write().seal()
2626    }
2627
2628    fn should_seal(&self, config: &SegmentConfig) -> bool {
2629        self.read().should_seal(config)
2630    }
2631
2632    fn iter(&self) -> Box<dyn Iterator<Item = &UnifiedEntity> + '_> {
2633        // Cannot return iterator with RwLock
2634        Box::new(std::iter::empty())
2635    }
2636
2637    fn iter_kind(&self, _kind_filter: &str) -> Box<dyn Iterator<Item = &UnifiedEntity> + '_> {
2638        Box::new(std::iter::empty())
2639    }
2640
2641    fn filter_metadata(&self, filters: &[(String, MetadataFilter)]) -> Vec<EntityId> {
2642        self.read().filter_metadata(filters)
2643    }
2644}
2645
2646#[cfg(test)]
2647mod tests {
2648    use std::collections::HashSet;
2649
2650    use super::*;
2651    use crate::runtime::mvcc::SnapshotContext;
2652    use crate::storage::transaction::snapshot::{Snapshot, SnapshotManager};
2653    use crate::storage::unified::entity::{EntityData, EntityKind, RowData};
2654    use reddb_types::Value;
2655
2656    #[test]
2657    fn ordered_fingerprint_scan_matches_legacy_sort_without_cloning_rows() {
2658        let manager = SegmentManager::new("fingerprint");
2659        let row = |id, label: &str| {
2660            UnifiedEntity::table_row(
2661                EntityId::new(id),
2662                "fingerprint",
2663                id,
2664                vec![Value::text(label)],
2665            )
2666        };
2667        manager
2668            .bulk_insert(vec![row(8, "eight"), row(2, "sealed-two"), row(5, "five")])
2669            .expect("sealed rows");
2670        manager.force_seal().expect("seal");
2671        manager
2672            .bulk_insert(vec![row(7, "seven"), row(2, "growing-two"), row(1, "one")])
2673            .expect("growing rows");
2674
2675        let mut expected = manager.query_all(|_| true);
2676        expected.sort_by_key(|entity| entity.id.raw());
2677        let expected: Vec<_> = expected
2678            .iter()
2679            .map(|entity| format!("{entity:?}"))
2680            .collect();
2681        let mut stored_addresses = HashSet::new();
2682        manager.for_each_entity(|entity| {
2683            stored_addresses.insert(entity as *const UnifiedEntity as usize);
2684            true
2685        });
2686
2687        let mut actual = Vec::new();
2688        manager.for_each_entity_in_id_order(|entity| {
2689            assert!(stored_addresses.contains(&(entity as *const UnifiedEntity as usize)));
2690            assert!(
2691                manager.growing.try_write().is_some(),
2692                "topology guard retained"
2693            );
2694            assert!(
2695                manager.sealed.try_write().is_some(),
2696                "topology guard retained"
2697            );
2698            actual.push(format!("{entity:?}"));
2699            true
2700        });
2701        assert_eq!(
2702            actual, expected,
2703            "equal IDs retain their original segment order"
2704        );
2705    }
2706
2707    #[test]
2708    fn ordered_fingerprint_scan_stops_early_and_releases_sources() {
2709        let manager = SegmentManager::new("fingerprint");
2710        for id in [3, 1, 2] {
2711            manager
2712                .insert(UnifiedEntity::table_row(
2713                    EntityId::new(id),
2714                    "fingerprint",
2715                    id,
2716                    vec![Value::Integer(id as i64)],
2717                ))
2718                .expect("row");
2719        }
2720        let source = manager.growing.read().as_ref().expect("source").clone();
2721        let handles = Arc::strong_count(&source);
2722        let mut seen = Vec::new();
2723        manager.for_each_entity_in_id_order(|entity| {
2724            seen.push(entity.id.raw());
2725            false
2726        });
2727        assert_eq!(seen, vec![1]);
2728        assert_eq!(Arc::strong_count(&source), handles);
2729        assert!(
2730            source.try_write().is_some(),
2731            "segment guard retained after early stop"
2732        );
2733    }
2734
2735    #[test]
2736    fn bounded_scan_survives_sealing_consolidation_and_new_writes() {
2737        let manager = SegmentManager::with_config(
2738            "vectors",
2739            ManagerConfig {
2740                max_sealed_segments: 1,
2741                consolidation_entities_per_tick: 10_000,
2742                ..Default::default()
2743            },
2744        );
2745        for part in 0..3 {
2746            manager
2747                .bulk_insert(
2748                    (1..=300)
2749                        .map(|offset| {
2750                            UnifiedEntity::vector(
2751                                EntityId::new(part * 300 + offset),
2752                                "vectors",
2753                                vec![1.0, 0.0],
2754                            )
2755                        })
2756                        .collect(),
2757                )
2758                .expect("batch");
2759            if part < 2 {
2760                manager.force_seal().expect("seal");
2761            }
2762        }
2763        let original_growing = manager.growing.read().as_ref().expect("growing").clone();
2764        let mut changed = false;
2765        let mut seen = Vec::new();
2766        assert!(manager.scan_batches(
2767            None,
2768            || true,
2769            |batch| {
2770                assert!(batch.len() <= super::super::segment::SCAN_BATCH_SIZE);
2771                assert!(
2772                    manager.growing.try_write().is_some(),
2773                    "consumer holds no topology guard"
2774                );
2775                assert!(
2776                    original_growing.try_write().is_some(),
2777                    "consumer holds no segment guard"
2778                );
2779                for entity in batch {
2780                    assert!(manager.get(entity.id).is_some(), "reentrant storage lookup");
2781                    seen.push(entity.id.raw());
2782                }
2783                if !changed {
2784                    changed = true;
2785                    manager.force_seal().expect("seal during scan");
2786                    manager
2787                        .insert(UnifiedEntity::vector(
2788                            EntityId::new(5000),
2789                            "vectors",
2790                            vec![1.0, 0.0],
2791                        ))
2792                        .expect("new write");
2793                    drain_maintenance(&manager);
2794                    assert!(manager.stats().consolidation.runs_completed > 0);
2795                    assert!(manager
2796                        .delete(EntityId::new(1))
2797                        .expect("delete after source retirement"));
2798                    assert!(manager.get(EntityId::new(1)).is_none());
2799                }
2800                true
2801            }
2802        ));
2803        seen.sort_unstable();
2804        assert_eq!(
2805            seen,
2806            (2..=900).collect::<Vec<_>>(),
2807            "no duplicate, missing or late candidates"
2808        );
2809        let mut after = Vec::new();
2810        assert!(manager.scan_batches(
2811            None,
2812            || true,
2813            |batch| {
2814                after.extend(batch.iter().map(|entity| entity.id.raw()));
2815                true
2816            }
2817        ));
2818        after.sort_unstable();
2819        let mut expected: Vec<_> = (2..=900).collect();
2820        expected.push(5000);
2821        assert_eq!(after, expected, "adopted entities have scan positions");
2822    }
2823
2824    #[test]
2825    fn bounded_scan_applies_snapshot_to_relocated_versions() {
2826        for (consolidate, bulk) in [(false, false), (false, true), (true, false), (true, true)] {
2827            let manager = SegmentManager::with_config(
2828                "vectors",
2829                ManagerConfig {
2830                    max_sealed_segments: 1,
2831                    ..Default::default()
2832                },
2833            );
2834            for ids in [[1, 2], [3, 4]] {
2835                let entities = ids.map(|id| {
2836                    let mut entity = UnifiedEntity::vector(EntityId::new(id), "vectors", vec![1.0]);
2837                    entity.set_xmin(3);
2838                    entity
2839                });
2840                if bulk {
2841                    manager
2842                        .bulk_insert(entities.into())
2843                        .expect("initial versions");
2844                } else {
2845                    for entity in entities {
2846                        manager.insert(entity).expect("initial version");
2847                    }
2848                }
2849                manager.force_seal().expect("seal source");
2850            }
2851            let snapshot = SnapshotContext {
2852                snapshot: Snapshot {
2853                    xid: 10,
2854                    in_progress: HashSet::new(),
2855                },
2856                manager: Arc::new(SnapshotManager::new()),
2857                own_xids: HashSet::new(),
2858                requires_index_fallback: false,
2859                serializable_reader: None,
2860            };
2861            let mut changed = false;
2862            let mut seen = Vec::new();
2863            assert!(manager.scan_batches(
2864                Some(&snapshot),
2865                || true,
2866                |batch| {
2867                    seen.extend(batch.iter().map(|entity| entity.id.raw()));
2868                    if !changed {
2869                        changed = true;
2870                        if consolidate {
2871                            drain_maintenance(&manager);
2872                            assert!(manager.stats().consolidation.runs_completed > 0);
2873                        }
2874                        for (id, xmax) in [(3, 8), (4, 12)] {
2875                            let mut entity =
2876                                manager.get(EntityId::new(id)).expect("retained version");
2877                            entity.set_xmax(xmax);
2878                            manager
2879                                .update(entity)
2880                                .expect("update after source retirement");
2881                        }
2882                    }
2883                    true
2884                }
2885            ));
2886            seen.sort_unstable();
2887            assert_eq!(seen, vec![1, 2, 4], "snapshot uses authoritative xmax");
2888            let mut again = Vec::new();
2889            assert!(manager.scan_batches(
2890                Some(&snapshot),
2891                || true,
2892                |batch| {
2893                    again.extend(batch.iter().map(|entity| entity.id.raw()));
2894                    true
2895                }
2896            ));
2897            again.sort_unstable();
2898            assert_eq!(
2899                again,
2900                vec![1, 2, 4],
2901                "old slots do not duplicate relocated versions"
2902            );
2903            let mut current = Vec::new();
2904            assert!(manager.scan_batches(
2905                None,
2906                || true,
2907                |batch| {
2908                    current.extend(batch.iter().map(|entity| entity.id.raw()));
2909                    true
2910                }
2911            ));
2912            current.sort_unstable();
2913            assert_eq!(
2914                current,
2915                vec![1, 2],
2916                "current view excludes both deleted versions"
2917            );
2918        }
2919    }
2920
2921    #[test]
2922    fn bounded_scan_keeps_flat_and_hash_positions_through_mutation() {
2923        let manager = SegmentManager::new("mixed");
2924        let vector = |id| UnifiedEntity::vector(EntityId::new(id), "mixed", vec![1.0]);
2925        manager
2926            .bulk_insert((1..=300).map(vector).collect())
2927            .expect("flat");
2928        manager.insert(vector(500)).expect("hash insert");
2929        manager
2930            .bulk_insert(vec![vector(502), vector(505)])
2931            .expect("gapped bulk");
2932        manager.delete(EntityId::new(2)).expect("flat delete");
2933        manager.delete(EntityId::new(505)).expect("hash delete");
2934        let mut changed = false;
2935        let mut seen = Vec::new();
2936        assert!(manager.scan_batches(
2937            None,
2938            || true,
2939            |batch| {
2940                seen.extend(batch.iter().map(|entity| entity.id.raw()));
2941                if !changed {
2942                    changed = true;
2943                    manager
2944                        .insert(vector(700))
2945                        .expect("append after cursor boundary");
2946                    manager
2947                        .update(UnifiedEntity::graph_node(
2948                            EntityId::new(500),
2949                            "mixed",
2950                            "Node",
2951                            HashMap::new(),
2952                        ))
2953                        .expect("structural update");
2954                }
2955                true
2956            }
2957        ));
2958        seen.sort_unstable();
2959        let mut expected: Vec<_> = (1..=300).filter(|id| *id != 2).collect();
2960        expected.extend([500, 502]);
2961        assert_eq!(seen, expected);
2962    }
2963
2964    #[test]
2965    fn bounded_scan_preserves_snapshot_and_discards_interrupted_batches() {
2966        let manager = SegmentManager::new("vectors");
2967        let mut entities = Vec::new();
2968        for (id, xmin, xmax) in [(1, 3, 12), (2, 12, 0), (3, 3, 0), (4, 3, 4)] {
2969            let mut entity = UnifiedEntity::vector(EntityId::new(id), "vectors", vec![1.0]);
2970            entity.set_xmin(xmin);
2971            entity.set_xmax(xmax);
2972            entities.push(entity);
2973        }
2974        manager.bulk_insert(entities).expect("versions");
2975        manager.force_seal().expect("seal");
2976        let snapshot = SnapshotContext {
2977            snapshot: Snapshot {
2978                xid: 10,
2979                in_progress: HashSet::from([4]),
2980            },
2981            manager: Arc::new(SnapshotManager::new()),
2982            own_xids: HashSet::new(),
2983            requires_index_fallback: false,
2984            serializable_reader: None,
2985        };
2986        let mut work = 0;
2987        let mut callbacks = 0;
2988        assert!(!manager.scan_batches(
2989            Some(&snapshot),
2990            || {
2991                work += 1;
2992                work <= 2
2993            },
2994            |_| {
2995                callbacks += 1;
2996                true
2997            }
2998        ));
2999        assert_eq!(callbacks, 0, "a stopped batch is not consumed");
3000        for (view, expected) in [(Some(&snapshot), vec![1, 3, 4]), (None, vec![2, 3])] {
3001            let mut seen = Vec::new();
3002            assert!(manager.scan_batches(
3003                view,
3004                || true,
3005                |batch| {
3006                    seen.extend(batch.iter().map(|entity| entity.id.raw()));
3007                    true
3008                }
3009            ));
3010            seen.sort_unstable();
3011            assert_eq!(seen, expected);
3012        }
3013    }
3014
3015    #[test]
3016    fn test_manager_basic() {
3017        let manager = SegmentManager::new("test_collection");
3018
3019        let entity = UnifiedEntity::table_row(
3020            manager.next_entity_id(),
3021            "users",
3022            1,
3023            vec![Value::text("Alice".to_string())],
3024        );
3025
3026        let id = manager.insert(entity).unwrap();
3027        assert!(manager.get(id).is_some());
3028        assert_eq!(manager.count(), 1);
3029    }
3030
3031    #[test]
3032    fn graph_pruning_preserves_physical_versions_and_charges_only_selected_segments() {
3033        let manager = Arc::new(SegmentManager::new("mixed"));
3034        manager
3035            .bulk_insert(
3036                (1..=128)
3037                    .map(|id| UnifiedEntity::vector(EntityId::new(id), "mixed", vec![]))
3038                    .collect(),
3039            )
3040            .expect("vector-only segment");
3041        manager.force_seal().expect("seal vectors");
3042        let mut old =
3043            UnifiedEntity::graph_node(EntityId::new(200), "mixed", "person", Default::default());
3044        old.set_xmin(3);
3045        old.set_xmax(12);
3046        let mut new =
3047            UnifiedEntity::graph_node(EntityId::new(201), "mixed", "person", Default::default());
3048        new.set_xmin(12);
3049        let edge = UnifiedEntity::graph_edge(
3050            EntityId::new(202),
3051            "mixed",
3052            "a",
3053            "b",
3054            1.0,
3055            Default::default(),
3056        );
3057        manager
3058            .bulk_insert(vec![old, new, edge])
3059            .expect("physical graph versions");
3060        manager.force_seal().expect("seal graph");
3061        manager
3062            .insert(UnifiedEntity::graph_node(
3063                EntityId::new(203),
3064                "mixed",
3065                "person",
3066                Default::default(),
3067            ))
3068            .expect("growing node");
3069        let snapshot = SnapshotContext {
3070            snapshot: Snapshot {
3071                xid: 10,
3072                in_progress: HashSet::new(),
3073            },
3074            manager: Arc::new(SnapshotManager::new()),
3075            own_xids: HashSet::new(),
3076            requires_index_fallback: false,
3077            serializable_reader: None,
3078        };
3079        std::thread::spawn(move || {
3080            for view in [None, Some(&snapshot)] {
3081                for kind in [GraphEntityKind::Node, GraphEntityKind::Edge] {
3082                    let expected: HashSet<_> = manager
3083                        .scan(view, |item| kind.matches(&item.kind))
3084                        .into_iter()
3085                        .map(|item| item.id)
3086                        .collect();
3087                    let actual: HashSet<_> = manager
3088                        .scan_graph_kind(view, kind)
3089                        .into_iter()
3090                        .map(|item| item.id)
3091                        .collect();
3092                    assert_eq!(actual, expected);
3093                    let mut visited = 0;
3094                    let mut candidates = HashSet::new();
3095                    manager.scan_graph_candidates_for_each(
3096                        view,
3097                        kind,
3098                        || true,
3099                        |item| {
3100                            visited += 1;
3101                            if kind.matches(&item.kind) {
3102                                candidates.insert(item.id);
3103                            }
3104                            true
3105                        },
3106                    );
3107                    assert_eq!(candidates, expected);
3108                    assert_eq!(
3109                        visited,
3110                        if matches!(kind, GraphEntityKind::Node) {
3111                            3
3112                        } else {
3113                            2
3114                        }
3115                    );
3116                }
3117            }
3118            let ids: HashSet<_> = manager
3119                .scan_graph_kind(Some(&snapshot), GraphEntityKind::Node)
3120                .into_iter()
3121                .map(|item| item.id.raw())
3122                .collect();
3123            assert_eq!(ids, HashSet::from([200, 203]));
3124            let ids: HashSet<_> = manager
3125                .scan_graph_kind(None, GraphEntityKind::Node)
3126                .into_iter()
3127                .map(|item| item.id.raw())
3128                .collect();
3129            assert_eq!(ids, HashSet::from([201, 203]));
3130            let mut visits = 0;
3131            manager.scan_graph_candidates_for_each(
3132                None,
3133                GraphEntityKind::Node,
3134                || true,
3135                |_| {
3136                    visits += 1;
3137                    false
3138                },
3139            );
3140            assert_eq!(
3141                visits, 1,
3142                "early termination must also stop subsequent segments"
3143            );
3144        })
3145        .join()
3146        .expect("snapshot worker");
3147    }
3148
3149    #[test]
3150    fn snapshot_scan_applies_table_driven_visibility_on_fresh_thread() {
3151        let manager = Arc::new(SegmentManager::new("accounts"));
3152        let cases = [
3153            ("legacy row", 0, 0, true),
3154            ("committed creator", 3, 0, true),
3155            ("future creator", 11, 0, false),
3156            ("in-progress creator", 4, 0, false),
3157            ("committed deleter", 3, 7, false),
3158            ("future deleter", 3, 11, true),
3159            ("in-progress deleter", 3, 4, true),
3160        ];
3161
3162        for (index, (_, xmin, xmax, _)) in cases.iter().enumerate() {
3163            let row_id = index as u64 + 1;
3164            let mut entity = UnifiedEntity::table_row(
3165                EntityId::new(row_id),
3166                "accounts",
3167                row_id,
3168                vec![Value::Integer(row_id as i64)],
3169            );
3170            entity.set_xmin(*xmin);
3171            entity.set_xmax(*xmax);
3172            manager.insert(entity).unwrap();
3173        }
3174
3175        let snapshot = SnapshotContext {
3176            snapshot: Snapshot {
3177                xid: 10,
3178                in_progress: HashSet::from([4]),
3179            },
3180            manager: Arc::new(SnapshotManager::new()),
3181            own_xids: HashSet::new(),
3182            requires_index_fallback: false,
3183            serializable_reader: None,
3184        };
3185
3186        let raw_visible_row_ids: HashSet<u64> = manager
3187            .query_all(|entity| entity_visible_with_context(Some(&snapshot), entity))
3188            .into_iter()
3189            .filter_map(|entity| match entity.kind {
3190                EntityKind::TableRow { row_id, .. } => Some(row_id),
3191                _ => None,
3192            })
3193            .collect();
3194
3195        let scanned = std::thread::spawn(move || manager.scan(Some(&snapshot), |_| true))
3196            .join()
3197            .unwrap();
3198        let visible_row_ids: HashSet<u64> = scanned
3199            .into_iter()
3200            .filter_map(|entity| match entity.kind {
3201                EntityKind::TableRow { row_id, .. } => Some(row_id),
3202                _ => None,
3203            })
3204            .collect();
3205        assert_eq!(visible_row_ids, raw_visible_row_ids);
3206
3207        for (index, (name, _, _, expected_visible)) in cases.iter().enumerate() {
3208            let row_id = index as u64 + 1;
3209            assert_eq!(
3210                visible_row_ids.contains(&row_id),
3211                *expected_visible,
3212                "{name} visibility mismatch"
3213            );
3214        }
3215    }
3216
3217    #[test]
3218    fn frameless_scan_hides_superseded_versions_and_moderated_rows() {
3219        // A `None` snapshot is the autocommit / prepared-fast-path read: it
3220        // must keep the resolver fallback (xmax == 0), never show every
3221        // version, and never panic (issue #2136 review).
3222        let manager = SegmentManager::new("accounts");
3223        let mut live =
3224            UnifiedEntity::table_row(EntityId::new(1), "accounts", 1, vec![Value::Integer(1)]);
3225        live.set_xmin(2);
3226        live.set_xmax(0);
3227        manager.insert(live).unwrap();
3228
3229        let mut superseded =
3230            UnifiedEntity::table_row(EntityId::new(2), "accounts", 2, vec![Value::Integer(2)]);
3231        superseded.set_xmin(2);
3232        superseded.set_xmax(9);
3233        manager.insert(superseded).unwrap();
3234
3235        let rows: Vec<u64> = manager
3236            .scan(None, |_| true)
3237            .into_iter()
3238            .filter_map(|entity| match entity.kind {
3239                EntityKind::TableRow { row_id, .. } => Some(row_id),
3240                _ => None,
3241            })
3242            .collect();
3243        assert_eq!(
3244            rows,
3245            vec![1],
3246            "frameless scan must hide superseded versions"
3247        );
3248    }
3249
3250    #[test]
3251    fn query_scan_callers_use_snapshot_api_for_visibility() {
3252        let table = include_str!("../../runtime/query_exec/table.rs");
3253        let aggregate = include_str!("../../runtime/query_exec/aggregate.rs");
3254
3255        assert_eq!(
3256            table.matches(".for_each_entity(|entity|").count(),
3257            1,
3258            "only the visibility-independent schema inspection may use the raw table iterator"
3259        );
3260        assert!(!table.contains(".query_all_zoned_with_stats("));
3261        assert!(!table.contains(".for_each_entity_zoned_with_stats("));
3262        assert!(!table.contains("TableRowMvccReadResolver::captured"));
3263
3264        assert!(!aggregate.contains("TableRowMvccReadResolver"));
3265        assert!(!aggregate.contains(".for_each_entity("));
3266        assert!(!aggregate.contains(".fold_entities_parallel("));
3267    }
3268
3269    #[test]
3270    fn remaining_visibility_scan_callers_use_snapshot_api() {
3271        let aggregate_pushdown =
3272            include_str!("../../runtime/query_exec/aggregate_pushdown_dispatch.rs");
3273        let ask = include_str!("../../runtime/ask_pipeline.rs");
3274        let dml = include_str!("../../runtime/impl_dml.rs");
3275        let dml_targets = include_str!("../../runtime/dml_target_scan.rs");
3276        let events = include_str!("../../runtime/impl_events.rs");
3277        let graph_commands = include_str!("../../runtime/impl_graph_commands.rs");
3278        let graph_dsl = include_str!("../../runtime/graph_dsl.rs");
3279        let graph_tvf = include_str!("../../runtime/graph_tvf.rs");
3280        let kv = include_str!("../../runtime/impl_kv.rs");
3281        let queue = include_str!("../../runtime/impl_queue.rs");
3282        let primary_queue = include_str!("../../runtime/primary_queue_store.rs");
3283        let record_search = include_str!("../../runtime/record_search.rs");
3284        let search = include_str!("../../runtime/impl_search.rs");
3285        let vector = include_str!("../../runtime/query_exec/vector.rs");
3286
3287        assert!(!aggregate_pushdown.contains("TableRowMvccReadResolver"));
3288        assert!(!aggregate_pushdown.contains(".for_each_entity("));
3289        assert!(!ask.contains("for entity in manager.query_all(|_| true)"));
3290        assert!(!dml.contains("let entities = manager.query_all(|_| true);"));
3291        // The DML target scan keeps raw iteration on purpose: its
3292        // visibility is kind-conditional (live table rows at the tip
3293        // version, everything else under the snapshot), which the uniform
3294        // scan API cannot express. `candidate_visible` is the single gate.
3295        assert_eq!(
3296            dml_targets
3297                .matches("self.candidate_visible(snapshot.as_ref(), entity)")
3298                .count(),
3299            2,
3300            "both raw DML iterations must route through candidate_visible"
3301        );
3302        // The event-backfill dedup set is deliberately visibility-free:
3303        // it must include consumed messages or backfill re-enqueues them.
3304        assert_eq!(
3305            events.matches("manager.query_all(").count(),
3306            1,
3307            "only the visibility-free backfill dedup may use query_all"
3308        );
3309        assert!(!graph_commands.contains("TableRowMvccReadResolver"));
3310        assert!(!graph_dsl.contains("entity_visible_with_context(snap_ctx.as_ref(), e)"));
3311        assert!(!graph_tvf.contains("entity_visible_with_context(snap_ctx.as_ref(), &entity)"));
3312        assert!(!kv.contains("TableRowMvccReadResolver"));
3313        assert!(!queue.contains("entity_visible_with_context(snap_ctx.as_ref(), entity)"));
3314        assert!(!primary_queue.contains("entity_visible_with_context(snap_ctx.as_ref(), entity)"));
3315        assert!(!record_search.contains("TableRowMvccReadResolver"));
3316        assert!(!search.contains("for entity in manager.query_all(|_| true)"));
3317        assert!(!vector.contains("manager.query_all("));
3318    }
3319
3320    /// Strip `#[cfg(test)] mod … { … }` blocks so the raw-iteration gate
3321    /// only sees production code. Blocks are matched at column zero and
3322    /// closed by brace balance, which is why a file may carry a test
3323    /// module in the middle and still keep production code after it.
3324    fn production_source(src: &str) -> String {
3325        let mut kept: Vec<&str> = Vec::new();
3326        let lines: Vec<&str> = src.lines().collect();
3327        let mut idx = 0;
3328        while idx < lines.len() {
3329            let starts_test_mod = lines[idx].starts_with("#[cfg(test)]")
3330                && lines
3331                    .get(idx + 1)
3332                    .is_some_and(|next| next.starts_with("mod "));
3333            if !starts_test_mod {
3334                kept.push(lines[idx]);
3335                idx += 1;
3336                continue;
3337            }
3338            idx += 1;
3339            let mut depth: isize = 0;
3340            while idx < lines.len() {
3341                depth += lines[idx].matches('{').count() as isize;
3342                depth -= lines[idx].matches('}').count() as isize;
3343                idx += 1;
3344                if depth <= 0 {
3345                    break;
3346                }
3347            }
3348        }
3349        kept.join("\n")
3350    }
3351
3352    /// Count raw (visibility-bypassing) iteration entry points.
3353    fn raw_iteration_sites(src: &str) -> usize {
3354        src.matches("query_all(").count()
3355            + src.matches(".for_each_entity").count()
3356            + src.matches("fold_entities_parallel(").count()
3357    }
3358
3359    #[test]
3360    fn raw_iteration_confined_to_maintenance_allowlist() {
3361        // The query paths migrated by Spec #2107 batches 1 and 2. Inside
3362        // this perimeter raw iteration is maintenance-only: it bypasses
3363        // MVCC visibility entirely, so every remaining site is either an
3364        // internal catalog/bookkeeping read that must observe all physical
3365        // versions, or one of the three exceptions the batch reviews
3366        // documented. A new raw-iteration site changes the count and fails
3367        // this gate — route it through `SegmentManager::scan*` instead.
3368        let allowlist: &[(&str, &str, usize, &str)] = &[
3369            (
3370                "runtime/query_exec/table.rs",
3371                include_str!("../../runtime/query_exec/table.rs"),
3372                1,
3373                "documented exception: schema inspection (does the collection ever \
3374                 observe these fields?) is visibility-independent",
3375            ),
3376            (
3377                "runtime/query_exec/aggregate.rs",
3378                include_str!("../../runtime/query_exec/aggregate.rs"),
3379                0,
3380                "fully migrated by batch 1",
3381            ),
3382            (
3383                "runtime/query_exec/aggregate_pushdown_dispatch.rs",
3384                include_str!("../../runtime/query_exec/aggregate_pushdown_dispatch.rs"),
3385                0,
3386                "fully migrated by batch 1",
3387            ),
3388            (
3389                "runtime/query_exec/vector.rs",
3390                include_str!("../../runtime/query_exec/vector.rs"),
3391                0,
3392                "fully migrated by batch 2",
3393            ),
3394            (
3395                "runtime/ask_pipeline.rs",
3396                include_str!("../../runtime/ask_pipeline.rs"),
3397                0,
3398                "fully migrated by batch 2",
3399            ),
3400            (
3401                "runtime/impl_dml.rs",
3402                include_str!("../../runtime/impl_dml.rs"),
3403                1,
3404                "documented exception: ON CONFLICT resolves a unique key against \
3405                 physical versions on purpose. A snapshot scan cannot see a row an \
3406                 uncommitted concurrent writer already holds the key for, which is \
3407                 exactly the case that must raise a serialization conflict rather \
3408                 than insert a duplicate; the same pass reaps index entries left by \
3409                 aborted writers. \
3410                 TODO(#2263 follow-up): narrow the candidates through the unique \
3411                 index instead of walking the collection",
3412            ),
3413            (
3414                "runtime/dml_target_scan.rs",
3415                include_str!("../../runtime/dml_target_scan.rs"),
3416                2,
3417                "documented exception: kind-conditional visibility the uniform scan \
3418                 API cannot express; both iterations gate on candidate_visible",
3419            ),
3420            (
3421                "runtime/impl_events.rs",
3422                include_str!("../../runtime/impl_events.rs"),
3423                1,
3424                "documented exception: backfill dedup must include consumed messages, \
3425                 so it is deliberately visibility-free",
3426            ),
3427            (
3428                "runtime/impl_graph_commands.rs",
3429                include_str!("../../runtime/impl_graph_commands.rs"),
3430                0,
3431                "native node properties resolve one snapshot-visible, RLS-admitted version",
3432            ),
3433            (
3434                "runtime/graph_dsl.rs",
3435                include_str!("../../runtime/graph_dsl.rs"),
3436                1,
3437                "remaining legacy debt: unused edge-property helper; search expansion \
3438                 now uses snapshot visitors and RLS-gated hydration",
3439            ),
3440            (
3441                "runtime/graph_tvf.rs",
3442                include_str!("../../runtime/graph_tvf.rs"),
3443                0,
3444                "fully migrated by batch 2",
3445            ),
3446            (
3447                "runtime/impl_kv.rs",
3448                include_str!("../../runtime/impl_kv.rs"),
3449                4,
3450                "two non-versioned-collection fallbacks (the versioned arms scan under \
3451                 the captured snapshot). Vault reads use snapshot scans. Offline vault \
3452                 export preserves all \
3453                 physical versions across tenants; restore's emptiness check must reject \
3454                 every physical row, including versions invisible to a snapshot",
3455            ),
3456            (
3457                "runtime/impl_queue.rs",
3458                include_str!("../../runtime/impl_queue.rs"),
3459                10,
3460                "maintenance: red_queue_meta bookkeeping (config, groups, acks, \
3461                 pending, dedup TTL reaper, gauge counts) — queue message bodies are \
3462                 read through scan. \
3463                 TODO(#2138 follow-up): QUEUE PENDING projects meta rows to clients",
3464            ),
3465            (
3466                "runtime/primary_queue_store.rs",
3467                include_str!("../../runtime/primary_queue_store.rs"),
3468                3,
3469                "maintenance: generic red_queue_meta read/delete helpers and the \
3470                 next-position allocator, which must not collide with rows invisible \
3471                 to the writer's snapshot",
3472            ),
3473            (
3474                "runtime/record_search.rs",
3475                include_str!("../../runtime/record_search.rs"),
3476                0,
3477                "fully migrated by batch 2",
3478            ),
3479            (
3480                "runtime/search_graph.rs",
3481                include_str!("../../runtime/search_graph.rs"),
3482                0,
3483                "search graph preparation uses snapshot visitors and gated hydration",
3484            ),
3485            (
3486                "runtime/impl_search.rs",
3487                include_str!("../../runtime/impl_search.rs"),
3488                1,
3489                "maintenance: ask-audit retention sweep must see every physical row",
3490            ),
3491        ];
3492
3493        for (path, src, allowed, reason) in allowlist {
3494            let found = raw_iteration_sites(&production_source(src));
3495            assert_eq!(
3496                found, *allowed,
3497                "{path}: {found} raw-iteration sites, allowlist permits {allowed} \
3498                 ({reason}). Raw iteration bypasses MVCC visibility — use \
3499                 SegmentManager::scan / scan_for_each / scan_fold_parallel / \
3500                 scan_zoned_with_stats, or extend the allowlist with a maintenance \
3501                 justification."
3502            );
3503        }
3504    }
3505
3506    #[test]
3507    fn explicit_snapshot_scan_ignores_ambient_thread_local() {
3508        let manager = Arc::new(SegmentManager::new("accounts"));
3509        // (xmin, xmax) — mix of committed, in-progress and future writers.
3510        let versions = [(0, 0), (3, 0), (11, 0), (4, 0), (3, 7), (3, 11), (3, 4)];
3511        for (index, (xmin, xmax)) in versions.iter().enumerate() {
3512            let row_id = index as u64 + 1;
3513            let mut entity = UnifiedEntity::table_row(
3514                EntityId::new(row_id),
3515                "accounts",
3516                row_id,
3517                vec![Value::Integer(row_id as i64)],
3518            );
3519            entity.set_xmin(*xmin);
3520            entity.set_xmax(*xmax);
3521            manager.insert(entity).unwrap();
3522        }
3523
3524        let explicit = SnapshotContext {
3525            snapshot: Snapshot {
3526                xid: 10,
3527                in_progress: HashSet::from([4]),
3528            },
3529            manager: Arc::new(SnapshotManager::new()),
3530            own_xids: HashSet::new(),
3531            requires_index_fallback: false,
3532            serializable_reader: None,
3533        };
3534        // A decoy statement frame that would hide almost everything if the
3535        // scan ever consulted ambient state instead of its argument.
3536        let decoy = SnapshotContext {
3537            snapshot: Snapshot {
3538                xid: 1,
3539                in_progress: HashSet::new(),
3540            },
3541            manager: Arc::new(SnapshotManager::new()),
3542            own_xids: HashSet::new(),
3543            requires_index_fallback: false,
3544            serializable_reader: None,
3545        };
3546
3547        let row_ids = |entities: Vec<UnifiedEntity>| -> HashSet<u64> {
3548            entities
3549                .into_iter()
3550                .filter_map(|entity| match entity.kind {
3551                    EntityKind::TableRow { row_id, .. } => Some(row_id),
3552                    _ => None,
3553                })
3554                .collect()
3555        };
3556
3557        let guard = crate::runtime::execution_context::CurrentSnapshotGuard::install(decoy);
3558        let on_installing_thread = row_ids(manager.scan(Some(&explicit), |_| true));
3559        drop(guard);
3560
3561        let spawned_manager = Arc::clone(&manager);
3562        let spawned_snapshot = explicit.clone();
3563        let on_fresh_thread = std::thread::spawn(move || {
3564            row_ids(spawned_manager.scan(Some(&spawned_snapshot), |_| true))
3565        })
3566        .join()
3567        .unwrap();
3568
3569        assert_eq!(
3570            on_installing_thread, on_fresh_thread,
3571            "an explicit snapshot must produce the same visible set on any thread"
3572        );
3573        assert_eq!(on_installing_thread, HashSet::from([1, 2, 6, 7]));
3574
3575        // The raw iterators are the maintenance contract: no visibility
3576        // filtering at all, on any thread, regardless of installed frames.
3577        let raw_manager = Arc::clone(&manager);
3578        let raw_count = std::thread::spawn(move || raw_manager.query_all(|_| true).len())
3579            .join()
3580            .unwrap();
3581        assert_eq!(
3582            raw_count,
3583            versions.len(),
3584            "raw iteration must expose every physical version"
3585        );
3586    }
3587
3588    #[test]
3589    fn bloom_may_contain_key_probes_inserted_rid_bytes() {
3590        let manager = SegmentManager::new("test_collection");
3591
3592        let entity = UnifiedEntity::table_row(
3593            manager.next_entity_id(),
3594            "users",
3595            1,
3596            vec![Value::text("Alice".to_string())],
3597        );
3598
3599        let id = manager.insert(entity).unwrap();
3600
3601        assert!(manager.bloom_may_contain_key(&id.raw().to_le_bytes()));
3602        assert!(manager.bloom_may_contain_key(id.raw().to_string().as_bytes()));
3603        assert!(!manager.bloom_may_contain_key(&u64::MAX.to_le_bytes()));
3604
3605        assert!(manager.delete(id).unwrap());
3606        assert!(!manager.bloom_may_contain_key(&id.raw().to_le_bytes()));
3607    }
3608
3609    #[test]
3610    fn zoned_scan_reports_pruned_segments_and_preserves_results() {
3611        let config = ManagerConfig {
3612            segment_config: SegmentConfig {
3613                max_entities: 2,
3614                ..Default::default()
3615            },
3616            ..Default::default()
3617        };
3618        let manager = SegmentManager::with_config("events", config);
3619
3620        for (idx, value) in [10, 20, 100, 110, 200].into_iter().enumerate() {
3621            let row = RowData::with_names(vec![Value::Integer(value)], vec!["ts".to_string()]);
3622            let entity = UnifiedEntity::new(
3623                manager.next_entity_id(),
3624                EntityKind::TableRow {
3625                    table: "events".into(),
3626                    row_id: (idx + 1) as u64,
3627                },
3628                EntityData::Row(row),
3629            );
3630            manager.insert(entity).unwrap();
3631        }
3632
3633        let full = manager.query_all(|entity| match &entity.data {
3634            EntityData::Row(row) => matches!(row.get_field("ts"), Some(Value::Integer(100))),
3635            _ => false,
3636        });
3637        let probe = Value::Integer(100);
3638        let (pruned, stats) =
3639            manager.query_all_zoned_with_stats(&[("ts", ZoneColPred::Eq(&probe))], |entity| {
3640                match &entity.data {
3641                    EntityData::Row(row) => {
3642                        matches!(row.get_field("ts"), Some(Value::Integer(100)))
3643                    }
3644                    _ => false,
3645                }
3646            });
3647
3648        assert_eq!(pruned.len(), full.len());
3649        assert_eq!(pruned[0].id, full[0].id);
3650        assert_eq!(stats.segments_total, 3);
3651        assert_eq!(stats.segments_scanned, 2);
3652        assert_eq!(stats.segments_pruned, 1);
3653    }
3654
3655    #[test]
3656    fn test_manager_auto_seal() {
3657        let config = ManagerConfig {
3658            segment_config: SegmentConfig {
3659                max_entities: 2,
3660                ..Default::default()
3661            },
3662            ..Default::default()
3663        };
3664
3665        let manager = SegmentManager::with_config("test", config);
3666
3667        // Insert first entity
3668        manager
3669            .insert(UnifiedEntity::vector(
3670                manager.next_entity_id(),
3671                "v",
3672                vec![0.1],
3673            ))
3674            .unwrap();
3675
3676        // Insert second entity (triggers seal check)
3677        manager
3678            .insert(UnifiedEntity::vector(
3679                manager.next_entity_id(),
3680                "v",
3681                vec![0.2],
3682            ))
3683            .unwrap();
3684
3685        // Insert third entity (should trigger auto-seal of first segment)
3686        manager
3687            .insert(UnifiedEntity::vector(
3688                manager.next_entity_id(),
3689                "v",
3690                vec![0.3],
3691            ))
3692            .unwrap();
3693
3694        let stats = manager.stats();
3695        assert_eq!(stats.total_entities, 3);
3696    }
3697
3698    #[test]
3699    fn test_manager_delete() {
3700        let manager = SegmentManager::new("test");
3701
3702        let id = manager
3703            .insert(UnifiedEntity::vector(
3704                manager.next_entity_id(),
3705                "v",
3706                vec![0.1],
3707            ))
3708            .unwrap();
3709
3710        assert!(manager.get(id).is_some());
3711        assert!(manager.delete(id).unwrap());
3712        assert!(manager.get(id).is_none());
3713    }
3714
3715    #[test]
3716    fn test_manager_metadata() {
3717        let manager = SegmentManager::new("test");
3718
3719        let id = manager
3720            .insert(UnifiedEntity::table_row(
3721                manager.next_entity_id(),
3722                "hosts",
3723                1,
3724                vec![Value::text("192.168.1.1".to_string())],
3725            ))
3726            .unwrap();
3727
3728        let mut meta = Metadata::new();
3729        meta.set(
3730            "os",
3731            super::super::metadata::MetadataValue::String("linux".to_string()),
3732        );
3733
3734        manager.set_metadata(id, meta).unwrap();
3735
3736        let retrieved = manager.get_metadata(id).unwrap();
3737        assert!(retrieved.has("os"));
3738    }
3739
3740    #[test]
3741    fn test_manager_query_by_kind() {
3742        let manager = SegmentManager::new("test");
3743
3744        manager
3745            .insert(UnifiedEntity::table_row(
3746                manager.next_entity_id(),
3747                "hosts",
3748                1,
3749                vec![],
3750            ))
3751            .unwrap();
3752
3753        manager
3754            .insert(UnifiedEntity::vector(
3755                manager.next_entity_id(),
3756                "embeddings",
3757                vec![0.1],
3758            ))
3759            .unwrap();
3760
3761        manager
3762            .insert(UnifiedEntity::table_row(
3763                manager.next_entity_id(),
3764                "hosts",
3765                2,
3766                vec![],
3767            ))
3768            .unwrap();
3769
3770        let rows = manager.get_by_kind("table");
3771        assert_eq!(rows.len(), 2);
3772
3773        let vectors = manager.get_by_kind("vector");
3774        assert_eq!(vectors.len(), 1);
3775    }
3776
3777    // ========================================================================
3778    // Consolidation — ADR 0073 §5
3779    // ========================================================================
3780
3781    /// A manager whose sealed set never trips the count trigger, so tests can
3782    /// exercise the tombstone/fragmentation triggers in isolation.
3783    fn consolidating_manager(entities_per_tick: usize) -> SegmentManager {
3784        SegmentManager::with_config(
3785            "test",
3786            ManagerConfig {
3787                max_sealed_segments: 1_000,
3788                consolidation_entities_per_tick: entities_per_tick,
3789                ..Default::default()
3790            },
3791        )
3792    }
3793
3794    /// Bulk-load `count` rows into a fresh segment and seal it. Bulk-inserted
3795    /// entities land in flat storage, where a tombstone keeps its payload
3796    /// resident — which is the memory consolidation reclaims.
3797    fn seal_bulk_segment(manager: &SegmentManager, count: usize) -> Vec<EntityId> {
3798        let entities: Vec<UnifiedEntity> = (0..count)
3799            .map(|i| {
3800                UnifiedEntity::table_row(
3801                    manager.next_entity_id(),
3802                    "users",
3803                    i as u64,
3804                    vec![Value::Integer(i as i64), Value::text(format!("row-{i}"))],
3805                )
3806            })
3807            .collect();
3808        let ids = manager.bulk_insert(entities).expect("bulk insert");
3809        manager.force_seal().expect("seal");
3810        ids
3811    }
3812
3813    fn live_ids(manager: &SegmentManager) -> Vec<u64> {
3814        let mut ids: Vec<u64> = manager
3815            .query_all(|_| true)
3816            .into_iter()
3817            .map(|entity| entity.id.raw())
3818            .collect();
3819        ids.sort_unstable();
3820        ids
3821    }
3822
3823    fn drain_maintenance(manager: &SegmentManager) -> usize {
3824        let mut ticks = 0;
3825        while manager.consolidation.read().is_some() || ticks == 0 {
3826            manager.run_maintenance().expect("maintenance");
3827            ticks += 1;
3828            assert!(ticks < 1_000, "consolidation failed to converge");
3829        }
3830        ticks
3831    }
3832
3833    #[test]
3834    fn graph_index_batches_pin_sources_and_hydrate_current_after_consolidation() {
3835        let manager = consolidating_manager(CONSOLIDATION_ENTITIES_PER_TICK);
3836        let ids = manager
3837            .bulk_insert(
3838                (1..=1024)
3839                    .map(|id| {
3840                        UnifiedEntity::graph_edge(
3841                            EntityId::new(id),
3842                            "step",
3843                            "2000",
3844                            "3000",
3845                            1.0,
3846                            HashMap::new(),
3847                        )
3848                    })
3849                    .collect(),
3850            )
3851            .expect("edges");
3852        manager.force_seal().expect("seal");
3853        for id in ids.iter().take(300) {
3854            manager.delete(*id).expect("fragment source");
3855        }
3856        let source = Arc::downgrade(&manager.sealed.read()[0]);
3857        let mut seen = Vec::new();
3858        let mut changed = false;
3859        let mut metadata_bytes = 0;
3860        assert!(manager.visit_graph_index_batches(GraphEntityKind::Edge, &[EntityId::new(2000)],
3861            || true,
3862            |bytes| { metadata_bytes += bytes; Ok::<_, ()>(()) },
3863            |batch| {
3864                assert!(batch.len() <= super::super::segment::SCAN_BATCH_SIZE);
3865                assert!(manager.growing.try_write().is_some(), "no growing topology guard");
3866                assert!(manager.sealed.try_write().is_some(), "no sealed topology guard");
3867                assert!(source.upgrade().expect("source pinned").try_write().is_some(), "no source guard");
3868                if !changed {
3869                    changed = true;
3870                    drain_maintenance(&manager);
3871                    assert!(manager.stats().consolidation.runs_completed > 0);
3872                    assert!(source.upgrade().is_some(), "retired cursor source remains pinned");
3873                    let mut updated = manager.get(EntityId::new(1024)).expect("future edge");
3874                    if let EntityKind::GraphEdge(edge) = &mut updated.kind { edge.weight = 2000; }
3875                    manager.update(updated).expect("update authoritative merged copy");
3876                }
3877                for id in batch {
3878                    let entity = manager.get(*id).expect("hydrate current manager");
3879                    if id.raw() == 1024 {
3880                        assert!(matches!(&entity.kind, EntityKind::GraphEdge(edge) if edge.weight == 2000));
3881                    }
3882                    seen.push(id.raw());
3883                }
3884                Ok(true)
3885            }).expect("cursor"));
3886        assert_eq!(seen, (301..=1024).collect::<Vec<_>>());
3887        assert!(
3888            source.upgrade().is_none(),
3889            "finished cursor releases retired source"
3890        );
3891        assert!(
3892            metadata_bytes < 4096,
3893            "fixed ID buffer plus source handles: {metadata_bytes}"
3894        );
3895    }
3896
3897    #[test]
3898    fn graph_index_batches_propagate_admission_and_cancel_before_partial_delivery() {
3899        let manager = SegmentManager::new("graph");
3900        manager
3901            .bulk_insert(
3902                (1..=1024)
3903                    .map(|id| {
3904                        UnifiedEntity::graph_edge(
3905                            EntityId::new(id),
3906                            "step",
3907                            "2000",
3908                            "3000",
3909                            1.0,
3910                            HashMap::new(),
3911                        )
3912                    })
3913                    .collect(),
3914            )
3915            .expect("edges");
3916        let mut delivered = 0;
3917        let denied = manager.visit_graph_index_batches(
3918            GraphEntityKind::Edge,
3919            &[EntityId::new(2000)],
3920            || true,
3921            |_| Err("out of memory"),
3922            |ids| {
3923                delivered += ids.len();
3924                Ok(true)
3925            },
3926        );
3927        assert_eq!(denied, Err("out of memory"));
3928        assert_eq!(delivered, 0);
3929        let mut work = 0;
3930        assert!(!manager
3931            .visit_graph_index_batches(
3932                GraphEntityKind::Edge,
3933                &[EntityId::new(2000)],
3934                || {
3935                    work += 1;
3936                    work < 100
3937                },
3938                |_| Ok::<_, ()>(()),
3939                |ids| {
3940                    delivered += ids.len();
3941                    Ok(true)
3942                }
3943            )
3944            .expect("cancelled cursor"));
3945        assert_eq!(
3946            delivered, 0,
3947            "cancelled partial batch cannot reach consumer"
3948        );
3949        assert!(!manager
3950            .visit_graph_index_batches(
3951                GraphEntityKind::Edge,
3952                &[EntityId::new(2000)],
3953                || true,
3954                |_| Ok::<_, ()>(()),
3955                |ids| {
3956                    delivered += ids.len();
3957                    Ok(false)
3958                }
3959            )
3960            .expect("consumer stop"));
3961        assert_eq!(delivered, super::super::segment::SCAN_BATCH_SIZE);
3962    }
3963
3964    #[test]
3965    fn retained_memory_tracks_two_readers_until_the_last_cursor_finishes() {
3966        let manager = consolidating_manager(CONSOLIDATION_ENTITIES_PER_TICK);
3967        let ids = seal_bulk_segment(&manager, 100);
3968        for id in ids.iter().take(40) {
3969            manager.delete(*id).expect("delete before scan");
3970        }
3971        let source_bytes = manager.resident_bytes();
3972        let source = Arc::downgrade(&manager.sealed.read()[0]);
3973        std::thread::scope(|scope| {
3974            let (ready, waiting) = std::sync::mpsc::channel();
3975            let (release_first, first_wait) = std::sync::mpsc::channel();
3976            let (release_last, last_wait) = std::sync::mpsc::channel();
3977            let reader = |resume: std::sync::mpsc::Receiver<()>,
3978                          ready: std::sync::mpsc::Sender<()>| {
3979                assert!(manager.scan_batches(
3980                    None,
3981                    || true,
3982                    |_| {
3983                        ready.send(()).expect("signal captured cursor");
3984                        let _ = resume.recv();
3985                        true
3986                    }
3987                ));
3988            };
3989            let ready_first = ready.clone();
3990            let first = scope.spawn(move || reader(first_wait, ready_first));
3991            let last = scope.spawn(move || reader(last_wait, ready));
3992            for _ in 0..2 {
3993                waiting
3994                    .recv_timeout(std::time::Duration::from_secs(10))
3995                    .expect("reader ready");
3996            }
3997            drain_maintenance(&manager);
3998            assert!(
3999                source.upgrade().is_some(),
4000                "both cursors pin the retired source"
4001            );
4002            let active_bytes = manager.sealed.read()[0].read().resident_bytes();
4003            let held = manager.resident_bytes();
4004            assert!(
4005                held >= active_bytes + source_bytes,
4006                "retired source remains resident"
4007            );
4008            release_first.send(()).expect("release first reader");
4009            first.join().expect("first reader");
4010            assert_eq!(
4011                manager.resident_bytes(),
4012                held,
4013                "one reader still pins the source"
4014            );
4015            release_last.send(()).expect("release last reader");
4016            last.join().expect("last reader");
4017            assert!(
4018                source.upgrade().is_none(),
4019                "accounting must not retain payloads"
4020            );
4021            assert_eq!(held - manager.resident_bytes(), source_bytes);
4022            assert_eq!(
4023                manager.stats().total_memory_bytes as u64,
4024                manager.resident_bytes()
4025            );
4026        });
4027    }
4028
4029    #[test]
4030    fn retained_memory_gates_runtime_growth_until_the_cursor_is_cancelled() {
4031        use crate::storage::memory_pools::MemoryPool;
4032        use crate::{RedDBOptions, RedDBRuntime};
4033
4034        let budget = 128 * 1024;
4035        let runtime =
4036            RedDBRuntime::with_options(RedDBOptions::in_memory().with_memory_budget(budget))
4037                .expect("runtime");
4038        runtime
4039            .db()
4040            .store()
4041            .create_collection("test")
4042            .expect("collection");
4043        let manager = runtime
4044            .db()
4045            .store()
4046            .get_collection("test")
4047            .expect("manager");
4048        let ids = seal_bulk_segment(&manager, 100);
4049        for id in ids.iter().take(40) {
4050            manager.delete(*id).expect("delete before scan");
4051        }
4052        let source_bytes = manager.resident_bytes();
4053        let mut growth = 0;
4054        let mut held_used = 0;
4055        assert!(!manager.scan_batches(
4056            None,
4057            || true,
4058            |_| {
4059                drain_maintenance(&manager);
4060                runtime.refresh_memory_accounting();
4061                // Other collections (including the runtime catalog) share this
4062                // arena, so derive headroom from the complete runtime sample.
4063                held_used = runtime.memory_accounting().total_used_bytes();
4064                growth = budget
4065                    .checked_sub(held_used)
4066                    .expect("fixture fits while the cursor is open")
4067                    + source_bytes / 2;
4068                assert!(growth > 0);
4069                assert!(
4070                    runtime
4071                        .admit_non_evictable_growth(
4072                            MemoryPool::SegmentArena,
4073                            "growth with pinned source",
4074                            growth,
4075                        )
4076                        .is_err(),
4077                    "retained source must participate in runtime admission"
4078                );
4079                false
4080            }
4081        ));
4082        runtime.refresh_memory_accounting();
4083        assert_eq!(
4084            held_used - runtime.memory_accounting().total_used_bytes(),
4085            source_bytes
4086        );
4087        let _reservation = runtime
4088            .admit_non_evictable_growth(
4089                MemoryPool::SegmentArena,
4090                "growth after cursor cancellation",
4091                growth,
4092            )
4093            .expect("the same growth fits once the cursor releases its source");
4094    }
4095
4096    #[test]
4097    fn retained_memory_includes_an_inflight_consolidation_copy() {
4098        let manager = consolidating_manager(1);
4099        let ids = seal_bulk_segment(&manager, 100);
4100        for id in ids.iter().take(40) {
4101            manager.delete(*id).expect("delete");
4102        }
4103        let before = manager.resident_bytes();
4104        assert!(manager.pressure_consolidation_tick());
4105        let copied = manager
4106            .consolidation
4107            .read()
4108            .as_ref()
4109            .expect("paced merge")
4110            .merged
4111            .resident_bytes();
4112        assert!(copied > 0);
4113        assert!(
4114            manager.resident_bytes() >= before + copied,
4115            "unpublished copy consumes memory"
4116        );
4117        drain_maintenance(&manager);
4118        assert!(
4119            manager.resident_bytes() < before,
4120            "completed merge releases the old storage"
4121        );
4122    }
4123
4124    #[test]
4125    fn delete_heavy_workload_reclaims_tombstoned_memory_and_counts_it() {
4126        let manager = consolidating_manager(CONSOLIDATION_ENTITIES_PER_TICK);
4127        let ids = seal_bulk_segment(&manager, 100);
4128
4129        let bytes_before_delete = manager.resident_bytes();
4130
4131        // 40% tombstones — past CONSOLIDATION_TOMBSTONE_RATIO.
4132        for id in ids.iter().take(40) {
4133            assert!(manager.delete(*id).expect("delete"));
4134        }
4135
4136        // Tombstones cost memory: the payload stays resident in flat storage
4137        // and the tombstone set grows.
4138        let bytes_with_tombstones = manager.resident_bytes();
4139        assert!(bytes_with_tombstones > bytes_before_delete);
4140
4141        let survivors = live_ids(&manager);
4142        assert_eq!(survivors.len(), 60);
4143
4144        drain_maintenance(&manager);
4145
4146        let stats = manager.stats();
4147        assert_eq!(stats.consolidation.runs_started, 1);
4148        assert_eq!(stats.consolidation.runs_completed, 1);
4149        assert_eq!(stats.consolidation.segments_merged, 1);
4150        assert_eq!(stats.consolidation.tombstones_reclaimed, 40);
4151        assert!(stats.consolidation.bytes_reclaimed > 0);
4152
4153        // The reclaimed memory is at least the tombstoned entities' share.
4154        let bytes_after = manager.resident_bytes();
4155        assert!(
4156            bytes_after <= bytes_before_delete,
4157            "consolidation must return the tombstones' memory: {bytes_after} > {bytes_before_delete}"
4158        );
4159        assert_eq!(
4160            bytes_with_tombstones - bytes_after,
4161            stats.consolidation.bytes_reclaimed
4162        );
4163        assert_eq!(stats.total_memory_bytes, bytes_after as usize);
4164
4165        assert_eq!(live_ids(&manager), survivors);
4166        assert_eq!(manager.sealed.read().len(), 1);
4167        assert_eq!(manager.sealed.read()[0].read().tombstone_count(), 0);
4168    }
4169
4170    #[test]
4171    fn query_results_are_identical_before_during_and_after_consolidation() {
4172        let manager = consolidating_manager(3);
4173        let ids = seal_bulk_segment(&manager, 20);
4174        seal_bulk_segment(&manager, 20);
4175        for id in ids.iter().take(10) {
4176            assert!(manager.delete(*id).expect("delete"));
4177        }
4178
4179        let before = live_ids(&manager);
4180        let survivor = *ids.last().expect("at least one row");
4181        let tombstoned = ids[0];
4182
4183        // Every mid-tick observation matches the pre-consolidation snapshot:
4184        // point reads, full scans, and the kind index (rebuilt by the merge).
4185        let mut mid_tick_observations = 0;
4186        while manager.consolidation.read().is_some() || mid_tick_observations == 0 {
4187            manager.run_maintenance().expect("maintenance");
4188            assert_eq!(live_ids(&manager), before);
4189            assert!(manager.get(survivor).is_some());
4190            assert!(manager.get(tombstoned).is_none());
4191            assert_eq!(manager.get_by_kind("table").len(), before.len());
4192            mid_tick_observations += 1;
4193            assert!(mid_tick_observations < 1_000);
4194        }
4195
4196        assert!(
4197            mid_tick_observations > 2,
4198            "expected the run to span several ticks, saw {mid_tick_observations}"
4199        );
4200        assert_eq!(live_ids(&manager), before);
4201        assert!(manager.get(survivor).is_some());
4202        assert!(manager.get(tombstoned).is_none());
4203        assert_eq!(manager.get_by_kind("table").len(), before.len());
4204    }
4205
4206    #[test]
4207    fn get_by_kind_reaches_sealed_segments() {
4208        let manager = consolidating_manager(CONSOLIDATION_ENTITIES_PER_TICK);
4209        let ids = seal_bulk_segment(&manager, 5);
4210        assert!(manager.delete(ids[0]).expect("delete"));
4211
4212        // The sealed list is walked through the segment read guard; the
4213        // `Arc<RwLock<GrowingSegment>>` impl of `iter_kind` cannot hand out
4214        // references across the lock and yields nothing.
4215        assert_eq!(manager.get_by_kind("table").len(), 4);
4216        assert_eq!(manager.get_by_kind("vector").len(), 0);
4217    }
4218
4219    #[test]
4220    fn consolidation_is_paced_by_the_per_tick_entity_bound() {
4221        const PER_TICK: usize = 4;
4222        let manager = consolidating_manager(PER_TICK);
4223        let ids = seal_bulk_segment(&manager, 60);
4224        for id in ids.iter().take(30) {
4225            assert!(manager.delete(*id).expect("delete"));
4226        }
4227
4228        // First tick opens the run and copies exactly one bound's worth.
4229        manager.run_maintenance().expect("maintenance");
4230        assert_eq!(manager.consolidation_progress(), Some(PER_TICK as u64));
4231
4232        // Each subsequent tick advances by no more than the bound, and the run
4233        // is still in flight — it never completes in one unbounded pass.
4234        let mut previous = PER_TICK as u64;
4235        let mut ticks = 1;
4236        while let Some(copied) = manager.consolidation_progress() {
4237            assert!(
4238                copied - previous <= PER_TICK as u64,
4239                "tick copied {} entities, bound is {PER_TICK}",
4240                copied - previous
4241            );
4242            previous = copied;
4243            manager.run_maintenance().expect("maintenance");
4244            ticks += 1;
4245            assert!(ticks < 100);
4246        }
4247
4248        // 30 survivors at 4 per tick: the run cannot have finished before the
4249        // eighth tick.
4250        assert!(ticks >= 8, "consolidation completed in only {ticks} ticks");
4251        assert_eq!(manager.stats().consolidation.runs_completed, 1);
4252        assert_eq!(live_ids(&manager).len(), 30);
4253    }
4254
4255    #[test]
4256    fn sealed_segment_count_above_the_limit_triggers_a_merge() {
4257        let manager = SegmentManager::with_config(
4258            "test",
4259            ManagerConfig {
4260                max_sealed_segments: 3,
4261                ..Default::default()
4262            },
4263        );
4264        for _ in 0..4 {
4265            seal_bulk_segment(&manager, 5);
4266        }
4267        assert_eq!(manager.sealed.read().len(), 4);
4268
4269        let before = live_ids(&manager);
4270        drain_maintenance(&manager);
4271
4272        // The knob finally does what it claimed: the sealed set collapses even
4273        // though not a single row was deleted.
4274        assert_eq!(manager.sealed.read().len(), 1);
4275        assert_eq!(manager.stats().consolidation.segments_merged, 4);
4276        assert_eq!(manager.stats().consolidation.tombstones_reclaimed, 0);
4277        assert_eq!(live_ids(&manager), before);
4278    }
4279
4280    #[test]
4281    fn a_clean_sealed_set_below_the_limit_is_never_consolidated() {
4282        let manager = consolidating_manager(CONSOLIDATION_ENTITIES_PER_TICK);
4283        seal_bulk_segment(&manager, 10);
4284        seal_bulk_segment(&manager, 10);
4285
4286        for _ in 0..5 {
4287            manager.run_maintenance().expect("maintenance");
4288        }
4289
4290        assert_eq!(manager.stats().consolidation.runs_started, 0);
4291        assert_eq!(manager.sealed.read().len(), 2);
4292    }
4293
4294    #[test]
4295    fn concurrent_readers_never_observe_a_missing_or_duplicated_entity() {
4296        use std::sync::atomic::AtomicBool;
4297
4298        let manager = Arc::new(consolidating_manager(2));
4299        let ids = seal_bulk_segment(&manager, 40);
4300        seal_bulk_segment(&manager, 40);
4301        for id in ids.iter().take(20) {
4302            assert!(manager.delete(*id).expect("delete"));
4303        }
4304
4305        let expected = live_ids(&manager);
4306        let stop = Arc::new(AtomicBool::new(false));
4307
4308        let readers: Vec<_> = (0..4)
4309            .map(|_| {
4310                let manager = Arc::clone(&manager);
4311                let stop = Arc::clone(&stop);
4312                let expected = expected.clone();
4313                std::thread::spawn(move || {
4314                    let mut scans = 0u64;
4315                    // Do-while: every reader scans at least once even when the
4316                    // drain finishes before this thread is first scheduled.
4317                    loop {
4318                        let mut seen: Vec<u64> = manager
4319                            .query_all(|_| true)
4320                            .into_iter()
4321                            .map(|entity| entity.id.raw())
4322                            .collect();
4323                        seen.sort_unstable();
4324                        // Sorting is not enough: a duplicated row would keep
4325                        // the set equal but change the length.
4326                        assert_eq!(seen, expected, "reader saw a torn sealed set");
4327                        scans += 1;
4328                        if stop.load(Ordering::Relaxed) {
4329                            break;
4330                        }
4331                    }
4332                    scans
4333                })
4334            })
4335            .collect();
4336
4337        drain_maintenance(&manager);
4338        stop.store(true, Ordering::Relaxed);
4339
4340        for reader in readers {
4341            let scans = reader.join().expect("reader thread");
4342            assert!(scans > 0, "reader never got to scan");
4343        }
4344
4345        assert_eq!(manager.stats().consolidation.runs_completed, 1);
4346        assert_eq!(live_ids(&manager), expected);
4347    }
4348
4349    #[test]
4350    fn a_row_deleted_mid_consolidation_is_not_resurrected_by_the_swap() {
4351        let manager = consolidating_manager(4);
4352        let ids = seal_bulk_segment(&manager, 20);
4353        for id in ids.iter().take(6) {
4354            assert!(manager.delete(*id).expect("delete"));
4355        }
4356
4357        // Copy the first bound's worth, then delete a row we just copied.
4358        manager.run_maintenance().expect("maintenance");
4359        assert_eq!(manager.consolidation_progress(), Some(4));
4360        let doomed = ids[6];
4361        assert!(manager.delete(doomed).expect("delete"));
4362
4363        let expected = live_ids(&manager);
4364        drain_maintenance(&manager);
4365
4366        assert!(manager.get(doomed).is_none(), "deleted row came back");
4367        assert_eq!(live_ids(&manager), expected);
4368    }
4369
4370    #[test]
4371    fn discarding_an_in_flight_consolidation_leaves_the_data_untouched() {
4372        let manager = consolidating_manager(3);
4373        let ids = seal_bulk_segment(&manager, 30);
4374        for id in ids.iter().take(12) {
4375            assert!(manager.delete(*id).expect("delete"));
4376        }
4377
4378        let before = live_ids(&manager);
4379        let sealed_before: Vec<SegmentId> = manager
4380            .sealed
4381            .read()
4382            .iter()
4383            .map(|segment| segment.read().id())
4384            .collect();
4385
4386        manager.run_maintenance().expect("maintenance");
4387        manager.run_maintenance().expect("maintenance");
4388        assert!(manager.consolidation.read().is_some());
4389
4390        // A crash between ticks drops the half-built merged segment. Sealed
4391        // segments are the durable truth, so nothing was lost — and the run is
4392        // simply started over.
4393        *manager.consolidation.write() = None;
4394
4395        assert_eq!(live_ids(&manager), before);
4396        let sealed_after: Vec<SegmentId> = manager
4397            .sealed
4398            .read()
4399            .iter()
4400            .map(|segment| segment.read().id())
4401            .collect();
4402        assert_eq!(sealed_after, sealed_before);
4403        assert_eq!(manager.stats().consolidation.runs_completed, 0);
4404
4405        drain_maintenance(&manager);
4406        assert_eq!(live_ids(&manager), before);
4407        assert_eq!(manager.stats().consolidation.runs_completed, 1);
4408    }
4409
4410    #[test]
4411    fn consolidation_preserves_entity_payload_metadata_and_sequence() {
4412        let manager = consolidating_manager(CONSOLIDATION_ENTITIES_PER_TICK);
4413
4414        // Metadata must be attached before the seal: `set_metadata` on a sealed
4415        // row rewrites it into the growing segment, which would take it out of
4416        // the segment under test.
4417        let entities: Vec<UnifiedEntity> = (0..10)
4418            .map(|i| {
4419                UnifiedEntity::table_row(
4420                    manager.next_entity_id(),
4421                    "users",
4422                    i as u64,
4423                    vec![Value::Integer(i as i64)],
4424                )
4425            })
4426            .collect();
4427        let ids = manager.bulk_insert(entities).expect("bulk insert");
4428
4429        let mut meta = Metadata::new();
4430        meta.set(
4431            "os",
4432            super::super::metadata::MetadataValue::String("linux".to_string()),
4433        );
4434        manager.set_metadata(ids[9], meta).expect("set metadata");
4435        manager.force_seal().expect("seal");
4436
4437        assert!(manager.delete(ids[0]).expect("delete"));
4438        assert!(manager.delete(ids[1]).expect("delete"));
4439        assert!(manager.delete(ids[2]).expect("delete"));
4440
4441        let before: Vec<UnifiedEntity> = {
4442            let mut entities = manager.query_all(|_| true);
4443            entities.sort_by_key(|entity| entity.id.raw());
4444            entities
4445        };
4446
4447        drain_maintenance(&manager);
4448
4449        let after: Vec<UnifiedEntity> = {
4450            let mut entities = manager.query_all(|_| true);
4451            entities.sort_by_key(|entity| entity.id.raw());
4452            entities
4453        };
4454
4455        let columns = |entity: &UnifiedEntity| match &entity.data {
4456            super::super::entity::EntityData::Row(row) => row.columns.clone(),
4457            _ => Vec::new(),
4458        };
4459
4460        assert_eq!(before.len(), after.len());
4461        for (old, new) in before.iter().zip(after.iter()) {
4462            assert_eq!(old.id, new.id);
4463            assert_eq!(columns(old), columns(new));
4464            assert_eq!(
4465                old.sequence_id, new.sequence_id,
4466                "merge must not re-issue sequence ids"
4467            );
4468        }
4469        assert!(manager
4470            .get_metadata(ids[9])
4471            .expect("metadata survives the merge")
4472            .has("os"));
4473    }
4474
4475    #[test]
4476    #[ignore = "lifecycle events intentionally no-op since the emit-channel refactor; drain_events returns empty — see SegmentManager::emit"]
4477    fn test_lifecycle_events() {
4478        let manager = SegmentManager::new("test");
4479
4480        manager
4481            .insert(UnifiedEntity::vector(
4482                manager.next_entity_id(),
4483                "v",
4484                vec![0.1],
4485            ))
4486            .unwrap();
4487
4488        let events = manager.drain_events();
4489
4490        // Should have: SegmentCreated, EntityInserted
4491        assert!(events
4492            .iter()
4493            .any(|e| matches!(e, LifecycleEvent::SegmentCreated(_))));
4494        assert!(events
4495            .iter()
4496            .any(|e| matches!(e, LifecycleEvent::EntityInserted(_, _))));
4497    }
4498}