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