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    /// Whether the published base still lists a row that has been physically
507    /// removed since it was published.
508    pub fn backing_row_is_removed(&self, id: EntityId) -> bool {
509        self.backing
510            .read()
511            .as_ref()
512            .is_some_and(|base| base.removed.contains(&id))
513    }
514
515    /// The rows the published base still lists that have been physically
516    /// removed since it was published.
517    pub fn backing_removed_rows(&self) -> Vec<EntityId> {
518        self.backing
519            .read()
520            .as_ref()
521            .map(|base| base.removed.iter().copied().collect())
522            .unwrap_or_default()
523    }
524
525    pub fn checkpoint_backing_view(
526        &self,
527        max_removed: usize,
528    ) -> Option<(Option<Arc<dyn CollectionRead + Send + Sync>>, Vec<EntityId>)> {
529        let guard = self.backing.read();
530        let Some(base) = guard.as_ref() else {
531            return Some((None, Vec::new()));
532        };
533        (base.removed.len() <= max_removed).then(|| {
534            (
535                Some(Arc::clone(&base.source)),
536                base.removed.iter().copied().collect(),
537            )
538        })
539    }
540
541    /// Preserve I/O and decode failures instead of treating them as absent rows.
542    pub fn try_get(
543        &self,
544        id: EntityId,
545        limit_bytes: usize,
546    ) -> Result<Option<UnifiedEntity>, StoreError> {
547        let backing = self.backing.read();
548        let limit_bytes = backing
549            .as_ref()
550            .map_or(limit_bytes, |base| limit_bytes.min(base.read_bytes_max));
551        if let Some(result) = self.get_with(id, |entity| {
552            let required_bytes = if limit_bytes == usize::MAX {
553                0
554            } else {
555                crate::storage::memory_size::entity_bytes(entity)
556            };
557            if required_bytes > limit_bytes {
558                Err(StoreError::ReadLimitExceeded {
559                    required_bytes,
560                    limit_bytes,
561                })
562            } else {
563                Ok(entity.clone())
564            }
565        }) {
566            let mut entity = result?;
567            self.restore_owned_row_schemas(std::iter::once(&mut entity));
568            return Ok(Some(entity));
569        }
570        let Some(backing) = backing.as_ref() else {
571            return Ok(None);
572        };
573        if backing.removed.contains(&id) {
574            return Ok(None);
575        }
576        let Some(record) = backing
577            .source
578            .get_record(id, limit_bytes.min(backing.read_bytes_max))?
579        else {
580            return Ok(None);
581        };
582        let (mut entity, _) = record.decode_with_budget(
583            backing.format_version,
584            limit_bytes.min(backing.read_bytes_max),
585        )?;
586        self.restore_owned_row_schemas(std::iter::once(&mut entity));
587        Ok(Some(entity))
588    }
589
590    /// Fallible keyed projection. Resident mode keeps the segment key indexes.
591    /// Prepared bases seek physical candidates through their paired key index;
592    /// unindexed legacy sources retain a one-row streaming fallback. Hosts must
593    /// fence publication, and callbacks must not mutate or re-enter this collection.
594    pub fn try_project_key_entity<T>(
595        &self,
596        key: &str,
597        snapshot: Option<&SnapshotContext>,
598        versioned: bool,
599        limit_bytes: usize,
600        mut project: impl FnMut(&UnifiedEntity) -> T,
601    ) -> Result<Option<T>, StoreError> {
602        let backing = self.backing.read();
603        let limit_bytes = backing
604            .as_ref()
605            .map_or(limit_bytes, |base| limit_bytes.min(base.read_bytes_max));
606        let mut best = self
607            .project_key_entity(key, snapshot, versioned, |entity| {
608                let required_bytes = if limit_bytes == usize::MAX {
609                    0
610                } else {
611                    crate::storage::memory_size::entity_bytes(entity)
612                };
613                if required_bytes > limit_bytes {
614                    Err(StoreError::ReadLimitExceeded {
615                        required_bytes,
616                        limit_bytes,
617                    })
618                } else {
619                    Ok((entity.xmin, project(entity)))
620                }
621            })
622            .transpose()?;
623        let Some(backing) = backing.as_ref() else {
624            return Ok(best.map(|(_, projected)| projected));
625        };
626        if !versioned && best.is_some() {
627            return Ok(best.map(|(_, projected)| projected));
628        }
629        let mut cursor = match backing.source.key_cursor(key)? {
630            Some(cursor) => cursor,
631            None => backing.source.cursor()?,
632        };
633        while let Some(id) = cursor.peek_id()? {
634            // A physical replacement or deletion masks the old base value,
635            // even when it no longer matches this logical key.
636            if backing.removed.contains(&id) || self.get_with(id, |_| ()).is_some() {
637                cursor.skip_record()?;
638                continue;
639            }
640            let record = cursor
641                .next_record(limit_bytes)?
642                .expect("invariant: peeked physical row exists");
643            let (mut entity, _) = record.decode_with_budget(backing.format_version, limit_bytes)?;
644            self.restore_owned_row_schemas(std::iter::once(&mut entity));
645            if crate::storage::segment_key_lookup::SegmentKeyLookup::key(&entity) != Some(key)
646                || (versioned && !Self::scan_entity_visible(snapshot, &entity))
647            {
648                continue;
649            }
650            if best.as_ref().is_none_or(|(xmin, _)| entity.xmin >= *xmin) {
651                best = Some((entity.xmin, project(&entity)));
652            }
653            if !versioned {
654                break;
655            }
656        }
657        Ok(best.map(|(_, projected)| projected))
658    }
659
660    /// Visit the merged physical view in ID order without hydrating the base.
661    /// Only overlay identities and one decoded base record are retained. Like
662    /// resident visitors, callbacks must not mutate or re-enter this collection.
663    pub fn try_for_each_entity(
664        &self,
665        limit_bytes: usize,
666        mut callback: impl FnMut(&UnifiedEntity) -> bool,
667    ) -> Result<(), StoreError> {
668        let backing_guard = self.backing.read();
669        let Some(backing) = backing_guard.as_ref() else {
670            self.for_each_entity(callback);
671            return Ok(());
672        };
673        self.try_for_each_backed_entity(backing, limit_bytes, 0, |entity| callback(&entity))
674    }
675
676    fn try_for_each_backed_entity(
677        &self,
678        backing: &BackingRead,
679        limit_bytes: usize,
680        mut skip: usize,
681        mut callback: impl FnMut(std::borrow::Cow<'_, UnifiedEntity>) -> bool,
682    ) -> Result<(), StoreError> {
683        let limit_bytes = limit_bytes.min(backing.read_bytes_max);
684        let mut identities = Vec::new();
685        self.for_each_entity(|entity| {
686            identities.push(entity.id);
687            true
688        });
689        identities.sort_unstable();
690        identities.dedup();
691        let mut identities = identities.into_iter().peekable();
692        let mut cursor = backing.source.cursor()?;
693        loop {
694            let base = cursor.peek_id()?;
695            let resident = identities.peek().copied();
696            if let Some(id) = resident.filter(|id| base.is_none_or(|base| *id <= base)) {
697                if base == Some(id) {
698                    cursor.skip_record()?;
699                }
700                identities.next();
701                let result = self.get_with(id, |entity| {
702                    if skip > 0 {
703                        skip -= 1;
704                        return Ok(true);
705                    }
706                    let required_bytes = crate::storage::memory_size::entity_bytes(entity);
707                    if required_bytes > limit_bytes {
708                        return Err(StoreError::ReadLimitExceeded {
709                            required_bytes,
710                            limit_bytes,
711                        });
712                    }
713                    Ok(callback(std::borrow::Cow::Borrowed(entity)))
714                });
715                if result.transpose()? == Some(false) {
716                    return Ok(());
717                }
718                continue;
719            }
720            let Some(id) = base else {
721                return Ok(());
722            };
723            if backing.removed.contains(&id) {
724                cursor.skip_record()?;
725                continue;
726            }
727            if skip > 0 {
728                skip -= 1;
729                cursor.skip_record()?;
730                continue;
731            }
732            let record = cursor
733                .next_record(limit_bytes)?
734                .expect("invariant: peeked physical row exists");
735            let (mut entity, _) = record.decode_with_budget(
736                backing.format_version,
737                limit_bytes.min(backing.read_bytes_max),
738            )?;
739            self.restore_owned_row_schemas(std::iter::once(&mut entity));
740            if !callback(std::borrow::Cow::Owned(entity)) {
741                return Ok(());
742            }
743        }
744    }
745
746    /// Page the same base/overlay physical view used by fallible query reads.
747    /// Prefix records are skipped without decoding; only the requested page is
748    /// cloned. The manager's counter includes base rows and resident mutations.
749    pub fn try_page_in_id_order(
750        &self,
751        offset: usize,
752        limit: usize,
753        limit_bytes: usize,
754    ) -> Result<(usize, Vec<UnifiedEntity>), StoreError> {
755        let backing_guard = self.backing.read();
756        let total = self.count();
757        if offset >= total || limit == 0 {
758            return Ok((total, Vec::new()));
759        }
760        let mut items = Vec::new();
761        let mut retained_bytes = 0_usize;
762        let mut error = None;
763        let mut capture = |mut entity: std::borrow::Cow<'_, UnifiedEntity>| {
764            // Eager file recovery sees these named records before runtime
765            // rehydrates the declared column schema. Reproduce that layout
766            // only for decoded base rows; live overlays keep their wire shape.
767            if let std::borrow::Cow::Owned(entity) = &mut entity {
768                self.restore_recovery_row_layout(entity, None);
769            }
770            let required_bytes =
771                retained_bytes.saturating_add(crate::storage::memory_size::entity_bytes(&entity));
772            if required_bytes > limit_bytes {
773                error = Some(StoreError::ReadLimitExceeded {
774                    required_bytes,
775                    limit_bytes,
776                });
777                return false;
778            }
779            retained_bytes = required_bytes;
780            items.push(entity.into_owned());
781            items.len() < limit
782        };
783        if let Some(backing) = backing_guard.as_ref() {
784            self.try_for_each_backed_entity(backing, limit_bytes, offset, &mut capture)?;
785        } else {
786            let mut skip = offset;
787            self.for_each_entity_in_id_order(|entity| {
788                if skip > 0 {
789                    skip -= 1;
790                    return true;
791                }
792                capture(std::borrow::Cow::Borrowed(entity))
793            });
794        }
795        if let Some(error) = error {
796            return Err(error);
797        }
798        self.restore_owned_row_schemas(items.iter_mut());
799        Ok((total, items))
800    }
801
802    /// Page a caller-filtered logical view while keeping the visible total exact.
803    /// Unlike post-page filtering, this never leaks the number or position of
804    /// rows rejected by `predicate`.
805    pub fn try_page_in_id_order_where(
806        &self,
807        offset: usize,
808        limit: usize,
809        limit_bytes: usize,
810        predicate: impl FnMut(&UnifiedEntity) -> bool,
811    ) -> Result<(usize, Vec<UnifiedEntity>), StoreError> {
812        self.try_page_in_id_order_where_at_snapshot(None, offset, limit, limit_bytes, predicate)
813    }
814
815    /// Page a caller-filtered logical view under an explicit MVCC snapshot.
816    /// Visibility is applied before the predicate, total, and offset so an
817    /// aborted writer or an in-progress deleter cannot distort pagination.
818    pub fn try_page_in_id_order_where_at_snapshot(
819        &self,
820        snapshot: Option<&SnapshotContext>,
821        offset: usize,
822        limit: usize,
823        limit_bytes: usize,
824        mut predicate: impl FnMut(&UnifiedEntity) -> bool,
825    ) -> Result<(usize, Vec<UnifiedEntity>), StoreError> {
826        let mut visible = 0_usize;
827        let mut retained_bytes = 0_usize;
828        let mut items = Vec::new();
829        let mut error = None;
830        self.try_scan_for_each(snapshot, limit_bytes, |entity| {
831            if !predicate(entity) {
832                return true;
833            }
834            let position = visible;
835            visible = visible.saturating_add(1);
836            if position < offset || items.len() >= limit {
837                return true;
838            }
839            let required_bytes =
840                retained_bytes.saturating_add(crate::storage::memory_size::entity_bytes(entity));
841            if required_bytes > limit_bytes {
842                error = Some(StoreError::ReadLimitExceeded {
843                    required_bytes,
844                    limit_bytes,
845                });
846                return false;
847            }
848            retained_bytes = required_bytes;
849            items.push(entity.clone());
850            true
851        })?;
852        if let Some(error) = error {
853            return Err(error);
854        }
855        self.restore_owned_row_schemas(items.iter_mut());
856        Ok((visible, items))
857    }
858
859    /// Physical key history. Indexed bases avoid unrelated payload reads;
860    /// resident and unindexed sources still verify each logical key.
861    pub fn try_for_each_key_entity(
862        &self,
863        key: &str,
864        mut callback: impl FnMut(&UnifiedEntity) -> bool,
865    ) -> Result<(), StoreError> {
866        if let Some(cursor) = self.try_paged_key_physical_cursor(key)? {
867            for record in cursor {
868                let (entity, _) = record?;
869                if !callback(&entity) {
870                    break;
871                }
872            }
873            return Ok(());
874        }
875        self.try_for_each_entity(usize::MAX, |entity| {
876            crate::storage::segment_key_lookup::SegmentKeyLookup::key(entity) != Some(key)
877                || callback(entity)
878        })
879    }
880
881    pub fn try_scan_for_each(
882        &self,
883        snapshot: Option<&SnapshotContext>,
884        limit_bytes: usize,
885        mut callback: impl FnMut(&UnifiedEntity) -> bool,
886    ) -> Result<(), StoreError> {
887        self.try_for_each_entity(limit_bytes, |entity| {
888            !Self::scan_entity_visible(snapshot, entity) || callback(entity)
889        })
890    }
891
892    /// The disk base has no segment zone summaries yet: scan all candidates
893    /// and retain the caller's residual predicate. Resident mode keeps pruning.
894    pub fn try_scan_for_each_zoned_with_stats(
895        &self,
896        snapshot: Option<&SnapshotContext>,
897        zone_preds: &[(&str, ZoneColPred<'_>)],
898        limit_bytes: usize,
899        callback: impl FnMut(&UnifiedEntity) -> bool,
900    ) -> Result<SegmentScanStats, StoreError> {
901        if !self.has_backing() {
902            return Ok(self.scan_for_each_zoned_with_stats(snapshot, zone_preds, callback));
903        }
904        self.try_scan_for_each(snapshot, limit_bytes, callback)?;
905        Ok(SegmentScanStats {
906            segments_total: 1,
907            segments_scanned: 1,
908            segments_pruned: 0,
909        })
910    }
911
912    /// Preserve the resident projection fast path; cold mode streams candidates.
913    /// Hosts own admission for retained projections independently of row decoding.
914    pub fn try_scan_project_zoned_with_stats<T, F>(
915        &self,
916        snapshot: Option<&SnapshotContext>,
917        zone_preds: &[(&str, ZoneColPred<'_>)],
918        read_bytes_max: usize,
919        project: F,
920    ) -> Result<(Vec<T>, SegmentScanStats), StoreError>
921    where
922        T: Send,
923        F: Fn(&UnifiedEntity) -> Option<T> + Sync,
924    {
925        if !self.has_backing() {
926            return Ok(self.scan_project_zoned_with_stats(snapshot, zone_preds, project));
927        }
928        let mut projected = Vec::new();
929        let stats = self.try_scan_for_each_zoned_with_stats(
930            snapshot,
931            zone_preds,
932            read_bytes_max,
933            |entity| {
934                if let Some(value) = project(entity) {
935                    projected.push(value);
936                }
937                true
938            },
939        )?;
940        Ok((projected, stats))
941    }
942
943    /// Point-read allowance applies to each row. Hosts separately admit the
944    /// retained output vector; this method is not a global result quota.
945    pub fn try_get_many(
946        &self,
947        ids: &[EntityId],
948        read_bytes_max: usize,
949    ) -> Result<Vec<Option<UnifiedEntity>>, StoreError> {
950        if !self.has_backing() && read_bytes_max == usize::MAX {
951            return Ok(self.get_many(ids));
952        }
953        ids.iter()
954            .map(|id| self.try_get(*id, read_bytes_max))
955            .collect()
956    }
957
958    pub fn try_for_each_id(
959        &self,
960        ids: &[EntityId],
961        read_bytes_max: usize,
962        mut visit: impl FnMut(usize, &UnifiedEntity) -> bool,
963    ) -> Result<(), StoreError> {
964        if self.has_backing() {
965            for (position, id) in ids.iter().enumerate() {
966                if let Some(entity) = self.try_get(*id, read_bytes_max)? {
967                    if !visit(position, &entity) {
968                        break;
969                    }
970                }
971            }
972            return Ok(());
973        }
974        let mut stopped = false;
975        let mut failure = None;
976        self.for_each_id(ids, |position, entity| {
977            if stopped {
978                return;
979            }
980            let required_bytes = if read_bytes_max == usize::MAX {
981                0
982            } else {
983                crate::storage::memory_size::entity_bytes(entity)
984            };
985            if required_bytes > read_bytes_max {
986                failure = Some(StoreError::ReadLimitExceeded {
987                    required_bytes,
988                    limit_bytes: read_bytes_max,
989                });
990                stopped = true;
991            } else {
992                stopped = !visit(position, entity);
993            }
994        });
995        failure.map_or(Ok(()), Err)
996    }
997
998    /// Inserts must not overwrite a physical identity in the published base.
999    pub(super) fn reject_backing_duplicate(&self, id: EntityId) -> Result<(), SegmentError> {
1000        let backing = self.backing.read();
1001        let Some(backing) = backing.as_ref() else {
1002            return Ok(());
1003        };
1004        if !backing.removed.contains(&id)
1005            && backing
1006                .source
1007                .get_record(id, backing.read_bytes_max)
1008                .map_err(|error| SegmentError::BackingRead(error.to_string()))?
1009                .is_some()
1010        {
1011            return Err(SegmentError::AlreadyExists(id));
1012        }
1013        Ok(())
1014    }
1015
1016    /// Metadata reads carry the same I/O failure contract as entity reads.
1017    pub fn try_get_metadata(
1018        &self,
1019        id: EntityId,
1020        limit_bytes: usize,
1021    ) -> Result<Option<Metadata>, StoreError> {
1022        let backing = self.backing.read();
1023        if self.get_with(id, |_| ()).is_some() {
1024            return Ok(self.get_metadata(id));
1025        }
1026        let Some(backing) = backing.as_ref() else {
1027            return Ok(None);
1028        };
1029        if backing.removed.contains(&id) {
1030            return Ok(None);
1031        }
1032        backing
1033            .source
1034            .get_record(id, limit_bytes.min(backing.read_bytes_max))?
1035            .map(|record| {
1036                record
1037                    .decode_with_budget(
1038                        backing.format_version,
1039                        limit_bytes.min(backing.read_bytes_max),
1040                    )
1041                    .map(|(_, metadata)| metadata)
1042            })
1043            .transpose()
1044            .map(Option::flatten)
1045    }
1046
1047    /// Rebuild one legacy per-row TTL projection entry without materializing
1048    /// the cold row. The caller inventories IDs in bounded ticks.
1049    pub fn rebuild_metadata_expiry(&self, id: EntityId) -> Result<(), StoreError> {
1050        if let Some(entity) = self.get(id) {
1051            let metadata = self.get_metadata(id);
1052            self.restore_metadata_expiry(&entity, metadata.as_ref());
1053            return Ok(());
1054        }
1055        let backing = self.backing.read();
1056        let Some(backing) = backing.as_ref() else {
1057            self.remove_metadata_expiry(id);
1058            return Ok(());
1059        };
1060        if backing.removed.contains(&id) {
1061            self.remove_metadata_expiry(id);
1062            return Ok(());
1063        }
1064        let record = backing.source.get_record(id, backing.read_bytes_max)?;
1065        let Some(record) = record else {
1066            self.remove_metadata_expiry(id);
1067            return Ok(());
1068        };
1069        let (entity, metadata) =
1070            record.decode_with_budget(backing.format_version, backing.read_bytes_max)?;
1071        self.restore_metadata_expiry(&entity, metadata.as_ref());
1072        Ok(())
1073    }
1074
1075    pub(super) fn materialize_backing_entity(&self, id: EntityId) -> Result<(), SegmentError> {
1076        if self.get_with(id, |_| ()).is_some() {
1077            return Ok(());
1078        }
1079        let record = {
1080            let backing = self.backing.read();
1081            let Some(backing) = backing.as_ref() else {
1082                return Ok(());
1083            };
1084            if backing.removed.contains(&id) {
1085                return Ok(());
1086            }
1087            backing
1088                .source
1089                .get_record(id, backing.read_bytes_max)
1090                .and_then(|record| {
1091                    record
1092                        .map(|record| {
1093                            record
1094                                .decode_with_budget(backing.format_version, backing.read_bytes_max)
1095                        })
1096                        .transpose()
1097                })
1098                .map_err(|error| SegmentError::BackingRead(error.to_string()))?
1099        };
1100        let Some((mut entity, metadata)) = record else {
1101            return Ok(());
1102        };
1103        self.restore_owned_row_schemas(std::iter::once(&mut entity));
1104        self.restore_snapshot_entity(entity)?;
1105        // This row was already included in the persisted cardinality.
1106        self.total_entities_atomic.fetch_sub(1, Ordering::Relaxed);
1107        if let Some(metadata) = metadata {
1108            self.set_metadata(id, metadata)?;
1109        }
1110        Ok(())
1111    }
1112
1113    pub(super) fn remember_backing_delete(&self, id: EntityId) {
1114        if let Some(backing) = self.backing.write().as_mut() {
1115            backing.removed.insert(id);
1116            backing.logged_removals.remove(&id);
1117            // A confirmation still waiting belongs to an earlier removal of this row.
1118            self.unconfirmed_removals
1119                .lock()
1120                .retain(|other| *other != id);
1121        }
1122    }
1123
1124    /// Called under the publication fence after a successful WAL append.
1125    #[doc(hidden)]
1126    pub fn confirm_logged_removals(&self, ids: &[EntityId]) {
1127        // Do not make collection maintenance wait for a base reader under the
1128        // host's publication fence: keep the confirmation for whoever takes
1129        // the backing next. Dropping it made the next checkpoint treat the
1130        // removal as unlogged and publish the whole collection again.
1131        let Some(mut backing) = self.backing.try_write() else {
1132            let mut waiting = self.unconfirmed_removals.lock();
1133            if waiting.len() + ids.len() <= crate::storage::segment::CHECKPOINT_MUTATIONS_MAX {
1134                waiting.extend_from_slice(ids);
1135            }
1136            return;
1137        };
1138        if let Some(base) = backing.as_mut() {
1139            self.fold_unconfirmed_removals(base);
1140            if base.removed.len() <= crate::storage::segment::CHECKPOINT_MUTATIONS_MAX {
1141                base.logged_removals
1142                    .extend(ids.iter().copied().filter(|id| base.removed.contains(id)));
1143            }
1144        }
1145    }
1146
1147    fn fold_unconfirmed_removals(&self, base: &mut BackingRead) {
1148        let waiting = std::mem::take(&mut *self.unconfirmed_removals.lock());
1149        if base.removed.len() <= crate::storage::segment::CHECKPOINT_MUTATIONS_MAX {
1150            base.logged_removals
1151                .extend(waiting.into_iter().filter(|id| base.removed.contains(id)));
1152        }
1153    }
1154
1155    pub fn backing_overlay(
1156        &self,
1157        mut encode: impl FnMut(&UnifiedEntity, Option<Metadata>) -> Option<Vec<u8>>,
1158    ) -> Option<(Arc<dyn CollectionRead + Send + Sync>, Arc<FrozenOverlay>)> {
1159        let backing = self.backing.read();
1160        let backing = backing.as_ref()?;
1161        let mut overlay: FrozenOverlay = backing.removed.iter().map(|id| (*id, None)).collect();
1162        self.for_each_entity_with_metadata(|entity, metadata| {
1163            if let Some(bytes) = encode(entity, metadata) {
1164                overlay.insert(entity.id, Some(Arc::from(bytes)));
1165            }
1166            true
1167        });
1168        Some((Arc::clone(&backing.source), Arc::new(overlay)))
1169    }
1170
1171    pub fn current_backing_overlay(
1172        &self,
1173    ) -> Option<(Arc<dyn CollectionRead + Send + Sync>, Arc<FrozenOverlay>)> {
1174        let version = self.backing.read().as_ref()?.format_version;
1175        self.backing_overlay(|entity, metadata| {
1176            Some(serialize_entity_record(entity, metadata.as_ref(), version))
1177        })
1178    }
1179
1180    fn current_backing_key_overlay(
1181        &self,
1182        key: &str,
1183    ) -> Result<Option<(Arc<dyn CollectionRead + Send + Sync>, Arc<FrozenOverlay>)>, StoreError>
1184    {
1185        let backing = self.backing.read();
1186        let Some(backing) = backing.as_ref() else {
1187            return Ok(None);
1188        };
1189        let mut overlay: FrozenOverlay = backing.removed.iter().map(|id| (*id, None)).collect();
1190        let schema = self.column_schema();
1191        let key_column = schema
1192            .as_ref()
1193            .and_then(|schema| schema.iter().position(|name| name == "key"));
1194        let mut failure = None;
1195        self.for_each_entity_source(|segment, entity| {
1196            let key_matches = match (&entity.data, key_column) {
1197                (crate::storage::entity::EntityData::Row(row), Some(index)) if row.named.is_none() && row.schema.is_none() => {
1198                    matches!(row.columns.get(index), Some(reddb_types::Value::Text(stored)) if stored.as_ref() == key)
1199                }
1200                _ => crate::storage::segment_key_lookup::SegmentKeyLookup::key(entity) == Some(key),
1201            };
1202            let bytes = if key_matches {
1203                let required_bytes = crate::storage::memory_size::entity_bytes(entity);
1204                if required_bytes > backing.read_bytes_max {
1205                    failure = Some(StoreError::ReadLimitExceeded {
1206                        required_bytes,
1207                        limit_bytes: backing.read_bytes_max,
1208                    });
1209                    return false;
1210                }
1211                let metadata = segment.get_metadata(entity.id);
1212                Some(Arc::from(serialize_entity_record(entity, metadata.as_ref(), backing.format_version)))
1213            } else {
1214                // A row renamed away from the requested key must still hide
1215                // the old base candidate. No unrelated payload/metadata copy.
1216                None
1217            };
1218            overlay.insert(entity.id, bytes);
1219            true
1220        });
1221        if let Some(error) = failure {
1222            return Err(error);
1223        }
1224        Ok(Some((Arc::clone(&backing.source), Arc::new(overlay))))
1225    }
1226}