uqa-storage 0.5.3

Document store, inverted index, IVF/HNSW vectors, B-tree, R*Tree, catalog
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
//
// Unified Query Algebra
//
// Copyright (c) 2023-2026 Cognica, Inc.
//

//! Provider-independent reads combine one pinned committed boundary with a fixed private command view.

mod fingerprint;
mod last;
mod selected;
pub use selected::SelectedRecordRead;

use std::cmp::Ordering;
use std::sync::Arc;

use uqa_core::memory::{BudgetedVec, MemoryReservation};

use crate::read_control::StorageReadControl;

use super::{
    CommitSequence, PreparedRecordWrite, PrivateRecordSnapshot, RecordVersion, ScannedRecord,
    SharedRecordValue, VersionResult,
};

#[derive(Clone, Copy)]
pub struct BorrowedRecord<'a> {
    pub revision: Option<CommitSequence>,
    pub value: Option<&'a [u8]>,
}

/// Visible revision metadata, including tombstones, without retaining the encoded payload.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct RecordMetadata {
    pub revision: Option<CommitSequence>,
    pub live: bool,
}

/// Exact identity of a live record on one committed/private view. Compare only for the same physical key; history and undo-branch identities distinguish equal payloads that were replaced.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct VisibleRecordRevision {
    database: super::DatabaseId,
    committed: Option<CommitSequence>,
    private: Option<super::PrivateRecordRevision>,
}

impl VisibleRecordRevision {
    pub(crate) fn committed(self, database: super::DatabaseId) -> Option<CommitSequence> {
        (self.database == database && self.private.is_none())
            .then_some(self.committed)
            .flatten()
    }

    /// The committed sequence this view includes, whether or not private changes accompany it.
    pub(crate) fn committed_sequence(self) -> Option<CommitSequence> {
        self.committed
    }

    pub(crate) fn database(self) -> super::DatabaseId {
        self.database
    }

    pub fn is_private(self) -> bool {
        self.private.is_some()
    }
}

impl From<BorrowedRecord<'_>> for RecordMetadata {
    fn from(record: BorrowedRecord<'_>) -> Self {
        Self {
            revision: record.revision,
            live: record.value.is_some(),
        }
    }
}

pub type RecordValueVisitor<'a> = dyn FnMut(Option<BorrowedRecord<'_>>) -> VersionResult<()> + 'a;
pub type RecordPointVisitor<'a> =
    dyn FnMut(&[u8], Option<BorrowedRecord<'_>>) -> VersionResult<bool> + 'a;
pub type RecordKeyIterator<'a> = dyn Iterator<Item = VersionResult<BudgetedVec<u8>>> + 'a;
pub type RecordScanVisitor<'a> = dyn FnMut(&[u8], BorrowedRecord<'_>) -> VersionResult<bool> + 'a;
pub type RecordKeyVisitor<'a> = dyn FnMut(&[u8], RecordMetadata) -> VersionResult<bool> + 'a;

/// A lazy sequence of metadata requests. A successful `advance` exposes one key until `accept` receives its result, including absent records and tombstones. These methods are storage-internal: they must not reenter a provider or execute user callbacks. Returning `false` closes the read window; an error stops before producing another key.
pub trait RecordMetadataRequests {
    fn advance(&mut self) -> VersionResult<bool>;
    fn key(&self) -> &[u8];
    fn accept(&mut self, metadata: Option<RecordMetadata>) -> VersionResult<()>;
}

/// A retained committed view whose lease protects visible versions until this owner is dropped. Provider read windows must finish inside each call, without retaining a physical writer or calling user code.
pub trait CommittedRecordSnapshot: Send + Sync {
    fn sequence(&self) -> CommitSequence;

    /// The provider's tombstone-reclamation epoch captured under the same admission as this snapshot. `None` means this provider does not supply reclamation-aware observations. Wrappers must forward the original value, never refresh it from current storage.
    fn reclamation_epoch(&self) -> Option<u64> {
        None
    }

    /// The provider's own snapshot type, which its native read paths may serve from physical projections at the same boundary. Wrappers must forward the original provider snapshot.
    fn provider_snapshot(&self) -> Option<&dyn std::any::Any> {
        None
    }

    /// The value [`VersionedPersistence::commit_monitor_version`](super::VersionedPersistence::commit_monitor_version) returned before this snapshot was captured. While the monitor still returns it, nothing was committed after the capture began, so this snapshot is the latest one. `None` when the provider has no monitor. Wrappers must forward the original value.
    fn commit_monitor(&self) -> Option<u64> {
        None
    }

    /// Take the monitor value another snapshot of this same sequence was captured at. Nothing was committed between the two captures, so this snapshot is the latest one for as long as the monitor returns that value. Returns false when the snapshot cannot change its value, and its holder then keeps the other snapshot instead. Keeping this one keeps what it has already read of its records.
    fn adopt_commit_monitor(&self, _monitor: u64) -> bool {
        false
    }

    /// Read a revision and tombstone marker without materializing its value when the provider supports key-only access.
    fn metadata(
        &self,
        key: &[u8],
        control: &StorageReadControl,
    ) -> VersionResult<Option<RecordMetadata>> {
        let mut found = None;
        self.visit_value(key, control, &mut |record| {
            found = record.map(Into::into);
            Ok(())
        })?;
        Ok(found)
    }

    /// Resolve requested revisions in input order through `metadata`, without fetching payloads on key-only providers. Providers may share one physical read window, admitted only after the first key; the snapshot boundary, cancellation and each point-read diagnostic remain unchanged.
    fn visit_metadata(
        &self,
        requests: &mut dyn RecordMetadataRequests,
        control: &StorageReadControl,
    ) -> VersionResult<()> {
        loop {
            control.check()?;
            if !requests.advance()? {
                return control.check().map_err(Into::into);
            }
            control.check()?;
            let metadata = self.metadata(requests.key(), control)?;
            requests.accept(metadata)?;
        }
    }

    /// Visit ordered record identities, including tombstones, without fetching values from providers with key-only access.
    fn visit_keys(
        &self,
        prefix: &[u8],
        after: Option<&[u8]>,
        limit: usize,
        control: &StorageReadControl,
        visit: &mut RecordKeyVisitor<'_>,
    ) -> VersionResult<()> {
        self.visit_prefix(prefix, after, limit, control, &mut |key, record| {
            visit(key, record.into())
        })
    }

    /// Visit the greatest visible identity with this prefix strictly before `before`, including a tombstone. Invoke the visitor at most once; providers may seek directly without reading preceding keys or values. The default preserves semantics for providers that only implement forward scans.
    fn visit_last_key(
        &self,
        prefix: &[u8],
        before: Option<&[u8]>,
        control: &StorageReadControl,
        visit: &mut RecordKeyVisitor<'_>,
    ) -> VersionResult<()> {
        last::by_scan(self, prefix, before, control, visit)
    }

    /// Return the newest revision at or before this snapshot, including tombstones. Missing identities return `None`.
    fn get(
        &self,
        key: &[u8],
        control: &StorageReadControl,
    ) -> VersionResult<Option<RecordVersion<SharedRecordValue>>>;

    /// Return at most `limit` unique keys in ascending order, strictly after `after`, including tombstones. A short page means that the prefix is exhausted at this snapshot; all pages keep the same boundary.
    fn scan(
        &self,
        prefix: &[u8],
        after: Option<&[u8]>,
        limit: usize,
        control: &StorageReadControl,
    ) -> VersionResult<BudgetedVec<ScannedRecord>>;

    /// Borrow provider-owned bytes for an internal storage visitor. Visitors must not reenter this snapshot or execute SQL/user callbacks.
    fn visit_value(
        &self,
        key: &[u8],
        control: &StorageReadControl,
        visit: &mut RecordValueVisitor<'_>,
    ) -> VersionResult<()> {
        let record = self.get(key, control)?;
        visit(record.as_ref().map(|record| BorrowedRecord {
            revision: Some(record.sequence()),
            value: record.value().map(|value| &***value),
        }))?;
        control.cancellation().check()?;
        Ok(())
    }

    /// Check a live value's encoded size before provider materialization, without changing revision or tombstone visibility. The default rejects unsupported providers rather than materializing through `get`.
    fn visit_value_bounded(
        &self,
        _key: &[u8],
        _max_bytes: usize,
        control: &StorageReadControl,
        _visit: &mut RecordValueVisitor<'_>,
    ) -> VersionResult<()> {
        control.check()?;
        Err(crate::StorageBackendError::Other(
            "size-bounded committed record reads are not supported".into(),
        )
        .into())
    }

    /// Borrow requested values in input order under one optional provider read window. Key production and visitors are internal and must not reenter storage or invoke user code. Produce one key at a time; a false visitor or an error stops before requesting the next key, including duplicate and missing identities.
    fn visit_values(
        &self,
        keys: &mut RecordKeyIterator<'_>,
        control: &StorageReadControl,
        visit: &mut RecordPointVisitor<'_>,
    ) -> VersionResult<()> {
        loop {
            control.check()?;
            let Some(key) = keys.next() else {
                return Ok(());
            };
            let key = key?;
            let mut more = true;
            self.visit_value(&key, control, &mut |record| {
                more = visit(&key, record)?;
                Ok(())
            })?;
            control.check()?;
            if !more {
                return Ok(());
            }
        }
    }

    /// Visit ordered versions until the limit, exhaustion or a visitor returning `false`. Implementations with borrowed pages avoid charging their encoded payloads to the caller's decode allowance.
    fn visit_prefix(
        &self,
        prefix: &[u8],
        after: Option<&[u8]>,
        limit: usize,
        control: &StorageReadControl,
        visit: &mut RecordScanVisitor<'_>,
    ) -> VersionResult<()> {
        control.cancellation().check()?;
        let mut cursor: Option<BudgetedVec<u8>> = None;
        let mut remaining = limit;
        while remaining != 0 {
            let mut page = self.scan(
                prefix,
                cursor.as_deref().or(after),
                remaining.min(64),
                control,
            )?;
            if page.is_empty() {
                break;
            }
            for record in page.iter() {
                control.cancellation().check()?;
                if !visit(
                    &record.key,
                    BorrowedRecord {
                        revision: Some(record.version.sequence()),
                        value: record.version.value().map(|value| &***value),
                    },
                )? {
                    control.cancellation().check()?;
                    return Ok(());
                }
                remaining -= 1;
            }
            cursor = page.pop().map(|record| record.key);
        }
        control.cancellation().check()?;
        Ok(())
    }
}

struct RetainedSnapshot<T> {
    snapshot: T,
    _memory: MemoryReservation,
}

/// Charge a provider snapshot's retained metadata before allocating its shared owner. The provider snapshot itself owns any version-retention lease required by its format.
pub fn retain_record_snapshot<T: CommittedRecordSnapshot + 'static>(
    snapshot: T,
    control: &StorageReadControl,
) -> VersionResult<Arc<dyn CommittedRecordSnapshot>> {
    control.cancellation().check()?;
    let memory = control
        .memory()
        .reserve(std::mem::size_of::<RetainedSnapshot<T>>())?;
    Ok(Arc::new(RetainedSnapshot {
        snapshot,
        _memory: memory,
    }))
}

impl<T: CommittedRecordSnapshot> CommittedRecordSnapshot for RetainedSnapshot<T> {
    fn sequence(&self) -> CommitSequence {
        self.snapshot.sequence()
    }
    fn reclamation_epoch(&self) -> Option<u64> {
        self.snapshot.reclamation_epoch()
    }
    fn provider_snapshot(&self) -> Option<&dyn std::any::Any> {
        self.snapshot.provider_snapshot()
    }
    fn commit_monitor(&self) -> Option<u64> {
        self.snapshot.commit_monitor()
    }
    fn adopt_commit_monitor(&self, monitor: u64) -> bool {
        self.snapshot.adopt_commit_monitor(monitor)
    }
    fn visit_last_key(
        &self,
        prefix: &[u8],
        before: Option<&[u8]>,
        control: &StorageReadControl,
        visit: &mut RecordKeyVisitor<'_>,
    ) -> VersionResult<()> {
        self.snapshot.visit_last_key(prefix, before, control, visit)
    }
    fn metadata(
        &self,
        key: &[u8],
        control: &StorageReadControl,
    ) -> VersionResult<Option<RecordMetadata>> {
        self.snapshot.metadata(key, control)
    }
    fn visit_metadata(
        &self,
        requests: &mut dyn RecordMetadataRequests,
        control: &StorageReadControl,
    ) -> VersionResult<()> {
        self.snapshot.visit_metadata(requests, control)
    }
    fn visit_keys(
        &self,
        prefix: &[u8],
        after: Option<&[u8]>,
        limit: usize,
        control: &StorageReadControl,
        visit: &mut RecordKeyVisitor<'_>,
    ) -> VersionResult<()> {
        self.snapshot
            .visit_keys(prefix, after, limit, control, visit)
    }
    fn get(
        &self,
        key: &[u8],
        control: &StorageReadControl,
    ) -> VersionResult<Option<RecordVersion<SharedRecordValue>>> {
        self.snapshot.get(key, control)
    }
    fn scan(
        &self,
        prefix: &[u8],
        after: Option<&[u8]>,
        limit: usize,
        control: &StorageReadControl,
    ) -> VersionResult<BudgetedVec<ScannedRecord>> {
        self.snapshot.scan(prefix, after, limit, control)
    }
    fn visit_value(
        &self,
        key: &[u8],
        control: &StorageReadControl,
        visit: &mut RecordValueVisitor<'_>,
    ) -> VersionResult<()> {
        self.snapshot.visit_value(key, control, visit)
    }
    fn visit_values(
        &self,
        keys: &mut RecordKeyIterator<'_>,
        control: &StorageReadControl,
        visit: &mut RecordPointVisitor<'_>,
    ) -> VersionResult<()> {
        self.snapshot.visit_values(keys, control, visit)
    }
    fn visit_value_bounded(
        &self,
        key: &[u8],
        max_bytes: usize,
        control: &StorageReadControl,
        visit: &mut RecordValueVisitor<'_>,
    ) -> VersionResult<()> {
        self.snapshot
            .visit_value_bounded(key, max_bytes, control, visit)
    }
    fn visit_prefix(
        &self,
        prefix: &[u8],
        after: Option<&[u8]>,
        limit: usize,
        control: &StorageReadControl,
        visit: &mut RecordScanVisitor<'_>,
    ) -> VersionResult<()> {
        self.snapshot
            .visit_prefix(prefix, after, limit, control, visit)
    }
}

/// Visible payload plus its original committed precondition. Private deletions remain observable as tombstones rather than falling back to the committed value.
pub struct VisibleRecord {
    original: Option<CommitSequence>,
    value: Option<SharedRecordValue>,
    private: bool,
}

impl VisibleRecord {
    pub fn original_revision(&self) -> Option<CommitSequence> {
        self.original
    }

    pub fn value(&self) -> Option<&[u8]> {
        self.value.as_ref().map(|value| &***value)
    }

    pub fn is_private(&self) -> bool {
        self.private
    }

    fn committed(version: RecordVersion<SharedRecordValue>) -> Self {
        let (sequence, value) = version.into_parts();
        Self {
            original: Some(sequence),
            value,
            private: false,
        }
    }

    fn private(write: &PreparedRecordWrite) -> Self {
        Self {
            original: write.expected(),
            value: write.shared_value(),
            private: true,
        }
    }
}

pub struct ScannedVisibleRecord {
    pub key: BudgetedVec<u8>,
    pub record: VisibleRecord,
}

/// Retain both boundaries across reads and paging. The transaction owner chooses when a later SQL command acquires a new committed snapshot; this reader never advances either boundary implicitly.
pub struct MergedRecordSnapshot {
    committed: Arc<dyn CommittedRecordSnapshot>,
    private: PrivateRecordSnapshot,
    serializable: Option<super::SerializableReadContext>,
}

impl MergedRecordSnapshot {
    pub(in crate::mvcc) fn retained_source(
        &self,
        key: &[u8],
        control: &StorageReadControl,
    ) -> VersionResult<Option<Arc<dyn crate::key_value::KeyValueRead + Send + Sync>>> {
        self.private.retained_source(key, control)
    }

    /// Select one live record's actual revision without materializing its payload. The owning provider supplies this snapshot's transaction-history identity, distinct from any restored data namespace.
    pub fn record_revision(
        &self,
        database: super::DatabaseId,
        key: &[u8],
        control: &StorageReadControl,
    ) -> VersionResult<Option<VisibleRecordRevision>> {
        control.check()?;
        let (metadata, private) = match self.private.revision_metadata(key, control)? {
            Some((metadata, revision)) => (Some(metadata), Some(revision)),
            None => (self.committed.metadata(key, control)?, None),
        };
        let Some(metadata) = metadata.filter(|record| record.live) else {
            control.check()?;
            return Ok(None);
        };
        control.check()?;
        Ok(Some(VisibleRecordRevision {
            database,
            committed: metadata.revision,
            private,
        }))
    }

    /// Share the committed owner and retain the original private revision under its existing allowance.
    pub fn try_clone(&self) -> VersionResult<Self> {
        Ok(Self {
            committed: Arc::clone(&self.committed),
            private: self.private.try_clone()?,
            serializable: self.serializable.clone(),
        })
    }

    pub fn new(
        committed: Arc<dyn CommittedRecordSnapshot>,
        private: PrivateRecordSnapshot,
    ) -> Self {
        Self {
            committed,
            private,
            serializable: None,
        }
    }

    pub(crate) fn with_serializable(
        mut self,
        context: Option<super::SerializableReadContext>,
    ) -> Self {
        self.serializable = context;
        self
    }

    /// Original logical reader attribution. Clones retain the same participant and fixed data boundaries.
    pub fn serializable(&self) -> Option<&super::SerializableReadContext> {
        self.serializable.as_ref()
    }

    pub fn sequence(&self) -> CommitSequence {
        self.committed.sequence()
    }

    /// Whole private command-root identity, restored together with its records on undo.
    pub fn private_revision(&self) -> Option<super::PrivateRecordRevision> {
        self.private.revision()
    }

    /// The pinned committed boundary underlying this command view, without private replacements.
    pub fn committed(&self) -> &dyn CommittedRecordSnapshot {
        self.committed.as_ref()
    }

    pub(super) fn retain_committed(&self) -> Arc<dyn CommittedRecordSnapshot> {
        Arc::clone(&self.committed)
    }

    /// Bounded private key metadata for provider-derived cache invalidation; values are never materialized.
    pub fn private_keys(
        &self,
        prefix: &[u8],
        after: Option<&[u8]>,
        limit: usize,
        control: &StorageReadControl,
    ) -> VersionResult<BudgetedVec<super::PrivateRecordKey>> {
        self.private.scan_keys(prefix, after, limit, control)
    }

    /// Newest private revisions per provider-selected cache scope, or exact changed keys when the provider supplies no classifier. The summary shares this view's undo boundary and spills under the same allowance.
    pub fn private_revision_scopes(
        &self,
        after: Option<&[u8]>,
        limit: usize,
        control: &StorageReadControl,
    ) -> VersionResult<BudgetedVec<super::PrivateRecordKey>> {
        self.private.revision_scopes(after, limit, control)
    }

    /// Read one complete provider-selected revision scope without scanning its changed records. The caller must pass a scope emitted by its provider's classifier, not a narrower or broader prefix. Providers without a classifier scan that prefix's key metadata using one retained cursor.
    pub fn private_scope_revision(
        &self,
        scope: &[u8],
        control: &StorageReadControl,
    ) -> VersionResult<Option<super::PrivateRecordRevision>> {
        self.private.scope_revision(scope, control)
    }

    /// Stream private entries on this command boundary without repeated key lookups. Providers can merge their committed rows with each entry's metadata or requested payload.
    pub fn private_cursor(
        &self,
        prefix: &[u8],
        after: Option<&[u8]>,
        control: &StorageReadControl,
    ) -> VersionResult<super::PrivateRecordCursor<'_>> {
        self.private.cursor(prefix, after, control)
    }

    pub fn visit_value(
        &self,
        key: &[u8],
        control: &StorageReadControl,
        visit: &mut RecordValueVisitor<'_>,
    ) -> VersionResult<()> {
        if let Some(write) = self.private.get(key, control)? {
            visit(Some(BorrowedRecord {
                revision: write.expected(),
                value: write.value(),
            }))?;
            control.cancellation().check()?;
            return Ok(());
        }
        self.committed.visit_value(key, control, visit)
    }

    /// Keep private replacements ahead of committed values while allowing an unchanged command view to reuse the provider's point-read window.
    pub fn visit_values(
        &self,
        keys: &mut RecordKeyIterator<'_>,
        control: &StorageReadControl,
        visit: &mut RecordPointVisitor<'_>,
    ) -> VersionResult<()> {
        self.selected(control).visit_values(keys, control, visit)
    }

    /// Preserve private replacement/tombstone precedence while enforcing the physical source's encoded-value cap.
    pub fn visit_value_bounded(
        &self,
        key: &[u8],
        max_bytes: usize,
        control: &StorageReadControl,
        visit: &mut RecordValueVisitor<'_>,
    ) -> VersionResult<()> {
        control.check()?;
        if let Some(write) = self.private.get(key, control)? {
            if let Some(value) = write.value() {
                control.check_value_size(value.len(), max_bytes)?;
            }
            visit(Some(BorrowedRecord {
                revision: write.expected(),
                value: write.value(),
            }))?;
            control.check()?;
            return Ok(());
        }
        self.committed
            .visit_value_bounded(key, max_bytes, control, visit)
    }

    pub fn visit_prefix(
        &self,
        prefix: &[u8],
        after: Option<&[u8]>,
        limit: usize,
        control: &StorageReadControl,
        visit: &mut RecordScanVisitor<'_>,
    ) -> VersionResult<()> {
        self.private.visit_merged::<super::projection::Values>(
            &*self.committed,
            prefix,
            after,
            limit,
            control,
            visit,
        )
    }

    pub fn metadata(
        &self,
        key: &[u8],
        control: &StorageReadControl,
    ) -> VersionResult<Option<RecordMetadata>> {
        if let Some(metadata) = self.private.metadata(key, control)? {
            return Ok(Some(metadata));
        }
        self.committed.metadata(key, control)
    }

    pub fn visit_keys(
        &self,
        prefix: &[u8],
        after: Option<&[u8]>,
        limit: usize,
        control: &StorageReadControl,
        visit: &mut RecordKeyVisitor<'_>,
    ) -> VersionResult<()> {
        self.private.visit_merged::<super::projection::Keys>(
            &*self.committed,
            prefix,
            after,
            limit,
            control,
            visit,
        )
    }

    /// Whether this view holds a private change of `key`, whose committed record is then not what a read of the key returns.
    pub fn has_private_change(
        &self,
        key: &[u8],
        control: &StorageReadControl,
    ) -> VersionResult<bool> {
        Ok(self.private.get(key, control)?.is_some())
    }

    pub fn get(
        &self,
        key: &[u8],
        control: &StorageReadControl,
    ) -> VersionResult<Option<VisibleRecord>> {
        if let Some(write) = self.private.get(key, control)? {
            return Ok(Some(VisibleRecord::private(&write)));
        }
        Ok(self
            .committed
            .get(key, control)?
            .map(VisibleRecord::committed))
    }

    /// Merge bounded pages without duplicate identities or payload copies. Tombstones are returned so callers can preserve revision observations even when no row is visible.
    pub fn scan(
        &self,
        prefix: &[u8],
        after: Option<&[u8]>,
        limit: usize,
        control: &StorageReadControl,
    ) -> VersionResult<BudgetedVec<ScannedVisibleRecord>> {
        control.cancellation().check()?;
        let mut result = BudgetedVec::new(control.memory());
        if limit == 0 {
            return Ok(result);
        }
        let (committed, _committed_memory) = self
            .committed
            .scan(prefix, after, limit, control)?
            .into_parts();
        let (private, _private_memory) = self
            .private
            .scan(prefix, after, limit, control)?
            .into_parts();
        let mut committed = committed.into_iter().peekable();
        let mut private = private.into_iter().peekable();
        while result.len() < limit {
            control.cancellation().check()?;
            let order = match (committed.peek(), private.peek()) {
                (Some(committed), Some(private)) => committed.key.as_ref().cmp(private.key()),
                (Some(_), None) => Ordering::Less,
                (None, Some(_)) => Ordering::Greater,
                (None, None) => break,
            };
            let record = match order {
                Ordering::Less => {
                    let committed = committed.next().expect("peeked committed record");
                    ScannedVisibleRecord {
                        key: committed.key,
                        record: VisibleRecord::committed(committed.version),
                    }
                }
                Ordering::Equal => {
                    let committed = committed.next().expect("peeked committed record");
                    let private = private.next().expect("peeked private record");
                    ScannedVisibleRecord {
                        key: committed.key,
                        record: VisibleRecord::private(&private),
                    }
                }
                Ordering::Greater => {
                    let private = private.next().expect("peeked private record");
                    let mut key = BudgetedVec::new(control.memory());
                    key.extend_from_slice(private.key())?;
                    ScannedVisibleRecord {
                        key,
                        record: VisibleRecord::private(&private),
                    }
                }
            };
            result.push(record)?;
        }
        Ok(result)
    }
}