Skip to main content

reddb_engine/storage/
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
15#![allow(clippy::too_many_arguments)] // Relocated native host entrypoints.
16
17mod backing;
18pub use backing::{CleanBackingCut, PagedEntityCursor};
19mod graph_index_merge;
20
21use parking_lot::RwLock;
22use std::collections::{BTreeSet, HashMap};
23use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
24use std::sync::{Arc, Weak};
25
26use super::entity::{EntityId, EntityKind, UnifiedEntity};
27use super::metadata::{Metadata, MetadataFilter, MetadataValue};
28use super::segment::{
29    GraphEntityKind, GrowingSegment, SegmentConfig, SegmentError, SegmentId, SegmentScanCursor,
30    SegmentState, UnifiedSegment, ZoneColPred,
31};
32use super::visibility_map::VisibilityMap;
33use crate::storage::visibility::entity_visible_with_context;
34use crate::transaction::read::SnapshotContext;
35
36/// Fraction of a collection's sealed entities that must be tombstoned before
37/// consolidation is worth its cost.
38///
39/// Tunable implementation constant, not a contract: it is surfaced read-only in
40/// `red.stats` so an operator can see what the engine decided, and it may move
41/// between releases without notice.
42pub const CONSOLIDATION_TOMBSTONE_RATIO: f64 = 0.20;
43
44/// Fraction of a collection's sealed bytes that consolidation would return to
45/// the budget (dead entity payloads plus the tombstone sets that bury them)
46/// before consolidation is worth its cost. See [`CONSOLIDATION_TOMBSTONE_RATIO`]
47/// on tunability.
48pub const CONSOLIDATION_FRAGMENTATION_RATIO: f64 = 0.30;
49
50/// Entities copied into the merged segment per maintenance tick.
51///
52/// ADR 0038 §3: consolidation is paced. A tick copies at most this many
53/// entities and returns; the half-built merged segment is carried to the next
54/// tick. No consolidation ever runs to completion in one unbounded pass.
55pub const CONSOLIDATION_ENTITIES_PER_TICK: usize = 4_096;
56
57/// Configuration for the segment manager
58#[derive(Debug, Clone)]
59pub struct ManagerConfig {
60    /// Segment configuration
61    pub segment_config: SegmentConfig,
62    /// Maximum number of sealed segments before consolidation
63    pub max_sealed_segments: usize,
64    /// Idle time (seconds) before auto-sealing
65    pub idle_seal_secs: u64,
66    /// Enable paced sealed-segment consolidation
67    pub enable_consolidation: bool,
68    /// Entities copied per maintenance tick while a consolidation is running
69    pub consolidation_entities_per_tick: usize,
70    /// Enable background archival
71    pub enable_archival: bool,
72    /// Age threshold for archival (seconds)
73    pub archive_age_secs: u64,
74}
75
76impl Default for ManagerConfig {
77    fn default() -> Self {
78        Self {
79            segment_config: SegmentConfig::default(),
80            max_sealed_segments: 10,
81            idle_seal_secs: 300, // 5 minutes
82            enable_consolidation: true,
83            consolidation_entities_per_tick: CONSOLIDATION_ENTITIES_PER_TICK,
84            enable_archival: true,
85            archive_age_secs: 86400 * 7, // 7 days
86        }
87    }
88}
89
90/// Consolidation counters for one collection (ADR 0073 §5).
91///
92/// These replace the `compact_ops` counter, which only ever counted a
93/// do-nothing branch.
94#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
95pub struct ConsolidationStats {
96    /// Consolidations that crossed a threshold and began copying.
97    pub runs_started: u64,
98    /// Consolidations that finished the swap.
99    pub runs_completed: u64,
100    /// Source segments retired by a completed swap.
101    pub segments_merged: u64,
102    /// Tombstones garbage-collected by completed swaps.
103    pub tombstones_reclaimed: u64,
104    /// Logical source-to-merged footprint reduction; readers may retain sources.
105    pub bytes_reclaimed: u64,
106}
107
108/// Manager statistics
109#[derive(Debug, Clone, Default)]
110pub struct ManagerStats {
111    /// Total entities across all segments
112    pub total_entities: usize,
113    /// Number of growing segments
114    pub growing_count: usize,
115    /// Number of sealed segments
116    pub sealed_count: usize,
117    /// Number of archived segments
118    pub archived_count: usize,
119    /// Total memory usage
120    pub total_memory_bytes: usize,
121    /// Number of seal operations
122    pub seal_ops: u64,
123    /// Consolidation counters
124    pub consolidation: ConsolidationStats,
125}
126
127#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
128pub struct SegmentScanStats {
129    pub segments_total: u64,
130    pub segments_scanned: u64,
131    pub segments_pruned: u64,
132}
133
134/// Lifecycle events for monitoring
135#[derive(Debug, Clone)]
136pub enum LifecycleEvent {
137    SegmentCreated(SegmentId),
138    SegmentSealed(SegmentId),
139    SegmentConsolidated {
140        source: Vec<SegmentId>,
141        target: SegmentId,
142    },
143    SegmentArchived(SegmentId),
144    EntityInserted(EntityId, SegmentId),
145    EntityDeleted(EntityId, SegmentId),
146}
147
148/// A consolidation in flight, carried across maintenance ticks.
149///
150/// The merged segment is built off to the side and is invisible to readers
151/// until the swap. Nothing here is durable: sealed segments are the truth (via
152/// the normal checkpoint path), so a crash mid-consolidation simply drops this
153/// state and the next boot starts over.
154struct Consolidation {
155    /// Source segments, frozen when the run started.
156    sources: Vec<SourceProgress>,
157    /// Id reserved for the merged segment.
158    merged_id: SegmentId,
159    /// The half-built merged segment.
160    merged: GrowingSegment,
161    /// Index into `sources` of the segment currently being copied.
162    cursor: usize,
163    /// Live ids of `sources[cursor]`, snapshotted when that source was opened.
164    pending_ids: Vec<EntityId>,
165    /// How many of `pending_ids` have been consumed.
166    pending_cursor: usize,
167    /// Entities copied so far, across every tick of this run.
168    entities_copied: u64,
169}
170
171/// Per-source bookkeeping for a consolidation in flight.
172struct SourceProgress {
173    id: SegmentId,
174    /// Ids copied out of this source into the merged segment.
175    copied: Vec<EntityId>,
176    /// The source's tombstone count when the run opened it, and `None` before
177    /// that. Tombstones only ever grow, so a source whose count is unchanged at
178    /// swap time saw no deletes after we started reading it — and every row we
179    /// copied out of it is still live. Anything else needs a per-row check.
180    ///
181    /// Recording this when the source is *opened*, not when it is drained, is
182    /// what makes the check sound: a row deleted between two copy ticks would
183    /// otherwise be invisible to the swap and get resurrected.
184    tombstones_at_open: Option<usize>,
185}
186
187struct PhysicalRootCacheEntry {
188    segments: Vec<(u64, u64)>,
189    seed: u64,
190    root: u64,
191}
192
193/// Resumable physical maintenance positions. Weak sources let consolidation
194/// release retired payloads; a later sweep revisits any replacement segments.
195#[doc(hidden)]
196pub struct PhysicalScanCursor {
197    sources: Vec<(Weak<RwLock<GrowingSegment>>, SegmentScanCursor)>,
198    source: usize,
199}
200
201#[derive(Default)]
202struct MetadataExpiryIndex {
203    by_deadline: BTreeSet<(u64, EntityId)>,
204    by_entity: HashMap<EntityId, u64>,
205}
206
207impl MetadataExpiryIndex {
208    fn replace(&mut self, entity_id: EntityId, deadline_ms: Option<u64>) {
209        if let Some(previous_ms) = self.by_entity.remove(&entity_id) {
210            self.by_deadline.remove(&(previous_ms, entity_id));
211        }
212        if let Some(deadline_ms) = deadline_ms {
213            self.by_deadline.insert((deadline_ms, entity_id));
214            self.by_entity.insert(entity_id, deadline_ms);
215        }
216    }
217
218    fn expired(&self, now_ms: u64, limit: usize) -> Vec<EntityId> {
219        if limit == 0 {
220            return Vec::new();
221        }
222        self.by_deadline
223            .range(..=(now_ms, EntityId::new(u64::MAX)))
224            .map(|(_, entity_id)| *entity_id)
225            .take(limit)
226            .collect()
227    }
228
229    fn scheduled_count(&self) -> usize {
230        self.by_entity.len()
231    }
232
233    fn entries(&self) -> Vec<(u64, EntityId)> {
234        self.by_deadline.iter().copied().collect()
235    }
236
237    fn replace_all(&mut self, entries: &[(u64, EntityId)]) {
238        self.by_deadline.clear();
239        self.by_entity.clear();
240        for &(deadline_ms, entity_id) in entries {
241            self.by_deadline.insert((deadline_ms, entity_id));
242            self.by_entity.insert(entity_id, deadline_ms);
243        }
244    }
245}
246
247fn metadata_u64(value: &MetadataValue) -> Option<u64> {
248    match value {
249        MetadataValue::Int(value) if *value >= 0 => Some(*value as u64),
250        MetadataValue::Timestamp(value) => Some(*value),
251        MetadataValue::Float(value)
252            if value.is_finite()
253                && value.is_sign_positive()
254                && value.fract().abs() < f64::EPSILON
255                && *value <= u64::MAX as f64 =>
256        {
257            Some(value.trunc() as u64)
258        }
259        MetadataValue::String(value) => value.parse().ok(),
260        _ => None,
261    }
262}
263
264fn metadata_expiry_deadline_ms(entity: &UnifiedEntity, metadata: &Metadata) -> Option<u64> {
265    let absolute_ms = metadata.get("_expires_at").and_then(metadata_u64);
266    let ttl_ms = metadata.get("_ttl_ms").and_then(metadata_u64).or_else(|| {
267        metadata
268            .get("_ttl")
269            .and_then(metadata_u64)
270            .and_then(|seconds| seconds.checked_mul(1_000))
271    });
272    let relative_ms = ttl_ms.map(|ttl_ms| {
273        entity
274            .created_at
275            .saturating_mul(1_000)
276            .saturating_add(ttl_ms)
277    });
278    match (absolute_ms, relative_ms) {
279        (Some(absolute_ms), Some(relative_ms)) => Some(absolute_ms.min(relative_ms)),
280        (Some(deadline_ms), None) | (None, Some(deadline_ms)) => Some(deadline_ms),
281        (None, None) => None,
282    }
283}
284
285impl PhysicalScanCursor {
286    #[doc(hidden)]
287    pub fn finished(&self) -> bool {
288        self.source == self.sources.len()
289    }
290}
291
292/// Roughly 64 MiB of hint entries per collection at the cap.
293const LIVE_ROW_VERSION_HINTS_MAX: usize = 2_000_000;
294
295/// Segment manager for a collection
296pub struct SegmentManager {
297    /// Statement-scoped constraint admission. Reentrant because SQL upserts
298    /// invoke the same typed mutation APIs while holding this collection gate.
299    row_constraint_lock: Arc<parking_lot::ReentrantMutex<()>>,
300    /// Collection name
301    collection: String,
302    /// Configuration
303    config: ManagerConfig,
304    /// Next segment ID counter
305    next_segment_id: AtomicU64,
306    /// Next entity ID counter
307    next_entity_id: AtomicU64,
308    next_sequence_id: AtomicU64,
309    /// Per-table auto-increment row ID (1, 2, 3... per collection)
310    next_row_id: AtomicU64,
311    /// Hot-path entity counter — lock-free, updated by every insert/delete.
312    /// Replaces stats.total_entities on the write path to eliminate a lock
313    /// acquisition per row (from 4 lock ops per insert → 2).
314    total_entities_atomic: AtomicU64,
315    /// Currently active growing segment
316    growing: RwLock<Option<Arc<RwLock<GrowingSegment>>>>,
317    /// Sealed segments (immutable, queryable)
318    sealed: RwLock<Vec<Arc<RwLock<GrowingSegment>>>>,
319    /// Retired sources still owned by readers. Weak handles never prolong payload lifetime.
320    retired: RwLock<Vec<Weak<RwLock<GrowingSegment>>>>,
321    /// Archived segment IDs (stored externally)
322    archived: RwLock<Vec<SegmentId>>,
323    /// Entity to segment mapping (for fast lookups by individually-inserted entities).
324    /// Bulk-inserted entities skip this map; their segment is found by sequential scan
325    /// of growing + sealed segments in get()/update()/delete().
326    entity_segment: RwLock<HashMap<EntityId, SegmentId>>,
327    /// Hint only: logical row id -> physical id of the live version last
328    /// inserted for it. Readers validate the hinted entity against storage, so
329    /// a stale or missing entry costs the version scan, never a wrong row.
330    live_row_version_hints: RwLock<HashMap<EntityId, EntityId>>,
331    /// Absolute deadlines derived from per-entity TTL metadata. Current paged
332    /// files persist this projection in their resume trailer; older files
333    /// rebuild it in bounded maintenance ticks. Sweeps are O(log N + batch).
334    metadata_expiry: RwLock<MetadataExpiryIndex>,
335    /// False only while an older paged generation is being inventoried in
336    /// bounded background ticks. New stores and versioned resume projections
337    /// start complete, including the empty case.
338    metadata_expiry_projection_ready: AtomicBool,
339    /// Shared column schema: column_name → index in Vec<Value>.
340    /// Populated on first bulk_insert. Enables columnar storage (Vec instead of HashMap per row).
341    column_schema: RwLock<Option<Arc<Vec<String>>>>,
342    // A bounded set of exact named-row shapes. Dynamic collections have no
343    // declared schema; sharing their names must not invent a table contract.
344    recovery_row_schemas: RwLock<Vec<Arc<Vec<String>>>>,
345    /// Statistics (slow path — not updated on every insert).
346    stats: RwLock<ManagerStats>,
347    /// Consolidation in flight, if any. Only `run_maintenance` touches it, so
348    /// at most one consolidation runs per collection at a time.
349    consolidation: RwLock<Option<Consolidation>>,
350    /// Event listeners (simplified - would be channels in production)
351    events: RwLock<Vec<LifecycleEvent>>,
352    /// Visibility map: sealed segment entity ranges marked as all-visible.
353    /// Growing segment is never all-visible (writes are in-flight).
354    /// Used by index-only scan decisions.
355    visibility_map: VisibilityMap,
356    physical_root_cache: parking_lot::Mutex<Option<PhysicalRootCacheEntry>>,
357    backing: RwLock<Option<backing::BackingRead>>,
358}
359
360impl SegmentManager {
361    /// Create a new segment manager
362    pub fn new(collection: impl Into<String>) -> Self {
363        Self::with_config(collection, ManagerConfig::default())
364    }
365
366    /// Create with custom configuration
367    pub fn with_config(collection: impl Into<String>, config: ManagerConfig) -> Self {
368        Self {
369            row_constraint_lock: Arc::new(parking_lot::ReentrantMutex::new(())),
370            physical_root_cache: parking_lot::Mutex::new(None),
371            backing: RwLock::new(None),
372            collection: collection.into(),
373            config,
374            next_segment_id: AtomicU64::new(1),
375            next_entity_id: AtomicU64::new(1),
376            next_sequence_id: AtomicU64::new(0),
377            next_row_id: AtomicU64::new(1),
378            total_entities_atomic: AtomicU64::new(0),
379            growing: RwLock::new(None),
380            sealed: RwLock::new(Vec::new()),
381            retired: RwLock::new(Vec::new()),
382            archived: RwLock::new(Vec::new()),
383            entity_segment: RwLock::new(HashMap::new()),
384            live_row_version_hints: RwLock::new(HashMap::new()),
385            metadata_expiry: RwLock::new(MetadataExpiryIndex::default()),
386            metadata_expiry_projection_ready: AtomicBool::new(true),
387            column_schema: RwLock::new(None),
388            recovery_row_schemas: RwLock::new(Vec::new()),
389            stats: RwLock::new(ManagerStats::default()),
390            consolidation: RwLock::new(None),
391            events: RwLock::new(Vec::new()),
392            visibility_map: VisibilityMap::new(),
393        }
394    }
395
396    #[doc(hidden)]
397    pub fn row_constraint_lock(&self) -> Arc<parking_lot::ReentrantMutex<()>> {
398        Arc::clone(&self.row_constraint_lock)
399    }
400
401    /// Get or create the shared column schema from first row's named fields.
402    pub fn get_or_init_schema(
403        &self,
404        named: &HashMap<String, reddb_types::Value>,
405    ) -> Arc<Vec<String>> {
406        {
407            let schema = self.column_schema.read();
408            if let Some(ref s) = *schema {
409                return Arc::clone(s);
410            }
411        }
412        let cols: Vec<String> = named.keys().cloned().collect();
413        let arc = Arc::new(cols);
414        *self.column_schema.write() = Some(Arc::clone(&arc));
415        arc
416    }
417
418    /// Get the column schema if it exists.
419    pub fn column_schema(&self) -> Option<Arc<Vec<String>>> {
420        self.column_schema.read().clone()
421    }
422
423    // Positional file records omit the shared column names. Restore them on
424    // owned reads before callers update fields or rebuild secondary indexes.
425    // Existing per-row names remain authoritative; segment contents stay raw.
426    #[doc(hidden)]
427    pub fn restore_owned_row_schemas<'a>(
428        &self,
429        entities: impl Iterator<Item = &'a mut UnifiedEntity>,
430    ) {
431        let schema = self.column_schema();
432        for entity in entities {
433            if let super::entity::EntityData::Row(row) = &mut entity.data {
434                if row.named.is_none() && row.schema.is_none() {
435                    row.schema = schema.clone();
436                }
437            }
438        }
439    }
440
441    #[doc(hidden)]
442    pub fn set_column_schema_if_empty(&self, columns: Vec<String>) {
443        if columns.is_empty()
444            || columns
445                .iter()
446                .collect::<std::collections::HashSet<_>>()
447                .len()
448                != columns.len()
449        {
450            return;
451        }
452        let mut schema = self.column_schema.write();
453        if schema.is_none() {
454            *schema = Some(Arc::new(columns));
455        }
456    }
457
458    /// Compact named records after recovery has restored the authoritative
459    /// column schema, before serving requests. Captured segments are skipped:
460    /// a cursor's immutable view must never change under it.
461    #[doc(hidden)]
462    pub fn compact_recovered_rows(&self) -> usize {
463        if self.recovery_preserves_named_rows() {
464            return 0;
465        }
466        let Some(schema) = self.column_schema() else {
467            return 0;
468        };
469        if schema
470            .iter()
471            .collect::<std::collections::HashSet<_>>()
472            .len()
473            != schema.len()
474        {
475            return 0;
476        }
477        let mut growing = self.growing.write();
478        let mut sealed = self.sealed.write();
479        let mut compacted = 0;
480        for segment in growing.iter_mut().chain(sealed.iter_mut()) {
481            if let Some(segment) = Arc::get_mut(segment) {
482                compacted += segment.get_mut().compact_recovered_rows(&schema);
483            }
484        }
485        compacted
486    }
487
488    /// Get collection name
489    pub fn collection(&self) -> &str {
490        &self.collection
491    }
492
493    /// Get configuration
494    pub fn config(&self) -> &ManagerConfig {
495        &self.config
496    }
497
498    /// Get statistics. Entity counts cover active segments; memory also covers
499    /// retained sources and unpublished consolidation work.
500    pub fn stats(&self) -> ManagerStats {
501        let mut s = self.stats.read().clone();
502        s.total_entities = self.total_entities_atomic.load(Ordering::Relaxed) as usize;
503        s.total_memory_bytes = self.resident_bytes() as usize;
504        s
505    }
506
507    /// Approximate resident segment memory, including tombstones, retired sources,
508    /// and the in-flight merge and its bookkeeping. This feeds budget admission.
509    pub fn resident_bytes(&self) -> u64 {
510        self.memory_usage().1
511    }
512
513    /// Resident segment payload/directory bytes and consolidation bookkeeping,
514    /// including retired sources. Unlike `resident_bytes`, excludes tombstones.
515    pub fn memory_bytes(&self) -> u64 {
516        self.memory_usage().0
517    }
518
519    /// Sample payload and resident bytes under the publication lock order:
520    /// consolidation, growing, sealed, retired. No entity scan or strong handle
521    /// is retained beyond this call; expired weak entries are pruned in place.
522    fn memory_usage(&self) -> (u64, u64) {
523        let consolidation = self.consolidation.read();
524        let growing = self.growing.read();
525        let sealed = self.sealed.read();
526        let mut retired = self.retired.write();
527        let mut payload = 0u64;
528        let mut resident = 0u64;
529        {
530            let mut add = |segment: &GrowingSegment| {
531                payload = payload.saturating_add(segment.memory_bytes());
532                resident = resident.saturating_add(segment.resident_bytes());
533            };
534            for segment in growing.iter().chain(sealed.iter()) {
535                add(&segment.read());
536            }
537            retired.retain(|source| {
538                if let Some(source) = source.upgrade() {
539                    add(&source.read());
540                    true
541                } else {
542                    false
543                }
544            });
545            if let Some(run) = consolidation.as_ref() {
546                add(&run.merged);
547            }
548        }
549        let mut bookkeeping =
550            (retired.capacity() * std::mem::size_of::<Weak<RwLock<GrowingSegment>>>()) as u64;
551        if let Some(run) = consolidation.as_ref() {
552            bookkeeping = bookkeeping
553                .saturating_add(
554                    (run.sources.capacity() * std::mem::size_of::<SourceProgress>()) as u64,
555                )
556                .saturating_add(
557                    (run.pending_ids.capacity() * std::mem::size_of::<EntityId>()) as u64,
558                );
559            for source in &run.sources {
560                bookkeeping = bookkeeping.saturating_add(
561                    (source.copied.capacity() * std::mem::size_of::<EntityId>()) as u64,
562                );
563            }
564        }
565        (
566            payload.saturating_add(bookkeeping),
567            resident.saturating_add(bookkeeping),
568        )
569    }
570
571    /// Bytes a pressure-triggered consolidation could plausibly return.
572    pub fn reclaimable_bytes(&self) -> u64 {
573        let growing = self.growing.read();
574        let sealed = self.sealed.read();
575        growing
576            .iter()
577            .chain(sealed.iter())
578            .map(|segment| segment.read().reclaimable_bytes())
579            .fold(0, u64::saturating_add)
580    }
581
582    /// Generate a new entity ID
583    pub fn next_entity_id(&self) -> EntityId {
584        EntityId::new(self.next_entity_id.fetch_add(1, Ordering::SeqCst))
585    }
586
587    /// Durable allocator state may be ahead of every surviving record.
588    pub fn identity_counters(&self) -> (u64, u64) {
589        (
590            self.next_entity_id.load(Ordering::SeqCst),
591            self.next_row_id.load(Ordering::SeqCst),
592        )
593    }
594
595    pub fn restore_identity_counters(&self, entity_id_next: u64, row_id_next: u64) {
596        assert!(
597            entity_id_next > 0 && row_id_next > 0,
598            "invariant: next identities are positive"
599        );
600        self.next_entity_id
601            .fetch_max(entity_id_next, Ordering::SeqCst);
602        self.next_row_id.fetch_max(row_id_next, Ordering::SeqCst);
603    }
604
605    pub fn sequence_id_next(&self) -> u64 {
606        let mut next = self.next_sequence_id.load(Ordering::SeqCst);
607        let growing = self.growing.read();
608        let sealed = self.sealed.read();
609        for segment in growing.iter().chain(sealed.iter()) {
610            next = next.max(segment.read().sequence_id_next());
611        }
612        self.next_sequence_id.fetch_max(next, Ordering::SeqCst);
613        next
614    }
615
616    pub fn restore_sequence_id_next(&self, next: u64) {
617        self.next_sequence_id.fetch_max(next, Ordering::SeqCst);
618    }
619
620    /// Generate a per-table sequential row ID (1, 2, 3... per collection)
621    pub fn next_row_id(&self) -> u64 {
622        self.next_row_id.fetch_add(1, Ordering::SeqCst)
623    }
624
625    /// Reserve `n` contiguous per-table row IDs with one atomic
626    /// fetch_add. Caller assigns `row_id = start + i` per entity.
627    /// Saves N-1 atomic RMWs on bulk inserts (25k atomics → 1).
628    pub fn reserve_row_ids(&self, n: u64) -> std::ops::Range<u64> {
629        let start = self.next_row_id.fetch_add(n, Ordering::SeqCst);
630        start..start + n
631    }
632
633    /// Advance the per-table row_id counter to at least `id + 1`.
634    /// Called during load to restore the counter from existing data.
635    pub fn register_row_id(&self, id: u64) {
636        let candidate = id.saturating_add(1);
637        let mut current = self.next_row_id.load(Ordering::SeqCst);
638        while candidate > current {
639            match self.next_row_id.compare_exchange(
640                current,
641                candidate,
642                Ordering::SeqCst,
643                Ordering::SeqCst,
644            ) {
645                Ok(_) => break,
646                Err(updated) => current = updated,
647            }
648        }
649    }
650
651    /// Get or create the active growing segment.
652    ///
653    /// Fast path: read lock only — no write contention when the segment already exists.
654    /// Concurrent writers each clone the `Arc` under a shared read lock, then compete
655    /// on the segment's own write lock. This eliminates the global write-lock serialisation
656    /// that previously throttled concurrent inserts to ~238 ops/s.
657    fn get_or_create_growing(&self) -> Arc<RwLock<GrowingSegment>> {
658        // Common case: segment already exists — shared read lock, zero contention.
659        {
660            let growing = self.growing.read();
661            if let Some(segment) = growing.as_ref() {
662                return Arc::clone(segment);
663            }
664        }
665
666        // Slow path: segment missing — take exclusive write lock to create it.
667        let mut growing = self.growing.write();
668        // Double-check: another thread may have created it between the two lock acquisitions.
669        if let Some(segment) = growing.as_ref() {
670            return Arc::clone(segment);
671        }
672
673        let id = self.next_segment_id.fetch_add(1, Ordering::SeqCst);
674        let segment = GrowingSegment::new(id, &self.collection);
675        segment.restore_sequence_id_next(self.next_sequence_id.load(Ordering::SeqCst));
676        let segment_arc = Arc::new(RwLock::new(segment));
677        *growing = Some(Arc::clone(&segment_arc));
678
679        self.emit(LifecycleEvent::SegmentCreated(id));
680
681        // Update growing_count in the slow-path stats struct.
682        // This is the rare segment-creation path — locking is fine here.
683        self.stats.write().growing_count += 1;
684
685        segment_arc
686    }
687
688    /// The logical id a live, unbranched row version answers for when its
689    /// physical id differs (i.e. it replaced an earlier version).
690    fn live_row_version_key(entity: &UnifiedEntity) -> Option<EntityId> {
691        let logical_id = entity.logical_id();
692        (matches!(entity.kind, EntityKind::TableRow { .. })
693            && logical_id != entity.id
694            && entity.xmax == 0
695            && entity.branch_version().is_none())
696        .then_some(logical_id)
697    }
698
699    /// Record where the live version of `logical_id` was last seen.
700    pub fn remember_live_row_version(&self, logical_id: EntityId, physical_id: EntityId) {
701        let mut hints = self.live_row_version_hints.write();
702        // Bounded: dropping every hint only sends readers back to the scan.
703        if hints.len() >= LIVE_ROW_VERSION_HINTS_MAX {
704            hints.clear();
705        }
706        hints.insert(logical_id, physical_id);
707    }
708
709    /// Record the live versions a walk of the collection passed. A hint that
710    /// is already present was written when a newer version was inserted, so
711    /// it is kept. Nothing is recorded once the hints are full: a walk must
712    /// not throw away the hints of rows that are being written.
713    pub fn remember_walked_live_row_versions(&self, walked: Vec<(EntityId, EntityId)>) {
714        if walked.is_empty() {
715            return;
716        }
717        let mut hints = self.live_row_version_hints.write();
718        for (logical_id, physical_id) in walked {
719            if hints.len() >= LIVE_ROW_VERSION_HINTS_MAX {
720                break;
721            }
722            hints.entry(logical_id).or_insert(physical_id);
723        }
724    }
725
726    /// How many live versions one walk may hand to
727    /// [`remember_walked_live_row_versions`](Self::remember_walked_live_row_versions).
728    pub const WALKED_LIVE_ROW_VERSIONS_MAX: usize = LIVE_ROW_VERSION_HINTS_MAX;
729
730    /// The live version of `logical_id`, if the hint still names one. Rows
731    /// that never changed are found by their own id and need no hint.
732    pub fn hinted_live_row_version(&self, logical_id: EntityId) -> Option<UnifiedEntity> {
733        let physical_id = *self.live_row_version_hints.read().get(&logical_id)?;
734        let entity = self.get(physical_id)?;
735        (entity.id == physical_id && Self::live_row_version_key(&entity) == Some(logical_id))
736            .then_some(entity)
737    }
738
739    /// Like [`Self::hinted_live_row_version`], but also finds a hinted version
740    /// that a checkpoint moved to the backing. Read failures propagate.
741    pub fn try_hinted_live_row_version(
742        &self,
743        logical_id: EntityId,
744        limit_bytes: usize,
745    ) -> Result<Option<UnifiedEntity>, crate::storage::error::StoreError> {
746        let Some(physical_id) = self.live_row_version_hints.read().get(&logical_id).copied() else {
747            return Ok(None);
748        };
749        Ok(self.try_get(physical_id, limit_bytes)?.filter(|entity| {
750            entity.id == physical_id && Self::live_row_version_key(entity) == Some(logical_id)
751        }))
752    }
753
754    /// Insert a new entity
755    pub fn insert(&self, mut entity: UnifiedEntity) -> Result<EntityId, SegmentError> {
756        if entity.id.raw() == 0 {
757            entity.id = self.next_entity_id();
758        }
759        self.reject_backing_duplicate(entity.id)?;
760        if self.has_backing() && self.get_with(entity.id, |_| ()).is_some() {
761            return Err(SegmentError::AlreadyExists(entity.id));
762        }
763        self.next_entity_id
764            .fetch_max(entity.id.raw().saturating_add(1), Ordering::SeqCst);
765        // Check if we need to seal the current segment first
766        self.maybe_seal_growing()?;
767
768        let segment_arc = self.get_or_create_growing();
769        let mut segment = segment_arc.write();
770
771        let entity_id = entity.id;
772        let segment_id = segment.id();
773
774        let version_hint = Self::live_row_version_key(&entity);
775        segment.insert(entity)?;
776        if let Some(logical_id) = version_hint {
777            self.remember_live_row_version(logical_id, entity_id);
778        }
779
780        // Lock-free counter update — eliminates the stats write lock on the hot path.
781        self.total_entities_atomic.fetch_add(1, Ordering::Relaxed);
782
783        // entity_segment map is intentionally NOT updated here.
784        // update() and update_hot() first probe the growing segment directly
785        // (growing.contains(entity.id)) before consulting this map, so entities
786        // that were just inserted are found without entity_segment. The map is
787        // only consulted for entities that may have been moved to sealed segments,
788        // which can't be updated anyway (state().is_writable() == false).
789        // Skipping this write removes one exclusive HashMap lock per insert.
790
791        self.emit(LifecycleEvent::EntityInserted(entity_id, segment_id));
792
793        Ok(entity_id)
794    }
795
796    // A tombstone belongs to its segment for the lifetime of captured cursors.
797    // Restoring that physical ID must use a successor segment, retaining both
798    // the original tombstone ordinal and the existing scan-position boundary.
799    fn with_restoration_segment<T>(
800        &self,
801        id: EntityId,
802        restore: impl FnOnce(&mut GrowingSegment) -> Result<T, SegmentError>,
803    ) -> Result<T, SegmentError> {
804        loop {
805            let segment = self.get_or_create_growing();
806            let mut growing = segment.write();
807            if !growing.state().is_writable() {
808                continue;
809            }
810            if !growing.is_tombstoned(id) {
811                return restore(&mut growing);
812            }
813            drop(growing);
814            self.force_seal()?;
815        }
816    }
817
818    fn recovery_preserves_named_rows(&self) -> bool {
819        // Internal catalog/configuration readers still consume named maps
820        // directly, including bootstrap before runtime initialization. Keep
821        // their established representation on both recovery compaction paths.
822        self.collection.starts_with("red_") || self.collection.starts_with("red.")
823    }
824
825    fn recovery_schema(
826        &self,
827        row: &super::entity::RowData,
828        column_schema: Option<Arc<Vec<String>>>,
829    ) -> Option<Arc<Vec<String>>> {
830        if self.recovery_preserves_named_rows() {
831            return None;
832        }
833        let named = row.named.as_ref()?;
834        let matches = |schema: &Vec<String>| {
835            schema.len() == named.len() && schema.iter().all(|name| named.contains_key(name))
836        };
837        if let Some(schema) = column_schema.filter(|schema| matches(schema)) {
838            return Some(schema);
839        }
840        {
841            let schemas = self.recovery_row_schemas.read();
842            if let Some(schema) = schemas.iter().find(|schema| matches(schema)) {
843                return Some(Arc::clone(schema));
844            }
845        }
846        let mut schemas = self.recovery_row_schemas.write();
847        if let Some(schema) = schemas.iter().find(|schema| matches(schema)) {
848            return Some(Arc::clone(schema));
849        }
850        const MAX_RECOVERY_ROW_SCHEMAS: usize = 16;
851        if schemas.len() >= MAX_RECOVERY_ROW_SCHEMAS {
852            return None;
853        }
854        let mut names: Vec<_> = named.keys().cloned().collect();
855        names.sort_unstable();
856        let schema = Arc::new(names);
857        schemas.push(Arc::clone(&schema));
858        Some(schema)
859    }
860
861    /// Apply the ordinary recovery row layout without retaining the entity.
862    /// Hosts comparing disk-backed views with resident recovery must use the
863    /// same bounded schema cache and positional-value preservation rules.
864    #[doc(hidden)]
865    pub fn restore_snapshot_row_layout(&self, entity: &mut UnifiedEntity) {
866        self.restore_recovery_row_layout(entity, self.column_schema());
867    }
868
869    fn restore_recovery_row_layout(
870        &self,
871        entity: &mut UnifiedEntity,
872        column_schema: Option<Arc<Vec<String>>>,
873    ) {
874        if let super::entity::EntityData::Row(row) = &mut entity.data {
875            if let Some(schema) = self.recovery_schema(row, column_schema) {
876                row.compact_with_schema(&schema);
877            }
878        }
879    }
880
881    /// Restore a snapshot image without allocating a new sequence identity.
882    #[doc(hidden)]
883    pub fn restore_snapshot_entity(
884        &self,
885        mut entity: UnifiedEntity,
886    ) -> Result<EntityId, SegmentError> {
887        self.restore_snapshot_row_layout(&mut entity);
888        self.maybe_seal_growing()?;
889        if self.get(entity.id).is_some() {
890            return Err(SegmentError::AlreadyExists(entity.id));
891        }
892        let entity_id = entity.id;
893        self.next_entity_id
894            .fetch_max(entity_id.raw().saturating_add(1), Ordering::SeqCst);
895        self.with_restoration_segment(entity_id, |segment| {
896            let segment_id = segment.id();
897            // Adoption retains sequence identity and advances its allocator.
898            segment.adopt_entity(entity, None);
899            self.total_entities_atomic.fetch_add(1, Ordering::Relaxed);
900            self.emit(LifecycleEvent::EntityInserted(entity_id, segment_id));
901            Ok(entity_id)
902        })
903    }
904
905    /// Insert multiple entities (batch) — sequential, one lock per item.
906    pub fn insert_batch(
907        &self,
908        entities: Vec<UnifiedEntity>,
909    ) -> Result<Vec<EntityId>, SegmentError> {
910        let mut ids = Vec::with_capacity(entities.len());
911        for entity in entities {
912            ids.push(self.insert(entity)?);
913        }
914        Ok(ids)
915    }
916
917    /// Turbo bulk insert — single lock acquisition for the entire batch.
918    /// Skips bloom filter and cross-ref indexing for maximum speed.
919    pub fn bulk_insert(
920        &self,
921        mut entities: Vec<UnifiedEntity>,
922    ) -> Result<Vec<EntityId>, SegmentError> {
923        // Reject the complete cold batch before publishing any of it.
924        if self.has_backing() {
925            let mut identities = std::collections::HashSet::with_capacity(entities.len());
926            for entity in &entities {
927                if entity.id.raw() != 0 {
928                    self.reject_backing_duplicate(entity.id)?;
929                    if self.get_with(entity.id, |_| ()).is_some() || !identities.insert(entity.id) {
930                        return Err(SegmentError::AlreadyExists(entity.id));
931                    }
932                }
933            }
934        }
935        // Assign IDs and per-table row_ids.
936        for entity in &mut entities {
937            if entity.id.raw() == 0 {
938                entity.id = self.next_entity_id();
939            }
940            self.next_entity_id
941                .fetch_max(entity.id.raw().saturating_add(1), Ordering::SeqCst);
942            if let super::entity::EntityKind::TableRow { ref mut row_id, .. } = entity.kind {
943                if *row_id == 0 {
944                    *row_id = self.next_row_id();
945                } else {
946                    self.register_row_id(*row_id);
947                }
948            }
949        }
950
951        // Convert named HashMap → positional Vec (compact memory representation)
952        // The schema (column order) is shared across all rows in the collection.
953        if let Some(first_row) = entities.first() {
954            if let super::entity::EntityData::Row(ref row) = first_row.data {
955                if let Some(ref named) = row.named {
956                    let schema = self.get_or_init_schema(named);
957                    for entity in &mut entities {
958                        if let super::entity::EntityData::Row(ref mut row) = entity.data {
959                            if let Some(named) = row.named.take() {
960                                let mut cols = Vec::with_capacity(schema.len());
961                                for col_name in schema.iter() {
962                                    cols.push(
963                                        named
964                                            .get(col_name)
965                                            .cloned()
966                                            .unwrap_or(reddb_types::Value::Null),
967                                    );
968                                }
969                                row.columns = cols;
970                                row.schema = Some(Arc::clone(&schema));
971                            }
972                        }
973                    }
974                }
975            }
976        }
977
978        let segment_arc = self.get_or_create_growing();
979        let mut segment = segment_arc.write();
980        // Single call to GrowingSegment.bulk_insert (one lock, no bloom/cross-refs)
981        let ids = segment.bulk_insert(entities)?;
982
983        // Skip entity-segment mapping for bulk inserts (saves ~56 bytes/entity).
984        // The get() method scans growing+sealed segments directly.
985
986        // Lock-free batch counter update.
987        self.total_entities_atomic
988            .fetch_add(ids.len() as u64, Ordering::Relaxed);
989
990        Ok(ids)
991    }
992
993    /// Get an entity by ID — scans growing then sealed segments.
994    pub fn get(&self, id: EntityId) -> Option<UnifiedEntity> {
995        let mut entity = self.get_with(id, Clone::clone)?;
996        self.restore_owned_row_schemas(std::iter::once(&mut entity));
997        Some(entity)
998    }
999
1000    /// Inspect under the segment lock, for example to bound a payload clone.
1001    /// The callback must not re-enter storage or runtime memory admission.
1002    #[doc(hidden)]
1003    pub fn get_with<T>(&self, id: EntityId, visit: impl FnOnce(&UnifiedEntity) -> T) -> Option<T> {
1004        // Growing segment first (most likely for recent inserts)
1005        if let Some(growing_arc) = self.growing.read().as_ref() {
1006            let growing = growing_arc.read();
1007            if let Some(entity) = growing.get(id) {
1008                return Some(visit(entity));
1009            }
1010        }
1011
1012        // Then sealed segments
1013        let sealed = self.sealed.read();
1014        for segment in sealed.iter() {
1015            let seg = segment.read();
1016            if let Some(entity) = seg.get(id) {
1017                return Some(visit(entity));
1018            }
1019        }
1020
1021        None
1022    }
1023
1024    /// Resolve a physical graph node reference without cloning historical payloads.
1025    /// This deliberately ignores MVCC: callers must authorize the visible logical
1026    /// node separately. The callback bounds every segment probe, including misses.
1027    #[doc(hidden)]
1028    pub fn graph_node_logical_id(
1029        &self,
1030        id: EntityId,
1031        mut before_segment: impl FnMut() -> bool,
1032    ) -> Option<EntityId> {
1033        if let Some(growing_arc) = self.growing.read().as_ref() {
1034            if !before_segment() {
1035                return None;
1036            }
1037            let growing = growing_arc.read();
1038            if let Some(entity) = growing.get(id) {
1039                return matches!(entity.kind, EntityKind::GraphNode(_))
1040                    .then(|| entity.logical_id());
1041            }
1042        }
1043        let sealed = self.sealed.read();
1044        for segment in sealed.iter() {
1045            if !before_segment() {
1046                return None;
1047            }
1048            let segment = segment.read();
1049            if let Some(entity) = segment.get(id) {
1050                return matches!(entity.kind, EntityKind::GraphNode(_))
1051                    .then(|| entity.logical_id());
1052            }
1053        }
1054        None
1055    }
1056
1057    /// Pin the source inventory across sealing/consolidation. Consumers hydrate
1058    /// IDs through the current manager and run outside all storage locks.
1059    /// Admission is also outside storage locks; a growing inventory retries only
1060    /// its small handle array. Each indexed candidate buffer has a fixed size.
1061    #[doc(hidden)]
1062    pub fn visit_graph_index_batches<E>(
1063        &self,
1064        kind: GraphEntityKind,
1065        keys: &[EntityId],
1066        mut before_work: impl FnMut() -> bool,
1067        mut admit: impl FnMut(usize) -> Result<(), E>,
1068        mut consume: impl FnMut(&[EntityId]) -> Result<bool, E>,
1069    ) -> Result<bool, E> {
1070        use super::segment::{GraphIndexCursor, SCAN_BATCH_SIZE};
1071        admit(std::mem::size_of::<[EntityId; SCAN_BATCH_SIZE]>())?;
1072        let mut admitted = 0;
1073        let sources = loop {
1074            let count = {
1075                let growing = self.growing.read();
1076                let sealed = self.sealed.read();
1077                sealed.len() + usize::from(growing.is_some())
1078            };
1079            let bytes = count.saturating_mul(std::mem::size_of::<(
1080                Arc<RwLock<GrowingSegment>>,
1081                GraphIndexCursor,
1082            )>());
1083            admit(bytes.saturating_sub(admitted))?;
1084            admitted = admitted.max(bytes);
1085            let mut sources = Vec::with_capacity(count);
1086            let growing = self.growing.read();
1087            let sealed = self.sealed.read();
1088            if sealed.len() + usize::from(growing.is_some()) > sources.capacity() {
1089                continue;
1090            }
1091            for segment in growing.iter().chain(sealed.iter()) {
1092                if !before_work() {
1093                    return Ok(false);
1094                }
1095                let view = segment.read();
1096                if !view.may_contain_graph_kind(kind) {
1097                    continue;
1098                }
1099                let Some(cursor) = view.graph_index_cursor(kind, keys, &mut before_work) else {
1100                    return Ok(false);
1101                };
1102                sources.push((Arc::clone(segment), cursor));
1103            }
1104            break sources;
1105        };
1106        let mut ids = [EntityId::new(0); SCAN_BATCH_SIZE];
1107        for (source, mut cursor) in sources {
1108            while !cursor.finished(keys) {
1109                let mut count = 0;
1110                {
1111                    let segment = source.read();
1112                    if !segment.may_contain_graph_kind(kind) {
1113                        break;
1114                    }
1115                    if !segment.graph_index_batch(
1116                        kind,
1117                        keys,
1118                        &mut cursor,
1119                        &mut before_work,
1120                        &mut |id| {
1121                            ids[count] = id;
1122                            count += 1;
1123                        },
1124                    ) {
1125                        return Ok(false);
1126                    }
1127                }
1128                if !before_work() || !consume(&ids[..count])? {
1129                    return Ok(false);
1130                }
1131            }
1132        }
1133        Ok(true)
1134    }
1135
1136    /// Batch-fetch multiple entities by ID in a single lock acquisition per segment.
1137    ///
1138    /// For indexed-scan result sets (up to ~5000 ids from range/bitmap lookup) this
1139    /// is 2-3 lock acquisitions total vs N×3 with individual `get()` calls.
1140    pub fn get_many(&self, ids: &[EntityId]) -> Vec<Option<UnifiedEntity>> {
1141        let schema = self.column_schema();
1142        let clone_row = |entity: &UnifiedEntity| {
1143            let mut owned = entity.clone();
1144            if let super::entity::EntityData::Row(row) = &mut owned.data {
1145                if row.schema.is_none() {
1146                    row.schema = schema.clone();
1147                }
1148            }
1149            owned
1150        };
1151        let mut out: Vec<Option<UnifiedEntity>> = vec![None; ids.len()];
1152        let mut remaining: Vec<usize> = (0..ids.len()).collect(); // indices still unfound
1153
1154        // Growing segment — one read lock for the entire batch.
1155        // Non-blocking first: if a writer is active, fall back to blocking.
1156        if let Some(growing_arc) = self.growing.read().as_ref() {
1157            let growing = if let Some(g) = growing_arc.try_read() {
1158                g
1159            } else {
1160                growing_arc.read()
1161            };
1162            remaining.retain(|&i| {
1163                if let Some(entity) = growing.get(ids[i]) {
1164                    out[i] = Some(clone_row(entity));
1165                    false // remove from remaining
1166                } else {
1167                    true // keep — not found yet
1168                }
1169            });
1170        }
1171
1172        if remaining.is_empty() {
1173            self.restore_owned_row_schemas(out.iter_mut().flatten());
1174            return out;
1175        }
1176
1177        // Sealed segments — one read lock per segment
1178        let sealed = self.sealed.read();
1179        for segment in sealed.iter() {
1180            if remaining.is_empty() {
1181                break;
1182            }
1183            let seg = segment.read();
1184            remaining.retain(|&i| {
1185                if let Some(entity) = seg.get(ids[i]) {
1186                    out[i] = Some(clone_row(entity));
1187                    false
1188                } else {
1189                    true
1190                }
1191            });
1192        }
1193
1194        drop(sealed);
1195        self.restore_owned_row_schemas(out.iter_mut().flatten());
1196        out
1197    }
1198
1199    /// Visitor-pattern batch fetch. Invokes `f(&UnifiedEntity, usize_index)`
1200    /// for each id that resolves, never cloning the entity.
1201    ///
1202    /// Used by scan hot paths (select_range, select_filtered) that
1203    /// materialize each entity into an output record and don't need
1204    /// an owned `UnifiedEntity`. Eliminates ~20% of scan CPU spent in
1205    /// `UnifiedEntity::clone` when `get_batch` is followed by
1206    /// `runtime_table_record_lean(entity)`.
1207    ///
1208    /// The closure runs while the segment read lock is held, so it
1209    /// must be short — avoid doing I/O or taking unrelated locks in
1210    /// `f`.
1211    pub fn for_each_id<F>(&self, ids: &[EntityId], mut f: F)
1212    where
1213        F: FnMut(usize, &UnifiedEntity),
1214    {
1215        // Thread-local scratch buffer for the "pending" index list.
1216        // Previous code allocated a fresh `Vec<usize>` of capacity
1217        // N on every call — 4200 × 1000 queries / scenario on the
1218        // select_range bench path. Take-and-restore pattern (vs
1219        // RefCell::borrow_mut) so user closures that recurse into
1220        // another `for_each_id` don't panic on a re-borrow; worst
1221        // case they allocate a fresh buffer and we lose the caching
1222        // win for that nested call.
1223        thread_local! {
1224            static REMAINING_SCRATCH: std::cell::Cell<Vec<usize>> =
1225                const { std::cell::Cell::new(Vec::new()) };
1226        }
1227
1228        let mut remaining: Vec<usize> = REMAINING_SCRATCH.with(|cell| cell.take());
1229        remaining.clear();
1230
1231        if let Some(growing_arc) = self.growing.read().as_ref() {
1232            let growing = if let Some(g) = growing_arc.try_read() {
1233                g
1234            } else {
1235                growing_arc.read()
1236            };
1237            for (i, id) in ids.iter().enumerate() {
1238                if let Some(entity) = growing.get(*id) {
1239                    f(i, entity);
1240                } else {
1241                    remaining.push(i);
1242                }
1243            }
1244        } else {
1245            remaining.reserve(ids.len());
1246            remaining.extend(0..ids.len());
1247        }
1248
1249        if !remaining.is_empty() {
1250            let sealed = self.sealed.read();
1251            for segment in sealed.iter() {
1252                if remaining.is_empty() {
1253                    break;
1254                }
1255                let seg = segment.read();
1256                remaining.retain(|&i| {
1257                    if let Some(entity) = seg.get(ids[i]) {
1258                        f(i, entity);
1259                        false
1260                    } else {
1261                        true
1262                    }
1263                });
1264            }
1265        }
1266
1267        REMAINING_SCRATCH.with(|cell| cell.set(remaining));
1268    }
1269
1270    /// Scan all segments for an entity
1271    #[allow(dead_code)] // Retain the existing native helper during extraction.
1272    fn scan_for_entity(&self, id: EntityId) -> Option<UnifiedEntity> {
1273        // Check growing
1274        if let Some(growing_arc) = self.growing.read().as_ref() {
1275            let growing = growing_arc.read();
1276            if let Some(entity) = growing.get(id) {
1277                return Some(entity.clone());
1278            }
1279        }
1280
1281        // Check sealed
1282        let sealed = self.sealed.read();
1283        for segment in sealed.iter() {
1284            if let Some(entity) = segment.get(id) {
1285                return Some(entity.clone());
1286            }
1287        }
1288
1289        None
1290    }
1291
1292    fn find_sealed_segment_arc(&self, id: EntityId) -> Option<Arc<RwLock<GrowingSegment>>> {
1293        let sealed = self.sealed.read();
1294        sealed
1295            .iter()
1296            .find(|segment_arc| segment_arc.read().contains(id))
1297            .map(Arc::clone)
1298    }
1299
1300    fn rewrite_sealed_entity_into_growing(
1301        &self,
1302        entity: UnifiedEntity,
1303        metadata: Option<&Metadata>,
1304    ) -> Result<(), SegmentError> {
1305        let entity_id = entity.id;
1306        let sealed_arc = self
1307            .find_sealed_segment_arc(entity_id)
1308            .ok_or(SegmentError::NotFound(entity_id))?;
1309
1310        let metadata_to_apply = {
1311            let mut sealed = sealed_arc.write();
1312            let existing_metadata = sealed.get_metadata(entity_id);
1313            if !sealed.force_delete(entity_id) {
1314                return Err(SegmentError::NotFound(entity_id));
1315            }
1316            metadata.cloned().or(existing_metadata)
1317        };
1318
1319        let growing_id = self.with_restoration_segment(entity_id, |growing| {
1320            growing.insert_preserving_sequence(entity)?;
1321            if let Some(metadata) = metadata_to_apply {
1322                growing.set_metadata(entity_id, metadata)?;
1323            }
1324            Ok(growing.id())
1325        })?;
1326
1327        self.entity_segment.write().insert(entity_id, growing_id);
1328        Ok(())
1329    }
1330
1331    /// Update an entity
1332    pub fn update(&self, entity: UnifiedEntity) -> Result<(), SegmentError> {
1333        self.materialize_backing_entity(entity.id)?;
1334        let entity_id = entity.id;
1335        let mut entity = Some(entity);
1336
1337        // Try growing segment directly (covers bulk-inserted entities without entity_segment map)
1338        if let Some(growing_arc) = self.growing.read().as_ref() {
1339            let mut growing = growing_arc.write();
1340            if growing.contains(entity_id) && growing.state().is_writable() {
1341                return growing.update(entity.take().expect("entity already moved"));
1342            }
1343        }
1344
1345        // Try entity_segment mapping for individually inserted entities
1346        let segment_id = self.entity_segment.read().get(&entity_id).copied();
1347        if let Some(seg_id) = segment_id {
1348            if let Some(growing_arc) = self.growing.read().as_ref() {
1349                let mut growing = growing_arc.write();
1350                if growing.id() == seg_id && growing.state().is_writable() {
1351                    return growing.update(entity.take().expect("entity already moved"));
1352                }
1353            }
1354        }
1355
1356        if let Some(entity) = entity.take() {
1357            return self.rewrite_sealed_entity_into_growing(entity, None);
1358        }
1359
1360        Err(SegmentError::NotFound(entity_id))
1361    }
1362
1363    /// Update an entity and, optionally, replace its metadata while holding
1364    /// the segment write lock only once.
1365    pub fn update_with_metadata(
1366        &self,
1367        entity: UnifiedEntity,
1368        metadata: Option<&Metadata>,
1369    ) -> Result<(), SegmentError> {
1370        self.materialize_backing_entity(entity.id)?;
1371        let entity_id = entity.id;
1372        let deadline_ms =
1373            metadata.and_then(|metadata| metadata_expiry_deadline_ms(&entity, metadata));
1374        let mut entity = Some(entity);
1375
1376        // Try growing segment directly (covers bulk-inserted entities without entity_segment map)
1377        if let Some(growing_arc) = self.growing.read().as_ref() {
1378            let mut growing = growing_arc.write();
1379            if growing.contains(entity_id) && growing.state().is_writable() {
1380                growing.update(entity.take().expect("entity already moved"))?;
1381                if let Some(metadata) = metadata {
1382                    growing.set_metadata(entity_id, metadata.clone())?;
1383                    self.metadata_expiry.write().replace(entity_id, deadline_ms);
1384                }
1385                return Ok(());
1386            }
1387        }
1388
1389        // Try entity_segment mapping for individually inserted entities
1390        let segment_id = self.entity_segment.read().get(&entity_id).copied();
1391        if let Some(seg_id) = segment_id {
1392            if let Some(growing_arc) = self.growing.read().as_ref() {
1393                let mut growing = growing_arc.write();
1394                if growing.id() == seg_id && growing.state().is_writable() {
1395                    growing.update(entity.take().expect("entity already moved"))?;
1396                    if let Some(metadata) = metadata {
1397                        growing.set_metadata(entity_id, metadata.clone())?;
1398                        self.metadata_expiry.write().replace(entity_id, deadline_ms);
1399                    }
1400                    return Ok(());
1401                }
1402            }
1403        }
1404
1405        if let Some(entity) = entity.take() {
1406            self.rewrite_sealed_entity_into_growing(entity, metadata)?;
1407            if metadata.is_some() {
1408                self.metadata_expiry.write().replace(entity_id, deadline_ms);
1409            }
1410            return Ok(());
1411        }
1412
1413        Err(SegmentError::NotFound(entity_id))
1414    }
1415
1416    /// HOT-update: like update but skips index work for unchanged columns.
1417    /// `modified_columns` is the list of column names actually changed by the
1418    /// UPDATE statement — lets us skip pk_index and cross_ref when safe.
1419    pub fn update_hot(
1420        &self,
1421        entity: UnifiedEntity,
1422        modified_columns: &[String],
1423    ) -> Result<(), SegmentError> {
1424        self.materialize_backing_entity(entity.id)?;
1425        let entity_id = entity.id;
1426        let mut entity = Some(entity);
1427
1428        if let Some(growing_arc) = self.growing.read().as_ref() {
1429            let mut growing = growing_arc.write();
1430            if growing.contains(entity_id) && growing.state().is_writable() {
1431                return growing.update_hot(
1432                    entity.take().expect("entity already moved"),
1433                    modified_columns,
1434                );
1435            }
1436        }
1437
1438        let segment_id = self.entity_segment.read().get(&entity_id).copied();
1439        if let Some(seg_id) = segment_id {
1440            if let Some(growing_arc) = self.growing.read().as_ref() {
1441                let mut growing = growing_arc.write();
1442                if growing.id() == seg_id && growing.state().is_writable() {
1443                    return growing.update_hot(
1444                        entity.take().expect("entity already moved"),
1445                        modified_columns,
1446                    );
1447                }
1448            }
1449        }
1450
1451        if let Some(entity) = entity.take() {
1452            return self.rewrite_sealed_entity_into_growing(entity, None);
1453        }
1454
1455        Err(SegmentError::NotFound(entity_id))
1456    }
1457
1458    /// HOT-update an entity and, optionally, replace its metadata while
1459    /// holding the segment write lock only once.
1460    pub fn update_hot_with_metadata(
1461        &self,
1462        entity: UnifiedEntity,
1463        modified_columns: &[String],
1464        metadata: Option<&Metadata>,
1465    ) -> Result<(), SegmentError> {
1466        self.materialize_backing_entity(entity.id)?;
1467        let entity_id = entity.id;
1468        let deadline_ms =
1469            metadata.and_then(|metadata| metadata_expiry_deadline_ms(&entity, metadata));
1470        let mut entity = Some(entity);
1471
1472        if let Some(growing_arc) = self.growing.read().as_ref() {
1473            let mut growing = growing_arc.write();
1474            if growing.contains(entity_id) && growing.state().is_writable() {
1475                growing.update_hot(
1476                    entity.take().expect("entity already moved"),
1477                    modified_columns,
1478                )?;
1479                if let Some(metadata) = metadata {
1480                    growing.set_metadata(entity_id, metadata.clone())?;
1481                    self.metadata_expiry.write().replace(entity_id, deadline_ms);
1482                }
1483                return Ok(());
1484            }
1485        }
1486
1487        let segment_id = self.entity_segment.read().get(&entity_id).copied();
1488        if let Some(seg_id) = segment_id {
1489            if let Some(growing_arc) = self.growing.read().as_ref() {
1490                let mut growing = growing_arc.write();
1491                if growing.id() == seg_id && growing.state().is_writable() {
1492                    growing.update_hot(
1493                        entity.take().expect("entity already moved"),
1494                        modified_columns,
1495                    )?;
1496                    if let Some(metadata) = metadata {
1497                        growing.set_metadata(entity_id, metadata.clone())?;
1498                        self.metadata_expiry.write().replace(entity_id, deadline_ms);
1499                    }
1500                    return Ok(());
1501                }
1502            }
1503        }
1504
1505        if let Some(entity) = entity.take() {
1506            self.rewrite_sealed_entity_into_growing(entity, metadata)?;
1507            if metadata.is_some() {
1508                self.metadata_expiry.write().replace(entity_id, deadline_ms);
1509            }
1510            return Ok(());
1511        }
1512
1513        Err(SegmentError::NotFound(entity_id))
1514    }
1515
1516    /// Batch HOT-update multiple entities while holding the growing-segment
1517    /// write lock only once when possible.
1518    pub fn update_hot_batch_with_metadata<'a, I>(&self, items: I) -> Result<(), SegmentError>
1519    where
1520        I: IntoIterator<Item = (&'a UnifiedEntity, &'a [String], Option<&'a Metadata>)>,
1521    {
1522        let items: Vec<(&UnifiedEntity, &[String], Option<&Metadata>)> =
1523            items.into_iter().collect();
1524        if items.is_empty() {
1525            return Ok(());
1526        }
1527
1528        if let Some(growing_arc) = self.growing.read().as_ref() {
1529            let mut growing = growing_arc.write();
1530            if growing.state().is_writable() {
1531                match growing.update_hot_batch_with_metadata(items.iter().copied()) {
1532                    Ok(()) => {
1533                        let mut expiry = self.metadata_expiry.write();
1534                        for (entity, _, metadata) in &items {
1535                            if let Some(metadata) = metadata {
1536                                expiry.replace(
1537                                    entity.id,
1538                                    metadata_expiry_deadline_ms(entity, metadata),
1539                                );
1540                            }
1541                        }
1542                        return Ok(());
1543                    }
1544                    Err(SegmentError::NotFound(_)) => {}
1545                    Err(other) => return Err(other),
1546                }
1547            }
1548        }
1549
1550        for (entity, modified_columns, metadata) in items {
1551            self.update_hot_with_metadata(entity.clone(), modified_columns, metadata)?;
1552        }
1553        Ok(())
1554    }
1555
1556    /// Delete an entity
1557    pub fn delete(&self, id: EntityId) -> Result<bool, SegmentError> {
1558        self.materialize_backing_entity(id)?;
1559        let deleted = self.delete_resident(id)?;
1560        if deleted {
1561            self.remember_backing_delete(id);
1562            self.metadata_expiry.write().replace(id, None);
1563        }
1564        Ok(deleted)
1565    }
1566
1567    fn delete_resident(&self, id: EntityId) -> Result<bool, SegmentError> {
1568        // Fast path: probe the growing segment directly — covers entities inserted via
1569        // insert() which no longer writes to entity_segment, and bulk-inserted entities.
1570        if let Some(growing_arc) = self.growing.read().as_ref() {
1571            let mut growing = growing_arc.write();
1572            if growing.contains(id) && growing.state().is_writable() {
1573                let seg_id = growing.id();
1574                let deleted = growing.delete(id)?;
1575                if deleted {
1576                    self.entity_segment.write().remove(&id);
1577                    self.total_entities_atomic.fetch_sub(1, Ordering::Relaxed);
1578                    self.emit(LifecycleEvent::EntityDeleted(id, seg_id));
1579                }
1580                return Ok(deleted);
1581            }
1582        }
1583
1584        // Fallback: check entity_segment map (populated for older insert() paths
1585        // or entities that were in a previous growing segment).
1586        let segment_id = self.entity_segment.read().get(&id).copied();
1587
1588        if let Some(seg_id) = segment_id {
1589            if let Some(growing_arc) = self.growing.read().as_ref() {
1590                let mut growing = growing_arc.write();
1591                if growing.id() == seg_id && growing.state().is_writable() {
1592                    let deleted = growing.delete(id)?;
1593                    if deleted {
1594                        self.entity_segment.write().remove(&id);
1595                        self.total_entities_atomic.fetch_sub(1, Ordering::Relaxed);
1596                        self.emit(LifecycleEvent::EntityDeleted(id, seg_id));
1597                    }
1598                    return Ok(deleted);
1599                }
1600            }
1601        }
1602
1603        // Fallback: entity is in a sealed segment (bulk-inserted, not in entity_segment map).
1604        // Single write-lock per segment to avoid TOCTOU race between contains() and force_delete().
1605        {
1606            let sealed = self.sealed.read();
1607            for segment_arc in sealed.iter() {
1608                let mut seg = segment_arc.write();
1609                let seg_id = seg.id();
1610                if seg.contains(id) {
1611                    let deleted = seg.force_delete(id);
1612                    drop(seg);
1613                    if deleted {
1614                        self.entity_segment.write().remove(&id);
1615                        self.total_entities_atomic.fetch_sub(1, Ordering::Relaxed);
1616                        self.emit(LifecycleEvent::EntityDeleted(id, seg_id));
1617                    }
1618                    return Ok(deleted);
1619                }
1620            }
1621        }
1622
1623        Ok(false)
1624    }
1625
1626    /// Remove rows the way [`delete_batch`](Self::delete_batch) does, but
1627    /// never queue behind a walk of the disk base. Removing a row from the
1628    /// base excludes such a walk, and a writer waiting for one makes every
1629    /// reader that arrives meanwhile wait too. A statement has to wait;
1630    /// maintenance stops at the first row it cannot remove within `wait` and
1631    /// returns what it removed, leaving the rest for a later pass.
1632    pub fn delete_batch_between_walks(
1633        &self,
1634        ids: &[EntityId],
1635        wait: std::time::Duration,
1636    ) -> Result<Vec<EntityId>, SegmentError> {
1637        if !self.has_backing() {
1638            return self.delete_batch(ids);
1639        }
1640        let mut deleted = Vec::new();
1641        for id in ids {
1642            if self.backing.try_write_for(wait).is_none() {
1643                break;
1644            }
1645            if self.delete(*id)? {
1646                deleted.push(*id);
1647            }
1648        }
1649        Ok(deleted)
1650    }
1651
1652    pub fn delete_batch(&self, ids: &[EntityId]) -> Result<Vec<EntityId>, SegmentError> {
1653        if self.has_backing() {
1654            let mut deleted = Vec::new();
1655            for id in ids {
1656                if self.delete(*id)? {
1657                    deleted.push(*id);
1658                }
1659            }
1660            return Ok(deleted);
1661        }
1662        if ids.is_empty() {
1663            return Ok(Vec::new());
1664        }
1665
1666        let mut deleted_ids = Vec::with_capacity(ids.len());
1667
1668        if let Some(growing_arc) = self.growing.read().as_ref() {
1669            let mut growing = growing_arc.write();
1670            if growing.state().is_writable() {
1671                let seg_id = growing.id();
1672                let deleted = growing.delete_batch(ids)?;
1673                if !deleted.is_empty() {
1674                    {
1675                        let mut entity_segment = self.entity_segment.write();
1676                        for id in &deleted {
1677                            entity_segment.remove(id);
1678                        }
1679                    }
1680                    self.total_entities_atomic
1681                        .fetch_sub(deleted.len() as u64, Ordering::Relaxed);
1682                    for id in &deleted {
1683                        self.emit(LifecycleEvent::EntityDeleted(*id, seg_id));
1684                    }
1685                    deleted_ids.extend(deleted);
1686                }
1687            }
1688        }
1689
1690        if deleted_ids.len() == ids.len() {
1691            let mut expiry = self.metadata_expiry.write();
1692            for id in &deleted_ids {
1693                expiry.replace(*id, None);
1694            }
1695            return Ok(deleted_ids);
1696        }
1697
1698        let deleted_set: std::collections::HashSet<EntityId> =
1699            deleted_ids.iter().copied().collect();
1700        for &id in ids {
1701            if deleted_set.contains(&id) {
1702                continue;
1703            }
1704            if self.delete(id)? {
1705                deleted_ids.push(id);
1706            }
1707        }
1708
1709        if !deleted_ids.is_empty() {
1710            let mut expiry = self.metadata_expiry.write();
1711            for id in &deleted_ids {
1712                expiry.replace(*id, None);
1713            }
1714        }
1715
1716        Ok(deleted_ids)
1717    }
1718
1719    /// Get metadata for an entity
1720    ///
1721    /// Callbacks of the entity scans call this for the row they are visiting,
1722    /// on the thread that already holds the read guards the scan took. A plain
1723    /// `read()` parks behind any writer that queued in between, while that
1724    /// writer waits for the scan's guards: neither ever proceeds. These are
1725    /// point reads, so they take the locks without yielding to a queued writer.
1726    pub fn get_metadata(&self, id: EntityId) -> Option<Metadata> {
1727        // Fast path: probe growing segment directly (no entity_segment needed).
1728        if let Some(growing_arc) = self.growing.read_recursive().as_ref() {
1729            let growing = growing_arc.read_recursive();
1730            if growing.contains(id) {
1731                return growing.get_metadata(id);
1732            }
1733        }
1734
1735        // Fallback: entity_segment map (for pre-existing or sealed entities)
1736        let segment_id = self.entity_segment.read_recursive().get(&id).copied();
1737
1738        let sealed = self.sealed.read_recursive();
1739        if let Some(seg_id) = segment_id {
1740            if let Some(growing_arc) = self.growing.read_recursive().as_ref() {
1741                let growing = growing_arc.read_recursive();
1742                if growing.id() == seg_id {
1743                    return growing.get_metadata(id);
1744                }
1745            }
1746
1747            for segment in sealed.iter() {
1748                let segment = segment.read_recursive();
1749                if segment.id() == seg_id {
1750                    return segment.get_metadata(id);
1751                }
1752            }
1753        }
1754
1755        sealed
1756            .iter()
1757            .find_map(|segment| {
1758                let segment = segment.read_recursive();
1759                segment.contains(id).then(|| segment.get_metadata(id))
1760            })
1761            .flatten()
1762    }
1763
1764    /// Set metadata for an entity
1765    pub fn set_metadata(&self, id: EntityId, metadata: Metadata) -> Result<(), SegmentError> {
1766        self.materialize_backing_entity(id)?;
1767        let entity = self.get(id).ok_or(SegmentError::NotFound(id))?;
1768        let deadline_ms = metadata_expiry_deadline_ms(&entity, &metadata);
1769        self.set_metadata_resident(id, metadata)?;
1770        self.metadata_expiry.write().replace(id, deadline_ms);
1771        Ok(())
1772    }
1773
1774    fn set_metadata_resident(&self, id: EntityId, metadata: Metadata) -> Result<(), SegmentError> {
1775        // Fast path: probe growing segment directly — covers entities inserted via
1776        // insert() which no longer writes to entity_segment.
1777        if let Some(growing_arc) = self.growing.read().as_ref() {
1778            let mut growing = growing_arc.write();
1779            if growing.contains(id) && growing.state().is_writable() {
1780                return growing.set_metadata(id, metadata);
1781            }
1782        }
1783
1784        // Fallback: entity_segment map (sealed or pre-atomic-path entities)
1785        let segment_id = self.entity_segment.read().get(&id).copied();
1786
1787        if let Some(seg_id) = segment_id {
1788            if let Some(growing_arc) = self.growing.read().as_ref() {
1789                let mut growing = growing_arc.write();
1790                if growing.id() == seg_id && growing.state().is_writable() {
1791                    return growing.set_metadata(id, metadata);
1792                }
1793            }
1794        }
1795
1796        if let Some(entity) = self.get(id) {
1797            return self.rewrite_sealed_entity_into_growing(entity, Some(&metadata));
1798        }
1799
1800        Err(SegmentError::NotFound(id))
1801    }
1802
1803    /// Return at most `limit` entity IDs whose persisted TTL metadata is due.
1804    /// The index is ordered by absolute deadline, so this does no entity scan.
1805    pub fn expired_metadata_ids(&self, now_ms: u64, limit: usize) -> Vec<EntityId> {
1806        self.metadata_expiry.read().expired(now_ms, limit)
1807    }
1808
1809    /// Number of entities carrying a valid absolute or relative TTL deadline.
1810    pub fn scheduled_metadata_expiry_count(&self) -> usize {
1811        self.metadata_expiry.read().scheduled_count()
1812    }
1813
1814    pub fn metadata_expiry_entries(&self) -> Vec<(u64, EntityId)> {
1815        self.metadata_expiry.read().entries()
1816    }
1817
1818    pub fn restore_metadata_expiry_projection(&self, entries: &[(u64, EntityId)], ready: bool) {
1819        self.metadata_expiry.write().replace_all(entries);
1820        self.metadata_expiry_projection_ready
1821            .store(ready, Ordering::Release);
1822    }
1823
1824    pub fn metadata_expiry_projection_ready(&self) -> bool {
1825        self.metadata_expiry_projection_ready
1826            .load(Ordering::Acquire)
1827    }
1828
1829    pub fn mark_metadata_expiry_projection_ready(&self) {
1830        self.metadata_expiry_projection_ready
1831            .store(true, Ordering::Release);
1832    }
1833
1834    pub fn remove_metadata_expiry(&self, entity_id: EntityId) {
1835        self.metadata_expiry.write().replace(entity_id, None);
1836    }
1837
1838    /// Rebuild the volatile deadline projection while recovery is already
1839    /// decoding a persisted record. This does not materialize the entity.
1840    pub fn restore_metadata_expiry(&self, entity: &UnifiedEntity, metadata: Option<&Metadata>) {
1841        let deadline_ms = (entity.xmax == 0)
1842            .then(|| metadata.and_then(|value| metadata_expiry_deadline_ms(entity, value)))
1843            .flatten();
1844        self.metadata_expiry.write().replace(entity.id, deadline_ms);
1845    }
1846
1847    /// Check if growing segment should be sealed
1848    fn maybe_seal_growing(&self) -> Result<(), SegmentError> {
1849        let should_seal = {
1850            let growing_opt = self.growing.read();
1851            if let Some(growing_arc) = growing_opt.as_ref() {
1852                let growing = growing_arc.read();
1853                growing.should_seal(&self.config.segment_config)
1854                    || growing.idle_secs() >= self.config.idle_seal_secs
1855            } else {
1856                false
1857            }
1858        };
1859
1860        if should_seal {
1861            self.seal_current()?;
1862        }
1863
1864        Ok(())
1865    }
1866
1867    /// Seal the current growing segment
1868    pub fn seal_current(&self) -> Result<SegmentId, SegmentError> {
1869        self.seal_current_if(|_| true)?
1870            .ok_or(SegmentError::InvalidState(SegmentState::Sealed))
1871    }
1872
1873    fn seal_current_if(
1874        &self,
1875        should_seal: impl FnOnce(&GrowingSegment) -> bool,
1876    ) -> Result<Option<SegmentId>, SegmentError> {
1877        let disk_residency = self.has_backing();
1878        // Keep topology publication atomic for cursors that capture growing
1879        // and sealed under the same lock order: growing, then sealed.
1880        let mut growing_slot = self.growing.write();
1881        if let Some(growing_arc) = growing_slot.as_ref() {
1882            let mut growing = growing_arc.write();
1883            if !should_seal(&growing) {
1884                return Ok(None);
1885            }
1886            if disk_residency {
1887                self.next_sequence_id
1888                    .fetch_max(growing.sequence_id_next(), Ordering::SeqCst);
1889            }
1890            let seg_id = growing.id();
1891            let entity_count = growing.stats().entity_count as u64;
1892
1893            // Seal it
1894            growing.seal()?;
1895
1896            // Move to sealed list (we need to extract it from the Arc)
1897            drop(growing); // Release write lock
1898
1899            // In a real implementation, we'd convert to SealedSegment here
1900            // For now, we keep it as-is since GrowingSegment implements UnifiedSegment
1901            let growing_arc = growing_slot
1902                .take()
1903                .expect("sealed source remains published");
1904            self.sealed.write().push(growing_arc);
1905            drop(growing_slot);
1906
1907            // Mark sealed segment pages all-visible — they're now immutable
1908            self.mark_sealed_pages_visible(entity_count);
1909
1910            // Update stats
1911            {
1912                let mut stats = self.stats.write();
1913                stats.growing_count = stats.growing_count.saturating_sub(1);
1914                stats.sealed_count += 1;
1915                stats.seal_ops += 1;
1916            }
1917
1918            self.emit(LifecycleEvent::SegmentSealed(seg_id));
1919
1920            return Ok(Some(seg_id));
1921        }
1922
1923        Ok(None)
1924    }
1925
1926    /// Force seal (for testing/manual control)
1927    pub fn force_seal(&self) -> Result<Option<SegmentId>, SegmentError> {
1928        let has_growing = self.growing.read().is_some();
1929        if has_growing {
1930            Ok(Some(self.seal_current()?))
1931        } else {
1932            Ok(None)
1933        }
1934    }
1935
1936    /// Fraction of "pages" in sealed segments that are marked all-visible.
1937    ///
1938    /// Sealed segments are immutable so all their rows are safe for
1939    /// index-only scans. The growing segment is never counted (writes
1940    /// may be in-flight). Uses `rows_per_page = 256` (matching 8 KB pages
1941    /// with ~32-byte rows).
1942    ///
1943    /// Returns a value in `[0.0, 1.0]`. 1.0 when all sealed rows are
1944    /// visible; 0.0 when there are no sealed segments.
1945    pub fn all_visible_fraction(&self) -> f64 {
1946        const ROWS_PER_PAGE: u32 = 256;
1947        let sealed = self.sealed.read();
1948        if sealed.is_empty() {
1949            return 0.0;
1950        }
1951        let mut total_pages: u64 = 0;
1952        for seg_arc in sealed.iter() {
1953            let seg = seg_arc.read();
1954            let entity_count = seg.stats().entity_count as u64;
1955            let pages = entity_count.div_ceil(ROWS_PER_PAGE as u64);
1956            total_pages += pages;
1957        }
1958        if total_pages == 0 {
1959            return 0.0;
1960        }
1961        let visible = self.visibility_map.all_visible_count();
1962        (visible as f64 / total_pages as f64).min(1.0)
1963    }
1964
1965    /// Mark all pages of newly sealed segments as all-visible in the
1966    /// visibility map. Called internally after `seal_current`.
1967    fn mark_sealed_pages_visible(&self, seg_entity_count: u64) {
1968        const ROWS_PER_PAGE: u32 = 256;
1969        let existing_visible = self.visibility_map.all_visible_count();
1970        // Append pages starting after the last known visible page
1971        let start_page = existing_visible as u32;
1972        let new_pages = seg_entity_count.div_ceil(ROWS_PER_PAGE as u64);
1973        let end_page = start_page + new_pages as u32;
1974        self.visibility_map.mark_range_visible(start_page, end_page);
1975    }
1976
1977    /// Probe a unique-key lookup in each segment under the same entity
1978    /// locks used by scans and writes. Lookup state is rebuilt lazily after
1979    /// recovery, consolidation, or a key-changing mutation.
1980    #[doc(hidden)]
1981    pub fn find_unique_key_conflict(
1982        &self,
1983        columns: &[Vec<String>],
1984        key_index: usize,
1985        signatures: &[String],
1986        exclude_id: Option<EntityId>,
1987        reserves_key: &impl Fn(&UnifiedEntity) -> bool,
1988    ) -> Option<EntityId> {
1989        if let Some(growing) = self.growing.read().as_ref() {
1990            if let Some(id) = growing.read().find_unique_key_conflict(
1991                columns,
1992                key_index,
1993                signatures,
1994                exclude_id,
1995                reserves_key,
1996            ) {
1997                return Some(id);
1998            }
1999        }
2000        for segment in self.sealed.read().iter() {
2001            if let Some(id) = segment.read().find_unique_key_conflict(
2002                columns,
2003                key_index,
2004                signatures,
2005                exclude_id,
2006                reserves_key,
2007            ) {
2008                return Some(id);
2009            }
2010        }
2011        None
2012    }
2013
2014    /// Iterate over all entities in-place without collecting into a Vec.
2015    ///
2016    /// The callback receives a reference to each entity. Return `true` to
2017    /// continue iteration, `false` to stop early (e.g. when a LIMIT is reached).
2018    /// This avoids the allocation and cloning overhead of `query_all`.
2019    pub fn for_each_entity<F>(&self, callback: F)
2020    where
2021        F: FnMut(&UnifiedEntity) -> bool,
2022    {
2023        self.for_each_entity_in_segments(|_| true, || true, callback);
2024    }
2025
2026    /// Segment identities and mutation counters, sampled without scanning rows.
2027    #[doc(hidden)]
2028    pub fn checkpoint_revisions(&self) -> Vec<(u64, u64)> {
2029        let growing = self.growing.read();
2030        let sealed = self.sealed.read();
2031        growing
2032            .iter()
2033            .chain(sealed.iter())
2034            .map(|segment| {
2035                let segment = segment.read();
2036                (segment.id(), segment.checkpoint_revision())
2037            })
2038            .collect()
2039    }
2040
2041    #[doc(hidden)]
2042    pub fn checkpoint_mutations_since(&self, before: &[(u64, u64)]) -> Option<Vec<EntityId>> {
2043        let growing = self.growing.read();
2044        let sealed = self.sealed.read();
2045        // Sealing moves the same segment from growing to sealed, and a later
2046        // write creates a new growing segment. Neither operation invalidates
2047        // the old segments' mutation journals. Match identities rather than
2048        // positions so these ordinary lifecycle changes retain sparse proofs.
2049        let previous: HashMap<_, _> = before.iter().copied().collect();
2050        if previous.len() != before.len() {
2051            return None;
2052        }
2053        let mut retained_sources = 0;
2054        let mut changed = std::collections::BTreeSet::new();
2055        for segment in growing.iter().chain(sealed.iter()) {
2056            let segment = segment.read();
2057            let revision = previous.get(&segment.id()).copied();
2058            retained_sources += usize::from(revision.is_some());
2059            // A new segment must account for its entire history from revision
2060            // zero. Missing or exhausted journals still reject the fast path.
2061            let revision = revision.unwrap_or(0);
2062            changed.extend(segment.checkpoint_mutations_since(revision)?);
2063            if changed.len() > super::segment::CHECKPOINT_MUTATIONS_MAX {
2064                return None;
2065            }
2066        }
2067        // Consolidation or removal can hide changes from an old source. Keep
2068        // conservative full validation whenever a previous identity is absent.
2069        (retained_sources == previous.len()).then(|| changed.into_iter().collect())
2070    }
2071
2072    #[doc(hidden)]
2073    pub fn checkpoint_tracking_bytes(&self) -> usize {
2074        let growing = self.growing.read();
2075        let sealed = self.sealed.read();
2076        growing
2077            .iter()
2078            .chain(sealed.iter())
2079            .map(|segment| segment.read().checkpoint_tracking_bytes())
2080            .sum()
2081    }
2082
2083    /// Reuse the derived metadata fingerprint only while its rows and stats match.
2084    #[doc(hidden)]
2085    pub fn cached_physical_root(&self, seed: u64, compute: impl FnOnce() -> u64) -> u64 {
2086        let segments = self.checkpoint_revisions();
2087        let mut cache = self.physical_root_cache.lock();
2088        if let Some(previous) = cache.as_ref() {
2089            if previous.seed == seed && previous.segments == segments {
2090                return previous.root;
2091            }
2092        }
2093        let root = compute();
2094        *cache = Some(PhysicalRootCacheEntry {
2095            segments,
2096            seed,
2097            root,
2098        });
2099        root
2100    }
2101
2102    /// Visit rows in the same stable ID order as sorting `query_all`, without
2103    /// cloning their payloads. The caller fences mutations while fingerprinting.
2104    /// Pin source segments, but hold only one segment guard during each visit.
2105    /// Callbacks must not re-enter storage while that guard is held.
2106    #[doc(hidden)]
2107    pub fn for_each_entity_in_id_order(&self, mut visit: impl FnMut(&UnifiedEntity) -> bool) {
2108        self.for_each_entity_source_in_id_order(|_, entity| visit(entity));
2109    }
2110
2111    /// Keep the physical scan's global ID order while cloning only its page.
2112    #[doc(hidden)]
2113    pub fn page_in_id_order(&self, offset: usize, limit: usize) -> (usize, Vec<UnifiedEntity>) {
2114        let end = offset.saturating_add(limit);
2115        let mut total = 0;
2116        let mut items = Vec::with_capacity(limit.min(self.count()));
2117        self.for_each_entity_in_id_order(|entity| {
2118            if total >= offset && total < end {
2119                items.push(entity.clone());
2120            }
2121            total += 1;
2122            true
2123        });
2124        self.restore_owned_row_schemas(items.iter_mut());
2125        (total, items)
2126    }
2127
2128    #[doc(hidden)]
2129    pub fn for_each_entity_with_metadata_in_id_order(
2130        &self,
2131        mut visit: impl FnMut(&UnifiedEntity, Option<Metadata>) -> bool,
2132    ) {
2133        self.for_each_entity_source_in_id_order(|segment, entity| {
2134            visit(entity, segment.get_metadata(entity.id))
2135        });
2136    }
2137
2138    fn for_each_entity_source_in_id_order(
2139        &self,
2140        mut visit: impl FnMut(&GrowingSegment, &UnifiedEntity) -> bool,
2141    ) {
2142        let segments: Vec<_> = {
2143            let growing = self.growing.read();
2144            let sealed = self.sealed.read();
2145            growing.iter().chain(sealed.iter()).cloned().collect()
2146        };
2147        let mut order = Vec::new();
2148        for (source, segment) in segments.iter().enumerate() {
2149            segment.read().for_each_fast(|entity| {
2150                order.push((entity.id, source));
2151                true
2152            });
2153        }
2154        order.sort_by_key(|(id, _)| id.raw());
2155        for (id, source) in order {
2156            let segment = segments[source].read();
2157            if let Some(entity) = segment.get(id) {
2158                if !visit(&segment, entity) {
2159                    break;
2160                }
2161            }
2162        }
2163    }
2164
2165    /// Visit borrowed rows with metadata under the same segment read guard.
2166    /// Callbacks must not re-enter this manager while the guard is held.
2167    #[doc(hidden)]
2168    pub fn for_each_entity_with_metadata(
2169        &self,
2170        mut callback: impl FnMut(&UnifiedEntity, Option<Metadata>) -> bool,
2171    ) {
2172        self.for_each_entity_source(|segment, entity| {
2173            callback(entity, segment.get_metadata(entity.id))
2174        });
2175    }
2176
2177    fn for_each_entity_source(
2178        &self,
2179        mut callback: impl FnMut(&GrowingSegment, &UnifiedEntity) -> bool,
2180    ) {
2181        if let Some(growing_arc) = self.growing.read().as_ref() {
2182            let growing = growing_arc.read();
2183            if !growing.for_each_fast(|entity| callback(&growing, entity)) {
2184                return;
2185            }
2186        }
2187        let sealed = self.sealed.read();
2188        for segment_arc in sealed.iter() {
2189            let segment = segment_arc.read();
2190            if !segment.for_each_fast(|entity| callback(&segment, entity)) {
2191                return;
2192            }
2193        }
2194    }
2195
2196    fn for_each_entity_in_segments<F>(
2197        &self,
2198        segment_filter: impl Fn(&GrowingSegment) -> bool,
2199        mut before_segment: impl FnMut() -> bool,
2200        mut callback: F,
2201    ) where
2202        F: FnMut(&UnifiedEntity) -> bool,
2203    {
2204        // Growing segment — direct iteration (no Box<dyn>)
2205        // Try non-blocking read first; fall back to blocking only when a writer
2206        // is actively holding the write lock (rare in read-heavy workloads).
2207        if let Some(growing_arc) = self.growing.read().as_ref() {
2208            if !before_segment() {
2209                return;
2210            }
2211            let growing = if let Some(g) = growing_arc.try_read() {
2212                g
2213            } else {
2214                growing_arc.read()
2215            };
2216            if segment_filter(&growing) && !growing.for_each_fast(&mut callback) {
2217                return;
2218            }
2219        }
2220
2221        // Sealed segments
2222        let sealed = self.sealed.read();
2223        for segment_arc in sealed.iter() {
2224            if !before_segment() {
2225                return;
2226            }
2227            let segment = segment_arc.read();
2228            if segment_filter(&segment) && !segment.for_each_fast(&mut callback) {
2229                return;
2230            }
2231        }
2232    }
2233
2234    /// Parallel fold across all entities. Each sealed segment is
2235    /// processed on its own rayon task; the growing segment stays on
2236    /// the caller thread (its read lock is briefly held).
2237    ///
2238    /// - `init` builds a fresh accumulator per thread.
2239    /// - `fold` mutates an accumulator with one entity at a time.
2240    /// - `reduce` combines two accumulators into one.
2241    ///
2242    /// The returned value is the reduction of every per-thread
2243    /// accumulator. Use this for aggregate-shape workloads (GROUP BY)
2244    /// where per-thread partial state can be merged cheaply.
2245    ///
2246    /// NOTE: when there are 0 or 1 sealed segments, the parallel path
2247    /// is skipped and the work runs sequentially to avoid rayon
2248    /// overhead on tiny tables.
2249    pub fn fold_entities_parallel<T, FInit, FFold, FReduce>(
2250        &self,
2251        init: FInit,
2252        fold: FFold,
2253        reduce: FReduce,
2254    ) -> T
2255    where
2256        T: Send,
2257        FInit: Fn() -> T + Send + Sync,
2258        FFold: Fn(T, &UnifiedEntity) -> T + Send + Sync,
2259        FReduce: Fn(T, T) -> T + Send + Sync,
2260    {
2261        #[cfg(not(target_arch = "wasm32"))]
2262        use rayon::prelude::*;
2263
2264        // Growing segment — always sequential (single writer lock,
2265        // usually small working set).
2266        let mut acc = init();
2267        if let Some(growing_arc) = self.growing.read().as_ref() {
2268            let growing = if let Some(g) = growing_arc.try_read() {
2269                g
2270            } else {
2271                growing_arc.read()
2272            };
2273            growing.for_each_fast(|entity| {
2274                acc = fold(std::mem::replace(&mut acc, init()), entity);
2275                true
2276            });
2277        }
2278
2279        // Sealed segments — snapshot the Arc list under the read lock,
2280        // then drop the lock so rayon workers can fan out without
2281        // blocking writers.
2282        let segments: Vec<_> = {
2283            let sealed = self.sealed.read();
2284            sealed.iter().cloned().collect()
2285        };
2286
2287        if segments.len() <= 1 {
2288            for seg_arc in &segments {
2289                let seg = seg_arc.read();
2290                seg.for_each_fast(|entity| {
2291                    acc = fold(std::mem::replace(&mut acc, init()), entity);
2292                    true
2293                });
2294            }
2295            return acc;
2296        }
2297
2298        #[cfg(not(target_arch = "wasm32"))]
2299        let segments = segments.into_par_iter();
2300        #[cfg(target_arch = "wasm32")]
2301        let segments = segments.into_iter();
2302        let partials = segments.map(|seg_arc| {
2303            let mut local = init();
2304            let seg = seg_arc.read();
2305            seg.for_each_fast(|entity| {
2306                local = fold(std::mem::replace(&mut local, init()), entity);
2307                true
2308            });
2309            local
2310        });
2311        #[cfg(not(target_arch = "wasm32"))]
2312        let sealed_acc = partials.reduce(&init, &reduce);
2313        #[cfg(target_arch = "wasm32")]
2314        let sealed_acc = partials.fold(init(), &reduce);
2315
2316        reduce(acc, sealed_acc)
2317    }
2318
2319    /// Zone-map-aware iteration across all segments.
2320    ///
2321    /// Like `for_each_entity`, but checks `zone_preds` against each segment's
2322    /// column zone maps before iterating. Segments where any predicate can
2323    /// definitively prove no rows match are skipped entirely.
2324    ///
2325    /// `zone_preds`: slice of `(column_name, ZoneColPred)` extracted from the WHERE clause.
2326    /// Empty slice → same behaviour as `for_each_entity` (no pruning).
2327    pub fn for_each_entity_zoned<F>(&self, zone_preds: &[(&str, ZoneColPred<'_>)], mut callback: F)
2328    where
2329        F: FnMut(&UnifiedEntity) -> bool,
2330    {
2331        let _ = self.for_each_entity_zoned_with_stats(zone_preds, &mut callback);
2332    }
2333
2334    pub fn for_each_entity_zoned_with_stats<F>(
2335        &self,
2336        zone_preds: &[(&str, ZoneColPred<'_>)],
2337        mut callback: F,
2338    ) -> SegmentScanStats
2339    where
2340        F: FnMut(&UnifiedEntity) -> bool,
2341    {
2342        let mut scan_stats = SegmentScanStats::default();
2343        // Growing segment — never skip (it's receiving writes, zones are partial).
2344        // Try a non-blocking read first: if a writer is currently inserting
2345        // (holding the write lock), try_read() returns None and we fall back to
2346        // the blocking read.  In low-contention workloads (reads far outnumber
2347        // writes) the try_read() almost always succeeds and readers never stall.
2348        if let Some(growing_arc) = self.growing.read().as_ref() {
2349            scan_stats.segments_total += 1;
2350            scan_stats.segments_scanned += 1;
2351            let growing = if let Some(g) = growing_arc.try_read() {
2352                g
2353            } else {
2354                growing_arc.read()
2355            };
2356            if !growing.for_each_fast(&mut callback) {
2357                return scan_stats;
2358            }
2359        }
2360
2361        // Sealed segments — check zone maps before iterating
2362        let sealed = self.sealed.read();
2363        for segment_arc in sealed.iter() {
2364            scan_stats.segments_total += 1;
2365            let segment = segment_arc.read();
2366            if !zone_preds.is_empty() && segment.can_skip_zone_preds(zone_preds) {
2367                scan_stats.segments_pruned += 1;
2368                continue; // entire segment pruned
2369            }
2370            scan_stats.segments_scanned += 1;
2371            if !segment.for_each_fast(&mut callback) {
2372                return scan_stats;
2373            }
2374        }
2375        scan_stats
2376    }
2377
2378    /// Zone-map-aware parallel query.
2379    ///
2380    /// Like `query_all` but applies `zone_preds` on the main thread to
2381    /// prune sealed segments before spawning workers — segments that
2382    /// provably contain no matching rows are skipped entirely.
2383    ///
2384    /// Zone check runs single-threaded (it reads per-segment metadata,
2385    /// not row data), so it's cheap. Surviving segments are then scanned
2386    /// in parallel using `std::thread::scope` when there are > 1 of them.
2387    pub fn query_all_zoned<F>(
2388        &self,
2389        zone_preds: &[(&str, ZoneColPred<'_>)],
2390        filter: F,
2391    ) -> Vec<UnifiedEntity>
2392    where
2393        F: Fn(&UnifiedEntity) -> bool + Sync,
2394    {
2395        self.query_all_zoned_with_stats(zone_preds, filter).0
2396    }
2397
2398    pub fn query_all_zoned_with_stats<F>(
2399        &self,
2400        zone_preds: &[(&str, ZoneColPred<'_>)],
2401        filter: F,
2402    ) -> (Vec<UnifiedEntity>, SegmentScanStats)
2403    where
2404        F: Fn(&UnifiedEntity) -> bool + Sync,
2405    {
2406        self.project_all_zoned_with_stats(zone_preds, |entity| {
2407            filter(entity).then(|| entity.clone())
2408        })
2409    }
2410
2411    fn project_all_zoned_with_stats<T, F>(
2412        &self,
2413        zone_preds: &[(&str, ZoneColPred<'_>)],
2414        project: F,
2415    ) -> (Vec<T>, SegmentScanStats)
2416    where
2417        T: Send,
2418        F: Fn(&UnifiedEntity) -> Option<T> + Sync,
2419    {
2420        let mut results = Vec::new();
2421        let mut scan_stats = SegmentScanStats::default();
2422
2423        // Growing segment — always scan, no zone skip (zones are partial).
2424        // Non-blocking try_read() avoids stalling behind in-progress inserts.
2425        if let Some(growing_arc) = self.growing.read().as_ref() {
2426            scan_stats.segments_total += 1;
2427            scan_stats.segments_scanned += 1;
2428            let growing = if let Some(g) = growing_arc.try_read() {
2429                g
2430            } else {
2431                growing_arc.read()
2432            };
2433            results.extend(growing.iter().filter_map(&project));
2434        }
2435
2436        // Sealed segments: zone-prune on main thread, then scan in parallel.
2437        let sealed = self.sealed.read();
2438        // Collect only the segments that survive zone-predicate pruning.
2439        let surviving: Vec<_> = sealed
2440            .iter()
2441            .filter(|seg_arc| {
2442                scan_stats.segments_total += 1;
2443                if zone_preds.is_empty() {
2444                    scan_stats.segments_scanned += 1;
2445                    return true;
2446                }
2447                let seg = seg_arc.read();
2448                if seg.can_skip_zone_preds(zone_preds) {
2449                    scan_stats.segments_pruned += 1;
2450                    false
2451                } else {
2452                    scan_stats.segments_scanned += 1;
2453                    true
2454                }
2455            })
2456            .collect();
2457
2458        let use_parallel = surviving.len() > 1 && crate::execution::should_parallelize();
2459
2460        if use_parallel {
2461            let project_ref = &project;
2462            let segment_results: Vec<Vec<T>> = std::thread::scope(|s| {
2463                surviving
2464                    .iter()
2465                    .map(|segment| {
2466                        s.spawn(move || {
2467                            segment
2468                                .read()
2469                                .iter()
2470                                .filter_map(project_ref)
2471                                .collect::<Vec<_>>()
2472                        })
2473                    })
2474                    .collect::<Vec<_>>()
2475                    .into_iter()
2476                    .map(|handle| match handle.join() {
2477                        Ok(batch) => batch,
2478                        Err(panic) => std::panic::resume_unwind(panic),
2479                    })
2480                    .collect()
2481            });
2482            for batch in segment_results {
2483                results.extend(batch);
2484            }
2485        } else {
2486            for segment_arc in surviving {
2487                let seg = segment_arc.read();
2488                results.extend(seg.iter().filter_map(&project));
2489            }
2490        }
2491
2492        (results, scan_stats)
2493    }
2494
2495    /// Visibility predicate for the `scan_*` family. `Some` delegates to the
2496    /// canonical `entity_visible_with_context`; `None` supports low-level
2497    /// callers that intentionally scan without a statement snapshot and keeps
2498    /// the documented resolver fallback — moderation gate plus hiding
2499    /// superseded physical versions — instead of showing every version.
2500    pub fn scan_entity_visible(snapshot: Option<&SnapshotContext>, entity: &UnifiedEntity) -> bool {
2501        match snapshot {
2502            Some(ctx) => entity_visible_with_context(Some(ctx), entity),
2503            None => {
2504                !crate::storage::visibility::entity_moderation_hidden(entity) && entity.xmax == 0
2505            }
2506        }
2507    }
2508
2509    /// Scan every segment under an explicit MVCC snapshot.
2510    ///
2511    /// Visibility is evaluated while each segment iterator is active, before
2512    /// the caller's filter. Unlike the raw iteration methods, this entry point
2513    /// does not consult thread-local snapshot state, so it preserves the same
2514    /// view when invoked from a different thread.
2515    pub fn scan<F>(&self, snapshot: Option<&SnapshotContext>, filter: F) -> Vec<UnifiedEntity>
2516    where
2517        F: Fn(&UnifiedEntity) -> bool + Sync,
2518    {
2519        self.query_all(|entity| Self::scan_entity_visible(snapshot, entity) && filter(entity))
2520    }
2521
2522    /// Probe each segment's physical key index, retaining MVCC history candidates.
2523    /// Cost is O(segment count + versions of this key), rather than all collection rows.
2524    /// `project` runs under a segment read guard: keep it bounded and do not
2525    /// re-enter storage. Only the owned projection leaves the guard.
2526    #[doc(hidden)]
2527    pub fn project_key_entity<T>(
2528        &self,
2529        key: &str,
2530        snapshot: Option<&SnapshotContext>,
2531        versioned: bool,
2532        mut project: impl FnMut(&UnifiedEntity) -> T,
2533    ) -> Option<T> {
2534        let mut probe = |segment: &GrowingSegment, best: &mut Option<(u64, T)>| {
2535            if let Some(entity) = segment.find_key_entity(key, versioned, &mut |entity| {
2536                !versioned || Self::scan_entity_visible(snapshot, entity)
2537            }) {
2538                if best.as_ref().is_none_or(|(xmin, _)| entity.xmin >= *xmin) {
2539                    *best = Some((entity.xmin, project(entity)));
2540                }
2541            }
2542        };
2543        let mut best = None;
2544        if let Some(growing) = self.growing.read().as_ref() {
2545            probe(&growing.read(), &mut best);
2546        }
2547        for segment in self.sealed.read().iter() {
2548            if !versioned && best.is_some() {
2549                break;
2550            }
2551            probe(&segment.read(), &mut best);
2552        }
2553        best.map(|(_, projected)| projected)
2554    }
2555
2556    /// Indexed resident producer-dedup lookup; disk candidates are merged by
2557    /// the store. The callback borrows rows under the segment read guard.
2558    #[doc(hidden)]
2559    pub fn visit_queue_dedup(
2560        &self,
2561        queue: &str,
2562        key: Option<&str>,
2563        now: u64,
2564        snapshot: Option<&SnapshotContext>,
2565        mut visit: impl FnMut(&UnifiedEntity) -> bool,
2566    ) {
2567        let mut visible = |entity: &UnifiedEntity| {
2568            (key.is_some() && !Self::scan_entity_visible(snapshot, entity)) || visit(entity)
2569        };
2570        if let Some(growing) = self.growing.read().as_ref() {
2571            if !growing
2572                .read()
2573                .visit_queue_dedup(queue, key, now, &mut visible)
2574            {
2575                return;
2576            }
2577        }
2578        for segment in self.sealed.read().iter() {
2579            if !segment
2580                .read()
2581                .visit_queue_dedup(queue, key, now, &mut visible)
2582            {
2583                return;
2584            }
2585        }
2586    }
2587
2588    /// Collect visible graph items, pruning only under the segment read guard.
2589    #[doc(hidden)]
2590    pub fn scan_graph_kind(
2591        &self,
2592        snapshot: Option<&SnapshotContext>,
2593        kind: GraphEntityKind,
2594    ) -> Vec<UnifiedEntity> {
2595        self.query_all_in_segments(
2596            |segment| segment.may_contain_graph_kind(kind),
2597            |entity| Self::scan_entity_visible(snapshot, entity) && kind.matches(&entity.kind),
2598        )
2599    }
2600
2601    /// Hydrate one bounded graph batch at a time. Payloads and policy callbacks
2602    /// leave storage locks; pinned cursors survive sealing and consolidation.
2603    /// Work is charged for pruned sources and every inspected physical slot.
2604    #[doc(hidden)]
2605    pub fn scan_graph_batches(
2606        &self,
2607        snapshot: Option<&SnapshotContext>,
2608        kind: GraphEntityKind,
2609        mut before_work: impl FnMut() -> bool,
2610        mut consume: impl FnMut(Vec<UnifiedEntity>) -> bool,
2611    ) -> bool {
2612        let segments = {
2613            let growing = self.growing.read();
2614            let sealed = self.sealed.read();
2615            let mut segments = Vec::with_capacity(sealed.len() + usize::from(growing.is_some()));
2616            for segment in growing.iter().chain(sealed.iter()) {
2617                if !before_work() {
2618                    return false;
2619                }
2620                let view = segment.read();
2621                if view.may_contain_graph_kind(kind) {
2622                    segments.push((Arc::clone(segment), view.scan_cursor()));
2623                }
2624            }
2625            segments
2626        };
2627        let mut ids = [EntityId::new(0); super::segment::SCAN_BATCH_SIZE];
2628        for (segment, mut cursor) in segments {
2629            while !cursor.finished() {
2630                let mut count = 0;
2631                {
2632                    let view = segment.read();
2633                    if !view.scan_batch(&mut cursor, &mut before_work, &mut |id| {
2634                        ids[count] = id;
2635                        count += 1;
2636                    }) {
2637                        return false;
2638                    }
2639                }
2640                if !before_work() {
2641                    return false;
2642                }
2643                // Hydration groups lookups by their current segment. Restore the
2644                // cursor's order when an update moved a candidate between sources.
2645                let mut batch = vec![None; count];
2646                self.for_each_id(&ids[..count], |position, entity| {
2647                    if kind.matches(&entity.kind) && Self::scan_entity_visible(snapshot, entity) {
2648                        batch[position] = Some(entity.clone());
2649                    }
2650                });
2651                if !before_work() || !consume(batch.into_iter().flatten().collect()) {
2652                    return false;
2653                }
2654            }
2655        }
2656        true
2657    }
2658
2659    /// Visit visible candidates in segments that may contain the requested kind.
2660    /// Non-graph items in those segments still reach the callback so work budgets
2661    /// charge every inspected visible candidate. RLS must run outside this callback.
2662    /// `before_segment` runs even for pruned segments; false stops the entire scan.
2663    #[doc(hidden)]
2664    pub fn scan_graph_candidates_for_each<F>(
2665        &self,
2666        snapshot: Option<&SnapshotContext>,
2667        kind: GraphEntityKind,
2668        before_segment: impl FnMut() -> bool,
2669        mut callback: F,
2670    ) where
2671        F: FnMut(&UnifiedEntity) -> bool,
2672    {
2673        self.for_each_entity_in_segments(
2674            |segment| segment.may_contain_graph_kind(kind),
2675            before_segment,
2676            |entity| !Self::scan_entity_visible(snapshot, entity) || callback(entity),
2677        );
2678    }
2679
2680    /// Visit every entity visible under an explicit MVCC snapshot.
2681    ///
2682    /// Returning `false` from `callback` stops the scan early. Hidden entities
2683    /// never reach the callback and therefore cannot stop the scan.
2684    pub fn scan_for_each<F>(&self, snapshot: Option<&SnapshotContext>, mut callback: F)
2685    where
2686        F: FnMut(&UnifiedEntity) -> bool,
2687    {
2688        self.for_each_entity(|entity| {
2689            !Self::scan_entity_visible(snapshot, entity) || callback(entity)
2690        });
2691    }
2692
2693    #[doc(hidden)]
2694    pub fn physical_scan_cursor(&self) -> PhysicalScanCursor {
2695        let growing = self.growing.read();
2696        let sealed = self.sealed.read();
2697        PhysicalScanCursor {
2698            sources: growing
2699                .iter()
2700                .chain(sealed.iter())
2701                .map(|segment| (Arc::downgrade(segment), segment.read().scan_cursor()))
2702                .collect(),
2703            source: 0,
2704        }
2705    }
2706
2707    /// At most one small ID batch; every inspected slot or retired source
2708    /// consumes work, including deleted entries that produce no candidate.
2709    #[doc(hidden)]
2710    pub fn physical_scan_batch(
2711        &self,
2712        cursor: &mut PhysicalScanCursor,
2713        work_left: &mut usize,
2714    ) -> Vec<EntityId> {
2715        let mut ids = Vec::with_capacity(super::segment::SCAN_BATCH_SIZE.min(*work_left));
2716        while !cursor.finished() && *work_left > 0 {
2717            let (source, position) = &mut cursor.sources[cursor.source];
2718            if position.finished() {
2719                *work_left -= 1;
2720                cursor.source += 1;
2721                continue;
2722            }
2723            let Some(segment) = source.upgrade() else {
2724                *work_left -= 1;
2725                cursor.source += 1;
2726                continue;
2727            };
2728            segment.read().scan_batch(
2729                position,
2730                &mut || {
2731                    if *work_left == 0 {
2732                        return false;
2733                    }
2734                    *work_left -= 1;
2735                    true
2736                },
2737                &mut |id| ids.push(id),
2738            );
2739            if position.finished() {
2740                cursor.source += 1;
2741            }
2742            if !ids.is_empty() {
2743                break;
2744            }
2745        }
2746        ids
2747    }
2748
2749    /// Capture segment membership and append boundaries, then hydrate bounded
2750    /// batches. The consumer runs outside topology and segment locks, so scoring
2751    /// and RLS may re-enter storage and writers can progress between batches.
2752    /// Retired sources pin positions only; hydration uses current segments so
2753    /// mutations after consolidation are visible to the snapshot predicate.
2754    #[doc(hidden)]
2755    pub fn scan_batches(
2756        &self,
2757        snapshot: Option<&SnapshotContext>,
2758        mut before_work: impl FnMut() -> bool,
2759        mut consume: impl FnMut(&[UnifiedEntity]) -> bool,
2760    ) -> bool {
2761        let segments = {
2762            let growing = self.growing.read();
2763            let sealed = self.sealed.read();
2764            let mut segments = Vec::with_capacity(sealed.len() + usize::from(growing.is_some()));
2765            for segment in growing.iter().chain(sealed.iter()) {
2766                if !before_work() {
2767                    return false;
2768                }
2769                let cursor = segment.read().scan_cursor();
2770                segments.push((Arc::clone(segment), cursor));
2771            }
2772            segments
2773        };
2774        let mut ids = Vec::new();
2775        let mut batch = Vec::new();
2776        for (segment, mut cursor) in segments {
2777            while !cursor.finished() {
2778                ids.clear();
2779                batch.clear();
2780                let batch_size = cursor.remaining().min(super::segment::SCAN_BATCH_SIZE);
2781                ids.reserve_exact(batch_size);
2782                batch.reserve_exact(batch_size);
2783                {
2784                    let segment = segment.read();
2785                    if !segment.scan_batch(&mut cursor, &mut before_work, &mut |id| ids.push(id)) {
2786                        return false;
2787                    }
2788                }
2789                // Sources can retire between batches. Consult authoritative storage
2790                // after releasing the source guard, just as the former ID-list scan did.
2791                if !before_work() {
2792                    return false;
2793                }
2794                self.for_each_id(&ids, |_, entity| {
2795                    if Self::scan_entity_visible(snapshot, entity) {
2796                        batch.push(entity.clone());
2797                    }
2798                });
2799                if !before_work() {
2800                    return false;
2801                }
2802                if !consume(&batch) {
2803                    return false;
2804                }
2805            }
2806        }
2807        true
2808    }
2809
2810    /// Fold entities visible under an explicit MVCC snapshot in parallel.
2811    pub fn scan_fold_parallel<T, FInit, FFold, FReduce>(
2812        &self,
2813        snapshot: Option<&SnapshotContext>,
2814        init: FInit,
2815        fold: FFold,
2816        reduce: FReduce,
2817    ) -> T
2818    where
2819        T: Send,
2820        FInit: Fn() -> T + Send + Sync,
2821        FFold: Fn(T, &UnifiedEntity) -> T + Send + Sync,
2822        FReduce: Fn(T, T) -> T + Send + Sync,
2823    {
2824        self.fold_entities_parallel(
2825            init,
2826            |acc, entity| {
2827                if Self::scan_entity_visible(snapshot, entity) {
2828                    fold(acc, entity)
2829                } else {
2830                    acc
2831                }
2832            },
2833            reduce,
2834        )
2835    }
2836
2837    /// Visit zone-map candidates visible under an explicit MVCC snapshot.
2838    pub fn scan_for_each_zoned_with_stats<F>(
2839        &self,
2840        snapshot: Option<&SnapshotContext>,
2841        zone_preds: &[(&str, ZoneColPred<'_>)],
2842        mut callback: F,
2843    ) -> SegmentScanStats
2844    where
2845        F: FnMut(&UnifiedEntity) -> bool,
2846    {
2847        self.for_each_entity_zoned_with_stats(zone_preds, |entity| {
2848            !Self::scan_entity_visible(snapshot, entity) || callback(entity)
2849        })
2850    }
2851
2852    /// Collect zone-map candidates visible under an explicit MVCC snapshot.
2853    pub fn scan_zoned_with_stats<F>(
2854        &self,
2855        snapshot: Option<&SnapshotContext>,
2856        zone_preds: &[(&str, ZoneColPred<'_>)],
2857        filter: F,
2858    ) -> (Vec<UnifiedEntity>, SegmentScanStats)
2859    where
2860        F: Fn(&UnifiedEntity) -> bool + Sync,
2861    {
2862        self.query_all_zoned_with_stats(zone_preds, |entity| {
2863            Self::scan_entity_visible(snapshot, entity) && filter(entity)
2864        })
2865    }
2866
2867    /// Project visible zone-map candidates while borrowing each source entity.
2868    /// Only the owned projection leaves the segment read guard. The callback
2869    /// must not mutate or re-enter the source collection.
2870    pub fn scan_project_zoned_with_stats<T, F>(
2871        &self,
2872        snapshot: Option<&SnapshotContext>,
2873        zone_preds: &[(&str, ZoneColPred<'_>)],
2874        project: F,
2875    ) -> (Vec<T>, SegmentScanStats)
2876    where
2877        T: Send,
2878        F: Fn(&UnifiedEntity) -> Option<T> + Sync,
2879    {
2880        self.project_all_zoned_with_stats(zone_preds, |entity| {
2881            if Self::scan_entity_visible(snapshot, entity) {
2882                project(entity)
2883            } else {
2884                None
2885            }
2886        })
2887    }
2888
2889    /// Query across all segments. Uses parallel scanning for sealed segments
2890    /// when more than one sealed segment exists.
2891    pub fn query_all<F>(&self, filter: F) -> Vec<UnifiedEntity>
2892    where
2893        F: Fn(&UnifiedEntity) -> bool + Sync,
2894    {
2895        let mut entities = self.query_all_in_segments(|_| true, filter);
2896        self.restore_owned_row_schemas(entities.iter_mut());
2897        entities
2898    }
2899
2900    fn query_all_in_segments<F>(
2901        &self,
2902        segment_filter: impl Fn(&GrowingSegment) -> bool + Sync,
2903        filter: F,
2904    ) -> Vec<UnifiedEntity>
2905    where
2906        F: Fn(&UnifiedEntity) -> bool + Sync,
2907    {
2908        let mut results = Vec::new();
2909
2910        // Query growing segment — try non-blocking read first (avoids stalling
2911        // behind an in-progress insert; falls back to blocking if writer is active).
2912        if let Some(growing_arc) = self.growing.read().as_ref() {
2913            let growing = if let Some(g) = growing_arc.try_read() {
2914                g
2915            } else {
2916                growing_arc.read()
2917            };
2918            if segment_filter(&growing) {
2919                results.extend(growing.iter().filter(|e| filter(e)).cloned());
2920            }
2921        }
2922
2923        // Query sealed segments — parallel when multiple exist AND multi-core
2924        let sealed = self.sealed.read();
2925        let use_parallel = sealed.len() > 1 && crate::execution::should_parallelize();
2926        if use_parallel {
2927            let filter_ref = &filter;
2928            let segment_filter_ref = &segment_filter;
2929            let segment_results: Vec<Vec<UnifiedEntity>> = std::thread::scope(|s| {
2930                sealed
2931                    .iter()
2932                    .map(|segment| {
2933                        s.spawn(move || {
2934                            let segment = segment.read();
2935                            if segment_filter_ref(&segment) {
2936                                segment
2937                                    .iter()
2938                                    .filter(|e| filter_ref(e))
2939                                    .cloned()
2940                                    .collect::<Vec<_>>()
2941                            } else {
2942                                Vec::new()
2943                            }
2944                        })
2945                    })
2946                    .collect::<Vec<_>>()
2947                    .into_iter()
2948                    .map(|handle| handle.join().unwrap_or_default())
2949                    .collect()
2950            });
2951            for batch in segment_results {
2952                results.extend(batch);
2953            }
2954        } else {
2955            for segment in sealed.iter() {
2956                let seg = segment.read();
2957                if segment_filter(&seg) {
2958                    results.extend(seg.iter().filter(|e| filter(e)).cloned());
2959                }
2960            }
2961        }
2962
2963        results
2964    }
2965
2966    /// Probe exact segment membership for a key without materializing matching entities.
2967    ///
2968    /// Returns `false` only when every consulted segment proves absence.
2969    /// Missing segment state is conservative and returns `true`.
2970    pub fn bloom_may_contain_key(&self, key: &[u8]) -> bool {
2971        if let Some(growing_arc) = self.growing.read().as_ref() {
2972            let growing = growing_arc.read();
2973            if growing.may_contain_exact_key(key) {
2974                return true;
2975            }
2976        } else {
2977            return true;
2978        }
2979
2980        let sealed = self.sealed.read();
2981        for segment_arc in sealed.iter() {
2982            let segment = segment_arc.read();
2983            if segment.may_contain_exact_key(key) {
2984                return true;
2985            }
2986        }
2987
2988        false
2989    }
2990
2991    /// Filter by metadata across all segments
2992    pub fn filter_metadata(&self, filters: &[(String, MetadataFilter)]) -> Vec<EntityId> {
2993        let mut results = Vec::new();
2994
2995        // Growing segment
2996        if let Some(growing_arc) = self.growing.read().as_ref() {
2997            let growing = growing_arc.read();
2998            results.extend(growing.filter_metadata(filters));
2999        }
3000
3001        // Sealed segments
3002        let sealed = self.sealed.read();
3003        for segment in sealed.iter() {
3004            results.extend(segment.filter_metadata(filters));
3005        }
3006
3007        results
3008    }
3009
3010    /// Get entities by kind
3011    pub fn get_by_kind(&self, kind: &str) -> Vec<UnifiedEntity> {
3012        let mut results = Vec::new();
3013
3014        // Growing segment
3015        if let Some(growing_arc) = self.growing.read().as_ref() {
3016            let growing = growing_arc.read();
3017            for entity in growing.iter_kind(kind) {
3018                results.push(entity.clone());
3019            }
3020        }
3021
3022        // Sealed segments. Iterate through the read guard, not the
3023        // `Arc<RwLock<GrowingSegment>>` impl of `iter_kind` — that one cannot
3024        // hand out references across the lock, so it returns an empty iterator
3025        // and every sealed entity was silently missing from the result.
3026        let sealed = self.sealed.read();
3027        for segment_arc in sealed.iter() {
3028            let segment = segment_arc.read();
3029            for entity in segment.iter_kind(kind) {
3030                results.push(entity.clone());
3031            }
3032        }
3033
3034        results
3035    }
3036
3037    /// Count entities
3038    pub fn count(&self) -> usize {
3039        self.total_entities_atomic.load(Ordering::Relaxed) as usize
3040    }
3041
3042    /// Get all segment IDs
3043    pub fn segment_ids(&self) -> Vec<SegmentId> {
3044        let mut ids = Vec::new();
3045
3046        if let Some(growing_arc) = self.growing.read().as_ref() {
3047            ids.push(growing_arc.read().id());
3048        }
3049
3050        let sealed = self.sealed.read();
3051        for segment in sealed.iter() {
3052            ids.push(segment.id());
3053        }
3054
3055        ids.extend(self.archived.read().iter().copied());
3056
3057        ids
3058    }
3059
3060    /// Emit a lifecycle event.
3061    ///
3062    /// Perf: this used to push onto a `RwLock<Vec<LifecycleEvent>>`
3063    /// on every insert / delete / seal. Nobody consumes that vec
3064    /// today (no subscription API, `drain_events` has no callers),
3065    /// so the write lock + push was pure tax — and the vec grew
3066    /// unbounded in long-running processes.
3067    ///
3068    /// Current behaviour: no-op. If we ever want the hooks back,
3069    /// replace this with a bounded channel or an actual subscriber
3070    /// registry; the callers (`insert`, `delete`, `maybe_seal_growing`)
3071    /// already pass well-typed events.
3072    #[inline]
3073    #[allow(clippy::unused_self)]
3074    fn emit(&self, _event: LifecycleEvent) {}
3075
3076    /// Drain events. Kept for API compatibility; always returns
3077    /// empty because `emit` no longer buffers.
3078    pub fn drain_events(&self) -> Vec<LifecycleEvent> {
3079        std::mem::take(&mut *self.events.write())
3080    }
3081
3082    /// Run maintenance (would be called periodically in production)
3083    pub fn run_maintenance(&self) -> Result<(), SegmentError> {
3084        // Auto-seal idle segments
3085        self.maybe_seal_growing()?;
3086
3087        if self.config.enable_consolidation {
3088            self.consolidation_tick();
3089        }
3090
3091        Ok(())
3092    }
3093
3094    // ========================================================================
3095    // Consolidation — ADR 0073 §5
3096    // ========================================================================
3097
3098    /// One paced step of sealed-segment consolidation.
3099    ///
3100    /// Starts a run when a threshold has been crossed, copies at most
3101    /// `consolidation_entities_per_tick` live entities into the merged segment,
3102    /// and swaps once every source has been drained. Returns without finishing
3103    /// otherwise — the half-built merged segment waits for the next tick.
3104    fn consolidation_tick(&self) {
3105        // Drop the read guard before `start_consolidation` takes the write
3106        // guard: `parking_lot` locks are not reentrant.
3107        let running = self.consolidation.read().is_some();
3108        if !running && !self.start_consolidation() {
3109            return;
3110        }
3111
3112        // Keep the accounting guard through publication: the merged allocation
3113        // must never disappear between the in-flight and active inventories.
3114        let mut guard = self.consolidation.write();
3115        let Some(run) = guard.as_mut() else {
3116            return;
3117        };
3118        self.copy_bounded(run);
3119        if run.cursor >= run.sources.len() {
3120            if let Some(run) = guard.take() {
3121                self.finish_consolidation(run);
3122            }
3123        }
3124    }
3125
3126    /// Evaluate the trigger and, when it fires, open a consolidation run.
3127    ///
3128    /// Returns `true` when a run was started.
3129    fn start_consolidation(&self) -> bool {
3130        let sources = self.select_candidates();
3131        self.start_consolidation_from_sources(sources)
3132    }
3133
3134    fn start_consolidation_from_sources(&self, sources: Vec<SegmentId>) -> bool {
3135        if sources.len() < 2 && !self.candidates_carry_tombstones(&sources) {
3136            return false;
3137        }
3138
3139        let merged_id = self.next_segment_id.fetch_add(1, Ordering::SeqCst);
3140        let merged = GrowingSegment::new(merged_id, &self.collection);
3141
3142        *self.consolidation.write() = Some(Consolidation {
3143            sources: sources
3144                .into_iter()
3145                .map(|id| SourceProgress {
3146                    id,
3147                    copied: Vec::new(),
3148                    tombstones_at_open: None,
3149                })
3150                .collect(),
3151            merged_id,
3152            merged,
3153            cursor: 0,
3154            pending_ids: Vec::new(),
3155            pending_cursor: 0,
3156            entities_copied: 0,
3157        });
3158
3159        self.stats.write().consolidation.runs_started += 1;
3160        true
3161    }
3162
3163    /// Run one paced consolidation tick because admission pressure needs
3164    /// reclaimable bytes, even if the background thresholds have not fired.
3165    ///
3166    /// Returns true when the call started or advanced a consolidation run.
3167    pub fn pressure_consolidation_tick(&self) -> bool {
3168        if !self.config.enable_consolidation {
3169            return false;
3170        }
3171
3172        let running = self.consolidation.read().is_some();
3173        if !running {
3174            // Foreground churn can exhaust the budget before a growing segment
3175            // reaches its ordinary size threshold. Publish only a dirty source;
3176            // the existing paced consolidation then reclaims its dead slots.
3177            if self
3178                .seal_current_if(|segment| segment.reclaimable_bytes() > 0)
3179                .is_err()
3180            {
3181                return false;
3182            }
3183            let sources = self.dirty_sealed_segments();
3184            if !self.start_consolidation_from_sources(sources) {
3185                return false;
3186            }
3187        }
3188
3189        self.consolidation_tick();
3190        true
3191    }
3192
3193    /// Which sealed segments this collection should merge, if any.
3194    ///
3195    /// Three thresholds, any of which arms consolidation:
3196    ///
3197    /// * **sealed-segment count** above `max_sealed_segments` — every sealed
3198    ///   segment merges, which is what that knob always claimed to do.
3199    /// * **tombstone ratio** — dead entities over total entities across the
3200    ///   sealed set, past [`CONSOLIDATION_TOMBSTONE_RATIO`].
3201    /// * **fragmentation** — reclaimable bytes over held bytes, past
3202    ///   [`CONSOLIDATION_FRAGMENTATION_RATIO`].
3203    ///
3204    /// The count trigger takes every sealed segment; the two budget triggers
3205    /// take only the segments that actually carry tombstones, so a clean
3206    /// segment is never rewritten for nothing.
3207    fn select_candidates(&self) -> Vec<SegmentId> {
3208        let sealed = self.sealed.read();
3209        if sealed.is_empty() {
3210            return Vec::new();
3211        }
3212
3213        if sealed.len() > self.config.max_sealed_segments {
3214            return sealed.iter().map(|segment| segment.read().id()).collect();
3215        }
3216
3217        let mut live = 0usize;
3218        let mut tombstones = 0usize;
3219        let mut held = 0u64;
3220        let mut reclaimable = 0u64;
3221        let mut dirty = Vec::new();
3222
3223        for segment_arc in sealed.iter() {
3224            let segment = segment_arc.read();
3225            live += segment.live_entity_count();
3226            tombstones += segment.tombstone_count();
3227            held += segment.resident_bytes();
3228            reclaimable += segment.reclaimable_bytes();
3229            if segment.tombstone_count() > 0 {
3230                dirty.push(segment.id());
3231            }
3232        }
3233
3234        let total = live + tombstones;
3235        let tombstone_ratio = if total == 0 {
3236            0.0
3237        } else {
3238            tombstones as f64 / total as f64
3239        };
3240        let fragmentation = if held == 0 {
3241            0.0
3242        } else {
3243            reclaimable as f64 / held as f64
3244        };
3245
3246        if tombstone_ratio >= CONSOLIDATION_TOMBSTONE_RATIO
3247            || fragmentation >= CONSOLIDATION_FRAGMENTATION_RATIO
3248        {
3249            return dirty;
3250        }
3251
3252        Vec::new()
3253    }
3254
3255    fn dirty_sealed_segments(&self) -> Vec<SegmentId> {
3256        self.sealed
3257            .read()
3258            .iter()
3259            .filter_map(|segment_arc| {
3260                let segment = segment_arc.read();
3261                (segment.reclaimable_bytes() > 0).then(|| segment.id())
3262            })
3263            .collect()
3264    }
3265
3266    /// A single candidate is still worth merging when it carries tombstones —
3267    /// the merge drops them. A single clean candidate is not.
3268    fn candidates_carry_tombstones(&self, sources: &[SegmentId]) -> bool {
3269        if sources.is_empty() {
3270            return false;
3271        }
3272        let sealed = self.sealed.read();
3273        sealed.iter().any(|segment_arc| {
3274            let segment = segment_arc.read();
3275            sources.contains(&segment.id()) && segment.tombstone_count() > 0
3276        })
3277    }
3278
3279    fn sealed_segment(&self, id: SegmentId) -> Option<Arc<RwLock<GrowingSegment>>> {
3280        let sealed = self.sealed.read();
3281        sealed
3282            .iter()
3283            .find(|segment| segment.read().id() == id)
3284            .map(Arc::clone)
3285    }
3286
3287    /// Copy at most one tick's worth of live entities into the merged segment.
3288    ///
3289    /// The per-tick bound is the pacing contract: a tick's cost is O(bound),
3290    /// independent of how many entities the run still has to move.
3291    fn copy_bounded(&self, run: &mut Consolidation) {
3292        let mut budget = self.config.consolidation_entities_per_tick;
3293
3294        while budget > 0 && run.cursor < run.sources.len() {
3295            let source_id = run.sources[run.cursor].id;
3296            let Some(source_arc) = self.sealed_segment(source_id) else {
3297                // The source vanished. Only consolidation removes sealed
3298                // segments and it is single-threaded per collection, so this
3299                // cannot happen today — skip it rather than resurrect its rows.
3300                run.cursor += 1;
3301                run.pending_ids.clear();
3302                run.pending_cursor = 0;
3303                continue;
3304            };
3305
3306            if run.sources[run.cursor].tombstones_at_open.is_none() {
3307                let source = source_arc.read();
3308                run.pending_ids = source.live_entity_ids();
3309                run.pending_cursor = 0;
3310                run.sources[run.cursor].tombstones_at_open = Some(source.tombstone_count());
3311            }
3312
3313            {
3314                let source = source_arc.read();
3315                while budget > 0 && run.pending_cursor < run.pending_ids.len() {
3316                    let id = run.pending_ids[run.pending_cursor];
3317                    run.pending_cursor += 1;
3318                    budget -= 1;
3319
3320                    // Tombstoned between the snapshot and now — it must not be
3321                    // resurrected into the merged segment.
3322                    let Some(entity) = source.get(id) else {
3323                        continue;
3324                    };
3325                    let metadata = source.get_metadata(id);
3326                    run.merged.adopt_entity(entity.clone(), metadata);
3327                    run.sources[run.cursor].copied.push(id);
3328                    run.entities_copied += 1;
3329                }
3330            }
3331
3332            if run.pending_cursor >= run.pending_ids.len() {
3333                run.cursor += 1;
3334                run.pending_ids.clear();
3335                run.pending_cursor = 0;
3336            }
3337        }
3338    }
3339
3340    /// Atomically replace the source segments with the merged one.
3341    ///
3342    /// The `sealed` write lock is the boundary: a reader holds the read lock
3343    /// for the whole of its scan, so it observes either the old set or the new
3344    /// set, never a gap and never both copies of a row.
3345    fn finish_consolidation(&self, mut run: Consolidation) {
3346        let mut sealed = self.sealed.write();
3347
3348        let mut positions = Vec::with_capacity(run.sources.len());
3349        for source in &run.sources {
3350            if let Some(index) = sealed
3351                .iter()
3352                .position(|segment| segment.read().id() == source.id)
3353            {
3354                positions.push(index);
3355            }
3356        }
3357        if positions.is_empty() {
3358            return;
3359        }
3360        positions.sort_unstable();
3361
3362        // Rows deleted from a source after we copied them must not come back.
3363        // A source whose tombstone count is unchanged saw no deletes while the
3364        // merge ran, so its copied rows need no per-row check.
3365        let mut stale = Vec::new();
3366        for source in &run.sources {
3367            let Some(source_arc) = sealed
3368                .iter()
3369                .find(|segment| segment.read().id() == source.id)
3370            else {
3371                continue;
3372            };
3373            let segment = source_arc.read();
3374            if source.tombstones_at_open == Some(segment.tombstone_count()) {
3375                continue;
3376            }
3377            stale.extend(
3378                source
3379                    .copied
3380                    .iter()
3381                    .copied()
3382                    .filter(|id| !segment.contains(*id)),
3383            );
3384        }
3385        for id in stale {
3386            run.merged.evict_entity(id);
3387        }
3388
3389        let reclaimed_bytes: u64 = positions
3390            .iter()
3391            .map(|&index| sealed[index].read().resident_bytes())
3392            .sum();
3393        let reclaimed_tombstones: u64 = positions
3394            .iter()
3395            .map(|&index| sealed[index].read().tombstone_count() as u64)
3396            .sum();
3397
3398        if run.merged.seal().is_err() {
3399            return;
3400        }
3401        let merged_bytes = run.merged.resident_bytes();
3402        let merged_arc = Arc::new(RwLock::new(run.merged));
3403
3404        {
3405            let mut retired = self.retired.write();
3406            retired.retain(|source| source.strong_count() > 0);
3407            for &index in positions.iter().rev() {
3408                let source = sealed.remove(index);
3409                if Arc::strong_count(&source) > 1 {
3410                    retired.push(Arc::downgrade(&source));
3411                }
3412            }
3413        }
3414        let insert_at = positions[0].min(sealed.len());
3415        sealed.insert(insert_at, Arc::clone(&merged_arc));
3416        drop(sealed);
3417
3418        // Remap the entity→segment hints that pointed at the retired sources.
3419        let source_ids: Vec<SegmentId> = run.sources.iter().map(|source| source.id).collect();
3420        {
3421            let mut entity_segment = self.entity_segment.write();
3422            for segment_id in entity_segment.values_mut() {
3423                if source_ids.contains(segment_id) {
3424                    *segment_id = run.merged_id;
3425                }
3426            }
3427        }
3428
3429        {
3430            let mut stats = self.stats.write();
3431            stats.sealed_count = stats
3432                .sealed_count
3433                .saturating_sub(positions.len())
3434                .saturating_add(1);
3435            let consolidation = &mut stats.consolidation;
3436            consolidation.runs_completed += 1;
3437            consolidation.segments_merged += positions.len() as u64;
3438            consolidation.tombstones_reclaimed += reclaimed_tombstones;
3439            consolidation.bytes_reclaimed += reclaimed_bytes.saturating_sub(merged_bytes);
3440        }
3441
3442        self.emit(LifecycleEvent::SegmentConsolidated {
3443            source: source_ids,
3444            target: run.merged_id,
3445        });
3446    }
3447
3448    /// Entities copied by the consolidation currently in flight, or `None` when
3449    /// none is running. Exposed for the pacing tests.
3450    #[cfg(test)]
3451    fn consolidation_progress(&self) -> Option<u64> {
3452        self.consolidation
3453            .read()
3454            .as_ref()
3455            .map(|run| run.entities_copied)
3456    }
3457}
3458
3459#[cfg(test)]
3460mod tests {
3461    use std::collections::HashSet;
3462
3463    use super::*;
3464    use crate::storage::entity::{EntityData, EntityKind, RowData};
3465    use crate::transaction::snapshot::{Snapshot, SnapshotManager};
3466    use reddb_types::Value;
3467
3468    #[test]
3469    fn recovery_view_projection_keeps_schema_bounds_without_retaining_rows_or_identities() {
3470        for collection in ["rows", "red_internal"] {
3471            let manager = SegmentManager::new(collection);
3472            let identities = manager.identity_counters();
3473            for id in 1..=18 {
3474                let field = format!("field_{id}");
3475                let mut entity =
3476                    UnifiedEntity::table_row(EntityId::new(id), collection, id, vec![]);
3477                entity.data = EntityData::Row(RowData {
3478                    columns: Vec::new(),
3479                    named: Some(HashMap::from([
3480                        (field.clone(), Value::Integer(id as i64)),
3481                        ("id".into(), Value::Integer(id as i64)),
3482                    ])),
3483                    schema: None,
3484                });
3485                manager.restore_snapshot_row_layout(&mut entity);
3486                let row = entity.data.as_row().expect("row");
3487                assert_eq!(row.get_field(&field), Some(&Value::Integer(id as i64)));
3488                assert_eq!(row.get_field("id"), Some(&Value::Integer(id as i64)));
3489                assert_eq!(
3490                    row.named.is_some(),
3491                    collection.starts_with("red_") || id > 16
3492                );
3493            }
3494            assert_eq!(manager.count(), 0, "a projection never adopts payloads");
3495            assert_eq!(manager.identity_counters(), identities);
3496            assert_eq!(
3497                manager.recovery_row_schemas.read().len(),
3498                if collection == "rows" { 16 } else { 0 }
3499            );
3500        }
3501    }
3502
3503    #[test]
3504    fn physical_pages_keep_global_order_across_segments_and_deleted_slots() {
3505        let manager = SegmentManager::new("pages");
3506        for group in [[50, 10], [30, 20]] {
3507            for id in group {
3508                let mut entity = UnifiedEntity::table_row(EntityId::new(id), "pages", id, vec![]);
3509                entity.data = EntityData::Row(RowData::with_names(
3510                    vec![Value::Integer(id as i64)],
3511                    vec!["id".into()],
3512                ));
3513                manager.insert(entity).unwrap();
3514            }
3515            manager.force_seal().unwrap();
3516        }
3517        manager
3518            .insert(UnifiedEntity::table_row(
3519                EntityId::new(40),
3520                "pages",
3521                40,
3522                vec![],
3523            ))
3524            .unwrap();
3525        let (total, page) = manager.page_in_id_order(1, 2);
3526        assert_eq!(total, 5);
3527        assert_eq!(
3528            page.iter()
3529                .map(|entity| entity.id.raw())
3530                .collect::<Vec<_>>(),
3531            [20, 30]
3532        );
3533        let EntityData::Row(row) = &page[0].data else {
3534            panic!("row")
3535        };
3536        assert_eq!(row.get_field("id"), Some(&Value::Integer(20)));
3537        manager.delete(EntityId::new(30)).unwrap();
3538        let (total, page) = manager.page_in_id_order(1, 2);
3539        assert_eq!(total, 4);
3540        assert_eq!(
3541            page.iter()
3542                .map(|entity| entity.id.raw())
3543                .collect::<Vec<_>>(),
3544            [20, 40]
3545        );
3546        for offset in [4, usize::MAX] {
3547            let (total, page) = manager.page_in_id_order(offset, 2);
3548            assert_eq!(total, 4);
3549            assert!(page.is_empty());
3550        }
3551    }
3552
3553    fn lookup_version(id: u64, key: &str, xmin: u64, xmax: u64) -> UnifiedEntity {
3554        let mut entity = UnifiedEntity::table_row(EntityId::new(id), "keys", id, vec![]);
3555        entity.data = EntityData::Row(RowData::with_names(
3556            vec![Value::text(key)],
3557            vec!["key".into()],
3558        ));
3559        entity.set_xmin(xmin);
3560        entity.set_xmax(xmax);
3561        entity
3562    }
3563
3564    #[test]
3565    fn key_lookup_matches_snapshot_scan_across_segments() {
3566        let manager = Arc::new(SegmentManager::new("keys"));
3567        for entity in [
3568            lookup_version(1, "changed", 3, 12),
3569            lookup_version(2, "deleted", 3, 7),
3570        ] {
3571            manager.insert(entity).expect("old version");
3572        }
3573        manager.force_seal().expect("seal old versions");
3574        for entity in [
3575            lookup_version(3, "changed", 12, 0),
3576            lookup_version(4, "pending", 4, 0),
3577            lookup_version(5, "own", 15, 0),
3578            lookup_version(6, "live", 3, 0),
3579        ] {
3580            manager.insert(entity).expect("new version");
3581        }
3582        std::thread::spawn(move || {
3583            let snapshot = SnapshotContext {
3584                branch: None,
3585                snapshot: Snapshot {
3586                    xid: 10,
3587                    in_progress: HashSet::from([4]),
3588                },
3589                manager: Arc::new(SnapshotManager::new()),
3590                own_xids: HashSet::from([15]),
3591                requires_index_fallback: false,
3592                hidden_writers_only: false,
3593                serializable_reader: None,
3594            };
3595            for snapshot in [Some(&snapshot), None] {
3596                for key in ["changed", "deleted", "pending", "own", "live", "absent"] {
3597                    let expected = manager
3598                        .scan(snapshot, |entity| {
3599                            crate::storage::segment_key_lookup::SegmentKeyLookup::key(entity)
3600                                == Some(key)
3601                        })
3602                        .into_iter()
3603                        .max_by_key(|entity| entity.xmin)
3604                        .map(|entity| entity.id);
3605                    assert_eq!(
3606                        manager.project_key_entity(key, snapshot, true, |entity| entity.id),
3607                        expected,
3608                        "key={key}"
3609                    );
3610                }
3611            }
3612            assert_eq!(
3613                manager.project_key_entity("changed", Some(&snapshot), true, |entity| entity.id),
3614                Some(EntityId::new(1))
3615            );
3616            assert_eq!(
3617                manager.project_key_entity("changed", None, true, |entity| entity.id),
3618                Some(EntityId::new(3))
3619            );
3620            assert!(manager
3621                .project_key_entity("deleted", None, true, |entity| entity.id)
3622                .is_none());
3623        })
3624        .join()
3625        .expect("snapshot worker");
3626    }
3627
3628    #[test]
3629    fn key_lookup_survives_paced_consolidation() {
3630        let manager = consolidating_manager(1);
3631        manager
3632            .bulk_insert(
3633                (1..=10)
3634                    .map(|id| lookup_version(id, &format!("key-{id}"), 1, 0))
3635                    .collect(),
3636            )
3637            .expect("rows");
3638        manager.force_seal().expect("seal");
3639        for id in 1..=4 {
3640            manager.delete(EntityId::new(id)).expect("delete");
3641        }
3642        assert!(manager.pressure_consolidation_tick());
3643        drain_maintenance(&manager);
3644        for id in 1..=10 {
3645            assert_eq!(
3646                manager.project_key_entity(&format!("key-{id}"), None, false, |entity| entity.id),
3647                (id > 4).then_some(EntityId::new(id))
3648            );
3649        }
3650    }
3651
3652    #[test]
3653    fn ordered_fingerprint_scan_matches_legacy_sort_without_cloning_rows() {
3654        let manager = SegmentManager::new("fingerprint");
3655        let row = |id, label: &str| {
3656            UnifiedEntity::table_row(
3657                EntityId::new(id),
3658                "fingerprint",
3659                id,
3660                vec![Value::text(label)],
3661            )
3662        };
3663        manager
3664            .bulk_insert(vec![row(8, "eight"), row(2, "sealed-two"), row(5, "five")])
3665            .expect("sealed rows");
3666        manager.force_seal().expect("seal");
3667        manager
3668            .bulk_insert(vec![row(7, "seven"), row(2, "growing-two"), row(1, "one")])
3669            .expect("growing rows");
3670
3671        let mut expected = manager.query_all(|_| true);
3672        expected.sort_by_key(|entity| entity.id.raw());
3673        let expected: Vec<_> = expected
3674            .iter()
3675            .map(|entity| format!("{entity:?}"))
3676            .collect();
3677        let mut stored_addresses = HashSet::new();
3678        manager.for_each_entity(|entity| {
3679            stored_addresses.insert(entity as *const UnifiedEntity as usize);
3680            true
3681        });
3682
3683        let mut actual = Vec::new();
3684        manager.for_each_entity_in_id_order(|entity| {
3685            assert!(stored_addresses.contains(&(entity as *const UnifiedEntity as usize)));
3686            assert!(
3687                manager.growing.try_write().is_some(),
3688                "topology guard retained"
3689            );
3690            assert!(
3691                manager.sealed.try_write().is_some(),
3692                "topology guard retained"
3693            );
3694            actual.push(format!("{entity:?}"));
3695            true
3696        });
3697        assert_eq!(
3698            actual, expected,
3699            "equal IDs retain their original segment order"
3700        );
3701    }
3702
3703    #[test]
3704    fn ordered_fingerprint_scan_stops_early_and_releases_sources() {
3705        let manager = SegmentManager::new("fingerprint");
3706        for id in [3, 1, 2] {
3707            manager
3708                .insert(UnifiedEntity::table_row(
3709                    EntityId::new(id),
3710                    "fingerprint",
3711                    id,
3712                    vec![Value::Integer(id as i64)],
3713                ))
3714                .expect("row");
3715        }
3716        let source = manager.growing.read().as_ref().expect("source").clone();
3717        let handles = Arc::strong_count(&source);
3718        let mut seen = Vec::new();
3719        manager.for_each_entity_in_id_order(|entity| {
3720            seen.push(entity.id.raw());
3721            false
3722        });
3723        assert_eq!(seen, vec![1]);
3724        assert_eq!(Arc::strong_count(&source), handles);
3725        assert!(
3726            source.try_write().is_some(),
3727            "segment guard retained after early stop"
3728        );
3729    }
3730
3731    #[test]
3732    fn bounded_scan_survives_sealing_consolidation_and_new_writes() {
3733        let manager = SegmentManager::with_config(
3734            "vectors",
3735            ManagerConfig {
3736                max_sealed_segments: 1,
3737                consolidation_entities_per_tick: 10_000,
3738                ..Default::default()
3739            },
3740        );
3741        for part in 0..3 {
3742            manager
3743                .bulk_insert(
3744                    (1..=300)
3745                        .map(|offset| {
3746                            UnifiedEntity::vector(
3747                                EntityId::new(part * 300 + offset),
3748                                "vectors",
3749                                vec![1.0, 0.0],
3750                            )
3751                        })
3752                        .collect(),
3753                )
3754                .expect("batch");
3755            if part < 2 {
3756                manager.force_seal().expect("seal");
3757            }
3758        }
3759        let original_growing = manager.growing.read().as_ref().expect("growing").clone();
3760        let mut changed = false;
3761        let mut seen = Vec::new();
3762        assert!(manager.scan_batches(
3763            None,
3764            || true,
3765            |batch| {
3766                assert!(batch.len() <= super::super::segment::SCAN_BATCH_SIZE);
3767                assert!(
3768                    manager.growing.try_write().is_some(),
3769                    "consumer holds no topology guard"
3770                );
3771                assert!(
3772                    original_growing.try_write().is_some(),
3773                    "consumer holds no segment guard"
3774                );
3775                for entity in batch {
3776                    assert!(manager.get(entity.id).is_some(), "reentrant storage lookup");
3777                    seen.push(entity.id.raw());
3778                }
3779                if !changed {
3780                    changed = true;
3781                    manager.force_seal().expect("seal during scan");
3782                    manager
3783                        .insert(UnifiedEntity::vector(
3784                            EntityId::new(5000),
3785                            "vectors",
3786                            vec![1.0, 0.0],
3787                        ))
3788                        .expect("new write");
3789                    drain_maintenance(&manager);
3790                    assert!(manager.stats().consolidation.runs_completed > 0);
3791                    assert!(manager
3792                        .delete(EntityId::new(1))
3793                        .expect("delete after source retirement"));
3794                    assert!(manager.get(EntityId::new(1)).is_none());
3795                }
3796                true
3797            }
3798        ));
3799        seen.sort_unstable();
3800        assert_eq!(
3801            seen,
3802            (2..=900).collect::<Vec<_>>(),
3803            "no duplicate, missing or late candidates"
3804        );
3805        let mut after = Vec::new();
3806        assert!(manager.scan_batches(
3807            None,
3808            || true,
3809            |batch| {
3810                after.extend(batch.iter().map(|entity| entity.id.raw()));
3811                true
3812            }
3813        ));
3814        after.sort_unstable();
3815        let mut expected: Vec<_> = (2..=900).collect();
3816        expected.push(5000);
3817        assert_eq!(after, expected, "adopted entities have scan positions");
3818    }
3819
3820    #[test]
3821    fn bounded_scan_applies_snapshot_to_relocated_versions() {
3822        for (consolidate, bulk) in [(false, false), (false, true), (true, false), (true, true)] {
3823            let manager = SegmentManager::with_config(
3824                "vectors",
3825                ManagerConfig {
3826                    max_sealed_segments: 1,
3827                    ..Default::default()
3828                },
3829            );
3830            for ids in [[1, 2], [3, 4]] {
3831                let entities = ids.map(|id| {
3832                    let mut entity = UnifiedEntity::vector(EntityId::new(id), "vectors", vec![1.0]);
3833                    entity.set_xmin(3);
3834                    entity
3835                });
3836                if bulk {
3837                    manager
3838                        .bulk_insert(entities.into())
3839                        .expect("initial versions");
3840                } else {
3841                    for entity in entities {
3842                        manager.insert(entity).expect("initial version");
3843                    }
3844                }
3845                manager.force_seal().expect("seal source");
3846            }
3847            let snapshot = SnapshotContext {
3848                branch: None,
3849                snapshot: Snapshot {
3850                    xid: 10,
3851                    in_progress: HashSet::new(),
3852                },
3853                manager: Arc::new(SnapshotManager::new()),
3854                own_xids: HashSet::new(),
3855                requires_index_fallback: false,
3856                hidden_writers_only: false,
3857                serializable_reader: None,
3858            };
3859            let mut changed = false;
3860            let mut seen = Vec::new();
3861            assert!(manager.scan_batches(
3862                Some(&snapshot),
3863                || true,
3864                |batch| {
3865                    seen.extend(batch.iter().map(|entity| entity.id.raw()));
3866                    if !changed {
3867                        changed = true;
3868                        if consolidate {
3869                            drain_maintenance(&manager);
3870                            assert!(manager.stats().consolidation.runs_completed > 0);
3871                        }
3872                        for (id, xmax) in [(3, 8), (4, 12)] {
3873                            let mut entity =
3874                                manager.get(EntityId::new(id)).expect("retained version");
3875                            entity.set_xmax(xmax);
3876                            manager
3877                                .update(entity)
3878                                .expect("update after source retirement");
3879                        }
3880                    }
3881                    true
3882                }
3883            ));
3884            seen.sort_unstable();
3885            assert_eq!(seen, vec![1, 2, 4], "snapshot uses authoritative xmax");
3886            let mut again = Vec::new();
3887            assert!(manager.scan_batches(
3888                Some(&snapshot),
3889                || true,
3890                |batch| {
3891                    again.extend(batch.iter().map(|entity| entity.id.raw()));
3892                    true
3893                }
3894            ));
3895            again.sort_unstable();
3896            assert_eq!(
3897                again,
3898                vec![1, 2, 4],
3899                "old slots do not duplicate relocated versions"
3900            );
3901            let mut current = Vec::new();
3902            assert!(manager.scan_batches(
3903                None,
3904                || true,
3905                |batch| {
3906                    current.extend(batch.iter().map(|entity| entity.id.raw()));
3907                    true
3908                }
3909            ));
3910            current.sort_unstable();
3911            assert_eq!(
3912                current,
3913                vec![1, 2],
3914                "current view excludes both deleted versions"
3915            );
3916        }
3917    }
3918
3919    #[test]
3920    fn bounded_scan_keeps_flat_and_hash_positions_through_mutation() {
3921        let manager = SegmentManager::new("mixed");
3922        let vector = |id| UnifiedEntity::vector(EntityId::new(id), "mixed", vec![1.0]);
3923        manager
3924            .bulk_insert((1..=300).map(vector).collect())
3925            .expect("flat");
3926        manager.insert(vector(500)).expect("hash insert");
3927        manager
3928            .bulk_insert(vec![vector(502), vector(505)])
3929            .expect("gapped bulk");
3930        manager.delete(EntityId::new(2)).expect("flat delete");
3931        manager.delete(EntityId::new(505)).expect("hash delete");
3932        let mut changed = false;
3933        let mut seen = Vec::new();
3934        assert!(manager.scan_batches(
3935            None,
3936            || true,
3937            |batch| {
3938                seen.extend(batch.iter().map(|entity| entity.id.raw()));
3939                if !changed {
3940                    changed = true;
3941                    manager
3942                        .insert(vector(700))
3943                        .expect("append after cursor boundary");
3944                    manager
3945                        .update(UnifiedEntity::graph_node(
3946                            EntityId::new(500),
3947                            "mixed",
3948                            "Node",
3949                            HashMap::new(),
3950                        ))
3951                        .expect("structural update");
3952                }
3953                true
3954            }
3955        ));
3956        seen.sort_unstable();
3957        let mut expected: Vec<_> = (1..=300).filter(|id| *id != 2).collect();
3958        expected.extend([500, 502]);
3959        assert_eq!(seen, expected);
3960    }
3961
3962    #[test]
3963    fn bounded_scan_preserves_snapshot_and_discards_interrupted_batches() {
3964        let manager = SegmentManager::new("vectors");
3965        let mut entities = Vec::new();
3966        for (id, xmin, xmax) in [(1, 3, 12), (2, 12, 0), (3, 3, 0), (4, 3, 4)] {
3967            let mut entity = UnifiedEntity::vector(EntityId::new(id), "vectors", vec![1.0]);
3968            entity.set_xmin(xmin);
3969            entity.set_xmax(xmax);
3970            entities.push(entity);
3971        }
3972        manager.bulk_insert(entities).expect("versions");
3973        manager.force_seal().expect("seal");
3974        let snapshot = SnapshotContext {
3975            branch: None,
3976            snapshot: Snapshot {
3977                xid: 10,
3978                in_progress: HashSet::from([4]),
3979            },
3980            manager: Arc::new(SnapshotManager::new()),
3981            own_xids: HashSet::new(),
3982            requires_index_fallback: false,
3983            hidden_writers_only: false,
3984            serializable_reader: None,
3985        };
3986        let mut work = 0;
3987        let mut callbacks = 0;
3988        assert!(!manager.scan_batches(
3989            Some(&snapshot),
3990            || {
3991                work += 1;
3992                work <= 2
3993            },
3994            |_| {
3995                callbacks += 1;
3996                true
3997            }
3998        ));
3999        assert_eq!(callbacks, 0, "a stopped batch is not consumed");
4000        for (view, expected) in [(Some(&snapshot), vec![1, 3, 4]), (None, vec![2, 3])] {
4001            let mut seen = Vec::new();
4002            assert!(manager.scan_batches(
4003                view,
4004                || true,
4005                |batch| {
4006                    seen.extend(batch.iter().map(|entity| entity.id.raw()));
4007                    true
4008                }
4009            ));
4010            seen.sort_unstable();
4011            assert_eq!(seen, expected);
4012        }
4013    }
4014
4015    #[test]
4016    fn test_manager_basic() {
4017        let manager = SegmentManager::new("test_collection");
4018
4019        let entity = UnifiedEntity::table_row(
4020            manager.next_entity_id(),
4021            "users",
4022            1,
4023            vec![Value::text("Alice".to_string())],
4024        );
4025
4026        let id = manager.insert(entity).unwrap();
4027        assert!(manager.get(id).is_some());
4028        assert_eq!(manager.count(), 1);
4029    }
4030
4031    #[test]
4032    fn graph_pruning_preserves_physical_versions_and_charges_only_selected_segments() {
4033        let manager = Arc::new(SegmentManager::new("mixed"));
4034        manager
4035            .bulk_insert(
4036                (1..=128)
4037                    .map(|id| UnifiedEntity::vector(EntityId::new(id), "mixed", vec![]))
4038                    .collect(),
4039            )
4040            .expect("vector-only segment");
4041        manager.force_seal().expect("seal vectors");
4042        let mut old =
4043            UnifiedEntity::graph_node(EntityId::new(200), "mixed", "person", Default::default());
4044        old.set_xmin(3);
4045        old.set_xmax(12);
4046        let mut new =
4047            UnifiedEntity::graph_node(EntityId::new(201), "mixed", "person", Default::default());
4048        new.set_xmin(12);
4049        let edge = UnifiedEntity::graph_edge(
4050            EntityId::new(202),
4051            "mixed",
4052            "a",
4053            "b",
4054            1.0,
4055            Default::default(),
4056        );
4057        manager
4058            .bulk_insert(vec![old, new, edge])
4059            .expect("physical graph versions");
4060        manager.force_seal().expect("seal graph");
4061        manager
4062            .insert(UnifiedEntity::graph_node(
4063                EntityId::new(203),
4064                "mixed",
4065                "person",
4066                Default::default(),
4067            ))
4068            .expect("growing node");
4069        let snapshot = SnapshotContext {
4070            branch: None,
4071            snapshot: Snapshot {
4072                xid: 10,
4073                in_progress: HashSet::new(),
4074            },
4075            manager: Arc::new(SnapshotManager::new()),
4076            own_xids: HashSet::new(),
4077            requires_index_fallback: false,
4078            hidden_writers_only: false,
4079            serializable_reader: None,
4080        };
4081        std::thread::spawn(move || {
4082            for view in [None, Some(&snapshot)] {
4083                for kind in [GraphEntityKind::Node, GraphEntityKind::Edge] {
4084                    let expected: HashSet<_> = manager
4085                        .scan(view, |item| kind.matches(&item.kind))
4086                        .into_iter()
4087                        .map(|item| item.id)
4088                        .collect();
4089                    let actual: HashSet<_> = manager
4090                        .scan_graph_kind(view, kind)
4091                        .into_iter()
4092                        .map(|item| item.id)
4093                        .collect();
4094                    assert_eq!(actual, expected);
4095                    let mut batched = HashSet::new();
4096                    assert!(manager.scan_graph_batches(
4097                        view,
4098                        kind,
4099                        || true,
4100                        |batch| {
4101                            batched.extend(batch.into_iter().map(|item| item.id));
4102                            true
4103                        }
4104                    ));
4105                    assert_eq!(batched, expected);
4106                    let mut visited = 0;
4107                    let mut candidates = HashSet::new();
4108                    manager.scan_graph_candidates_for_each(
4109                        view,
4110                        kind,
4111                        || true,
4112                        |item| {
4113                            visited += 1;
4114                            if kind.matches(&item.kind) {
4115                                candidates.insert(item.id);
4116                            }
4117                            true
4118                        },
4119                    );
4120                    assert_eq!(candidates, expected);
4121                    assert_eq!(
4122                        visited,
4123                        if matches!(kind, GraphEntityKind::Node) {
4124                            3
4125                        } else {
4126                            2
4127                        }
4128                    );
4129                }
4130            }
4131            let ids: HashSet<_> = manager
4132                .scan_graph_kind(Some(&snapshot), GraphEntityKind::Node)
4133                .into_iter()
4134                .map(|item| item.id.raw())
4135                .collect();
4136            assert_eq!(ids, HashSet::from([200, 203]));
4137            let ids: HashSet<_> = manager
4138                .scan_graph_kind(None, GraphEntityKind::Node)
4139                .into_iter()
4140                .map(|item| item.id.raw())
4141                .collect();
4142            assert_eq!(ids, HashSet::from([201, 203]));
4143            let mut visits = 0;
4144            manager.scan_graph_candidates_for_each(
4145                None,
4146                GraphEntityKind::Node,
4147                || true,
4148                |_| {
4149                    visits += 1;
4150                    false
4151                },
4152            );
4153            assert_eq!(
4154                visits, 1,
4155                "early termination must also stop subsequent segments"
4156            );
4157        })
4158        .join()
4159        .expect("snapshot worker");
4160    }
4161
4162    #[test]
4163    fn snapshot_scan_applies_table_driven_visibility_on_fresh_thread() {
4164        let manager = Arc::new(SegmentManager::new("accounts"));
4165        let cases = [
4166            ("legacy row", 0, 0, true),
4167            ("committed creator", 3, 0, true),
4168            ("future creator", 11, 0, false),
4169            ("in-progress creator", 4, 0, false),
4170            ("committed deleter", 3, 7, false),
4171            ("future deleter", 3, 11, true),
4172            ("in-progress deleter", 3, 4, true),
4173        ];
4174
4175        for (index, (_, xmin, xmax, _)) in cases.iter().enumerate() {
4176            let row_id = index as u64 + 1;
4177            let mut entity = UnifiedEntity::table_row(
4178                EntityId::new(row_id),
4179                "accounts",
4180                row_id,
4181                vec![Value::Integer(row_id as i64)],
4182            );
4183            entity.set_xmin(*xmin);
4184            entity.set_xmax(*xmax);
4185            manager.insert(entity).unwrap();
4186        }
4187
4188        let snapshot = SnapshotContext {
4189            branch: None,
4190            snapshot: Snapshot {
4191                xid: 10,
4192                in_progress: HashSet::from([4]),
4193            },
4194            manager: Arc::new(SnapshotManager::new()),
4195            own_xids: HashSet::new(),
4196            requires_index_fallback: false,
4197            hidden_writers_only: false,
4198            serializable_reader: None,
4199        };
4200
4201        let raw_visible_row_ids: HashSet<u64> = manager
4202            .query_all(|entity| entity_visible_with_context(Some(&snapshot), entity))
4203            .into_iter()
4204            .filter_map(|entity| match entity.kind {
4205                EntityKind::TableRow { row_id, .. } => Some(row_id),
4206                _ => None,
4207            })
4208            .collect();
4209
4210        let scanned = std::thread::spawn(move || manager.scan(Some(&snapshot), |_| true))
4211            .join()
4212            .unwrap();
4213        let visible_row_ids: HashSet<u64> = scanned
4214            .into_iter()
4215            .filter_map(|entity| match entity.kind {
4216                EntityKind::TableRow { row_id, .. } => Some(row_id),
4217                _ => None,
4218            })
4219            .collect();
4220        assert_eq!(visible_row_ids, raw_visible_row_ids);
4221
4222        for (index, (name, _, _, expected_visible)) in cases.iter().enumerate() {
4223            let row_id = index as u64 + 1;
4224            assert_eq!(
4225                visible_row_ids.contains(&row_id),
4226                *expected_visible,
4227                "{name} visibility mismatch"
4228            );
4229        }
4230    }
4231
4232    #[test]
4233    fn frameless_scan_hides_superseded_versions_and_moderated_rows() {
4234        // A `None` snapshot is the autocommit / prepared-fast-path read: it
4235        // must keep the resolver fallback (xmax == 0), never show every
4236        // version, and never panic (issue #2136 review).
4237        let manager = SegmentManager::new("accounts");
4238        let mut live =
4239            UnifiedEntity::table_row(EntityId::new(1), "accounts", 1, vec![Value::Integer(1)]);
4240        live.set_xmin(2);
4241        live.set_xmax(0);
4242        manager.insert(live).unwrap();
4243
4244        let mut superseded =
4245            UnifiedEntity::table_row(EntityId::new(2), "accounts", 2, vec![Value::Integer(2)]);
4246        superseded.set_xmin(2);
4247        superseded.set_xmax(9);
4248        manager.insert(superseded).unwrap();
4249
4250        let rows: Vec<u64> = manager
4251            .scan(None, |_| true)
4252            .into_iter()
4253            .filter_map(|entity| match entity.kind {
4254                EntityKind::TableRow { row_id, .. } => Some(row_id),
4255                _ => None,
4256            })
4257            .collect();
4258        assert_eq!(
4259            rows,
4260            vec![1],
4261            "frameless scan must hide superseded versions"
4262        );
4263    }
4264
4265    #[test]
4266    fn bloom_may_contain_key_probes_inserted_rid_bytes() {
4267        let manager = SegmentManager::new("test_collection");
4268
4269        let entity = UnifiedEntity::table_row(
4270            manager.next_entity_id(),
4271            "users",
4272            1,
4273            vec![Value::text("Alice".to_string())],
4274        );
4275
4276        let id = manager.insert(entity).unwrap();
4277
4278        assert!(manager.bloom_may_contain_key(&id.raw().to_le_bytes()));
4279        assert!(manager.bloom_may_contain_key(id.raw().to_string().as_bytes()));
4280        assert!(!manager.bloom_may_contain_key(&u64::MAX.to_le_bytes()));
4281
4282        assert!(manager.delete(id).unwrap());
4283        assert!(!manager.bloom_may_contain_key(&id.raw().to_le_bytes()));
4284    }
4285
4286    #[test]
4287    fn zoned_scan_reports_pruned_segments_and_preserves_results() {
4288        let config = ManagerConfig {
4289            segment_config: SegmentConfig {
4290                max_entities: 2,
4291                ..Default::default()
4292            },
4293            ..Default::default()
4294        };
4295        let manager = SegmentManager::with_config("events", config);
4296
4297        for (idx, value) in [10, 20, 100, 110, 200].into_iter().enumerate() {
4298            let row = RowData::with_names(vec![Value::Integer(value)], vec!["ts".to_string()]);
4299            let entity = UnifiedEntity::new(
4300                manager.next_entity_id(),
4301                EntityKind::TableRow {
4302                    table: "events".into(),
4303                    row_id: (idx + 1) as u64,
4304                },
4305                EntityData::Row(row),
4306            );
4307            manager.insert(entity).unwrap();
4308        }
4309
4310        let full = manager.query_all(|entity| match &entity.data {
4311            EntityData::Row(row) => matches!(row.get_field("ts"), Some(Value::Integer(100))),
4312            _ => false,
4313        });
4314        let probe = Value::Integer(100);
4315        let (pruned, stats) =
4316            manager.query_all_zoned_with_stats(&[("ts", ZoneColPred::Eq(&probe))], |entity| {
4317                match &entity.data {
4318                    EntityData::Row(row) => {
4319                        matches!(row.get_field("ts"), Some(Value::Integer(100)))
4320                    }
4321                    _ => false,
4322                }
4323            });
4324
4325        assert_eq!(pruned.len(), full.len());
4326        assert_eq!(pruned[0].id, full[0].id);
4327        assert_eq!(stats.segments_total, 3);
4328        assert_eq!(stats.segments_scanned, 2);
4329        assert_eq!(stats.segments_pruned, 1);
4330    }
4331
4332    #[test]
4333    fn projected_zoned_scan_preserves_segment_order_and_pruning() {
4334        let manager = SegmentManager::with_config(
4335            "events",
4336            ManagerConfig {
4337                segment_config: SegmentConfig {
4338                    max_entities: 2,
4339                    ..Default::default()
4340                },
4341                ..Default::default()
4342            },
4343        );
4344        for (index, value) in [10, 20, 100, 110, 200].into_iter().enumerate() {
4345            let mut entity = UnifiedEntity::table_row(
4346                EntityId::new(index as u64 + 1),
4347                "events",
4348                index as u64 + 1,
4349                vec![],
4350            );
4351            entity.data = EntityData::Row(RowData::with_names(
4352                vec![Value::Integer(value)],
4353                vec!["ts".into()],
4354            ));
4355            manager.insert(entity).expect("test row");
4356        }
4357        assert_eq!(manager.stats().sealed_count, 2);
4358        let project = |entity: &UnifiedEntity| match entity.data.as_row()?.get_field("ts")? {
4359            Value::Integer(value) => Some(*value),
4360            _ => None,
4361        };
4362        let (all, stats) = manager.scan_project_zoned_with_stats(None, &[], project);
4363        let (legacy, _) = manager.scan_zoned_with_stats(None, &[], |_| true);
4364        assert_eq!(all, legacy.iter().filter_map(project).collect::<Vec<_>>());
4365        assert_eq!(all[0], 200, "growing segment first");
4366        assert!(all[1..3].iter().all(|value| [10, 20].contains(value)));
4367        assert!(all[3..5].iter().all(|value| [100, 110].contains(value)));
4368        assert_eq!(stats.segments_total, 3);
4369        assert_eq!(stats.segments_scanned, 3);
4370        assert_eq!(stats.segments_pruned, 0);
4371        let probe = Value::Integer(100);
4372        let (pruned, stats) = manager.scan_project_zoned_with_stats(
4373            None,
4374            &[("ts", ZoneColPred::Gte(&probe))],
4375            |entity| project(entity).filter(|value| *value >= 100),
4376        );
4377        assert_eq!(
4378            pruned,
4379            all.into_iter()
4380                .filter(|value| *value >= 100)
4381                .collect::<Vec<_>>()
4382        );
4383        assert_eq!(stats.segments_total, 3);
4384        assert_eq!(stats.segments_scanned, 2);
4385        assert_eq!(stats.segments_pruned, 1);
4386        let (empty, _) = manager.scan_project_zoned_with_stats(None, &[], |_| None::<u64>);
4387        assert!(empty.is_empty(), "projection may reject every candidate");
4388
4389        let failure = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
4390            manager.scan_project_zoned_with_stats(None, &[], |entity| {
4391                let value = project(entity)?;
4392                assert_ne!(value, 10, "injected projection worker failure");
4393                Some(value)
4394            })
4395        }));
4396        assert!(
4397            failure.is_err(),
4398            "a failed worker must not return a successful partial scan"
4399        );
4400    }
4401
4402    #[test]
4403    fn projected_zoned_scan_checks_visibility_before_projection_on_workers() {
4404        let manager = SegmentManager::with_config(
4405            "accounts",
4406            ManagerConfig {
4407                segment_config: SegmentConfig {
4408                    max_entities: 2,
4409                    ..Default::default()
4410                },
4411                ..Default::default()
4412            },
4413        );
4414        for (id, xmin, xmax) in [(1, 3, 12), (2, 12, 0), (3, 3, 0), (4, 3, 4), (5, 3, 0)] {
4415            let mut entity = UnifiedEntity::table_row(EntityId::new(id), "accounts", id, vec![]);
4416            entity.set_xmin(xmin);
4417            entity.set_xmax(xmax);
4418            manager.insert(entity).expect("versioned test row");
4419        }
4420        let mut hidden = UnifiedEntity::table_row(EntityId::new(6), "accounts", 6, vec![]);
4421        hidden.data = EntityData::Row(RowData::with_names(
4422            vec![Value::text("pending")],
4423            vec!["__moderation_status".into()],
4424        ));
4425        manager.insert(hidden).expect("moderated row");
4426        assert_eq!(manager.stats().sealed_count, 2);
4427        let snapshot = SnapshotContext {
4428            branch: None,
4429            snapshot: Snapshot {
4430                xid: 10,
4431                in_progress: HashSet::from([4]),
4432            },
4433            manager: Arc::new(SnapshotManager::new()),
4434            own_xids: HashSet::new(),
4435            requires_index_fallback: false,
4436            hidden_writers_only: false,
4437            serializable_reader: None,
4438        };
4439        std::thread::spawn(move || {
4440            for (view, expected) in [(Some(&snapshot), vec![5, 1, 3, 4]), (None, vec![5, 2, 3])] {
4441                let called = std::sync::Mutex::new(Vec::new());
4442                let (rows, stats) = manager.scan_project_zoned_with_stats(view, &[], |entity| {
4443                    let id = entity.id.raw();
4444                    assert!(
4445                        expected.contains(&id),
4446                        "invisible entity reached projection: {id}"
4447                    );
4448                    called.lock().expect("callback log").push(id);
4449                    Some(id)
4450                });
4451                let (legacy, _) = manager.scan_zoned_with_stats(view, &[], |_| true);
4452                assert_eq!(
4453                    rows,
4454                    legacy
4455                        .iter()
4456                        .map(|entity| entity.id.raw())
4457                        .collect::<Vec<_>>()
4458                );
4459                assert_eq!(rows[0], 5, "visible growing row first");
4460                let mut called = called.into_inner().expect("callback log");
4461                called.sort_unstable();
4462                let mut expected = expected;
4463                expected.sort_unstable();
4464                assert_eq!(called, expected, "each visible row projected exactly once");
4465                assert_eq!(stats.segments_total, 3);
4466                assert_eq!(stats.segments_scanned, 3);
4467            }
4468        })
4469        .join()
4470        .expect("projected scan worker");
4471    }
4472
4473    #[test]
4474    fn test_manager_auto_seal() {
4475        let config = ManagerConfig {
4476            segment_config: SegmentConfig {
4477                max_entities: 2,
4478                ..Default::default()
4479            },
4480            ..Default::default()
4481        };
4482
4483        let manager = SegmentManager::with_config("test", config);
4484
4485        // Insert first entity
4486        manager
4487            .insert(UnifiedEntity::vector(
4488                manager.next_entity_id(),
4489                "v",
4490                vec![0.1],
4491            ))
4492            .unwrap();
4493
4494        // Insert second entity (triggers seal check)
4495        manager
4496            .insert(UnifiedEntity::vector(
4497                manager.next_entity_id(),
4498                "v",
4499                vec![0.2],
4500            ))
4501            .unwrap();
4502
4503        // Insert third entity (should trigger auto-seal of first segment)
4504        manager
4505            .insert(UnifiedEntity::vector(
4506                manager.next_entity_id(),
4507                "v",
4508                vec![0.3],
4509            ))
4510            .unwrap();
4511
4512        let stats = manager.stats();
4513        assert_eq!(stats.total_entities, 3);
4514    }
4515
4516    #[test]
4517    fn test_manager_delete() {
4518        let manager = SegmentManager::new("test");
4519
4520        let id = manager
4521            .insert(UnifiedEntity::vector(
4522                manager.next_entity_id(),
4523                "v",
4524                vec![0.1],
4525            ))
4526            .unwrap();
4527
4528        assert!(manager.get(id).is_some());
4529        assert!(manager.delete(id).unwrap());
4530        assert!(manager.get(id).is_none());
4531    }
4532
4533    /// A scan callback reads the metadata of the row it is visiting while a
4534    /// writer queues for the same segment.
4535    #[test]
4536    fn metadata_read_inside_a_scan_does_not_wait_for_a_queued_writer() {
4537        use std::sync::mpsc;
4538        use std::time::Duration;
4539
4540        for sealed in [false, true] {
4541            let manager = Arc::new(SegmentManager::new("test"));
4542            let id = manager
4543                .insert(UnifiedEntity::table_row(
4544                    manager.next_entity_id(),
4545                    "hosts",
4546                    1,
4547                    vec![Value::text("192.168.1.1".to_string())],
4548                ))
4549                .unwrap();
4550            let mut meta = Metadata::new();
4551            meta.set("os", MetadataValue::String("linux".to_string()));
4552            manager.set_metadata(id, meta).unwrap();
4553            if sealed {
4554                manager.force_seal().unwrap();
4555            }
4556
4557            let (visiting, writer_may_queue) = mpsc::channel();
4558            let (done, finished) = mpsc::channel();
4559            let scan = {
4560                let manager = Arc::clone(&manager);
4561                std::thread::spawn(move || {
4562                    let mut seen = None;
4563                    manager.for_each_entity(|entity| {
4564                        visiting.send(()).unwrap();
4565                        // Long enough for the writer to queue behind this scan.
4566                        std::thread::sleep(Duration::from_millis(300));
4567                        seen = manager.get_metadata(entity.id);
4568                        true
4569                    });
4570                    done.send(seen.is_some_and(|meta| meta.has("os"))).unwrap();
4571                })
4572            };
4573            writer_may_queue.recv().unwrap();
4574            let writer = {
4575                let manager = Arc::clone(&manager);
4576                std::thread::spawn(move || {
4577                    let mut meta = Metadata::new();
4578                    meta.set("os", MetadataValue::String("bsd".to_string()));
4579                    manager.set_metadata(id, meta).unwrap();
4580                })
4581            };
4582            assert_eq!(
4583                finished.recv_timeout(Duration::from_secs(20)),
4584                Ok(true),
4585                "sealed={sealed}: the scan callback and the queued writer wait for each other"
4586            );
4587            scan.join().unwrap();
4588            writer.join().unwrap();
4589            assert!(manager.get_metadata(id).unwrap().has("os"));
4590        }
4591    }
4592
4593    #[test]
4594    fn test_manager_metadata() {
4595        let manager = SegmentManager::new("test");
4596
4597        let id = manager
4598            .insert(UnifiedEntity::table_row(
4599                manager.next_entity_id(),
4600                "hosts",
4601                1,
4602                vec![Value::text("192.168.1.1".to_string())],
4603            ))
4604            .unwrap();
4605
4606        let mut meta = Metadata::new();
4607        meta.set(
4608            "os",
4609            super::super::metadata::MetadataValue::String("linux".to_string()),
4610        );
4611
4612        manager.set_metadata(id, meta).unwrap();
4613
4614        let retrieved = manager.get_metadata(id).unwrap();
4615        assert!(retrieved.has("os"));
4616    }
4617
4618    #[test]
4619    fn metadata_expiry_index_is_bounded_rekeyed_and_removed_with_entity() {
4620        let manager = SegmentManager::new("sessions");
4621        let mut first = UnifiedEntity::table_row(EntityId::new(1), "sessions", 1, vec![]);
4622        first.created_at = 10;
4623        let mut second = UnifiedEntity::table_row(EntityId::new(2), "sessions", 2, vec![]);
4624        second.created_at = 20;
4625        manager.insert(first).expect("first session");
4626        manager.insert(second).expect("second session");
4627
4628        let mut relative = Metadata::new();
4629        relative.set("_ttl_ms", MetadataValue::Int(5_000));
4630        manager
4631            .set_metadata(EntityId::new(1), relative)
4632            .expect("relative TTL");
4633        let mut absolute = Metadata::new();
4634        absolute.set("_expires_at", MetadataValue::Timestamp(30_000));
4635        manager
4636            .set_metadata(EntityId::new(2), absolute)
4637            .expect("absolute expiry");
4638
4639        assert_eq!(manager.scheduled_metadata_expiry_count(), 2);
4640        assert_eq!(
4641            manager.expired_metadata_ids(30_000, 1),
4642            vec![EntityId::new(1)],
4643            "the deadline index must stop at the requested batch"
4644        );
4645        assert_eq!(
4646            manager.expired_metadata_ids(30_000, 2),
4647            vec![EntityId::new(1), EntityId::new(2)]
4648        );
4649
4650        let mut postponed = Metadata::new();
4651        postponed.set("_expires_at", MetadataValue::Timestamp(60_000));
4652        manager
4653            .set_metadata(EntityId::new(1), postponed)
4654            .expect("postpone expiry");
4655        assert_eq!(
4656            manager.expired_metadata_ids(30_000, 2),
4657            vec![EntityId::new(2)],
4658            "metadata replacement must remove the stale deadline"
4659        );
4660
4661        assert!(manager.delete(EntityId::new(2)).expect("delete session"));
4662        assert!(manager
4663            .expired_metadata_ids(u64::MAX, 2)
4664            .contains(&EntityId::new(1)));
4665        assert!(!manager
4666            .expired_metadata_ids(u64::MAX, 2)
4667            .contains(&EntityId::new(2)));
4668        assert_eq!(manager.scheduled_metadata_expiry_count(), 1);
4669    }
4670
4671    #[test]
4672    fn test_manager_query_by_kind() {
4673        let manager = SegmentManager::new("test");
4674
4675        manager
4676            .insert(UnifiedEntity::table_row(
4677                manager.next_entity_id(),
4678                "hosts",
4679                1,
4680                vec![],
4681            ))
4682            .unwrap();
4683
4684        manager
4685            .insert(UnifiedEntity::vector(
4686                manager.next_entity_id(),
4687                "embeddings",
4688                vec![0.1],
4689            ))
4690            .unwrap();
4691
4692        manager
4693            .insert(UnifiedEntity::table_row(
4694                manager.next_entity_id(),
4695                "hosts",
4696                2,
4697                vec![],
4698            ))
4699            .unwrap();
4700
4701        let rows = manager.get_by_kind("table");
4702        assert_eq!(rows.len(), 2);
4703
4704        let vectors = manager.get_by_kind("vector");
4705        assert_eq!(vectors.len(), 1);
4706    }
4707
4708    // ========================================================================
4709    // Consolidation — ADR 0073 §5
4710    // ========================================================================
4711
4712    /// A manager whose sealed set never trips the count trigger, so tests can
4713    /// exercise the tombstone/fragmentation triggers in isolation.
4714    fn consolidating_manager(entities_per_tick: usize) -> SegmentManager {
4715        SegmentManager::with_config(
4716            "test",
4717            ManagerConfig {
4718                max_sealed_segments: 1_000,
4719                consolidation_entities_per_tick: entities_per_tick,
4720                ..Default::default()
4721            },
4722        )
4723    }
4724
4725    /// Bulk-load `count` rows into a fresh segment and seal it. Bulk-inserted
4726    /// entities land in flat storage, where a tombstone keeps its payload
4727    /// resident — which is the memory consolidation reclaims.
4728    fn seal_bulk_segment(manager: &SegmentManager, count: usize) -> Vec<EntityId> {
4729        let entities: Vec<UnifiedEntity> = (0..count)
4730            .map(|i| {
4731                UnifiedEntity::table_row(
4732                    manager.next_entity_id(),
4733                    "users",
4734                    i as u64,
4735                    vec![Value::Integer(i as i64), Value::text(format!("row-{i}"))],
4736                )
4737            })
4738            .collect();
4739        let ids = manager.bulk_insert(entities).expect("bulk insert");
4740        manager.force_seal().expect("seal");
4741        ids
4742    }
4743
4744    fn live_ids(manager: &SegmentManager) -> Vec<u64> {
4745        let mut ids: Vec<u64> = manager
4746            .query_all(|_| true)
4747            .into_iter()
4748            .map(|entity| entity.id.raw())
4749            .collect();
4750        ids.sort_unstable();
4751        ids
4752    }
4753
4754    fn drain_maintenance(manager: &SegmentManager) -> usize {
4755        let mut ticks = 0;
4756        while manager.consolidation.read().is_some() || ticks == 0 {
4757            manager.run_maintenance().expect("maintenance");
4758            ticks += 1;
4759            assert!(ticks < 1_000, "consolidation failed to converge");
4760        }
4761        ticks
4762    }
4763
4764    #[test]
4765    fn graph_batches_bound_payloads_and_hydrate_current_entities_after_sealing() {
4766        let manager = SegmentManager::new("graph");
4767        let node =
4768            |id| UnifiedEntity::graph_node(EntityId::new(id), "graph", "node", HashMap::new());
4769        manager
4770            .bulk_insert((1..=1024).map(node).collect())
4771            .expect("nodes");
4772        let mut hidden = node(1025);
4773        hidden.set_xmax(5);
4774        manager.insert(hidden).expect("hidden version");
4775        manager
4776            .insert(UnifiedEntity::vector(EntityId::new(1026), "graph", vec![]))
4777            .expect("mixed kind");
4778        let mut work = 0;
4779        let mut delivered = 0;
4780        assert!(!manager.scan_graph_batches(
4781            None,
4782            GraphEntityKind::Node,
4783            || {
4784                work += 1;
4785                work < 100
4786            },
4787            |batch| {
4788                delivered += batch.len();
4789                true
4790            }
4791        ));
4792        assert_eq!(delivered, 0, "cancelled partial batch must not escape");
4793        let mut seen = Vec::new();
4794        assert!(manager.scan_graph_batches(None, GraphEntityKind::Node, || true, |batch| {
4795            assert!(batch.len() <= super::super::segment::SCAN_BATCH_SIZE);
4796            assert!(manager.growing.try_write().is_some(), "no topology guard");
4797            assert!(manager.sealed.try_write().is_some(), "no sealed guard");
4798            if seen.is_empty() {
4799                manager.force_seal().expect("seal during delivery");
4800                manager.insert(node(2000)).expect("append beyond captured boundary");
4801                let mut updated = node(900);
4802                if let EntityKind::GraphNode(node) = &mut updated.kind {
4803                    node.label = "updated".into();
4804                }
4805                manager.update(updated).expect("update unread candidate");
4806            }
4807            for entity in batch {
4808                if entity.id.raw() == 900 {
4809                    assert!(matches!(&entity.kind, EntityKind::GraphNode(node) if node.label == "updated"));
4810                }
4811                seen.push(entity.id.raw());
4812            }
4813            true
4814        }));
4815        assert_eq!(seen, (1..=1024).collect::<Vec<_>>());
4816    }
4817
4818    #[test]
4819    fn graph_index_batches_pin_sources_and_hydrate_current_after_consolidation() {
4820        let manager = consolidating_manager(CONSOLIDATION_ENTITIES_PER_TICK);
4821        let ids = manager
4822            .bulk_insert(
4823                (1..=1024)
4824                    .map(|id| {
4825                        UnifiedEntity::graph_edge(
4826                            EntityId::new(id),
4827                            "step",
4828                            "2000",
4829                            "3000",
4830                            1.0,
4831                            HashMap::new(),
4832                        )
4833                    })
4834                    .collect(),
4835            )
4836            .expect("edges");
4837        manager.force_seal().expect("seal");
4838        for id in ids.iter().take(300) {
4839            manager.delete(*id).expect("fragment source");
4840        }
4841        let source = Arc::downgrade(&manager.sealed.read()[0]);
4842        let mut seen = Vec::new();
4843        let mut changed = false;
4844        let mut metadata_bytes = 0;
4845        assert!(manager.visit_graph_index_batches(GraphEntityKind::Edge, &[EntityId::new(2000)],
4846            || true,
4847            |bytes| { metadata_bytes += bytes; Ok::<_, ()>(()) },
4848            |batch| {
4849                assert!(batch.len() <= super::super::segment::SCAN_BATCH_SIZE);
4850                assert!(manager.growing.try_write().is_some(), "no growing topology guard");
4851                assert!(manager.sealed.try_write().is_some(), "no sealed topology guard");
4852                assert!(source.upgrade().expect("source pinned").try_write().is_some(), "no source guard");
4853                if !changed {
4854                    changed = true;
4855                    drain_maintenance(&manager);
4856                    assert!(manager.stats().consolidation.runs_completed > 0);
4857                    assert!(source.upgrade().is_some(), "retired cursor source remains pinned");
4858                    let mut updated = manager.get(EntityId::new(1024)).expect("future edge");
4859                    if let EntityKind::GraphEdge(edge) = &mut updated.kind { edge.weight = 2000; }
4860                    manager.update(updated).expect("update authoritative merged copy");
4861                }
4862                for id in batch {
4863                    let entity = manager.get(*id).expect("hydrate current manager");
4864                    if id.raw() == 1024 {
4865                        assert!(matches!(&entity.kind, EntityKind::GraphEdge(edge) if edge.weight == 2000));
4866                    }
4867                    seen.push(id.raw());
4868                }
4869                Ok(true)
4870            }).expect("cursor"));
4871        assert_eq!(seen, (301..=1024).collect::<Vec<_>>());
4872        assert!(
4873            source.upgrade().is_none(),
4874            "finished cursor releases retired source"
4875        );
4876        assert!(
4877            metadata_bytes < 4096,
4878            "fixed ID buffer plus source handles: {metadata_bytes}"
4879        );
4880    }
4881
4882    #[test]
4883    fn graph_index_batches_propagate_admission_and_cancel_before_partial_delivery() {
4884        let manager = SegmentManager::new("graph");
4885        manager
4886            .bulk_insert(
4887                (1..=1024)
4888                    .map(|id| {
4889                        UnifiedEntity::graph_edge(
4890                            EntityId::new(id),
4891                            "step",
4892                            "2000",
4893                            "3000",
4894                            1.0,
4895                            HashMap::new(),
4896                        )
4897                    })
4898                    .collect(),
4899            )
4900            .expect("edges");
4901        let mut delivered = 0;
4902        let denied = manager.visit_graph_index_batches(
4903            GraphEntityKind::Edge,
4904            &[EntityId::new(2000)],
4905            || true,
4906            |_| Err("out of memory"),
4907            |ids| {
4908                delivered += ids.len();
4909                Ok(true)
4910            },
4911        );
4912        assert_eq!(denied, Err("out of memory"));
4913        assert_eq!(delivered, 0);
4914        let mut work = 0;
4915        assert!(!manager
4916            .visit_graph_index_batches(
4917                GraphEntityKind::Edge,
4918                &[EntityId::new(2000)],
4919                || {
4920                    work += 1;
4921                    work < 100
4922                },
4923                |_| Ok::<_, ()>(()),
4924                |ids| {
4925                    delivered += ids.len();
4926                    Ok(true)
4927                }
4928            )
4929            .expect("cancelled cursor"));
4930        assert_eq!(
4931            delivered, 0,
4932            "cancelled partial batch cannot reach consumer"
4933        );
4934        assert!(!manager
4935            .visit_graph_index_batches(
4936                GraphEntityKind::Edge,
4937                &[EntityId::new(2000)],
4938                || true,
4939                |_| Ok::<_, ()>(()),
4940                |ids| {
4941                    delivered += ids.len();
4942                    Ok(false)
4943                }
4944            )
4945            .expect("consumer stop"));
4946        assert_eq!(delivered, super::super::segment::SCAN_BATCH_SIZE);
4947    }
4948
4949    #[test]
4950    fn retained_memory_tracks_two_readers_until_the_last_cursor_finishes() {
4951        let manager = consolidating_manager(CONSOLIDATION_ENTITIES_PER_TICK);
4952        let ids = seal_bulk_segment(&manager, 100);
4953        for id in ids.iter().take(40) {
4954            manager.delete(*id).expect("delete before scan");
4955        }
4956        let source_bytes = manager.resident_bytes();
4957        let source = Arc::downgrade(&manager.sealed.read()[0]);
4958        std::thread::scope(|scope| {
4959            let (ready, waiting) = std::sync::mpsc::channel();
4960            let (release_first, first_wait) = std::sync::mpsc::channel();
4961            let (release_last, last_wait) = std::sync::mpsc::channel();
4962            let reader = |resume: std::sync::mpsc::Receiver<()>,
4963                          ready: std::sync::mpsc::Sender<()>| {
4964                assert!(manager.scan_batches(
4965                    None,
4966                    || true,
4967                    |_| {
4968                        ready.send(()).expect("signal captured cursor");
4969                        let _ = resume.recv();
4970                        true
4971                    }
4972                ));
4973            };
4974            let ready_first = ready.clone();
4975            let first = scope.spawn(move || reader(first_wait, ready_first));
4976            let last = scope.spawn(move || reader(last_wait, ready));
4977            for _ in 0..2 {
4978                waiting
4979                    .recv_timeout(std::time::Duration::from_secs(10))
4980                    .expect("reader ready");
4981            }
4982            drain_maintenance(&manager);
4983            assert!(
4984                source.upgrade().is_some(),
4985                "both cursors pin the retired source"
4986            );
4987            let active_bytes = manager.sealed.read()[0].read().resident_bytes();
4988            let held = manager.resident_bytes();
4989            assert!(
4990                held >= active_bytes + source_bytes,
4991                "retired source remains resident"
4992            );
4993            release_first.send(()).expect("release first reader");
4994            first.join().expect("first reader");
4995            assert_eq!(
4996                manager.resident_bytes(),
4997                held,
4998                "one reader still pins the source"
4999            );
5000            release_last.send(()).expect("release last reader");
5001            last.join().expect("last reader");
5002            assert!(
5003                source.upgrade().is_none(),
5004                "accounting must not retain payloads"
5005            );
5006            assert_eq!(held - manager.resident_bytes(), source_bytes);
5007            assert_eq!(
5008                manager.stats().total_memory_bytes as u64,
5009                manager.resident_bytes()
5010            );
5011        });
5012    }
5013
5014    #[test]
5015    fn physical_cursor_tracks_individual_and_mixed_insertions() {
5016        for mode in 0..3 {
5017            let manager = SegmentManager::new("physical_rows");
5018            let row = |id| {
5019                UnifiedEntity::table_row(
5020                    EntityId::new(id),
5021                    "physical_rows",
5022                    id,
5023                    vec![Value::Integer(id as i64)],
5024                )
5025            };
5026            match mode {
5027                0 => {
5028                    for id in [10, 30, 20] {
5029                        manager.insert(row(id)).expect("individual row");
5030                    }
5031                }
5032                1 => {
5033                    manager.insert(row(10)).expect("individual prefix");
5034                    manager
5035                        .bulk_insert(vec![row(30), row(31)])
5036                        .expect("batch suffix");
5037                }
5038                _ => {
5039                    manager
5040                        .bulk_insert(vec![row(30), row(31)])
5041                        .expect("batch prefix");
5042                    manager.insert(row(10)).expect("individual suffix");
5043                }
5044            }
5045            let mut cursor = manager.physical_scan_cursor();
5046            let mut ids = Vec::new();
5047            for _ in 0..32 {
5048                if cursor.finished() {
5049                    break;
5050                }
5051                let mut work = 1;
5052                let batch = manager.physical_scan_batch(&mut cursor, &mut work);
5053                assert!(batch.len() <= 1);
5054                ids.extend(batch.into_iter().map(|id| id.raw()));
5055            }
5056            assert!(cursor.finished());
5057            ids.sort_unstable();
5058            assert_eq!(
5059                ids,
5060                if mode == 0 {
5061                    vec![10, 20, 30]
5062                } else {
5063                    vec![10, 30, 31]
5064                },
5065                "mode={mode}"
5066            );
5067        }
5068    }
5069
5070    fn growing_tombstones_fixture() -> SegmentManager {
5071        let manager = consolidating_manager(1);
5072        let ids = manager
5073            .bulk_insert(
5074                (0..64)
5075                    .map(|id| {
5076                        UnifiedEntity::table_row(
5077                            manager.next_entity_id(),
5078                            "users",
5079                            id,
5080                            vec![Value::Blob(vec![7; 2048])],
5081                        )
5082                    })
5083                    .collect(),
5084            )
5085            .expect("growing rows");
5086        for id in ids.iter().take(48) {
5087            manager.delete(*id).expect("physical tombstone");
5088        }
5089        assert_eq!(manager.stats().sealed_count, 0);
5090        manager
5091    }
5092
5093    #[test]
5094    fn pressure_consolidation_reclaims_unsealed_tombstones() {
5095        let manager = growing_tombstones_fixture();
5096        let before = manager.resident_bytes();
5097        assert!(manager.reclaimable_bytes() > 0);
5098        assert!(manager.pressure_consolidation_tick());
5099        drain_maintenance(&manager);
5100        assert_eq!(live_ids(&manager), (49..=64).collect::<Vec<_>>());
5101        assert!(manager.resident_bytes() < before);
5102        assert_eq!(manager.stats().consolidation.tombstones_reclaimed, 48);
5103    }
5104
5105    #[test]
5106    fn pressure_consolidation_preserves_pinned_growing_source_accounting() {
5107        let manager = growing_tombstones_fixture();
5108        let source = Arc::clone(manager.growing.read().as_ref().expect("growing source"));
5109        let weak = Arc::downgrade(&source);
5110        assert!(manager.pressure_consolidation_tick());
5111        drain_maintenance(&manager);
5112        assert_eq!(live_ids(&manager), (49..=64).collect::<Vec<_>>());
5113        let source_bytes = source.read().resident_bytes();
5114        let held = manager.resident_bytes();
5115        assert!(held >= source_bytes);
5116        drop(source);
5117        assert!(weak.upgrade().is_none());
5118        assert_eq!(held - manager.resident_bytes(), source_bytes);
5119    }
5120
5121    #[test]
5122    fn pressure_consolidation_keeps_clean_and_disabled_growing_sources_open() {
5123        let clean = consolidating_manager(1);
5124        clean
5125            .insert(UnifiedEntity::table_row(
5126                clean.next_entity_id(),
5127                "users",
5128                1,
5129                vec![Value::Integer(1)],
5130            ))
5131            .expect("clean row");
5132        assert!(!clean.pressure_consolidation_tick());
5133        assert_eq!(clean.stats().sealed_count, 0);
5134        let mut disabled = growing_tombstones_fixture();
5135        disabled.config.enable_consolidation = false;
5136        assert!(!disabled.pressure_consolidation_tick());
5137        assert_eq!(disabled.stats().sealed_count, 0);
5138        assert_eq!(live_ids(&disabled), (49..=64).collect::<Vec<_>>());
5139    }
5140
5141    #[test]
5142    fn retained_memory_includes_an_inflight_consolidation_copy() {
5143        let manager = consolidating_manager(1);
5144        let ids = seal_bulk_segment(&manager, 100);
5145        for id in ids.iter().take(40) {
5146            manager.delete(*id).expect("delete");
5147        }
5148        let before = manager.resident_bytes();
5149        assert!(manager.pressure_consolidation_tick());
5150        let copied = manager
5151            .consolidation
5152            .read()
5153            .as_ref()
5154            .expect("paced merge")
5155            .merged
5156            .resident_bytes();
5157        assert!(copied > 0);
5158        assert!(
5159            manager.resident_bytes() >= before + copied,
5160            "unpublished copy consumes memory"
5161        );
5162        drain_maintenance(&manager);
5163        assert!(
5164            manager.resident_bytes() < before,
5165            "completed merge releases the old storage"
5166        );
5167    }
5168
5169    #[test]
5170    fn delete_heavy_workload_reclaims_tombstoned_memory_and_counts_it() {
5171        let manager = consolidating_manager(CONSOLIDATION_ENTITIES_PER_TICK);
5172        let ids = seal_bulk_segment(&manager, 100);
5173
5174        let bytes_before_delete = manager.resident_bytes();
5175
5176        // 40% tombstones — past CONSOLIDATION_TOMBSTONE_RATIO.
5177        for id in ids.iter().take(40) {
5178            assert!(manager.delete(*id).expect("delete"));
5179        }
5180
5181        // Tombstones cost memory: the payload stays resident in flat storage
5182        // and the tombstone set grows.
5183        let bytes_with_tombstones = manager.resident_bytes();
5184        assert!(bytes_with_tombstones > bytes_before_delete);
5185
5186        let survivors = live_ids(&manager);
5187        assert_eq!(survivors.len(), 60);
5188
5189        drain_maintenance(&manager);
5190
5191        let stats = manager.stats();
5192        assert_eq!(stats.consolidation.runs_started, 1);
5193        assert_eq!(stats.consolidation.runs_completed, 1);
5194        assert_eq!(stats.consolidation.segments_merged, 1);
5195        assert_eq!(stats.consolidation.tombstones_reclaimed, 40);
5196        assert!(stats.consolidation.bytes_reclaimed > 0);
5197
5198        // The reclaimed memory is at least the tombstoned entities' share.
5199        let bytes_after = manager.resident_bytes();
5200        assert!(
5201            bytes_after <= bytes_before_delete,
5202            "consolidation must return the tombstones' memory: {bytes_after} > {bytes_before_delete}"
5203        );
5204        assert_eq!(
5205            bytes_with_tombstones - bytes_after,
5206            stats.consolidation.bytes_reclaimed
5207        );
5208        assert_eq!(stats.total_memory_bytes, bytes_after as usize);
5209
5210        assert_eq!(live_ids(&manager), survivors);
5211        assert_eq!(manager.sealed.read().len(), 1);
5212        assert_eq!(manager.sealed.read()[0].read().tombstone_count(), 0);
5213    }
5214
5215    #[test]
5216    fn query_results_are_identical_before_during_and_after_consolidation() {
5217        let manager = consolidating_manager(3);
5218        let ids = seal_bulk_segment(&manager, 20);
5219        seal_bulk_segment(&manager, 20);
5220        for id in ids.iter().take(10) {
5221            assert!(manager.delete(*id).expect("delete"));
5222        }
5223
5224        let before = live_ids(&manager);
5225        let survivor = *ids.last().expect("at least one row");
5226        let tombstoned = ids[0];
5227
5228        // Every mid-tick observation matches the pre-consolidation snapshot:
5229        // point reads, full scans, and the kind index (rebuilt by the merge).
5230        let mut mid_tick_observations = 0;
5231        while manager.consolidation.read().is_some() || mid_tick_observations == 0 {
5232            manager.run_maintenance().expect("maintenance");
5233            assert_eq!(live_ids(&manager), before);
5234            assert!(manager.get(survivor).is_some());
5235            assert!(manager.get(tombstoned).is_none());
5236            assert_eq!(manager.get_by_kind("table").len(), before.len());
5237            mid_tick_observations += 1;
5238            assert!(mid_tick_observations < 1_000);
5239        }
5240
5241        assert!(
5242            mid_tick_observations > 2,
5243            "expected the run to span several ticks, saw {mid_tick_observations}"
5244        );
5245        assert_eq!(live_ids(&manager), before);
5246        assert!(manager.get(survivor).is_some());
5247        assert!(manager.get(tombstoned).is_none());
5248        assert_eq!(manager.get_by_kind("table").len(), before.len());
5249    }
5250
5251    #[test]
5252    fn get_by_kind_reaches_sealed_segments() {
5253        let manager = consolidating_manager(CONSOLIDATION_ENTITIES_PER_TICK);
5254        let ids = seal_bulk_segment(&manager, 5);
5255        assert!(manager.delete(ids[0]).expect("delete"));
5256
5257        // The sealed list is walked through the segment read guard; the
5258        // `Arc<RwLock<GrowingSegment>>` impl of `iter_kind` cannot hand out
5259        // references across the lock and yields nothing.
5260        assert_eq!(manager.get_by_kind("table").len(), 4);
5261        assert_eq!(manager.get_by_kind("vector").len(), 0);
5262    }
5263
5264    #[test]
5265    fn consolidation_is_paced_by_the_per_tick_entity_bound() {
5266        const PER_TICK: usize = 4;
5267        let manager = consolidating_manager(PER_TICK);
5268        let ids = seal_bulk_segment(&manager, 60);
5269        for id in ids.iter().take(30) {
5270            assert!(manager.delete(*id).expect("delete"));
5271        }
5272
5273        // First tick opens the run and copies exactly one bound's worth.
5274        manager.run_maintenance().expect("maintenance");
5275        assert_eq!(manager.consolidation_progress(), Some(PER_TICK as u64));
5276
5277        // Each subsequent tick advances by no more than the bound, and the run
5278        // is still in flight — it never completes in one unbounded pass.
5279        let mut previous = PER_TICK as u64;
5280        let mut ticks = 1;
5281        while let Some(copied) = manager.consolidation_progress() {
5282            assert!(
5283                copied - previous <= PER_TICK as u64,
5284                "tick copied {} entities, bound is {PER_TICK}",
5285                copied - previous
5286            );
5287            previous = copied;
5288            manager.run_maintenance().expect("maintenance");
5289            ticks += 1;
5290            assert!(ticks < 100);
5291        }
5292
5293        // 30 survivors at 4 per tick: the run cannot have finished before the
5294        // eighth tick.
5295        assert!(ticks >= 8, "consolidation completed in only {ticks} ticks");
5296        assert_eq!(manager.stats().consolidation.runs_completed, 1);
5297        assert_eq!(live_ids(&manager).len(), 30);
5298    }
5299
5300    #[test]
5301    fn sealed_segment_count_above_the_limit_triggers_a_merge() {
5302        let manager = SegmentManager::with_config(
5303            "test",
5304            ManagerConfig {
5305                max_sealed_segments: 3,
5306                ..Default::default()
5307            },
5308        );
5309        for _ in 0..4 {
5310            seal_bulk_segment(&manager, 5);
5311        }
5312        assert_eq!(manager.sealed.read().len(), 4);
5313
5314        let before = live_ids(&manager);
5315        drain_maintenance(&manager);
5316
5317        // The knob finally does what it claimed: the sealed set collapses even
5318        // though not a single row was deleted.
5319        assert_eq!(manager.sealed.read().len(), 1);
5320        assert_eq!(manager.stats().consolidation.segments_merged, 4);
5321        assert_eq!(manager.stats().consolidation.tombstones_reclaimed, 0);
5322        assert_eq!(live_ids(&manager), before);
5323    }
5324
5325    #[test]
5326    fn a_clean_sealed_set_below_the_limit_is_never_consolidated() {
5327        let manager = consolidating_manager(CONSOLIDATION_ENTITIES_PER_TICK);
5328        seal_bulk_segment(&manager, 10);
5329        seal_bulk_segment(&manager, 10);
5330
5331        for _ in 0..5 {
5332            manager.run_maintenance().expect("maintenance");
5333        }
5334
5335        assert_eq!(manager.stats().consolidation.runs_started, 0);
5336        assert_eq!(manager.sealed.read().len(), 2);
5337    }
5338
5339    #[test]
5340    fn concurrent_readers_never_observe_a_missing_or_duplicated_entity() {
5341        use std::sync::atomic::AtomicBool;
5342
5343        let manager = Arc::new(consolidating_manager(2));
5344        let ids = seal_bulk_segment(&manager, 40);
5345        seal_bulk_segment(&manager, 40);
5346        for id in ids.iter().take(20) {
5347            assert!(manager.delete(*id).expect("delete"));
5348        }
5349
5350        let expected = live_ids(&manager);
5351        let stop = Arc::new(AtomicBool::new(false));
5352
5353        let readers: Vec<_> = (0..4)
5354            .map(|_| {
5355                let manager = Arc::clone(&manager);
5356                let stop = Arc::clone(&stop);
5357                let expected = expected.clone();
5358                std::thread::spawn(move || {
5359                    let mut scans = 0u64;
5360                    // Do-while: every reader scans at least once even when the
5361                    // drain finishes before this thread is first scheduled.
5362                    loop {
5363                        let mut seen: Vec<u64> = manager
5364                            .query_all(|_| true)
5365                            .into_iter()
5366                            .map(|entity| entity.id.raw())
5367                            .collect();
5368                        seen.sort_unstable();
5369                        // Sorting is not enough: a duplicated row would keep
5370                        // the set equal but change the length.
5371                        assert_eq!(seen, expected, "reader saw a torn sealed set");
5372                        scans += 1;
5373                        if stop.load(Ordering::Relaxed) {
5374                            break;
5375                        }
5376                    }
5377                    scans
5378                })
5379            })
5380            .collect();
5381
5382        drain_maintenance(&manager);
5383        stop.store(true, Ordering::Relaxed);
5384
5385        for reader in readers {
5386            let scans = reader.join().expect("reader thread");
5387            assert!(scans > 0, "reader never got to scan");
5388        }
5389
5390        assert_eq!(manager.stats().consolidation.runs_completed, 1);
5391        assert_eq!(live_ids(&manager), expected);
5392    }
5393
5394    #[test]
5395    fn a_row_deleted_mid_consolidation_is_not_resurrected_by_the_swap() {
5396        let manager = consolidating_manager(4);
5397        let ids = seal_bulk_segment(&manager, 20);
5398        for id in ids.iter().take(6) {
5399            assert!(manager.delete(*id).expect("delete"));
5400        }
5401
5402        // Copy the first bound's worth, then delete a row we just copied.
5403        manager.run_maintenance().expect("maintenance");
5404        assert_eq!(manager.consolidation_progress(), Some(4));
5405        let doomed = ids[6];
5406        assert!(manager.delete(doomed).expect("delete"));
5407
5408        let expected = live_ids(&manager);
5409        drain_maintenance(&manager);
5410
5411        assert!(manager.get(doomed).is_none(), "deleted row came back");
5412        assert_eq!(live_ids(&manager), expected);
5413    }
5414
5415    #[test]
5416    fn discarding_an_in_flight_consolidation_leaves_the_data_untouched() {
5417        let manager = consolidating_manager(3);
5418        let ids = seal_bulk_segment(&manager, 30);
5419        for id in ids.iter().take(12) {
5420            assert!(manager.delete(*id).expect("delete"));
5421        }
5422
5423        let before = live_ids(&manager);
5424        let sealed_before: Vec<SegmentId> = manager
5425            .sealed
5426            .read()
5427            .iter()
5428            .map(|segment| segment.read().id())
5429            .collect();
5430
5431        manager.run_maintenance().expect("maintenance");
5432        manager.run_maintenance().expect("maintenance");
5433        assert!(manager.consolidation.read().is_some());
5434
5435        // A crash between ticks drops the half-built merged segment. Sealed
5436        // segments are the durable truth, so nothing was lost — and the run is
5437        // simply started over.
5438        *manager.consolidation.write() = None;
5439
5440        assert_eq!(live_ids(&manager), before);
5441        let sealed_after: Vec<SegmentId> = manager
5442            .sealed
5443            .read()
5444            .iter()
5445            .map(|segment| segment.read().id())
5446            .collect();
5447        assert_eq!(sealed_after, sealed_before);
5448        assert_eq!(manager.stats().consolidation.runs_completed, 0);
5449
5450        drain_maintenance(&manager);
5451        assert_eq!(live_ids(&manager), before);
5452        assert_eq!(manager.stats().consolidation.runs_completed, 1);
5453    }
5454
5455    #[test]
5456    fn consolidation_preserves_entity_payload_metadata_and_sequence() {
5457        let manager = consolidating_manager(CONSOLIDATION_ENTITIES_PER_TICK);
5458
5459        // Metadata must be attached before the seal: `set_metadata` on a sealed
5460        // row rewrites it into the growing segment, which would take it out of
5461        // the segment under test.
5462        let entities: Vec<UnifiedEntity> = (0..10)
5463            .map(|i| {
5464                UnifiedEntity::table_row(
5465                    manager.next_entity_id(),
5466                    "users",
5467                    i as u64,
5468                    vec![Value::Integer(i as i64)],
5469                )
5470            })
5471            .collect();
5472        let ids = manager.bulk_insert(entities).expect("bulk insert");
5473
5474        let mut meta = Metadata::new();
5475        meta.set(
5476            "os",
5477            super::super::metadata::MetadataValue::String("linux".to_string()),
5478        );
5479        manager.set_metadata(ids[9], meta).expect("set metadata");
5480        manager.force_seal().expect("seal");
5481
5482        assert!(manager.delete(ids[0]).expect("delete"));
5483        assert!(manager.delete(ids[1]).expect("delete"));
5484        assert!(manager.delete(ids[2]).expect("delete"));
5485
5486        let before: Vec<UnifiedEntity> = {
5487            let mut entities = manager.query_all(|_| true);
5488            entities.sort_by_key(|entity| entity.id.raw());
5489            entities
5490        };
5491
5492        drain_maintenance(&manager);
5493
5494        let after: Vec<UnifiedEntity> = {
5495            let mut entities = manager.query_all(|_| true);
5496            entities.sort_by_key(|entity| entity.id.raw());
5497            entities
5498        };
5499
5500        let columns = |entity: &UnifiedEntity| match &entity.data {
5501            super::super::entity::EntityData::Row(row) => row.columns.clone(),
5502            _ => Vec::new(),
5503        };
5504
5505        assert_eq!(before.len(), after.len());
5506        for (old, new) in before.iter().zip(after.iter()) {
5507            assert_eq!(old.id, new.id);
5508            assert_eq!(columns(old), columns(new));
5509            assert_eq!(
5510                old.sequence_id, new.sequence_id,
5511                "merge must not re-issue sequence ids"
5512            );
5513        }
5514        assert!(manager
5515            .get_metadata(ids[9])
5516            .expect("metadata survives the merge")
5517            .has("os"));
5518    }
5519}