Skip to main content

reddb_engine/storage/manager/
backing.rs

1//! Disk-backed collection state. Publication remains a host-owned write fence.
2
3use super::*;
4use crate::storage::collection_read::{
5    CollectionCursor, CollectionRead, FrozenOverlay, MergedCollection,
6};
7use crate::storage::error::StoreError;
8use crate::storage::metadata_codec::serialize_entity_record;
9use std::collections::HashSet;
10
11/// How long an in-place append waits for base readers that are merely busy.
12const UNSHARED_BACKING_WAIT: std::time::Duration = std::time::Duration::from_millis(50);
13/// A scan of the base holds it for as long as the collection is large, and the
14/// alternative to waiting for it is to publish every one of those rows again,
15/// at several times a scan's cost per row. So the wait grows with the rows at
16/// stake, up to a bound a caller holding a publication fence can afford.
17const UNSHARED_BACKING_WAIT_PER_ROW: std::time::Duration = std::time::Duration::from_micros(25);
18const UNSHARED_BACKING_WAIT_MAX: std::time::Duration = std::time::Duration::from_secs(3);
19
20pub(super) struct BackingRead {
21    pub source: Arc<dyn CollectionRead + Send + Sync>,
22    pub root_page: u32,
23    pub total_entities: u64,
24    pub format_version: u32,
25    pub read_bytes_max: usize,
26    pub removed: HashSet<EntityId>,
27    // Bounded subset of tombstones whose physical delete was appended to the WAL.
28    logged_removals: HashSet<EntityId>,
29}
30
31/// A cold collection with no resident changes at the checkpoint boundary.
32pub struct CleanBackingCut {
33    source: Arc<dyn CollectionRead + Send + Sync>,
34    physical_count: u64,
35}
36
37impl CleanBackingCut {
38    fn matches(&self, base: &BackingRead, root: u32, format: u32, read_limit: usize) -> bool {
39        Arc::ptr_eq(&base.source, &self.source)
40            && base.root_page == root
41            && base.format_version == format
42            && base.read_bytes_max == read_limit
43            && base.total_entities == self.physical_count
44    }
45}
46
47/// Frozen base/overlay cursor for a lazy query source. The source generation
48/// remains pinned through the owned page cursor, not a manager topology lock.
49pub struct PagedEntityCursor {
50    cursor: Box<dyn CollectionCursor>,
51    format_version: u32,
52    read_bytes_max: usize,
53    snapshot: Option<SnapshotContext>,
54    visible_only: bool,
55    schema: Option<Arc<Vec<String>>>,
56    key: Option<String>,
57    finished: bool,
58}
59
60impl Iterator for PagedEntityCursor {
61    type Item = Result<(UnifiedEntity, Option<Metadata>), StoreError>;
62    fn next(&mut self) -> Option<Self::Item> {
63        if self.finished {
64            return None;
65        }
66        loop {
67            let record = match self.cursor.next_record(self.read_bytes_max) {
68                Ok(Some(record)) => record,
69                Ok(None) => {
70                    self.finished = true;
71                    return None;
72                }
73                Err(error) => {
74                    self.finished = true;
75                    return Some(Err(error));
76                }
77            };
78            let (mut entity, metadata) =
79                match record.decode_with_budget(self.format_version, self.read_bytes_max) {
80                    Ok(record) => record,
81                    Err(error) => {
82                        self.finished = true;
83                        return Some(Err(error));
84                    }
85                };
86            if self.visible_only
87                && !SegmentManager::scan_entity_visible(self.snapshot.as_ref(), &entity)
88            {
89                continue;
90            }
91            if let super::super::entity::EntityData::Row(row) = &mut entity.data {
92                if row.named.is_none() && row.schema.is_none() {
93                    row.schema = self.schema.clone();
94                }
95            }
96            if self.key.as_deref().is_some_and(|key| {
97                crate::storage::segment_key_lookup::SegmentKeyLookup::key(&entity) != Some(key)
98            }) {
99                continue;
100            }
101            return Some(Ok((entity, metadata)));
102        }
103    }
104}
105
106impl SegmentManager {
107    /// Visit the physical base and resident replacements without an ID-order
108    /// workspace. This is for order-independent metadata reductions, not SQL
109    /// ordering. The host must fence writers throughout this reduction so a
110    /// materialized base row cannot be counted twice. Callbacks must not mutate
111    /// or re-enter this collection.
112    pub fn try_for_each_entity_unordered(
113        &self,
114        limit_bytes: usize,
115        mut callback: impl FnMut(&UnifiedEntity) -> bool,
116    ) -> Result<(), StoreError> {
117        let backing_guard = self.backing.read();
118        let Some(backing) = backing_guard.as_ref() else {
119            self.for_each_entity(callback);
120            return Ok(());
121        };
122        let limit_bytes = limit_bytes.min(backing.read_bytes_max);
123        let mut cursor = backing.source.cursor()?;
124        while let Some(id) = cursor.peek_id()? {
125            if backing.removed.contains(&id) || self.get_with(id, |_| ()).is_some() {
126                cursor.skip_record()?;
127                continue;
128            }
129            let record = cursor
130                .next_record(limit_bytes)?
131                .expect("invariant: peeked physical row exists");
132            let (mut entity, _) = record.decode_with_budget(backing.format_version, limit_bytes)?;
133            self.restore_owned_row_schemas(std::iter::once(&mut entity));
134            if !callback(&entity) {
135                return Ok(());
136            }
137        }
138        let mut result = Ok(());
139        self.for_each_entity(|entity| {
140            let required_bytes = crate::storage::memory_size::entity_bytes(entity);
141            if required_bytes > limit_bytes {
142                result = Err(StoreError::ReadLimitExceeded {
143                    required_bytes,
144                    limit_bytes,
145                });
146                return false;
147            }
148            callback(entity)
149        });
150        result
151    }
152
153    /// The host must fence publication while capturing the base and overlay.
154    /// This retains O(dirty overlay) state and decodes at most one base row.
155    pub fn try_paged_entity_cursor(
156        &self,
157        snapshot: Option<SnapshotContext>,
158    ) -> Result<Option<PagedEntityCursor>, StoreError> {
159        self.try_paged_cursor(snapshot, true, None)
160    }
161
162    /// Raw physical records and their frozen metadata, including superseded
163    /// versions. Hosts fence publication while capturing this cursor.
164    pub fn try_paged_physical_cursor(&self) -> Result<Option<PagedEntityCursor>, StoreError> {
165        self.try_paged_cursor(None, false, None)
166    }
167
168    /// Freeze only this key's payloads and metadata, retaining other dirty IDs
169    /// as masks. Every decoded candidate is checked against the logical key.
170    pub fn try_paged_key_entity_cursor(
171        &self,
172        key: &str,
173        snapshot: Option<SnapshotContext>,
174    ) -> Result<Option<PagedEntityCursor>, StoreError> {
175        self.try_paged_cursor(snapshot, true, Some(key))
176    }
177
178    /// Like the visible keyed cursor, but includes superseded physical history.
179    pub fn try_paged_key_physical_cursor(
180        &self,
181        key: &str,
182    ) -> Result<Option<PagedEntityCursor>, StoreError> {
183        self.try_paged_cursor(None, false, Some(key))
184    }
185
186    fn try_paged_cursor(
187        &self,
188        snapshot: Option<SnapshotContext>,
189        visible_only: bool,
190        key: Option<&str>,
191    ) -> Result<Option<PagedEntityCursor>, StoreError> {
192        let Some((format_version, read_bytes_max)) = self
193            .backing
194            .read()
195            .as_ref()
196            .map(|base| (base.format_version, base.read_bytes_max))
197        else {
198            return Ok(None);
199        };
200        let view = match key {
201            Some(key) => self.current_backing_key_overlay(key)?,
202            None => self.current_backing_overlay(),
203        };
204        let Some((base, overlay)) = view else {
205            return Ok(None);
206        };
207        let merged = MergedCollection::new(base.as_ref(), overlay);
208        let cursor = match key {
209            Some(key) => match merged.owned_key_cursor(key)? {
210                Some(cursor) => cursor,
211                None => merged.owned_cursor()?,
212            },
213            None => merged.owned_cursor()?,
214        };
215        Ok(Some(PagedEntityCursor {
216            cursor,
217            format_version,
218            read_bytes_max,
219            snapshot,
220            visible_only,
221            schema: self.column_schema(),
222            key: key.map(str::to_owned),
223            finished: false,
224        }))
225    }
226
227    pub fn has_backing(&self) -> bool {
228        self.backing.read().is_some()
229    }
230
231    /// Identity of the immutable base currently installed by the host.
232    pub fn backing_root_page(&self) -> Option<u32> {
233        self.backing.read().as_ref().map(|base| base.root_page)
234    }
235
236    /// The host applies the same row allowance to model-specific expansion
237    /// such as decrypting a compressed Vault value after native record decode.
238    pub fn backing_read_bytes_max(&self) -> Option<usize> {
239        self.backing
240            .read()
241            .as_ref()
242            .map(|backing| backing.read_bytes_max)
243    }
244
245    /// Capture under the host write fence. Pinning the source also excludes
246    /// in-place modifications to the base until the decision to retain it.
247    pub fn clean_backing_cut(&self) -> Option<CleanBackingCut> {
248        let guard = self.backing.read();
249        let base = guard.as_ref()?;
250        (base.removed.is_empty()
251            && base.logged_removals.is_empty()
252            && base.total_entities == self.count() as u64
253            && self.consolidation.read().is_none()
254            && self.growing.read().is_none()
255            && self.sealed.read().is_empty())
256        .then(|| CleanBackingCut {
257            source: Arc::clone(&base.source),
258            physical_count: base.total_entities,
259        })
260    }
261
262    /// Install the checkpoint projection under the host write fence. Return
263    /// the installed segment revisions, or None when the captured base is still
264    /// current and the caller must retain its original revision boundary.
265    pub fn publish_checkpoint_backing<
266        P: crate::storage::page_store::PageStore + Send + Sync + 'static,
267    >(
268        &self,
269        cut: Option<&CleanBackingCut>,
270        source: crate::storage::collection_read::PagedCollection<P>,
271        root_page: u32,
272        format_version: u32,
273        read_bytes_max: usize,
274    ) -> Option<Vec<(u64, u64)>> {
275        if let Some(cut) = cut {
276            let backing = self.backing.read();
277            if backing
278                .as_ref()
279                .is_some_and(|base| cut.matches(base, root_page, format_version, read_bytes_max))
280                && source.shares_primary_with(cut.source.as_ref())
281            {
282                if source.shares_trees_with(cut.source.as_ref()) {
283                    return None;
284                }
285                // Only the lookup tree changed. Writers are fenced by the host,
286                // so releasing the shared guard here cannot replace the base.
287                drop(backing);
288                self.backing
289                    .write()
290                    .as_mut()
291                    .expect("fenced checkpoint base")
292                    .source = Arc::new(source);
293                return None;
294            }
295        }
296        self.install_paged_backing(
297            source,
298            root_page,
299            format_version,
300            read_bytes_max,
301            self.count() as u64,
302        );
303        Some(self.checkpoint_revisions())
304    }
305
306    /// Install a published base under the host's write fence. An untouched cold
307    /// table can keep serving base readers without taking the exclusive lock.
308    pub fn install_paged_backing<
309        P: crate::storage::page_store::PageStore + Send + Sync + 'static,
310    >(
311        &self,
312        source: crate::storage::collection_read::PagedCollection<P>,
313        root_page: u32,
314        format_version: u32,
315        read_bytes_max: usize,
316        total_entities: u64,
317    ) {
318        if self.backing.read().as_ref().is_some_and(|base| {
319            base.root_page == root_page
320                && base.format_version == format_version
321                && base.read_bytes_max == read_bytes_max
322                && base.total_entities == total_entities
323                && base.removed.is_empty()
324                && base.logged_removals.is_empty()
325                && source.shares_trees_with(base.source.as_ref())
326                && self.consolidation.read().is_none()
327                && self.growing.read().is_none()
328                && self.sealed.read().is_empty()
329        }) {
330            return;
331        }
332        self.install_backing(
333            Arc::new(source),
334            root_page,
335            format_version,
336            read_bytes_max,
337            total_entities,
338        );
339    }
340
341    /// The host must fence writers and publish the new durable tree first.
342    /// Captured resident readers retain their old sources through weak tracking.
343    pub fn install_backing(
344        &self,
345        source: Arc<dyn CollectionRead + Send + Sync>,
346        root_page: u32,
347        format_version: u32,
348        read_bytes_max: usize,
349        total_entities: u64,
350    ) {
351        let mut backing = self.backing.write();
352        let mut consolidation = self.consolidation.write();
353        let mut growing = self.growing.write();
354        let mut sealed = self.sealed.write();
355        let mut retired = self.retired.write();
356        if let Some(source) = growing.take() {
357            self.restore_sequence_id_next(source.read().sequence_id_next());
358            retired.push(Arc::downgrade(&source));
359        }
360        for source in sealed.drain(..) {
361            self.restore_sequence_id_next(source.read().sequence_id_next());
362            retired.push(Arc::downgrade(&source));
363        }
364        *consolidation = None;
365        self.entity_segment.write().clear();
366        self.total_entities_atomic
367            .store(total_entities, Ordering::Relaxed);
368        *backing = Some(BackingRead {
369            source,
370            root_page,
371            total_entities,
372            format_version,
373            read_bytes_max,
374            removed: HashSet::new(),
375            logged_removals: HashSet::new(),
376        });
377        self.unconfirmed_removals.lock().clear();
378    }
379
380    /// Fence acquisition of new base readers while a host checks all native
381    /// cursor/tree pins and applies WAL-protected inserts. The source must have
382    /// no strong or weak owners outside this manager. The host still owns the
383    /// mutation/publication fence and must not re-enter backing methods here.
384    /// A successful projection updates the root and its exact physical count.
385    ///
386    /// The host calls this inside the pager's ownership epoch. A base reader
387    /// loads its pages without waiting for that epoch, so the bounded wait
388    /// here outlasts a read in progress, and a scan of a collection in
389    /// proportion to its size; a base that stays in use longer is declined
390    /// like any other reader pin.
391    #[doc(hidden)]
392    pub fn try_with_unshared_backing<T>(
393        &self,
394        root_page: u32,
395        update: impl FnOnce() -> (T, Option<(u32, u64)>),
396    ) -> Option<T> {
397        self.try_with_unshared_backing_delta(root_page, 0, |_| update())
398    }
399
400    /// Under the host's publication fence, allow a bounded set of WAL-confirmed
401    /// physical deletes alongside the resident changes. Unlogged removes and
402    /// borrowed generations require immutable replacement.
403    #[doc(hidden)]
404    pub fn try_with_unshared_backing_delta<T>(
405        &self,
406        root_page: u32,
407        max_removals: usize,
408        update: impl FnOnce(&HashSet<EntityId>) -> (T, Option<(u32, u64)>),
409    ) -> Option<T> {
410        self.try_with_unshared_backing_source_delta(root_page, max_removals, |_, removed| {
411            update(removed)
412        })
413    }
414
415    /// Check derived tree identity while the unique backing source is fenced.
416    #[doc(hidden)]
417    pub fn try_with_unshared_backing_source_delta<T>(
418        &self,
419        root_page: u32,
420        max_removals: usize,
421        update: impl FnOnce(&dyn CollectionRead, &HashSet<EntityId>) -> (T, Option<(u32, u64)>),
422    ) -> Option<T> {
423        let rows = u32::try_from(self.count()).unwrap_or(u32::MAX);
424        let wait = UNSHARED_BACKING_WAIT_PER_ROW
425            .saturating_mul(rows)
426            .clamp(UNSHARED_BACKING_WAIT, UNSHARED_BACKING_WAIT_MAX);
427        let mut backing = self.backing.try_write_for(wait)?;
428        let backing = backing.as_mut()?;
429        self.fold_unconfirmed_removals(backing);
430        if backing.root_page != root_page
431            || backing.removed.len() > max_removals
432            || backing.removed.len() != backing.logged_removals.len()
433            || Arc::get_mut(&mut backing.source).is_none()
434        {
435            return None;
436        }
437        let (result, published) = update(backing.source.as_ref(), &backing.removed);
438        if let Some((root_page, total_entities)) = published {
439            backing.root_page = root_page;
440            backing.total_entities = total_entities;
441            backing.removed.clear();
442            backing.logged_removals.clear();
443            self.unconfirmed_removals.lock().clear();
444        }
445        Some(result)
446    }
447
448    /// Why `try_with_unshared_backing_source_delta` declined, for the host's
449    /// log. The host still holds its publication fence, so the answer is the
450    /// one that call saw unless a reader left in between.
451    #[doc(hidden)]
452    pub fn backing_delta_refusal(&self, root_page: u32, max_removals: usize) -> &'static str {
453        let Some(mut backing) = self.backing.try_write_for(UNSHARED_BACKING_WAIT) else {
454            return "a reader holds the backing lock";
455        };
456        let Some(backing) = backing.as_mut() else {
457            return "the collection has no backing";
458        };
459        if backing.root_page != root_page {
460            "the backing was published from another root"
461        } else if backing.removed.len() > max_removals {
462            "more rows were removed than one delta takes"
463        } else if backing.removed.len() != backing.logged_removals.len() {
464            "rows were removed without a WAL record"
465        } else if Arc::get_mut(&mut backing.source).is_none() {
466            "a reader holds the backing source"
467        } else {
468            "a reader held the backing and has left"
469        }
470    }
471
472    pub fn backing_count_at_root(&self, root_page: u32) -> Option<u64> {
473        self.backing
474            .read()
475            .as_ref()
476            .filter(|base| base.root_page == root_page)
477            .map(|base| base.total_entities)
478    }
479
480    /// Reconcile a verified physical count while a recovered store is still
481    /// exclusively owned and has not been made available to readers.
482    #[doc(hidden)]
483    pub fn set_recovered_backing_count(&self, root_page: u32, count: u64) -> bool {
484        let mut backing = self.backing.write();
485        let Some(backing) = backing.as_mut() else {
486            return false;
487        };
488        if backing.root_page != root_page {
489            return false;
490        }
491        backing.total_entities = count;
492        true
493    }
494
495    /// Whether a projected base posting has been replaced or physically
496    /// removed. The host must fence publication/mutations while merging the
497    /// projected base with resident rows. This never reads a base payload.
498    pub fn backing_row_is_shadowed(&self, id: EntityId) -> bool {
499        let backing = self.backing.read();
500        backing
501            .as_ref()
502            .is_none_or(|base| base.removed.contains(&id))
503            || self.get_with(id, |_| ()).is_some()
504    }
505
506    /// The rows the published base still lists that have been physically
507    /// removed since it was published.
508    pub fn backing_removed_rows(&self) -> Vec<EntityId> {
509        self.backing
510            .read()
511            .as_ref()
512            .map(|base| base.removed.iter().copied().collect())
513            .unwrap_or_default()
514    }
515
516    pub fn checkpoint_backing_view(
517        &self,
518        max_removed: usize,
519    ) -> Option<(Option<Arc<dyn CollectionRead + Send + Sync>>, Vec<EntityId>)> {
520        let guard = self.backing.read();
521        let Some(base) = guard.as_ref() else {
522            return Some((None, Vec::new()));
523        };
524        (base.removed.len() <= max_removed).then(|| {
525            (
526                Some(Arc::clone(&base.source)),
527                base.removed.iter().copied().collect(),
528            )
529        })
530    }
531
532    /// Preserve I/O and decode failures instead of treating them as absent rows.
533    pub fn try_get(
534        &self,
535        id: EntityId,
536        limit_bytes: usize,
537    ) -> Result<Option<UnifiedEntity>, StoreError> {
538        let backing = self.backing.read();
539        let limit_bytes = backing
540            .as_ref()
541            .map_or(limit_bytes, |base| limit_bytes.min(base.read_bytes_max));
542        if let Some(result) = self.get_with(id, |entity| {
543            let required_bytes = if limit_bytes == usize::MAX {
544                0
545            } else {
546                crate::storage::memory_size::entity_bytes(entity)
547            };
548            if required_bytes > limit_bytes {
549                Err(StoreError::ReadLimitExceeded {
550                    required_bytes,
551                    limit_bytes,
552                })
553            } else {
554                Ok(entity.clone())
555            }
556        }) {
557            let mut entity = result?;
558            self.restore_owned_row_schemas(std::iter::once(&mut entity));
559            return Ok(Some(entity));
560        }
561        let Some(backing) = backing.as_ref() else {
562            return Ok(None);
563        };
564        if backing.removed.contains(&id) {
565            return Ok(None);
566        }
567        let Some(record) = backing
568            .source
569            .get_record(id, limit_bytes.min(backing.read_bytes_max))?
570        else {
571            return Ok(None);
572        };
573        let (mut entity, _) = record.decode_with_budget(
574            backing.format_version,
575            limit_bytes.min(backing.read_bytes_max),
576        )?;
577        self.restore_owned_row_schemas(std::iter::once(&mut entity));
578        Ok(Some(entity))
579    }
580
581    /// Fallible keyed projection. Resident mode keeps the segment key indexes.
582    /// Prepared bases seek physical candidates through their paired key index;
583    /// unindexed legacy sources retain a one-row streaming fallback. Hosts must
584    /// fence publication, and callbacks must not mutate or re-enter this collection.
585    pub fn try_project_key_entity<T>(
586        &self,
587        key: &str,
588        snapshot: Option<&SnapshotContext>,
589        versioned: bool,
590        limit_bytes: usize,
591        mut project: impl FnMut(&UnifiedEntity) -> T,
592    ) -> Result<Option<T>, StoreError> {
593        let backing = self.backing.read();
594        let limit_bytes = backing
595            .as_ref()
596            .map_or(limit_bytes, |base| limit_bytes.min(base.read_bytes_max));
597        let mut best = self
598            .project_key_entity(key, snapshot, versioned, |entity| {
599                let required_bytes = if limit_bytes == usize::MAX {
600                    0
601                } else {
602                    crate::storage::memory_size::entity_bytes(entity)
603                };
604                if required_bytes > limit_bytes {
605                    Err(StoreError::ReadLimitExceeded {
606                        required_bytes,
607                        limit_bytes,
608                    })
609                } else {
610                    Ok((entity.xmin, project(entity)))
611                }
612            })
613            .transpose()?;
614        let Some(backing) = backing.as_ref() else {
615            return Ok(best.map(|(_, projected)| projected));
616        };
617        if !versioned && best.is_some() {
618            return Ok(best.map(|(_, projected)| projected));
619        }
620        let mut cursor = match backing.source.key_cursor(key)? {
621            Some(cursor) => cursor,
622            None => backing.source.cursor()?,
623        };
624        while let Some(id) = cursor.peek_id()? {
625            // A physical replacement or deletion masks the old base value,
626            // even when it no longer matches this logical key.
627            if backing.removed.contains(&id) || self.get_with(id, |_| ()).is_some() {
628                cursor.skip_record()?;
629                continue;
630            }
631            let record = cursor
632                .next_record(limit_bytes)?
633                .expect("invariant: peeked physical row exists");
634            let (mut entity, _) = record.decode_with_budget(backing.format_version, limit_bytes)?;
635            self.restore_owned_row_schemas(std::iter::once(&mut entity));
636            if crate::storage::segment_key_lookup::SegmentKeyLookup::key(&entity) != Some(key)
637                || (versioned && !Self::scan_entity_visible(snapshot, &entity))
638            {
639                continue;
640            }
641            if best.as_ref().is_none_or(|(xmin, _)| entity.xmin >= *xmin) {
642                best = Some((entity.xmin, project(&entity)));
643            }
644            if !versioned {
645                break;
646            }
647        }
648        Ok(best.map(|(_, projected)| projected))
649    }
650
651    /// Visit the merged physical view in ID order without hydrating the base.
652    /// Only overlay identities and one decoded base record are retained. Like
653    /// resident visitors, callbacks must not mutate or re-enter this collection.
654    pub fn try_for_each_entity(
655        &self,
656        limit_bytes: usize,
657        mut callback: impl FnMut(&UnifiedEntity) -> bool,
658    ) -> Result<(), StoreError> {
659        let backing_guard = self.backing.read();
660        let Some(backing) = backing_guard.as_ref() else {
661            self.for_each_entity(callback);
662            return Ok(());
663        };
664        self.try_for_each_backed_entity(backing, limit_bytes, 0, |entity| callback(&entity))
665    }
666
667    fn try_for_each_backed_entity(
668        &self,
669        backing: &BackingRead,
670        limit_bytes: usize,
671        mut skip: usize,
672        mut callback: impl FnMut(std::borrow::Cow<'_, UnifiedEntity>) -> bool,
673    ) -> Result<(), StoreError> {
674        let limit_bytes = limit_bytes.min(backing.read_bytes_max);
675        let mut identities = Vec::new();
676        self.for_each_entity(|entity| {
677            identities.push(entity.id);
678            true
679        });
680        identities.sort_unstable();
681        identities.dedup();
682        let mut identities = identities.into_iter().peekable();
683        let mut cursor = backing.source.cursor()?;
684        loop {
685            let base = cursor.peek_id()?;
686            let resident = identities.peek().copied();
687            if let Some(id) = resident.filter(|id| base.is_none_or(|base| *id <= base)) {
688                if base == Some(id) {
689                    cursor.skip_record()?;
690                }
691                identities.next();
692                let result = self.get_with(id, |entity| {
693                    if skip > 0 {
694                        skip -= 1;
695                        return Ok(true);
696                    }
697                    let required_bytes = crate::storage::memory_size::entity_bytes(entity);
698                    if required_bytes > limit_bytes {
699                        return Err(StoreError::ReadLimitExceeded {
700                            required_bytes,
701                            limit_bytes,
702                        });
703                    }
704                    Ok(callback(std::borrow::Cow::Borrowed(entity)))
705                });
706                if result.transpose()? == Some(false) {
707                    return Ok(());
708                }
709                continue;
710            }
711            let Some(id) = base else {
712                return Ok(());
713            };
714            if backing.removed.contains(&id) {
715                cursor.skip_record()?;
716                continue;
717            }
718            if skip > 0 {
719                skip -= 1;
720                cursor.skip_record()?;
721                continue;
722            }
723            let record = cursor
724                .next_record(limit_bytes)?
725                .expect("invariant: peeked physical row exists");
726            let (mut entity, _) = record.decode_with_budget(
727                backing.format_version,
728                limit_bytes.min(backing.read_bytes_max),
729            )?;
730            self.restore_owned_row_schemas(std::iter::once(&mut entity));
731            if !callback(std::borrow::Cow::Owned(entity)) {
732                return Ok(());
733            }
734        }
735    }
736
737    /// Page the same base/overlay physical view used by fallible query reads.
738    /// Prefix records are skipped without decoding; only the requested page is
739    /// cloned. The manager's counter includes base rows and resident mutations.
740    pub fn try_page_in_id_order(
741        &self,
742        offset: usize,
743        limit: usize,
744        limit_bytes: usize,
745    ) -> Result<(usize, Vec<UnifiedEntity>), StoreError> {
746        let backing_guard = self.backing.read();
747        let total = self.count();
748        if offset >= total || limit == 0 {
749            return Ok((total, Vec::new()));
750        }
751        let mut items = Vec::new();
752        let mut retained_bytes = 0_usize;
753        let mut error = None;
754        let mut capture = |mut entity: std::borrow::Cow<'_, UnifiedEntity>| {
755            // Eager file recovery sees these named records before runtime
756            // rehydrates the declared column schema. Reproduce that layout
757            // only for decoded base rows; live overlays keep their wire shape.
758            if let std::borrow::Cow::Owned(entity) = &mut entity {
759                self.restore_recovery_row_layout(entity, None);
760            }
761            let required_bytes =
762                retained_bytes.saturating_add(crate::storage::memory_size::entity_bytes(&entity));
763            if required_bytes > limit_bytes {
764                error = Some(StoreError::ReadLimitExceeded {
765                    required_bytes,
766                    limit_bytes,
767                });
768                return false;
769            }
770            retained_bytes = required_bytes;
771            items.push(entity.into_owned());
772            items.len() < limit
773        };
774        if let Some(backing) = backing_guard.as_ref() {
775            self.try_for_each_backed_entity(backing, limit_bytes, offset, &mut capture)?;
776        } else {
777            let mut skip = offset;
778            self.for_each_entity_in_id_order(|entity| {
779                if skip > 0 {
780                    skip -= 1;
781                    return true;
782                }
783                capture(std::borrow::Cow::Borrowed(entity))
784            });
785        }
786        if let Some(error) = error {
787            return Err(error);
788        }
789        self.restore_owned_row_schemas(items.iter_mut());
790        Ok((total, items))
791    }
792
793    /// Page a caller-filtered logical view while keeping the visible total exact.
794    /// Unlike post-page filtering, this never leaks the number or position of
795    /// rows rejected by `predicate`.
796    pub fn try_page_in_id_order_where(
797        &self,
798        offset: usize,
799        limit: usize,
800        limit_bytes: usize,
801        predicate: impl FnMut(&UnifiedEntity) -> bool,
802    ) -> Result<(usize, Vec<UnifiedEntity>), StoreError> {
803        self.try_page_in_id_order_where_at_snapshot(None, offset, limit, limit_bytes, predicate)
804    }
805
806    /// Page a caller-filtered logical view under an explicit MVCC snapshot.
807    /// Visibility is applied before the predicate, total, and offset so an
808    /// aborted writer or an in-progress deleter cannot distort pagination.
809    pub fn try_page_in_id_order_where_at_snapshot(
810        &self,
811        snapshot: Option<&SnapshotContext>,
812        offset: usize,
813        limit: usize,
814        limit_bytes: usize,
815        mut predicate: impl FnMut(&UnifiedEntity) -> bool,
816    ) -> Result<(usize, Vec<UnifiedEntity>), StoreError> {
817        let mut visible = 0_usize;
818        let mut retained_bytes = 0_usize;
819        let mut items = Vec::new();
820        let mut error = None;
821        self.try_scan_for_each(snapshot, limit_bytes, |entity| {
822            if !predicate(entity) {
823                return true;
824            }
825            let position = visible;
826            visible = visible.saturating_add(1);
827            if position < offset || items.len() >= limit {
828                return true;
829            }
830            let required_bytes =
831                retained_bytes.saturating_add(crate::storage::memory_size::entity_bytes(entity));
832            if required_bytes > limit_bytes {
833                error = Some(StoreError::ReadLimitExceeded {
834                    required_bytes,
835                    limit_bytes,
836                });
837                return false;
838            }
839            retained_bytes = required_bytes;
840            items.push(entity.clone());
841            true
842        })?;
843        if let Some(error) = error {
844            return Err(error);
845        }
846        self.restore_owned_row_schemas(items.iter_mut());
847        Ok((visible, items))
848    }
849
850    /// Physical key history. Indexed bases avoid unrelated payload reads;
851    /// resident and unindexed sources still verify each logical key.
852    pub fn try_for_each_key_entity(
853        &self,
854        key: &str,
855        mut callback: impl FnMut(&UnifiedEntity) -> bool,
856    ) -> Result<(), StoreError> {
857        if let Some(cursor) = self.try_paged_key_physical_cursor(key)? {
858            for record in cursor {
859                let (entity, _) = record?;
860                if !callback(&entity) {
861                    break;
862                }
863            }
864            return Ok(());
865        }
866        self.try_for_each_entity(usize::MAX, |entity| {
867            crate::storage::segment_key_lookup::SegmentKeyLookup::key(entity) != Some(key)
868                || callback(entity)
869        })
870    }
871
872    pub fn try_scan_for_each(
873        &self,
874        snapshot: Option<&SnapshotContext>,
875        limit_bytes: usize,
876        mut callback: impl FnMut(&UnifiedEntity) -> bool,
877    ) -> Result<(), StoreError> {
878        self.try_for_each_entity(limit_bytes, |entity| {
879            !Self::scan_entity_visible(snapshot, entity) || callback(entity)
880        })
881    }
882
883    /// The disk base has no segment zone summaries yet: scan all candidates
884    /// and retain the caller's residual predicate. Resident mode keeps pruning.
885    pub fn try_scan_for_each_zoned_with_stats(
886        &self,
887        snapshot: Option<&SnapshotContext>,
888        zone_preds: &[(&str, ZoneColPred<'_>)],
889        limit_bytes: usize,
890        callback: impl FnMut(&UnifiedEntity) -> bool,
891    ) -> Result<SegmentScanStats, StoreError> {
892        if !self.has_backing() {
893            return Ok(self.scan_for_each_zoned_with_stats(snapshot, zone_preds, callback));
894        }
895        self.try_scan_for_each(snapshot, limit_bytes, callback)?;
896        Ok(SegmentScanStats {
897            segments_total: 1,
898            segments_scanned: 1,
899            segments_pruned: 0,
900        })
901    }
902
903    /// Preserve the resident projection fast path; cold mode streams candidates.
904    /// Hosts own admission for retained projections independently of row decoding.
905    pub fn try_scan_project_zoned_with_stats<T, F>(
906        &self,
907        snapshot: Option<&SnapshotContext>,
908        zone_preds: &[(&str, ZoneColPred<'_>)],
909        read_bytes_max: usize,
910        project: F,
911    ) -> Result<(Vec<T>, SegmentScanStats), StoreError>
912    where
913        T: Send,
914        F: Fn(&UnifiedEntity) -> Option<T> + Sync,
915    {
916        if !self.has_backing() {
917            return Ok(self.scan_project_zoned_with_stats(snapshot, zone_preds, project));
918        }
919        let mut projected = Vec::new();
920        let stats = self.try_scan_for_each_zoned_with_stats(
921            snapshot,
922            zone_preds,
923            read_bytes_max,
924            |entity| {
925                if let Some(value) = project(entity) {
926                    projected.push(value);
927                }
928                true
929            },
930        )?;
931        Ok((projected, stats))
932    }
933
934    /// Point-read allowance applies to each row. Hosts separately admit the
935    /// retained output vector; this method is not a global result quota.
936    pub fn try_get_many(
937        &self,
938        ids: &[EntityId],
939        read_bytes_max: usize,
940    ) -> Result<Vec<Option<UnifiedEntity>>, StoreError> {
941        if !self.has_backing() && read_bytes_max == usize::MAX {
942            return Ok(self.get_many(ids));
943        }
944        ids.iter()
945            .map(|id| self.try_get(*id, read_bytes_max))
946            .collect()
947    }
948
949    pub fn try_for_each_id(
950        &self,
951        ids: &[EntityId],
952        read_bytes_max: usize,
953        mut visit: impl FnMut(usize, &UnifiedEntity) -> bool,
954    ) -> Result<(), StoreError> {
955        if self.has_backing() {
956            for (position, id) in ids.iter().enumerate() {
957                if let Some(entity) = self.try_get(*id, read_bytes_max)? {
958                    if !visit(position, &entity) {
959                        break;
960                    }
961                }
962            }
963            return Ok(());
964        }
965        let mut stopped = false;
966        let mut failure = None;
967        self.for_each_id(ids, |position, entity| {
968            if stopped {
969                return;
970            }
971            let required_bytes = if read_bytes_max == usize::MAX {
972                0
973            } else {
974                crate::storage::memory_size::entity_bytes(entity)
975            };
976            if required_bytes > read_bytes_max {
977                failure = Some(StoreError::ReadLimitExceeded {
978                    required_bytes,
979                    limit_bytes: read_bytes_max,
980                });
981                stopped = true;
982            } else {
983                stopped = !visit(position, entity);
984            }
985        });
986        failure.map_or(Ok(()), Err)
987    }
988
989    /// Inserts must not overwrite a physical identity in the published base.
990    pub(super) fn reject_backing_duplicate(&self, id: EntityId) -> Result<(), SegmentError> {
991        let backing = self.backing.read();
992        let Some(backing) = backing.as_ref() else {
993            return Ok(());
994        };
995        if !backing.removed.contains(&id)
996            && backing
997                .source
998                .get_record(id, backing.read_bytes_max)
999                .map_err(|error| SegmentError::BackingRead(error.to_string()))?
1000                .is_some()
1001        {
1002            return Err(SegmentError::AlreadyExists(id));
1003        }
1004        Ok(())
1005    }
1006
1007    /// Metadata reads carry the same I/O failure contract as entity reads.
1008    pub fn try_get_metadata(
1009        &self,
1010        id: EntityId,
1011        limit_bytes: usize,
1012    ) -> Result<Option<Metadata>, StoreError> {
1013        let backing = self.backing.read();
1014        if self.get_with(id, |_| ()).is_some() {
1015            return Ok(self.get_metadata(id));
1016        }
1017        let Some(backing) = backing.as_ref() else {
1018            return Ok(None);
1019        };
1020        if backing.removed.contains(&id) {
1021            return Ok(None);
1022        }
1023        backing
1024            .source
1025            .get_record(id, limit_bytes.min(backing.read_bytes_max))?
1026            .map(|record| {
1027                record
1028                    .decode_with_budget(
1029                        backing.format_version,
1030                        limit_bytes.min(backing.read_bytes_max),
1031                    )
1032                    .map(|(_, metadata)| metadata)
1033            })
1034            .transpose()
1035            .map(Option::flatten)
1036    }
1037
1038    /// Rebuild one legacy per-row TTL projection entry without materializing
1039    /// the cold row. The caller inventories IDs in bounded ticks.
1040    pub fn rebuild_metadata_expiry(&self, id: EntityId) -> Result<(), StoreError> {
1041        if let Some(entity) = self.get(id) {
1042            let metadata = self.get_metadata(id);
1043            self.restore_metadata_expiry(&entity, metadata.as_ref());
1044            return Ok(());
1045        }
1046        let backing = self.backing.read();
1047        let Some(backing) = backing.as_ref() else {
1048            self.remove_metadata_expiry(id);
1049            return Ok(());
1050        };
1051        if backing.removed.contains(&id) {
1052            self.remove_metadata_expiry(id);
1053            return Ok(());
1054        }
1055        let record = backing.source.get_record(id, backing.read_bytes_max)?;
1056        let Some(record) = record else {
1057            self.remove_metadata_expiry(id);
1058            return Ok(());
1059        };
1060        let (entity, metadata) =
1061            record.decode_with_budget(backing.format_version, backing.read_bytes_max)?;
1062        self.restore_metadata_expiry(&entity, metadata.as_ref());
1063        Ok(())
1064    }
1065
1066    pub(super) fn materialize_backing_entity(&self, id: EntityId) -> Result<(), SegmentError> {
1067        if self.get_with(id, |_| ()).is_some() {
1068            return Ok(());
1069        }
1070        let record = {
1071            let backing = self.backing.read();
1072            let Some(backing) = backing.as_ref() else {
1073                return Ok(());
1074            };
1075            if backing.removed.contains(&id) {
1076                return Ok(());
1077            }
1078            backing
1079                .source
1080                .get_record(id, backing.read_bytes_max)
1081                .and_then(|record| {
1082                    record
1083                        .map(|record| {
1084                            record
1085                                .decode_with_budget(backing.format_version, backing.read_bytes_max)
1086                        })
1087                        .transpose()
1088                })
1089                .map_err(|error| SegmentError::BackingRead(error.to_string()))?
1090        };
1091        let Some((mut entity, metadata)) = record else {
1092            return Ok(());
1093        };
1094        self.restore_owned_row_schemas(std::iter::once(&mut entity));
1095        self.restore_snapshot_entity(entity)?;
1096        // This row was already included in the persisted cardinality.
1097        self.total_entities_atomic.fetch_sub(1, Ordering::Relaxed);
1098        if let Some(metadata) = metadata {
1099            self.set_metadata(id, metadata)?;
1100        }
1101        Ok(())
1102    }
1103
1104    pub(super) fn remember_backing_delete(&self, id: EntityId) {
1105        if let Some(backing) = self.backing.write().as_mut() {
1106            backing.removed.insert(id);
1107            backing.logged_removals.remove(&id);
1108            // A confirmation still waiting belongs to an earlier removal of this row.
1109            self.unconfirmed_removals
1110                .lock()
1111                .retain(|other| *other != id);
1112        }
1113    }
1114
1115    /// Called under the publication fence after a successful WAL append.
1116    #[doc(hidden)]
1117    pub fn confirm_logged_removals(&self, ids: &[EntityId]) {
1118        // Do not make collection maintenance wait for a base reader under the
1119        // host's publication fence: keep the confirmation for whoever takes
1120        // the backing next. Dropping it made the next checkpoint treat the
1121        // removal as unlogged and publish the whole collection again.
1122        let Some(mut backing) = self.backing.try_write() else {
1123            let mut waiting = self.unconfirmed_removals.lock();
1124            if waiting.len() + ids.len() <= crate::storage::segment::CHECKPOINT_MUTATIONS_MAX {
1125                waiting.extend_from_slice(ids);
1126            }
1127            return;
1128        };
1129        if let Some(base) = backing.as_mut() {
1130            self.fold_unconfirmed_removals(base);
1131            if base.removed.len() <= crate::storage::segment::CHECKPOINT_MUTATIONS_MAX {
1132                base.logged_removals
1133                    .extend(ids.iter().copied().filter(|id| base.removed.contains(id)));
1134            }
1135        }
1136    }
1137
1138    fn fold_unconfirmed_removals(&self, base: &mut BackingRead) {
1139        let waiting = std::mem::take(&mut *self.unconfirmed_removals.lock());
1140        if base.removed.len() <= crate::storage::segment::CHECKPOINT_MUTATIONS_MAX {
1141            base.logged_removals
1142                .extend(waiting.into_iter().filter(|id| base.removed.contains(id)));
1143        }
1144    }
1145
1146    pub fn backing_overlay(
1147        &self,
1148        mut encode: impl FnMut(&UnifiedEntity, Option<Metadata>) -> Option<Vec<u8>>,
1149    ) -> Option<(Arc<dyn CollectionRead + Send + Sync>, Arc<FrozenOverlay>)> {
1150        let backing = self.backing.read();
1151        let backing = backing.as_ref()?;
1152        let mut overlay: FrozenOverlay = backing.removed.iter().map(|id| (*id, None)).collect();
1153        self.for_each_entity_with_metadata(|entity, metadata| {
1154            if let Some(bytes) = encode(entity, metadata) {
1155                overlay.insert(entity.id, Some(Arc::from(bytes)));
1156            }
1157            true
1158        });
1159        Some((Arc::clone(&backing.source), Arc::new(overlay)))
1160    }
1161
1162    pub fn current_backing_overlay(
1163        &self,
1164    ) -> Option<(Arc<dyn CollectionRead + Send + Sync>, Arc<FrozenOverlay>)> {
1165        let version = self.backing.read().as_ref()?.format_version;
1166        self.backing_overlay(|entity, metadata| {
1167            Some(serialize_entity_record(entity, metadata.as_ref(), version))
1168        })
1169    }
1170
1171    fn current_backing_key_overlay(
1172        &self,
1173        key: &str,
1174    ) -> Result<Option<(Arc<dyn CollectionRead + Send + Sync>, Arc<FrozenOverlay>)>, StoreError>
1175    {
1176        let backing = self.backing.read();
1177        let Some(backing) = backing.as_ref() else {
1178            return Ok(None);
1179        };
1180        let mut overlay: FrozenOverlay = backing.removed.iter().map(|id| (*id, None)).collect();
1181        let schema = self.column_schema();
1182        let key_column = schema
1183            .as_ref()
1184            .and_then(|schema| schema.iter().position(|name| name == "key"));
1185        let mut failure = None;
1186        self.for_each_entity_source(|segment, entity| {
1187            let key_matches = match (&entity.data, key_column) {
1188                (crate::storage::entity::EntityData::Row(row), Some(index)) if row.named.is_none() && row.schema.is_none() => {
1189                    matches!(row.columns.get(index), Some(reddb_types::Value::Text(stored)) if stored.as_ref() == key)
1190                }
1191                _ => crate::storage::segment_key_lookup::SegmentKeyLookup::key(entity) == Some(key),
1192            };
1193            let bytes = if key_matches {
1194                let required_bytes = crate::storage::memory_size::entity_bytes(entity);
1195                if required_bytes > backing.read_bytes_max {
1196                    failure = Some(StoreError::ReadLimitExceeded {
1197                        required_bytes,
1198                        limit_bytes: backing.read_bytes_max,
1199                    });
1200                    return false;
1201                }
1202                let metadata = segment.get_metadata(entity.id);
1203                Some(Arc::from(serialize_entity_record(entity, metadata.as_ref(), backing.format_version)))
1204            } else {
1205                // A row renamed away from the requested key must still hide
1206                // the old base candidate. No unrelated payload/metadata copy.
1207                None
1208            };
1209            overlay.insert(entity.id, bytes);
1210            true
1211        });
1212        if let Some(error) = failure {
1213            return Err(error);
1214        }
1215        Ok(Some((Arc::clone(&backing.source), Arc::new(overlay))))
1216    }
1217}