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