reddb_engine/transaction/
read.rs1use std::sync::Arc;
4
5#[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 pub hidden_writers_only: bool,
31 pub serializable_reader: Option<super::snapshot::Xid>,
32}
33
34#[derive(Clone, Debug)]
37pub struct BranchReadView {
38 pub writer_epoch: u64,
39 pub epochs: std::collections::BTreeMap<u64, super::snapshot::Snapshot>,
40}
41
42pub 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
194pub 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#[inline]
216pub fn visibility_check(ctx: &SnapshotContext, xmin: u64, xmax: u64) -> bool {
217 if xmin != 0 && ctx.manager.is_aborted(xmin) {
221 return false;
222 }
223 let effective_xmax = if xmax != 0 && ctx.manager.is_aborted(xmax) {
225 0
226 } else {
227 xmax
228 };
229 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 return false;
237 }
238 if own_xmin {
239 return true;
240 }
241 ctx.snapshot.sees(xmin, effective_xmax)
242}
243
244pub 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
260pub 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
282pub 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 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
312pub 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 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}