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