Skip to main content

reddb_engine/transaction/
read.rs

1//! Explicit snapshot visibility for entity reads. Hosts retain auth, tenant,
2//! moderation and ambient statement-frame policy around these helpers.
3use std::sync::Arc;
4
5/// Snapshot + manager pair used for read-path visibility checks.
6///
7/// The manager is needed in addition to the snapshot because `aborted`
8/// state mutates after the snapshot is captured — a ROLLBACK by a
9/// committed-at-capture-time writer must still hide its tuples. Keeping
10/// the Arc around is O(pointer) and the RwLock reads on `is_aborted`
11/// are cheap (HashSet lookup under a parking_lot read guard).
12///
13/// `own_xids` (Phase 2.3.2e) lists the xids belonging to the current
14/// connection's transaction — the parent xid plus open and released
15/// savepoint sub-xids. The visibility rule promotes rows stamped with
16/// these xids to "always visible (unless aborted)" so the writer sees
17/// its own nested-savepoint writes even though their xids exceed
18/// `snapshot.xid`.
19#[derive(Clone)]
20pub struct SnapshotContext {
21    pub branch: Option<Arc<BranchReadView>>,
22    pub snapshot: super::snapshot::Snapshot,
23    pub manager: Arc<super::snapshot::SnapshotManager>,
24    pub own_xids: std::collections::HashSet<super::snapshot::Xid>,
25    pub requires_index_fallback: bool,
26    /// `requires_index_fallback` is set for no other reason than a real
27    /// writer hidden by `snapshot`. A reader that knows its collection can
28    /// ask whether that writer touches it
29    /// ([`SnapshotManager::snapshot_hides_real_writers_of`](super::snapshot::SnapshotManager::snapshot_hides_real_writers_of)).
30    pub hidden_writers_only: bool,
31    pub serializable_reader: Option<super::snapshot::Xid>,
32}
33
34/// Each inherited epoch is frozen at its fork/merge snapshot. Only the current
35/// writer epoch follows the connection's live transaction snapshot.
36#[derive(Clone, Debug)]
37pub struct BranchReadView {
38    pub writer_epoch: u64,
39    pub epochs: std::collections::BTreeMap<u64, super::snapshot::Snapshot>,
40}
41
42/// Unique keys reserve pending writes in the current epoch, but ancestor
43/// epochs keep their frozen fork view. A sibling branch never reserves a key.
44pub fn entity_reserves_unique_key(
45    ctx: &SnapshotContext,
46    entity: &crate::storage::entity::UnifiedEntity,
47) -> bool {
48    let (Some(view), Some(version)) = (&ctx.branch, entity.branch_version()) else {
49        return ctx
50            .manager
51            .row_reserves_unique_key(entity.xmin, entity.xmax, &ctx.own_xids);
52    };
53    let inserted = if version.origin == view.writer_epoch {
54        ctx.manager
55            .row_reserves_unique_key(entity.xmin, 0, &ctx.own_xids)
56    } else {
57        view.epochs.get(&version.origin).is_some_and(|snapshot| {
58            !ctx.manager.is_aborted(entity.xmin) && snapshot.sees(entity.xmin, 0)
59        })
60    };
61    if !inserted {
62        return false;
63    }
64    let deleted = |epoch, xid| {
65        if xid == 0 {
66            return false;
67        }
68        if epoch == view.writer_epoch {
69            !ctx.manager.row_reserves_unique_key(0, xid, &ctx.own_xids)
70        } else {
71            view.epochs
72                .get(&epoch)
73                .is_some_and(|snapshot| !ctx.manager.is_aborted(xid) && snapshot.sees(xid, 0))
74        }
75    };
76    !deleted(version.origin, entity.xmax)
77        && !version
78            .deletions
79            .iter()
80            .any(|&(epoch, xid)| deleted(epoch, xid))
81}
82
83pub fn entity_visibility_check(
84    ctx: &SnapshotContext,
85    entity: &crate::storage::entity::UnifiedEntity,
86) -> bool {
87    let (Some(view), Some(version)) = (&ctx.branch, entity.branch_version()) else {
88        return visibility_check(ctx, entity.xmin, entity.xmax);
89    };
90    let visible_xid = |epoch, xid| {
91        view.epochs.get(&epoch).is_some_and(|snapshot| {
92            xid == 0
93                || (!ctx.manager.is_aborted(xid)
94                    && (ctx.own_xids.contains(&xid) || snapshot.sees(xid, 0)))
95        })
96    };
97    visible_xid(version.origin, entity.xmin)
98        && (entity.xmax == 0 || !visible_xid(version.origin, entity.xmax))
99        && !version
100            .deletions
101            .iter()
102            .any(|&(epoch, xid)| visible_xid(epoch, xid))
103}
104
105#[cfg(test)]
106mod branch_tests {
107    use super::*;
108    use crate::storage::entity::{EntityId, UnifiedEntity};
109    use crate::transaction::snapshot::{Snapshot, SnapshotManager};
110    use std::collections::{BTreeMap, HashSet};
111
112    fn context(epoch: u64, inherited: u64) -> SnapshotContext {
113        let mut epochs = BTreeMap::from([(
114            0,
115            Snapshot {
116                xid: inherited,
117                in_progress: HashSet::new(),
118            },
119        )]);
120        epochs.insert(
121            epoch,
122            Snapshot {
123                xid: 100,
124                in_progress: HashSet::new(),
125            },
126        );
127        SnapshotContext {
128            branch: Some(Arc::new(BranchReadView {
129                writer_epoch: epoch,
130                epochs,
131            })),
132            snapshot: Snapshot {
133                xid: 100,
134                in_progress: HashSet::new(),
135            },
136            manager: Arc::new(SnapshotManager::new()),
137            own_xids: HashSet::new(),
138            requires_index_fallback: true,
139            hidden_writers_only: false,
140            serializable_reader: None,
141        }
142    }
143
144    #[test]
145    fn sibling_updates_and_deletes_have_independent_visibility() {
146        let mut base = UnifiedEntity::table_row(EntityId::new(1), "items", 1, vec![]);
147        base.set_xmin(10);
148        base.set_branch_origin(0);
149        base.set_branch_xmax(0, 30);
150        base.set_branch_xmax(1, 40);
151        let main = context(0, 100);
152        let first = context(1, 20);
153        let second = context(2, 20);
154        assert!(!entity_visibility_check(&main, &base));
155        assert!(!entity_visibility_check(&first, &base));
156        assert!(entity_visibility_check(&second, &base));
157        base.set_branch_xmax(2, 50);
158        base.set_branch_xmax(1, 0);
159        assert!(
160            entity_visibility_check(&first, &base),
161            "rollback only revives its branch"
162        );
163        assert!(!entity_visibility_check(&second, &base));
164        let mut replacement = base.clone();
165        replacement.set_branch_origin(1);
166        replacement.set_xmin(40);
167        replacement.set_xmax(0);
168        assert!(entity_visibility_check(&first, &replacement));
169        assert!(!entity_visibility_check(&main, &replacement));
170        assert!(!entity_visibility_check(&second, &replacement));
171    }
172
173    #[test]
174    fn active_and_aborted_branch_deletes_remain_invisible() {
175        let mut entity = UnifiedEntity::table_row(EntityId::new(1), "items", 1, vec![]);
176        entity.set_branch_origin(0);
177        entity.set_xmin(10);
178        entity.set_branch_xmax(1, 40);
179        let mut reader = context(1, 20);
180        Arc::make_mut(reader.branch.as_mut().expect("view"))
181            .epochs
182            .get_mut(&1)
183            .expect("writer epoch")
184            .in_progress
185            .insert(40);
186        assert!(entity_visibility_check(&reader, &entity));
187        reader.own_xids.insert(40);
188        assert!(!entity_visibility_check(&reader, &entity));
189        reader.manager.rollback(40);
190        assert!(entity_visibility_check(&reader, &entity));
191    }
192}
193
194/// Record an admitted table-row read after the host has applied visibility and
195/// policy gates. SSI keys use logical identity, shared by all physical versions.
196pub fn record_serializable_read(
197    ctx: &SnapshotContext,
198    entity: &crate::storage::entity::UnifiedEntity,
199) {
200    let Some(reader) = ctx.serializable_reader else {
201        return;
202    };
203    if !matches!(
204        &entity.kind,
205        crate::storage::entity::EntityKind::TableRow { .. }
206    ) {
207        return;
208    }
209    ctx.manager
210        .record_serializable_read(reader, entity.kind.collection(), entity.logical_id());
211}
212
213/// Apply captured MVCC visibility, including own/aborted savepoint writers.
214/// This predicate supplies no authorization, tenant or moderation policy.
215#[inline]
216pub fn visibility_check(ctx: &SnapshotContext, xmin: u64, xmax: u64) -> bool {
217    // Writer aborted → tuple never existed from any future reader's view.
218    // Checked *before* the own-xids fast path so an aborted own-sub-xid
219    // (rolled-back savepoint) stays hidden from the parent.
220    if xmin != 0 && ctx.manager.is_aborted(xmin) {
221        return false;
222    }
223    // Deleter aborted → treat xmax as unset; fall back to xmin-only check.
224    let effective_xmax = if xmax != 0 && ctx.manager.is_aborted(xmax) {
225        0
226    } else {
227        xmax
228    };
229    // Phase 2.3.2e: own-tx writes are always visible to the connection
230    // that stamped them, even when xmin/xmax exceed `snapshot.xid` (as
231    // happens for sub-xids allocated by SAVEPOINT after BEGIN).
232    let own_xmin = xmin != 0 && ctx.own_xids.contains(&xmin);
233    let own_xmax = effective_xmax != 0 && ctx.own_xids.contains(&effective_xmax);
234    if own_xmax {
235        // This connection deleted the row via this xid — hide it from self.
236        return false;
237    }
238    if own_xmin {
239        return true;
240    }
241    ctx.snapshot.sees(xmin, effective_xmax)
242}
243
244/// Candidate access for the canonical table-row version selector. The store
245/// supplies only physical versions of the requested collection/logical identity.
246pub trait TableRowVersionStore {
247    fn table_row_versions_by_logical_id(
248        &self,
249        collection: &str,
250        logical_id: crate::storage::entity::EntityId,
251    ) -> Vec<crate::storage::entity::UnifiedEntity>;
252
253    fn get_table_row_by_logical_id(
254        &self,
255        collection: &str,
256        logical_id: crate::storage::entity::EntityId,
257    ) -> Option<crate::storage::entity::UnifiedEntity>;
258}
259
260/// Select the newest visible physical version, or use the current-row lookup
261/// when the host has no snapshot requiring history. The host's predicate retains
262/// table-kind, authorization and moderation gates before materialization.
263pub fn resolve_logical_id(
264    store: &impl TableRowVersionStore,
265    collection: &str,
266    logical_id: crate::storage::entity::EntityId,
267    select_versions: bool,
268    mut visible: impl FnMut(&crate::storage::entity::UnifiedEntity) -> bool,
269) -> Option<crate::storage::entity::UnifiedEntity> {
270    if select_versions {
271        return store
272            .table_row_versions_by_logical_id(collection, logical_id)
273            .into_iter()
274            .filter(|entity| visible(entity))
275            .max_by_key(|entity| entity.xmin);
276    }
277    store
278        .get_table_row_by_logical_id(collection, logical_id)
279        .filter(|entity| visible(entity))
280}
281
282/// Fallible version access streams candidates instead of retaining a history Vec.
283/// Hosts supply only versions of the requested collection/logical identity.
284pub trait FallibleTableRowVersionStore {
285    type Error;
286
287    fn try_get_table_row_by_logical_id(
288        &self,
289        collection: &str,
290        logical_id: crate::storage::entity::EntityId,
291    ) -> Result<Option<crate::storage::entity::UnifiedEntity>, Self::Error>;
292
293    fn try_for_each_table_row_version(
294        &self,
295        collection: &str,
296        logical_id: crate::storage::entity::EntityId,
297        visit: impl FnMut(&crate::storage::entity::UnifiedEntity) -> bool,
298    ) -> Result<(), Self::Error>;
299
300    /// The live head of `logical_id`'s version chain (`xmax == 0`), when the
301    /// host can name it without walking the collection and no other version
302    /// can be visible alongside it. `None` always falls back to the walk.
303    fn try_live_table_row_head(
304        &self,
305        _collection: &str,
306        _logical_id: crate::storage::entity::EntityId,
307    ) -> Result<Option<crate::storage::entity::UnifiedEntity>, Self::Error> {
308        Ok(None)
309    }
310}
311
312/// Retain one selected version; a later read failure invalidates the selection.
313pub fn try_resolve_logical_id<S: FallibleTableRowVersionStore>(
314    store: &S,
315    collection: &str,
316    logical_id: crate::storage::entity::EntityId,
317    select_versions: bool,
318    mut visible: impl FnMut(&crate::storage::entity::UnifiedEntity) -> bool,
319) -> Result<Option<crate::storage::entity::UnifiedEntity>, S::Error> {
320    if !select_versions {
321        return store
322            .try_get_table_row_by_logical_id(collection, logical_id)
323            .map(|entity| entity.filter(|entity| visible(entity)));
324    }
325    // Every earlier version was closed by a transaction that committed no
326    // later than the head's writer, so a reader that sees the head sees no
327    // other version of the row: the walk below would select the same entity.
328    if let Some(head) = store.try_live_table_row_head(collection, logical_id)? {
329        if visible(&head) {
330            return Ok(Some(head));
331        }
332    }
333    let mut selected: Option<crate::storage::entity::UnifiedEntity> = None;
334    store.try_for_each_table_row_version(collection, logical_id, |entity| {
335        if visible(entity) && selected.as_ref().is_none_or(|old| entity.xmin >= old.xmin) {
336            selected = Some(entity.clone());
337        }
338        true
339    })?;
340    Ok(selected)
341}