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