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