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