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, EncodedRecord, 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    /// Pin the installed base without copying its set of physical removals.
237    pub fn backing_source(&self) -> Option<Arc<dyn CollectionRead + Send + Sync>> {
238        self.backing
239            .read()
240            .as_ref()
241            .map(|base| Arc::clone(&base.source))
242    }
243
244    /// The host applies the same row allowance to model-specific expansion
245    /// such as decrypting a compressed Vault value after native record decode.
246    pub fn backing_read_bytes_max(&self) -> Option<usize> {
247        self.backing
248            .read()
249            .as_ref()
250            .map(|backing| backing.read_bytes_max)
251    }
252
253    /// Capture under the host write fence. Pinning the source also excludes
254    /// in-place modifications to the base until the decision to retain it.
255    pub fn clean_backing_cut(&self) -> Option<CleanBackingCut> {
256        let guard = self.backing.read();
257        let base = guard.as_ref()?;
258        (base.removed.is_empty()
259            && base.logged_removals.is_empty()
260            && base.total_entities == self.count() as u64
261            && self.consolidation.read().is_none()
262            && self.growing.read().is_none()
263            && self.sealed.read().is_empty())
264        .then(|| CleanBackingCut {
265            source: Arc::clone(&base.source),
266            physical_count: base.total_entities,
267        })
268    }
269
270    /// Install the checkpoint projection under the host write fence. Return
271    /// the installed segment revisions, or None when the captured base is still
272    /// current and the caller must retain its original revision boundary.
273    pub fn publish_checkpoint_backing<
274        P: crate::storage::page_store::PageStore + Send + Sync + 'static,
275    >(
276        &self,
277        cut: Option<&CleanBackingCut>,
278        source: crate::storage::collection_read::PagedCollection<P>,
279        root_page: u32,
280        format_version: u32,
281        read_bytes_max: usize,
282    ) -> Option<Vec<(u64, u64)>> {
283        if let Some(cut) = cut {
284            let backing = self.backing.read();
285            if backing
286                .as_ref()
287                .is_some_and(|base| cut.matches(base, root_page, format_version, read_bytes_max))
288                && source.shares_primary_with(cut.source.as_ref())
289            {
290                if source.shares_trees_with(cut.source.as_ref()) {
291                    return None;
292                }
293                // Only the lookup tree changed. Writers are fenced by the host,
294                // so releasing the shared guard here cannot replace the base.
295                drop(backing);
296                self.backing
297                    .write()
298                    .as_mut()
299                    .expect("fenced checkpoint base")
300                    .source = Arc::new(source);
301                return None;
302            }
303        }
304        self.install_paged_backing(
305            source,
306            root_page,
307            format_version,
308            read_bytes_max,
309            self.count() as u64,
310        );
311        Some(self.checkpoint_revisions())
312    }
313
314    /// Install a published base under the host's write fence. An untouched cold
315    /// table can keep serving base readers without taking the exclusive lock.
316    pub fn install_paged_backing<
317        P: crate::storage::page_store::PageStore + Send + Sync + 'static,
318    >(
319        &self,
320        source: crate::storage::collection_read::PagedCollection<P>,
321        root_page: u32,
322        format_version: u32,
323        read_bytes_max: usize,
324        total_entities: u64,
325    ) {
326        if self.backing.read().as_ref().is_some_and(|base| {
327            base.root_page == root_page
328                && base.format_version == format_version
329                && base.read_bytes_max == read_bytes_max
330                && base.total_entities == total_entities
331                && base.removed.is_empty()
332                && base.logged_removals.is_empty()
333                && source.shares_trees_with(base.source.as_ref())
334                && self.consolidation.read().is_none()
335                && self.growing.read().is_none()
336                && self.sealed.read().is_empty()
337        }) {
338            return;
339        }
340        self.install_backing(
341            Arc::new(source),
342            root_page,
343            format_version,
344            read_bytes_max,
345            total_entities,
346        );
347    }
348
349    /// The host must fence writers and publish the new durable tree first.
350    /// Captured resident readers retain their old sources through weak tracking.
351    pub fn install_backing(
352        &self,
353        source: Arc<dyn CollectionRead + Send + Sync>,
354        root_page: u32,
355        format_version: u32,
356        read_bytes_max: usize,
357        total_entities: u64,
358    ) {
359        let mut backing = self.backing.write();
360        let mut consolidation = self.consolidation.write();
361        let mut growing = self.growing.write();
362        let mut sealed = self.sealed.write();
363        let mut retired = self.retired.write();
364        if let Some(source) = growing.take() {
365            self.restore_sequence_id_next(source.read().sequence_id_next());
366            retired.push(Arc::downgrade(&source));
367        }
368        for source in sealed.drain(..) {
369            self.restore_sequence_id_next(source.read().sequence_id_next());
370            retired.push(Arc::downgrade(&source));
371        }
372        *consolidation = None;
373        self.entity_segment.write().clear();
374        self.total_entities_atomic
375            .store(total_entities, Ordering::Relaxed);
376        *backing = Some(BackingRead {
377            source,
378            root_page,
379            total_entities,
380            format_version,
381            read_bytes_max,
382            removed: HashSet::new(),
383            logged_removals: HashSet::new(),
384        });
385        self.unconfirmed_removals.lock().clear();
386    }
387
388    /// Fence acquisition of new base readers while a host checks all native
389    /// cursor/tree pins and applies WAL-protected inserts. The source must have
390    /// no strong or weak owners outside this manager. The host still owns the
391    /// mutation/publication fence and must not re-enter backing methods here.
392    /// A successful projection updates the root and its exact physical count.
393    ///
394    /// The host calls this inside the pager's ownership epoch. A base reader
395    /// loads its pages without waiting for that epoch, so the bounded wait
396    /// here outlasts a read in progress, and a scan of a collection in
397    /// proportion to its size; a base that stays in use longer is declined
398    /// like any other reader pin.
399    #[doc(hidden)]
400    pub fn try_with_unshared_backing<T>(
401        &self,
402        root_page: u32,
403        update: impl FnOnce() -> (T, Option<(u32, u64)>),
404    ) -> Option<T> {
405        self.try_with_unshared_backing_delta(root_page, 0, |_| update())
406    }
407
408    /// Under the host's publication fence, allow a bounded set of WAL-confirmed
409    /// physical deletes alongside the resident changes. Unlogged removes and
410    /// borrowed generations require immutable replacement.
411    #[doc(hidden)]
412    pub fn try_with_unshared_backing_delta<T>(
413        &self,
414        root_page: u32,
415        max_removals: usize,
416        update: impl FnOnce(&HashSet<EntityId>) -> (T, Option<(u32, u64)>),
417    ) -> Option<T> {
418        self.try_with_unshared_backing_source_delta(root_page, max_removals, |_, removed| {
419            update(removed)
420        })
421    }
422
423    /// Check derived tree identity while the unique backing source is fenced.
424    #[doc(hidden)]
425    pub fn try_with_unshared_backing_source_delta<T>(
426        &self,
427        root_page: u32,
428        max_removals: usize,
429        update: impl FnOnce(&dyn CollectionRead, &HashSet<EntityId>) -> (T, Option<(u32, u64)>),
430    ) -> Option<T> {
431        let rows = u32::try_from(self.count()).unwrap_or(u32::MAX);
432        let wait = UNSHARED_BACKING_WAIT_PER_ROW
433            .saturating_mul(rows)
434            .clamp(UNSHARED_BACKING_WAIT, UNSHARED_BACKING_WAIT_MAX);
435        let mut backing = self.backing.try_write_for(wait)?;
436        let backing = backing.as_mut()?;
437        self.fold_unconfirmed_removals(backing);
438        if backing.root_page != root_page
439            || backing.removed.len() > max_removals
440            || backing.removed.len() != backing.logged_removals.len()
441            || Arc::get_mut(&mut backing.source).is_none()
442        {
443            return None;
444        }
445        let (result, published) = update(backing.source.as_ref(), &backing.removed);
446        if let Some((root_page, total_entities)) = published {
447            backing.root_page = root_page;
448            backing.total_entities = total_entities;
449            backing.removed.clear();
450            backing.logged_removals.clear();
451            self.unconfirmed_removals.lock().clear();
452        }
453        Some(result)
454    }
455
456    /// Whether a delta could have the backing right now: nothing is reading
457    /// it. For a host that can come back later, where the alternative to the
458    /// delta is to publish every row of the collection again.
459    #[doc(hidden)]
460    pub fn backing_is_free(&self) -> bool {
461        match self.backing.try_write() {
462            Some(mut backing) => backing
463                .as_mut()
464                .is_none_or(|backing| Arc::get_mut(&mut backing.source).is_some()),
465            None => false,
466        }
467    }
468
469    /// Why `try_with_unshared_backing_source_delta` declined, for the host's
470    /// log. The host still holds its publication fence, so the answer is the
471    /// one that call saw unless a reader left in between.
472    #[doc(hidden)]
473    pub fn backing_delta_refusal(&self, root_page: u32, max_removals: usize) -> &'static str {
474        let Some(mut backing) = self.backing.try_write_for(UNSHARED_BACKING_WAIT) else {
475            return "a reader holds the backing lock";
476        };
477        let Some(backing) = backing.as_mut() else {
478            return "the collection has no backing";
479        };
480        if backing.root_page != root_page {
481            "the backing was published from another root"
482        } else if backing.removed.len() > max_removals {
483            "more rows were removed than one delta takes"
484        } else if backing.removed.len() != backing.logged_removals.len() {
485            "rows were removed without a WAL record"
486        } else if Arc::get_mut(&mut backing.source).is_none() {
487            "a reader holds the backing source"
488        } else {
489            "a reader held the backing and has left"
490        }
491    }
492
493    pub fn backing_count_at_root(&self, root_page: u32) -> Option<u64> {
494        self.backing
495            .read()
496            .as_ref()
497            .filter(|base| base.root_page == root_page)
498            .map(|base| base.total_entities)
499    }
500
501    /// Reconcile a verified physical count while a recovered store is still
502    /// exclusively owned and has not been made available to readers.
503    #[doc(hidden)]
504    pub fn set_recovered_backing_count(&self, root_page: u32, count: u64) -> bool {
505        let mut backing = self.backing.write();
506        let Some(backing) = backing.as_mut() else {
507            return false;
508        };
509        if backing.root_page != root_page {
510            return false;
511        }
512        backing.total_entities = count;
513        true
514    }
515
516    /// Whether a projected base posting has been replaced or physically
517    /// removed. The host must fence publication/mutations while merging the
518    /// projected base with resident rows. This never reads a base payload.
519    pub fn backing_row_is_shadowed(&self, id: EntityId) -> bool {
520        let backing = self.backing.read();
521        backing
522            .as_ref()
523            .is_none_or(|base| base.removed.contains(&id))
524            || self.get_with(id, |_| ()).is_some()
525    }
526
527    /// Whether the published base still lists a row that has been physically
528    /// removed since it was published.
529    pub fn backing_row_is_removed(&self, id: EntityId) -> bool {
530        self.backing
531            .read()
532            .as_ref()
533            .is_some_and(|base| base.removed.contains(&id))
534    }
535
536    /// The rows the published base still lists that have been physically
537    /// removed since it was published.
538    pub fn backing_removed_rows(&self) -> Vec<EntityId> {
539        self.backing
540            .read()
541            .as_ref()
542            .map(|base| base.removed.iter().copied().collect())
543            .unwrap_or_default()
544    }
545
546    pub fn checkpoint_backing_view(
547        &self,
548        max_removed: usize,
549    ) -> Option<(Option<Arc<dyn CollectionRead + Send + Sync>>, Vec<EntityId>)> {
550        let guard = self.backing.read();
551        let Some(base) = guard.as_ref() else {
552            return Some((None, Vec::new()));
553        };
554        (base.removed.len() <= max_removed).then(|| {
555            (
556                Some(Arc::clone(&base.source)),
557                base.removed.iter().copied().collect(),
558            )
559        })
560    }
561
562    /// Preserve I/O and decode failures instead of treating them as absent rows.
563    pub fn try_get(
564        &self,
565        id: EntityId,
566        limit_bytes: usize,
567    ) -> Result<Option<UnifiedEntity>, StoreError> {
568        self.try_get_with_base(id, limit_bytes, |base, limit| {
569            base.source.get_record(id, limit)
570        })
571    }
572
573    fn try_get_with_base(
574        &self,
575        id: EntityId,
576        limit_bytes: usize,
577        read_base: impl FnOnce(&BackingRead, usize) -> Result<Option<EncodedRecord>, StoreError>,
578    ) -> Result<Option<UnifiedEntity>, StoreError> {
579        let backing = self.backing.read();
580        let limit_bytes = backing
581            .as_ref()
582            .map_or(limit_bytes, |base| limit_bytes.min(base.read_bytes_max));
583        if let Some(result) = self.get_with(id, |entity| {
584            let required_bytes = if limit_bytes == usize::MAX {
585                0
586            } else {
587                crate::storage::memory_size::entity_bytes(entity)
588            };
589            if required_bytes > limit_bytes {
590                Err(StoreError::ReadLimitExceeded {
591                    required_bytes,
592                    limit_bytes,
593                })
594            } else {
595                Ok(entity.clone())
596            }
597        }) {
598            let mut entity = result?;
599            self.restore_owned_row_schemas(std::iter::once(&mut entity));
600            return Ok(Some(entity));
601        }
602        let Some(backing) = backing.as_ref() else {
603            return Ok(None);
604        };
605        if backing.removed.contains(&id) {
606            return Ok(None);
607        }
608        let Some(record) = read_base(backing, limit_bytes)? else {
609            return Ok(None);
610        };
611        let (mut entity, _) = record.decode_with_budget(
612            backing.format_version,
613            limit_bytes.min(backing.read_bytes_max),
614        )?;
615        self.restore_owned_row_schemas(std::iter::once(&mut entity));
616        Ok(Some(entity))
617    }
618
619    /// Fallible keyed projection. Resident mode keeps the segment key indexes.
620    /// Prepared bases seek physical candidates through their paired key index;
621    /// unindexed legacy sources retain a one-row streaming fallback. Hosts must
622    /// fence publication, and callbacks must not mutate or re-enter this collection.
623    pub fn try_project_key_entity<T>(
624        &self,
625        key: &str,
626        snapshot: Option<&SnapshotContext>,
627        versioned: bool,
628        limit_bytes: usize,
629        mut project: impl FnMut(&UnifiedEntity) -> T,
630    ) -> Result<Option<T>, StoreError> {
631        let backing = self.backing.read();
632        let limit_bytes = backing
633            .as_ref()
634            .map_or(limit_bytes, |base| limit_bytes.min(base.read_bytes_max));
635        let mut best = self
636            .project_key_entity(key, snapshot, versioned, |entity| {
637                let required_bytes = if limit_bytes == usize::MAX {
638                    0
639                } else {
640                    crate::storage::memory_size::entity_bytes(entity)
641                };
642                if required_bytes > limit_bytes {
643                    Err(StoreError::ReadLimitExceeded {
644                        required_bytes,
645                        limit_bytes,
646                    })
647                } else {
648                    Ok((entity.xmin, project(entity)))
649                }
650            })
651            .transpose()?;
652        let Some(backing) = backing.as_ref() else {
653            return Ok(best.map(|(_, projected)| projected));
654        };
655        if !versioned && best.is_some() {
656            return Ok(best.map(|(_, projected)| projected));
657        }
658        let mut cursor = match backing.source.key_cursor(key)? {
659            Some(cursor) => cursor,
660            None => backing.source.cursor()?,
661        };
662        while let Some(id) = cursor.peek_id()? {
663            // A physical replacement or deletion masks the old base value,
664            // even when it no longer matches this logical key.
665            if backing.removed.contains(&id) || self.get_with(id, |_| ()).is_some() {
666                cursor.skip_record()?;
667                continue;
668            }
669            let record = cursor
670                .next_record(limit_bytes)?
671                .expect("invariant: peeked physical row exists");
672            let (mut entity, _) = record.decode_with_budget(backing.format_version, limit_bytes)?;
673            self.restore_owned_row_schemas(std::iter::once(&mut entity));
674            if crate::storage::segment_key_lookup::SegmentKeyLookup::key(&entity) != Some(key)
675                || (versioned && !Self::scan_entity_visible(snapshot, &entity))
676            {
677                continue;
678            }
679            if best.as_ref().is_none_or(|(xmin, _)| entity.xmin >= *xmin) {
680                best = Some((entity.xmin, project(&entity)));
681            }
682            if !versioned {
683                break;
684            }
685        }
686        Ok(best.map(|(_, projected)| projected))
687    }
688
689    /// Visit the merged physical view in ID order without hydrating the base.
690    /// Only overlay identities and one decoded base record are retained. Like
691    /// resident visitors, callbacks must not mutate or re-enter this collection.
692    pub fn try_for_each_entity(
693        &self,
694        limit_bytes: usize,
695        mut callback: impl FnMut(&UnifiedEntity) -> bool,
696    ) -> Result<(), StoreError> {
697        let backing_guard = self.backing.read();
698        let Some(backing) = backing_guard.as_ref() else {
699            self.for_each_entity(callback);
700            return Ok(());
701        };
702        self.try_for_each_backed_entity(backing, limit_bytes, 0, |entity| callback(&entity))
703    }
704
705    fn try_for_each_backed_entity(
706        &self,
707        backing: &BackingRead,
708        limit_bytes: usize,
709        mut skip: usize,
710        mut callback: impl FnMut(std::borrow::Cow<'_, UnifiedEntity>) -> bool,
711    ) -> Result<(), StoreError> {
712        let limit_bytes = limit_bytes.min(backing.read_bytes_max);
713        let mut identities = Vec::new();
714        self.for_each_entity(|entity| {
715            identities.push(entity.id);
716            true
717        });
718        identities.sort_unstable();
719        identities.dedup();
720        let mut identities = identities.into_iter().peekable();
721        let mut cursor = backing.source.cursor()?;
722        loop {
723            let base = cursor.peek_id()?;
724            let resident = identities.peek().copied();
725            if let Some(id) = resident.filter(|id| base.is_none_or(|base| *id <= base)) {
726                if base == Some(id) {
727                    cursor.skip_record()?;
728                }
729                identities.next();
730                let result = self.get_with(id, |entity| {
731                    if skip > 0 {
732                        skip -= 1;
733                        return Ok(true);
734                    }
735                    let required_bytes = crate::storage::memory_size::entity_bytes(entity);
736                    if required_bytes > limit_bytes {
737                        return Err(StoreError::ReadLimitExceeded {
738                            required_bytes,
739                            limit_bytes,
740                        });
741                    }
742                    Ok(callback(std::borrow::Cow::Borrowed(entity)))
743                });
744                if result.transpose()? == Some(false) {
745                    return Ok(());
746                }
747                continue;
748            }
749            let Some(id) = base else {
750                return Ok(());
751            };
752            if backing.removed.contains(&id) {
753                cursor.skip_record()?;
754                continue;
755            }
756            if skip > 0 {
757                skip -= 1;
758                cursor.skip_record()?;
759                continue;
760            }
761            let record = cursor
762                .next_record(limit_bytes)?
763                .expect("invariant: peeked physical row exists");
764            let (mut entity, _) = record.decode_with_budget(
765                backing.format_version,
766                limit_bytes.min(backing.read_bytes_max),
767            )?;
768            self.restore_owned_row_schemas(std::iter::once(&mut entity));
769            if !callback(std::borrow::Cow::Owned(entity)) {
770                return Ok(());
771            }
772        }
773    }
774
775    /// Page the same base/overlay physical view used by fallible query reads.
776    /// Prefix records are skipped without decoding; only the requested page is
777    /// cloned. The manager's counter includes base rows and resident mutations.
778    pub fn try_page_in_id_order(
779        &self,
780        offset: usize,
781        limit: usize,
782        limit_bytes: usize,
783    ) -> Result<(usize, Vec<UnifiedEntity>), StoreError> {
784        let backing_guard = self.backing.read();
785        let total = self.count();
786        if offset >= total || limit == 0 {
787            return Ok((total, Vec::new()));
788        }
789        let mut items = Vec::new();
790        let mut retained_bytes = 0_usize;
791        let mut error = None;
792        let mut capture = |mut entity: std::borrow::Cow<'_, UnifiedEntity>| {
793            // Eager file recovery sees these named records before runtime
794            // rehydrates the declared column schema. Reproduce that layout
795            // only for decoded base rows; live overlays keep their wire shape.
796            if let std::borrow::Cow::Owned(entity) = &mut entity {
797                self.restore_recovery_row_layout(entity, None);
798            }
799            let required_bytes =
800                retained_bytes.saturating_add(crate::storage::memory_size::entity_bytes(&entity));
801            if required_bytes > limit_bytes {
802                error = Some(StoreError::ReadLimitExceeded {
803                    required_bytes,
804                    limit_bytes,
805                });
806                return false;
807            }
808            retained_bytes = required_bytes;
809            items.push(entity.into_owned());
810            items.len() < limit
811        };
812        if let Some(backing) = backing_guard.as_ref() {
813            self.try_for_each_backed_entity(backing, limit_bytes, offset, &mut capture)?;
814        } else {
815            let mut skip = offset;
816            self.for_each_entity_in_id_order(|entity| {
817                if skip > 0 {
818                    skip -= 1;
819                    return true;
820                }
821                capture(std::borrow::Cow::Borrowed(entity))
822            });
823        }
824        if let Some(error) = error {
825            return Err(error);
826        }
827        self.restore_owned_row_schemas(items.iter_mut());
828        Ok((total, items))
829    }
830
831    /// Page a caller-filtered logical view while keeping the visible total exact.
832    /// Unlike post-page filtering, this never leaks the number or position of
833    /// rows rejected by `predicate`.
834    pub fn try_page_in_id_order_where(
835        &self,
836        offset: usize,
837        limit: usize,
838        limit_bytes: usize,
839        predicate: impl FnMut(&UnifiedEntity) -> bool,
840    ) -> Result<(usize, Vec<UnifiedEntity>), StoreError> {
841        self.try_page_in_id_order_where_at_snapshot(None, offset, limit, limit_bytes, predicate)
842    }
843
844    /// Page a caller-filtered logical view under an explicit MVCC snapshot.
845    /// Visibility is applied before the predicate, total, and offset so an
846    /// aborted writer or an in-progress deleter cannot distort pagination.
847    pub fn try_page_in_id_order_where_at_snapshot(
848        &self,
849        snapshot: Option<&SnapshotContext>,
850        offset: usize,
851        limit: usize,
852        limit_bytes: usize,
853        mut predicate: impl FnMut(&UnifiedEntity) -> bool,
854    ) -> Result<(usize, Vec<UnifiedEntity>), StoreError> {
855        let mut visible = 0_usize;
856        let mut retained_bytes = 0_usize;
857        let mut items = Vec::new();
858        let mut error = None;
859        self.try_scan_for_each(snapshot, limit_bytes, |entity| {
860            if !predicate(entity) {
861                return true;
862            }
863            let position = visible;
864            visible = visible.saturating_add(1);
865            if position < offset || items.len() >= limit {
866                return true;
867            }
868            let required_bytes =
869                retained_bytes.saturating_add(crate::storage::memory_size::entity_bytes(entity));
870            if required_bytes > limit_bytes {
871                error = Some(StoreError::ReadLimitExceeded {
872                    required_bytes,
873                    limit_bytes,
874                });
875                return false;
876            }
877            retained_bytes = required_bytes;
878            items.push(entity.clone());
879            true
880        })?;
881        if let Some(error) = error {
882            return Err(error);
883        }
884        self.restore_owned_row_schemas(items.iter_mut());
885        Ok((visible, items))
886    }
887
888    /// Physical key history. Indexed bases avoid unrelated payload reads;
889    /// resident and unindexed sources still verify each logical key.
890    pub fn try_for_each_key_entity(
891        &self,
892        key: &str,
893        mut callback: impl FnMut(&UnifiedEntity) -> bool,
894    ) -> Result<(), StoreError> {
895        if let Some(cursor) = self.try_paged_key_physical_cursor(key)? {
896            for record in cursor {
897                let (entity, _) = record?;
898                if !callback(&entity) {
899                    break;
900                }
901            }
902            return Ok(());
903        }
904        self.try_for_each_entity(usize::MAX, |entity| {
905            crate::storage::segment_key_lookup::SegmentKeyLookup::key(entity) != Some(key)
906                || callback(entity)
907        })
908    }
909
910    pub fn try_scan_for_each(
911        &self,
912        snapshot: Option<&SnapshotContext>,
913        limit_bytes: usize,
914        mut callback: impl FnMut(&UnifiedEntity) -> bool,
915    ) -> Result<(), StoreError> {
916        self.try_for_each_entity(limit_bytes, |entity| {
917            !Self::scan_entity_visible(snapshot, entity) || callback(entity)
918        })
919    }
920
921    /// The disk base has no segment zone summaries yet: scan all candidates
922    /// and retain the caller's residual predicate. Resident mode keeps pruning.
923    pub fn try_scan_for_each_zoned_with_stats(
924        &self,
925        snapshot: Option<&SnapshotContext>,
926        zone_preds: &[(&str, ZoneColPred<'_>)],
927        limit_bytes: usize,
928        callback: impl FnMut(&UnifiedEntity) -> bool,
929    ) -> Result<SegmentScanStats, StoreError> {
930        if !self.has_backing() {
931            return Ok(self.scan_for_each_zoned_with_stats(snapshot, zone_preds, callback));
932        }
933        self.try_scan_for_each(snapshot, limit_bytes, callback)?;
934        Ok(SegmentScanStats {
935            segments_total: 1,
936            segments_scanned: 1,
937            segments_pruned: 0,
938        })
939    }
940
941    /// Preserve the resident projection fast path; cold mode streams candidates.
942    /// Hosts own admission for retained projections independently of row decoding.
943    pub fn try_scan_project_zoned_with_stats<T, F>(
944        &self,
945        snapshot: Option<&SnapshotContext>,
946        zone_preds: &[(&str, ZoneColPred<'_>)],
947        read_bytes_max: usize,
948        project: F,
949    ) -> Result<(Vec<T>, SegmentScanStats), StoreError>
950    where
951        T: Send,
952        F: Fn(&UnifiedEntity) -> Option<T> + Sync,
953    {
954        if !self.has_backing() {
955            return Ok(self.scan_project_zoned_with_stats(snapshot, zone_preds, project));
956        }
957        let mut projected = Vec::new();
958        let stats = self.try_scan_for_each_zoned_with_stats(
959            snapshot,
960            zone_preds,
961            read_bytes_max,
962            |entity| {
963                if let Some(value) = project(entity) {
964                    projected.push(value);
965                }
966                true
967            },
968        )?;
969        Ok((projected, stats))
970    }
971
972    /// Point-read allowance applies to each row. Hosts separately admit the
973    /// retained output vector; this method is not a global result quota.
974    pub fn try_get_many(
975        &self,
976        ids: &[EntityId],
977        read_bytes_max: usize,
978    ) -> Result<Vec<Option<UnifiedEntity>>, StoreError> {
979        if !self.has_backing() && read_bytes_max == usize::MAX {
980            return Ok(self.get_many(ids));
981        }
982        ids.iter()
983            .map(|id| self.try_get(*id, read_bytes_max))
984            .collect()
985    }
986
987    pub fn try_for_each_id(
988        &self,
989        ids: &[EntityId],
990        read_bytes_max: usize,
991        mut visit: impl FnMut(usize, &UnifiedEntity) -> bool,
992    ) -> Result<(), StoreError> {
993        if self.has_backing() {
994            for (position, id) in ids.iter().enumerate() {
995                if let Some(entity) = self.try_get(*id, read_bytes_max)? {
996                    if !visit(position, &entity) {
997                        break;
998                    }
999                }
1000            }
1001            return Ok(());
1002        }
1003        let mut stopped = false;
1004        let mut failure = None;
1005        self.for_each_id(ids, |position, entity| {
1006            if stopped {
1007                return;
1008            }
1009            let required_bytes = if read_bytes_max == usize::MAX {
1010                0
1011            } else {
1012                crate::storage::memory_size::entity_bytes(entity)
1013            };
1014            if required_bytes > read_bytes_max {
1015                failure = Some(StoreError::ReadLimitExceeded {
1016                    required_bytes,
1017                    limit_bytes: read_bytes_max,
1018                });
1019                stopped = true;
1020            } else {
1021                stopped = !visit(position, entity);
1022            }
1023        });
1024        failure.map_or(Ok(()), Err)
1025    }
1026
1027    /// Visit ascending physical IDs while sharing the current leaf. A pinned
1028    /// backing cannot change in place. If publication replaces it, each later
1029    /// read uses the current source, just as in `try_for_each_id`.
1030    pub fn try_for_each_sorted_id(
1031        &self,
1032        ids: &[EntityId],
1033        read_bytes_max: usize,
1034        mut visit: impl FnMut(usize, &UnifiedEntity) -> bool,
1035    ) -> Result<(), StoreError> {
1036        if ids.len() < 2 {
1037            return self.try_for_each_id(ids, read_bytes_max, visit);
1038        }
1039        let Some(source) = self.backing_source() else {
1040            return self.try_for_each_id(ids, read_bytes_max, visit);
1041        };
1042        let Some(mut probe) = source.sorted_record_probe() else {
1043            return self.try_for_each_id(ids, read_bytes_max, visit);
1044        };
1045        for (position, &id) in ids.iter().enumerate() {
1046            let entity = self.try_get_with_base(id, read_bytes_max, |base, limit| {
1047                if Arc::ptr_eq(&source, &base.source) {
1048                    probe(id, limit)
1049                } else {
1050                    base.source.get_record(id, limit)
1051                }
1052            })?;
1053            if let Some(entity) = entity {
1054                if !visit(position, &entity) {
1055                    break;
1056                }
1057            }
1058        }
1059        Ok(())
1060    }
1061
1062    /// Inserts must not overwrite a physical identity in the published base.
1063    pub(super) fn reject_backing_duplicate(&self, id: EntityId) -> Result<(), SegmentError> {
1064        let backing = self.backing.read();
1065        let Some(backing) = backing.as_ref() else {
1066            return Ok(());
1067        };
1068        if !backing.removed.contains(&id)
1069            && backing
1070                .source
1071                .get_record(id, backing.read_bytes_max)
1072                .map_err(|error| SegmentError::BackingRead(error.to_string()))?
1073                .is_some()
1074        {
1075            return Err(SegmentError::AlreadyExists(id));
1076        }
1077        Ok(())
1078    }
1079
1080    /// Metadata reads carry the same I/O failure contract as entity reads.
1081    pub fn try_get_metadata(
1082        &self,
1083        id: EntityId,
1084        limit_bytes: usize,
1085    ) -> Result<Option<Metadata>, StoreError> {
1086        let backing = self.backing.read();
1087        if self.get_with(id, |_| ()).is_some() {
1088            return Ok(self.get_metadata(id));
1089        }
1090        let Some(backing) = backing.as_ref() else {
1091            return Ok(None);
1092        };
1093        if backing.removed.contains(&id) {
1094            return Ok(None);
1095        }
1096        backing
1097            .source
1098            .get_record(id, limit_bytes.min(backing.read_bytes_max))?
1099            .map(|record| {
1100                record
1101                    .decode_with_budget(
1102                        backing.format_version,
1103                        limit_bytes.min(backing.read_bytes_max),
1104                    )
1105                    .map(|(_, metadata)| metadata)
1106            })
1107            .transpose()
1108            .map(Option::flatten)
1109    }
1110
1111    /// Rebuild one legacy per-row TTL projection entry without materializing
1112    /// the cold row. The caller inventories IDs in bounded ticks.
1113    pub fn rebuild_metadata_expiry(&self, id: EntityId) -> Result<(), StoreError> {
1114        if let Some(entity) = self.get(id) {
1115            let metadata = self.get_metadata(id);
1116            self.restore_metadata_expiry(&entity, metadata.as_ref());
1117            return Ok(());
1118        }
1119        let backing = self.backing.read();
1120        let Some(backing) = backing.as_ref() else {
1121            self.remove_metadata_expiry(id);
1122            return Ok(());
1123        };
1124        if backing.removed.contains(&id) {
1125            self.remove_metadata_expiry(id);
1126            return Ok(());
1127        }
1128        let record = backing.source.get_record(id, backing.read_bytes_max)?;
1129        let Some(record) = record else {
1130            self.remove_metadata_expiry(id);
1131            return Ok(());
1132        };
1133        let (entity, metadata) =
1134            record.decode_with_budget(backing.format_version, backing.read_bytes_max)?;
1135        self.restore_metadata_expiry(&entity, metadata.as_ref());
1136        Ok(())
1137    }
1138
1139    pub(super) fn materialize_backing_entity(&self, id: EntityId) -> Result<(), SegmentError> {
1140        if self.get_with(id, |_| ()).is_some() {
1141            return Ok(());
1142        }
1143        let record = {
1144            let backing = self.backing.read();
1145            let Some(backing) = backing.as_ref() else {
1146                return Ok(());
1147            };
1148            if backing.removed.contains(&id) {
1149                return Ok(());
1150            }
1151            backing
1152                .source
1153                .get_record(id, backing.read_bytes_max)
1154                .and_then(|record| {
1155                    record
1156                        .map(|record| {
1157                            record
1158                                .decode_with_budget(backing.format_version, backing.read_bytes_max)
1159                        })
1160                        .transpose()
1161                })
1162                .map_err(|error| SegmentError::BackingRead(error.to_string()))?
1163        };
1164        let Some((mut entity, metadata)) = record else {
1165            return Ok(());
1166        };
1167        self.restore_owned_row_schemas(std::iter::once(&mut entity));
1168        self.restore_snapshot_entity(entity)?;
1169        // This row was already included in the persisted cardinality.
1170        self.total_entities_atomic.fetch_sub(1, Ordering::Relaxed);
1171        if let Some(metadata) = metadata {
1172            self.set_metadata(id, metadata)?;
1173        }
1174        Ok(())
1175    }
1176
1177    pub(super) fn remember_backing_delete(&self, id: EntityId) {
1178        if let Some(backing) = self.backing.write().as_mut() {
1179            backing.removed.insert(id);
1180            backing.logged_removals.remove(&id);
1181            // A confirmation still waiting belongs to an earlier removal of this row.
1182            self.unconfirmed_removals
1183                .lock()
1184                .retain(|other| *other != id);
1185        }
1186    }
1187
1188    /// Called under the publication fence after a successful WAL append.
1189    #[doc(hidden)]
1190    pub fn confirm_logged_removals(&self, ids: &[EntityId]) {
1191        // Do not make collection maintenance wait for a base reader under the
1192        // host's publication fence: keep the confirmation for whoever takes
1193        // the backing next. Dropping it made the next checkpoint treat the
1194        // removal as unlogged and publish the whole collection again.
1195        let Some(mut backing) = self.backing.try_write() else {
1196            let mut waiting = self.unconfirmed_removals.lock();
1197            if waiting.len() + ids.len() <= crate::storage::segment::CHECKPOINT_MUTATIONS_MAX {
1198                waiting.extend_from_slice(ids);
1199            }
1200            return;
1201        };
1202        if let Some(base) = backing.as_mut() {
1203            self.fold_unconfirmed_removals(base);
1204            if base.removed.len() <= crate::storage::segment::CHECKPOINT_MUTATIONS_MAX {
1205                base.logged_removals
1206                    .extend(ids.iter().copied().filter(|id| base.removed.contains(id)));
1207            }
1208        }
1209    }
1210
1211    fn fold_unconfirmed_removals(&self, base: &mut BackingRead) {
1212        let waiting = std::mem::take(&mut *self.unconfirmed_removals.lock());
1213        if base.removed.len() <= crate::storage::segment::CHECKPOINT_MUTATIONS_MAX {
1214            base.logged_removals
1215                .extend(waiting.into_iter().filter(|id| base.removed.contains(id)));
1216        }
1217    }
1218
1219    pub fn backing_overlay(
1220        &self,
1221        mut encode: impl FnMut(&UnifiedEntity, Option<Metadata>) -> Option<Vec<u8>>,
1222    ) -> Option<(Arc<dyn CollectionRead + Send + Sync>, Arc<FrozenOverlay>)> {
1223        let backing = self.backing.read();
1224        let backing = backing.as_ref()?;
1225        let mut overlay: FrozenOverlay = backing.removed.iter().map(|id| (*id, None)).collect();
1226        self.for_each_entity_with_metadata(|entity, metadata| {
1227            if let Some(bytes) = encode(entity, metadata) {
1228                overlay.insert(entity.id, Some(Arc::from(bytes)));
1229            }
1230            true
1231        });
1232        Some((Arc::clone(&backing.source), Arc::new(overlay)))
1233    }
1234
1235    pub fn current_backing_overlay(
1236        &self,
1237    ) -> Option<(Arc<dyn CollectionRead + Send + Sync>, Arc<FrozenOverlay>)> {
1238        let version = self.backing.read().as_ref()?.format_version;
1239        self.backing_overlay(|entity, metadata| {
1240            Some(serialize_entity_record(entity, metadata.as_ref(), version))
1241        })
1242    }
1243
1244    fn current_backing_key_overlay(
1245        &self,
1246        key: &str,
1247    ) -> Result<Option<(Arc<dyn CollectionRead + Send + Sync>, Arc<FrozenOverlay>)>, StoreError>
1248    {
1249        let backing = self.backing.read();
1250        let Some(backing) = backing.as_ref() else {
1251            return Ok(None);
1252        };
1253        let mut overlay: FrozenOverlay = backing.removed.iter().map(|id| (*id, None)).collect();
1254        let schema = self.column_schema();
1255        let key_column = schema
1256            .as_ref()
1257            .and_then(|schema| schema.iter().position(|name| name == "key"));
1258        let mut failure = None;
1259        self.for_each_entity_source(|segment, entity| {
1260            let key_matches = match (&entity.data, key_column) {
1261                (crate::storage::entity::EntityData::Row(row), Some(index)) if row.named.is_none() && row.schema.is_none() => {
1262                    matches!(row.columns.get(index), Some(reddb_types::Value::Text(stored)) if stored.as_ref() == key)
1263                }
1264                _ => crate::storage::segment_key_lookup::SegmentKeyLookup::key(entity) == Some(key),
1265            };
1266            let bytes = if key_matches {
1267                let required_bytes = crate::storage::memory_size::entity_bytes(entity);
1268                if required_bytes > backing.read_bytes_max {
1269                    failure = Some(StoreError::ReadLimitExceeded {
1270                        required_bytes,
1271                        limit_bytes: backing.read_bytes_max,
1272                    });
1273                    return false;
1274                }
1275                let metadata = segment.get_metadata(entity.id);
1276                Some(Arc::from(serialize_entity_record(entity, metadata.as_ref(), backing.format_version)))
1277            } else {
1278                // A row renamed away from the requested key must still hide
1279                // the old base candidate. No unrelated payload/metadata copy.
1280                None
1281            };
1282            overlay.insert(entity.id, bytes);
1283            true
1284        });
1285        if let Some(error) = failure {
1286            return Err(error);
1287        }
1288        Ok(Some((Arc::clone(&backing.source), Arc::new(overlay))))
1289    }
1290}