Skip to main content

reddb_engine/storage/manager/
backing.rs

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