Skip to main content

reddb_engine/transaction/
snapshot.rs

1//! Live optimistic MVCC snapshot, outcome and SSI tracking.
2//!
3//! This in-process state allocates transaction IDs, captures transaction and
4//! statement snapshots, retains vacuum horizons, tracks aborted writers and
5//! detects dangerous serializable read/write structures. The host runtime owns
6//! write conflict validation, WAL publication and recovery of transaction outcomes.
7//! Moving this state into the shared engine does not itself provide durability.
8
9use std::collections::{HashMap, HashSet};
10use std::sync::atomic::{AtomicU64, Ordering};
11use std::sync::Arc;
12
13use super::IsolationLevel;
14use crate::storage::entity_id::EntityId;
15
16/// Default autocommit-xid pool batch size. Each refill reserves this
17/// many xids in a single `fetch_add` so back-to-back autocommit inserts
18/// share one atomic op instead of paying it per row. Sized small to
19/// keep a pristine `peek_next_xid()` close to the truth — VACUUM and
20/// diagnostics observe the allocator high-water mark. Snapshots exclude
21/// reserved-but-unused slots from visibility until a later snapshot.
22pub(crate) const AUTOCOMMIT_POOL_BATCH: u64 = 16;
23
24/// A transaction identifier. Monotonic across the lifetime of the process.
25pub type Xid = u64;
26
27/// Reserved xid meaning "not inside a transaction" — pre-MVCC rows stamp
28/// this value so they stay visible to every snapshot.
29pub const XID_NONE: Xid = 0;
30
31/// Immutable snapshot taken at transaction start or statement start.
32///
33/// Callers evaluate `UnifiedEntity::is_visible(snapshot.xid)` on every
34/// row returned from storage to filter out rows created by concurrent
35/// transactions that hadn't committed when the snapshot was taken.
36#[derive(Debug, Clone)]
37pub struct Snapshot {
38    /// The snapshot's xid — every row with `xmin <= xid` created before
39    /// the snapshot is visible (assuming `xmax` hasn't passed).
40    pub xid: Xid,
41    /// Active transactions and reserved-but-unissued pool xids at capture.
42    /// Their writes must be *hidden* even when `xmin <= xid`, because
43    /// the writer hadn't committed yet from this snapshot's point of view.
44    pub in_progress: HashSet<Xid>,
45}
46
47impl Snapshot {
48    /// Is a row with this xmin/xmax visible under this snapshot?
49    ///
50    /// Delegates to [`super::visibility::is_visible`] — the deep
51    /// module that owns the full MVCC visibility predicate. The
52    /// `aborted` argument is empty here because `Snapshot` does not
53    /// carry the manager-level aborted set; callers that need the
54    /// rolled-back-writer rule should consult [`SnapshotManager`]
55    /// directly, or evolve `Snapshot` to embed an aborted view.
56    pub fn sees(&self, xmin: Xid, xmax: Xid) -> bool {
57        super::visibility::is_visible(xmin, xmax, self.xid, &self.in_progress, &HashSet::new())
58    }
59}
60
61/// Per-transaction state tracked on the runtime while BEGIN/COMMIT/ROLLBACK
62/// is active. Attached to a connection by the runtime Transaction State module.
63#[derive(Debug, Clone)]
64pub struct TxnContext {
65    pub xid: Xid,
66    pub isolation: IsolationLevel,
67    /// Snapshot captured at BEGIN (SnapshotIsolation / Serializable) or
68    /// refreshed per-statement (ReadCommitted).
69    pub snapshot: Snapshot,
70    /// Ordered list of `(savepoint_name, sub_xid)` entries (Phase
71    /// 2.3.2e savepoints). Each SAVEPOINT pushes a freshly-allocated
72    /// xid onto this stack; writes stamp xmin/xmax with the top entry
73    /// so ROLLBACK TO SAVEPOINT can mark only those writes as aborted.
74    /// RELEASE SAVEPOINT pops the named level plus everything above it
75    /// without aborting — the sub-xids keep their effects and commit
76    /// together with the parent. Empty stack means "writes use `xid`
77    /// directly", matching pre-savepoint behaviour.
78    pub savepoints: Vec<(String, Xid)>,
79    /// Sub-xids popped by `RELEASE SAVEPOINT` that should still commit
80    /// alongside the parent. PG semantics: released subtxns keep their
81    /// writes — they're promoted to parent-visible at COMMIT. Stored
82    /// separately from `savepoints` so their names are gone (cannot be
83    /// rolled back or released again) while their xids remain trackable.
84    pub released_sub_xids: Vec<Xid>,
85}
86
87impl TxnContext {
88    /// Xid new writes in this connection should stamp onto tuples — the
89    /// innermost open savepoint, or the parent xid when no savepoint is
90    /// active.
91    pub fn writer_xid(&self) -> Xid {
92        self.savepoints.last().map(|(_, x)| *x).unwrap_or(self.xid)
93    }
94}
95
96/// Central allocator and liveness tracker.
97///
98/// Uses an atomic counter for xid allocation and a parking_lot-guarded
99/// HashSet for in-progress/aborted bookkeeping. The sets stay small —
100/// only unfinished transactions plus a finite rollback history — so a
101/// plain HashSet outperforms more complex data structures here.
102///
103/// # Autocommit xid pool
104///
105/// Single-row autocommit writes (`MutationEngine::append_one`) need an
106/// xid that's "born committed" — they call `begin()` then `commit()`
107/// back-to-back before the row is even durable. The pre-commit pool
108/// (`autocommit_pool_*`) batches the reservation: one
109/// `next_xid.fetch_add(BATCH)` reserves a contiguous range of xids,
110/// each handed out via a single atomic without touching the
111/// `RwLock<ManagerState>`. Pool xids are never inserted into `active`
112/// or `aborted` so they look like already-committed transactions to
113/// every snapshot — identical visibility semantics to the legacy
114/// `begin()/commit()` pair (which also leaves the xid in neither set).
115pub struct SnapshotManager {
116    next_xid: AtomicU64,
117    /// Newest xid handed out by `begin`, never one from the autocommit pool.
118    last_real_xid: AtomicU64,
119    /// Newest of those that did not name the one collection it changes.
120    last_unscoped_xid: AtomicU64,
121    /// A replayed change used a pool xid: from then on the pool no longer
122    /// serves inserts alone and every hidden xid counts as a writer.
123    replays_changes: std::sync::atomic::AtomicBool,
124    visibility_revision: AtomicU64,
125    state: parking_lot::RwLock<ManagerState>,
126    /// Reservation window for the autocommit pool. A single
127    /// `parking_lot::Mutex` protects two `u64`s — `next` (next xid to
128    /// hand out) and `end` (exclusive upper bound). When `next == end`
129    /// the next caller refills by reserving `AUTOCOMMIT_POOL_BATCH`
130    /// xids in a single `next_xid.fetch_add`, dropping the lock cost
131    /// from one acquire-per-xid (the legacy `begin()`+`commit()` pair)
132    /// to one acquire-per-`AUTOCOMMIT_POOL_BATCH` xids. A plain Mutex
133    /// is enough here — the critical section is two stores and an
134    /// atomic add, and contention is bounded by the writer count.
135    autocommit_pool: parking_lot::Mutex<AutocommitPool>,
136}
137
138pub type LogicalRowKey = (String, EntityId);
139
140#[derive(Default)]
141struct SerializableTxnState {
142    read_set: HashSet<LogicalRowKey>,
143    vault_reads: HashSet<(String, Option<String>, Option<String>)>,
144    incoming_rw: HashSet<Xid>,
145    outgoing_rw: HashSet<Xid>,
146    committed: bool,
147}
148
149#[derive(Default)]
150struct AutocommitPool {
151    next: Xid,
152    end: Xid,
153    /// First xid of each recent reservation, oldest first. Lets a snapshot
154    /// tell the insert slots in its `in_progress` from real writers. A batch
155    /// that fell off the end is forgotten, and its xids then count as real
156    /// writers: the answer only errs towards caution.
157    batches: std::collections::VecDeque<Xid>,
158}
159
160/// Reservations remembered by [`AutocommitPool::batches`].
161const AUTOCOMMIT_POOL_BATCH_HISTORY: usize = 4096;
162
163impl AutocommitPool {
164    fn reserved(&self, xid: Xid) -> bool {
165        let after = self.batches.partition_point(|start| *start <= xid);
166        after
167            .checked_sub(1)
168            .and_then(|index| self.batches.get(index))
169            .is_some_and(|start| xid - start < AUTOCOMMIT_POOL_BATCH)
170    }
171}
172
173#[derive(Default)]
174struct ManagerState {
175    /// xids that have started but not yet committed/rolled back.
176    active: HashSet<Xid>,
177    /// Active autocommit updates whose publication is fenced by the durable
178    /// result-cache epoch. They remain active for MVCC and vacuum.
179    cache_coherent_updates: HashSet<Xid>,
180    /// Oldest version required by each active transaction's captured snapshot.
181    /// A newer reader can exclude an older writer even after that writer commits.
182    snapshot_horizons: HashMap<Xid, Xid>,
183    /// Captured statement frames also need history without an active SQL
184    /// transaction. Counts let nested frames retain the same horizon safely.
185    statement_horizons: HashMap<Xid, usize>,
186    /// xids that rolled back. `is_visible` MUST treat these as invisible
187    /// (the writer never committed). The set is pruned lazily by VACUUM.
188    aborted: HashSet<Xid>,
189    /// A low-level rollback of a non-active xid may invalidate already stored
190    /// rows without a new row mutation. Checkpoint caches must validate fully.
191    untracked_visibility_revision: u64,
192    /// xids that must NOT be reclaimed by VACUUM because some higher-level
193    /// object (a VCS commit, a long-lived replica snapshot) still points
194    /// at them. Reference-counted so multiple pins coexist; decrementing
195    /// to zero removes the entry. `prune_aborted` skips any xid present
196    /// here so its row versions stay readable.
197    pinned: HashMap<Xid, u32>,
198    serializable: HashMap<Xid, SerializableTxnState>,
199    /// The one collection a real writer changes, for writers that said so
200    /// when they began. One that is not here may change any collection; a
201    /// bounded history only ever forgets towards that answer.
202    scopes: std::collections::BTreeMap<Xid, Arc<str>>,
203    /// Newest scoped writer of each collection.
204    last_scoped: HashMap<Arc<str>, Xid>,
205}
206
207/// Scoped writers remembered by [`ManagerState::scopes`].
208const SCOPED_WRITER_HISTORY: usize = 8192;
209
210/// Releases a statement's history requirement on every frame exit path.
211pub struct SnapshotRetentionGuard {
212    manager: Arc<SnapshotManager>,
213    horizon: Xid,
214}
215
216impl Drop for SnapshotRetentionGuard {
217    fn drop(&mut self) {
218        let mut state = self.manager.state.write();
219        let count = state
220            .statement_horizons
221            .get_mut(&self.horizon)
222            .expect("a live snapshot retention guard has a registered horizon");
223        if *count == 1 {
224            state.statement_horizons.remove(&self.horizon);
225        } else {
226            *count -= 1;
227        }
228    }
229}
230
231impl SnapshotManager {
232    pub fn new() -> Self {
233        Self {
234            // Start at 1 so xid=0 keeps its pre-MVCC "everyone sees it" meaning.
235            next_xid: AtomicU64::new(1),
236            last_real_xid: AtomicU64::new(0),
237            last_unscoped_xid: AtomicU64::new(0),
238            replays_changes: std::sync::atomic::AtomicBool::new(false),
239            visibility_revision: AtomicU64::new(0),
240            state: parking_lot::RwLock::new(ManagerState::default()),
241            // Pool starts empty — first caller triggers a refill.
242            autocommit_pool: parking_lot::Mutex::new(AutocommitPool::default()),
243        }
244    }
245
246    /// Allocate a new xid and mark it active. Returns the xid for
247    /// stamping onto `UnifiedEntity::xmin/xmax`.
248    ///
249    /// Allocation and the `active` insert happen together under the state
250    /// write lock. This is load-bearing for first-committer-wins: a
251    /// concurrent snapshot (state read lock) must never observe a
252    /// *lower-numbered* still-running xid as absent from `active`. Were the
253    /// `fetch_add` done outside the lock, a writer that grabbed the smaller
254    /// xid could still be mid-`begin()` while a later transaction snapshots
255    /// a larger xid — the smaller xid would be missing from `in_progress`,
256    /// yet `xmin <= snapshot.xid`, so the snapshot would treat that
257    /// concurrent (later possibly-committed) writer as visible. That both
258    /// leaks an uncommitted row into a peer's read and lets two writers on
259    /// the same row both commit. Serialising allocation under the lock
260    /// guarantees any xid smaller than a taken snapshot's xid is already in
261    /// `active` (or already finished), so `in_progress` is never short a
262    /// concurrent writer.
263    pub fn begin(&self) -> Xid {
264        self.begin_inner(false, None)
265    }
266
267    /// Begin an autocommit update whose data publication is fenced by the
268    /// durable result-cache epoch. Callers must retain that fence through WAL
269    /// publication and finish the xid only after durable publication.
270    #[doc(hidden)]
271    pub fn begin_cache_coherent_update(&self) -> Xid {
272        self.begin_inner(true, None)
273    }
274
275    /// [`begin`](Self::begin) for a writer that changes rows of `collection`
276    /// only, such as an autocommit UPDATE or DELETE. A reader of another
277    /// collection does not have to treat it as a writer that can have left
278    /// its indexes behind.
279    pub fn begin_in(&self, collection: &str) -> Xid {
280        self.begin_inner(false, Some(collection))
281    }
282
283    /// [`begin_cache_coherent_update`](Self::begin_cache_coherent_update)
284    /// scoped like [`begin_in`](Self::begin_in).
285    #[doc(hidden)]
286    pub fn begin_cache_coherent_update_in(&self, collection: &str) -> Xid {
287        self.begin_inner(true, Some(collection))
288    }
289
290    fn begin_inner(&self, cache_coherent: bool, scope: Option<&str>) -> Xid {
291        let mut state = self.state.write();
292        // A real writer advances beyond the reserved autocommit range. Retire
293        // its unused slots so later inserts cannot receive older identities
294        // and pin fresh statements' vacuum horizons behind committed deletes.
295        let mut pool = self.autocommit_pool.lock();
296        pool.next = pool.end;
297        let xid = self.next_xid.fetch_add(1, Ordering::Relaxed);
298        self.last_real_xid.fetch_max(xid, Ordering::Release);
299        match scope {
300            Some(collection) => {
301                let collection: Arc<str> = match state.last_scoped.get_key_value(collection) {
302                    Some((known, _)) => Arc::clone(known),
303                    None => Arc::from(collection),
304                };
305                state.last_scoped.insert(Arc::clone(&collection), xid);
306                if state.scopes.len() == SCOPED_WRITER_HISTORY {
307                    state.scopes.pop_first();
308                }
309                state.scopes.insert(xid, collection);
310            }
311            None => {
312                self.last_unscoped_xid.fetch_max(xid, Ordering::Release);
313            }
314        }
315        state.active.insert(xid);
316        if cache_coherent {
317            state.cache_coherent_updates.insert(xid);
318        }
319        self.visibility_revision.fetch_add(1, Ordering::Release);
320        xid
321    }
322
323    /// Capture a fresh *read-committed* snapshot at this instant: sees every
324    /// transaction that has committed so far and hides every still-active
325    /// one. Unlike [`snapshot`], the caller supplies no xid — the snapshot
326    /// id is the current allocator high-water mark, read *under the same
327    /// state lock* that [`begin`] holds while it bumps the counter and
328    /// inserts into `active`. That mutual exclusion is what makes the read
329    /// atomic: a concurrent `begin()` is either wholly visible (counter
330    /// bumped AND present in `active`, hence hidden as in-progress) or
331    /// wholly invisible (neither) — never the torn state where its xid sits
332    /// below the high-water mark yet is missing from `active`, which would
333    /// leak an uncommitted writer as visible.
334    ///
335    /// Used for RMW pre-image reads that must always observe the latest
336    /// committed row version rather than a pinned statement snapshot.
337    pub fn fresh_read_snapshot(&self) -> Snapshot {
338        let state = self.state.read();
339        self.fresh_read_snapshot_locked(&state)
340    }
341
342    fn fresh_read_snapshot_locked(&self, state: &ManagerState) -> Snapshot {
343        let pool = self.autocommit_pool.lock();
344        // Visibility uses an inclusive bound. The allocator points at the
345        // next, not the last, xid; including it admits the next future writer.
346        let xid = self.next_xid.load(Ordering::Relaxed).saturating_sub(1);
347        let mut in_progress: HashSet<Xid> = state.active.iter().copied().collect();
348        // Reserved-but-unissued pool slots are future writers even though
349        // their numbers can be below this snapshot's high-water mark.
350        in_progress.extend(pool.next..pool.end);
351        Snapshot { xid, in_progress }
352    }
353
354    /// Whether `snapshot` hides a writer that may already have written.
355    ///
356    /// Every read snapshot lists the reserved-but-unissued autocommit slots
357    /// in `in_progress`, so a row written with one of them later stays
358    /// invisible. Until a slot is issued it has written nothing, and no index
359    /// can be behind it. A slot issued since the snapshot was taken counts as
360    /// a writer here, so the answer only errs towards `true`.
361    pub fn snapshot_hides_writers(&self, snapshot: &Snapshot) -> bool {
362        let pool = self.autocommit_pool.lock();
363        snapshot
364            .in_progress
365            .iter()
366            .any(|xid| !(pool.next..pool.end).contains(xid))
367    }
368
369    /// Whether `snapshot` hides a transaction that can have removed index
370    /// entries: one begun with [`begin`](Self::begin) and still in flight when
371    /// the snapshot was taken.
372    ///
373    /// An autocommit INSERT draws its xid from the reserved pool. It adds rows
374    /// and their index entries and removes none, so it cannot leave an index
375    /// behind this snapshot whether it ran before or after it was taken.
376    ///
377    /// Once a change was replayed with a pool xid
378    /// ([`allocate_replayed_xid`](Self::allocate_replayed_xid)) the pool no
379    /// longer serves inserts alone, and this answers like
380    /// [`snapshot_hides_writers`](Self::snapshot_hides_writers).
381    pub fn snapshot_hides_real_writers(&self, snapshot: &Snapshot) -> bool {
382        if self.replays_changes.load(Ordering::Acquire) {
383            return self.snapshot_hides_writers(snapshot);
384        }
385        let pool = self.autocommit_pool.lock();
386        snapshot.in_progress.iter().any(|xid| !pool.reserved(*xid))
387    }
388
389    /// Whether a transaction was begun with [`begin`](Self::begin) after
390    /// `snapshot` was taken. Autocommit inserts do not count; see
391    /// [`snapshot_hides_real_writers`](Self::snapshot_hides_real_writers).
392    pub fn real_writer_began_after(&self, snapshot: &Snapshot) -> bool {
393        if self.replays_changes.load(Ordering::Acquire) {
394            let current = self.fresh_read_snapshot();
395            return self.oldest_active_xid().is_some()
396                || snapshot.xid != current.xid
397                || snapshot.in_progress != current.in_progress;
398        }
399        self.last_real_xid.load(Ordering::Acquire) > snapshot.xid
400    }
401
402    /// [`snapshot_hides_real_writers`](Self::snapshot_hides_real_writers)
403    /// for a reader of `collection`: a hidden writer that named another
404    /// collection when it began ([`begin_in`](Self::begin_in)) does not count.
405    pub fn snapshot_hides_real_writers_of(&self, snapshot: &Snapshot, collection: &str) -> bool {
406        if self.replays_changes.load(Ordering::Acquire) {
407            return self.snapshot_hides_writers(snapshot);
408        }
409        let state = self.state.read();
410        let pool = self.autocommit_pool.lock();
411        snapshot.in_progress.iter().any(|xid| {
412            !pool.reserved(*xid)
413                && state
414                    .scopes
415                    .get(xid)
416                    .is_none_or(|scope| &**scope == collection)
417        })
418    }
419
420    /// Waits, at most `wait`, until no real writer that can change
421    /// `collection` is in flight. Returns whether that was reached. A
422    /// statement that would otherwise scan the collection because such a
423    /// writer is hidden from its snapshot can wait the few milliseconds the
424    /// writer takes and read a fresh snapshot instead.
425    pub fn await_real_writers_of(&self, collection: &str, wait: std::time::Duration) -> bool {
426        let pending = || {
427            let state = self.state.read();
428            state.active.iter().any(|xid| {
429                state
430                    .scopes
431                    .get(xid)
432                    .is_none_or(|scope| &**scope == collection)
433            })
434        };
435        let deadline = std::time::Instant::now() + wait;
436        while pending() {
437            if std::time::Instant::now() >= deadline {
438                return false;
439            }
440            std::thread::sleep(std::time::Duration::from_micros(200));
441        }
442        true
443    }
444
445    /// [`real_writer_began_after`](Self::real_writer_began_after) for a
446    /// reader of `collection`; see
447    /// [`snapshot_hides_real_writers_of`](Self::snapshot_hides_real_writers_of).
448    pub fn real_writer_of_began_after(&self, snapshot: &Snapshot, collection: &str) -> bool {
449        if self.replays_changes.load(Ordering::Acquire) {
450            return self.real_writer_began_after(snapshot);
451        }
452        self.last_unscoped_xid.load(Ordering::Acquire) > snapshot.xid
453            || self
454                .state
455                .read()
456                .last_scoped
457                .get(collection)
458                .is_some_and(|xid| *xid > snapshot.xid)
459    }
460
461    /// [`allocate_committed_xid`](Self::allocate_committed_xid) for a
462    /// replayed change, which can be an update or a delete. See
463    /// [`snapshot_hides_real_writers`](Self::snapshot_hides_real_writers).
464    pub fn allocate_replayed_xid(&self) -> Xid {
465        self.replays_changes.store(true, Ordering::Release);
466        self.allocate_committed_xid()
467    }
468
469    /// Capture and register under the same lock used by GC cutoff selection.
470    /// Registering only when the snapshot is installed leaves a capture-to-read
471    /// interval in which a committed writer's old versions can be reclaimed.
472    pub fn fresh_retained_snapshot(self: &Arc<Self>) -> (Snapshot, SnapshotRetentionGuard) {
473        let mut state = self.state.write();
474        let snapshot = self.fresh_read_snapshot_locked(&state);
475        let guard = self.retain_snapshot_locked(&snapshot, &mut state);
476        (snapshot, guard)
477    }
478
479    /// Retain a snapshot already protected by its parent transaction, outer
480    /// statement frame, or historical reference while transferring ownership.
481    pub fn retain_snapshot(
482        self: &Arc<Self>,
483        snapshot: Snapshot,
484    ) -> (Snapshot, SnapshotRetentionGuard) {
485        let mut state = self.state.write();
486        let guard = self.retain_snapshot_locked(&snapshot, &mut state);
487        (snapshot, guard)
488    }
489
490    fn retain_snapshot_locked(
491        self: &Arc<Self>,
492        snapshot: &Snapshot,
493        state: &mut ManagerState,
494    ) -> SnapshotRetentionGuard {
495        // Deletes already visible to the snapshot need no old version. An
496        // excluded writer can be older than its inclusive high-water mark.
497        let horizon = snapshot
498            .in_progress
499            .iter()
500            .copied()
501            .fold(snapshot.xid.saturating_add(1), Xid::min);
502        *state.statement_horizons.entry(horizon).or_default() += 1;
503        SnapshotRetentionGuard {
504            manager: Arc::clone(self),
505            horizon,
506        }
507    }
508
509    /// Capture a point-in-time snapshot. Must be called after `begin()`
510    /// when using SnapshotIsolation/Serializable. ReadCommitted refreshes
511    /// this per statement via the same call.
512    pub fn snapshot(&self, xid: Xid) -> Snapshot {
513        let mut state = self.state.write();
514        // Active xids other than our own appear as "in-progress" to us.
515        let pool = self.autocommit_pool.lock();
516        let mut in_progress: HashSet<Xid> =
517            state.active.iter().copied().filter(|&x| x != xid).collect();
518        in_progress.extend(pool.next..pool.end);
519        if state.active.contains(&xid) {
520            let horizon = in_progress.iter().copied().fold(xid, Xid::min);
521            state
522                .snapshot_horizons
523                .entry(xid)
524                .and_modify(|previous| *previous = (*previous).min(horizon))
525                .or_insert(horizon);
526        }
527        Snapshot { xid, in_progress }
528    }
529
530    /// Mark a transaction as committed. Its writes become visible to
531    /// future snapshots; earlier snapshots keep their own view.
532    pub fn commit(&self, xid: Xid) {
533        let mut state = self.state.write();
534        let was_active = state.active.remove(&xid);
535        state.cache_coherent_updates.remove(&xid);
536        state.snapshot_horizons.remove(&xid);
537        // Also clear from aborted set in case of prior rollback_to call
538        // that touched this xid (defensive; normally a no-op).
539        let was_aborted = state.aborted.remove(&xid);
540        if was_active || was_aborted {
541            self.visibility_revision.fetch_add(1, Ordering::Release);
542        }
543        if let Some(ssi) = state.serializable.get_mut(&xid) {
544            ssi.committed = true;
545        }
546        Self::prune_serializable_state(&mut state);
547    }
548
549    /// Allocate an xid that is *born committed* — for autocommit
550    /// callers (`MutationEngine::append_one`) that previously paid two
551    /// `state.write()` lock acquisitions per row to insert-then-remove
552    /// from the active set.
553    ///
554    /// The returned xid is never inserted into `active` and never into
555    /// `aborted`, which matches the steady state of the legacy
556    /// `begin()/commit()` pair when called back-to-back: the xid leaves
557    /// the manager's tracking sets unobservably. Concurrent readers
558    /// therefore see it as an already-committed transaction once
559    /// `xmin <= snapshot.xid`, which is exactly the semantics the
560    /// autocommit path needs.
561    ///
562    /// Implementation: a small reservation pool (`AUTOCOMMIT_POOL_BATCH`
563    /// xids) is reserved with one `fetch_add`. Each caller hands itself
564    /// the next xid via a single atomic. When the pool drains, the
565    /// next caller serialises briefly through `autocommit_pool_refill`
566    /// to bump the window, then falls back into the lock-free hot path.
567    ///
568    /// Durability note: this method does NOT make the row durable —
569    /// it only allocates the identifier. The caller must complete the
570    /// usual WAL-append + fsync cycle before acknowledging the write.
571    /// Pre-allocating the xid is safe because the xid carries no
572    /// promise that any row exists; it's just a number for `xmin`.
573    pub fn allocate_committed_xid(&self) -> Xid {
574        let mut pool = self.autocommit_pool.lock();
575        if pool.next >= pool.end {
576            // Reserve the next contiguous range. A single
577            // `fetch_add(BATCH)` on the global counter — equivalent to
578            // BATCH back-to-back `begin()` calls in terms of xid
579            // numbering, but with zero `state.write()` traffic.
580            let start = self
581                .next_xid
582                .fetch_add(AUTOCOMMIT_POOL_BATCH, Ordering::Relaxed);
583            pool.next = start;
584            pool.end = start + AUTOCOMMIT_POOL_BATCH;
585            if pool.batches.len() == AUTOCOMMIT_POOL_BATCH_HISTORY {
586                pool.batches.pop_front();
587            }
588            pool.batches.push_back(start);
589        }
590        let xid = pool.next;
591        pool.next += 1;
592        xid
593    }
594
595    /// Mark a transaction as rolled back. Its writes MUST stay hidden
596    /// from every future read — `is_visible` consults the aborted set
597    /// before honouring a row's `xmin`.
598    pub fn rollback(&self, xid: Xid) {
599        let mut state = self.state.write();
600        state.snapshot_horizons.remove(&xid);
601        let was_active = state.active.remove(&xid);
602        state.cache_coherent_updates.remove(&xid);
603        let newly_aborted = state.aborted.insert(xid);
604        if newly_aborted && !was_active {
605            state.untracked_visibility_revision = state
606                .untracked_visibility_revision
607                .checked_add(1)
608                .expect("visibility invalidation counter must not overflow");
609        }
610        if was_active || newly_aborted {
611            self.visibility_revision.fetch_add(1, Ordering::Release);
612        }
613        state.serializable.remove(&xid);
614        for ssi in state.serializable.values_mut() {
615            ssi.incoming_rw.remove(&xid);
616            ssi.outgoing_rw.remove(&xid);
617        }
618        Self::prune_serializable_state(&mut state);
619    }
620
621    pub fn begin_serializable(&self, xid: Xid) {
622        self.state.write().serializable.entry(xid).or_default();
623    }
624
625    pub fn record_serializable_read(&self, reader: Xid, collection: &str, logical_id: EntityId) {
626        let mut state = self.state.write();
627        if let Some(ssi) = state.serializable.get_mut(&reader) {
628            ssi.read_set.insert((collection.to_string(), logical_id));
629        }
630    }
631
632    pub fn record_serializable_vault_read(
633        &self,
634        reader: Xid,
635        collection: &str,
636        tenant: Option<&str>,
637        key: Option<&str>,
638    ) {
639        if let Some(ssi) = self.state.write().serializable.get_mut(&reader) {
640            ssi.vault_reads.insert((
641                collection.into(),
642                tenant.map(str::to_owned),
643                key.map(str::to_owned),
644            ));
645        }
646    }
647
648    pub fn serializable_vault_commit_would_be_dangerous(
649        &self,
650        writer: Xid,
651        write_set: &HashSet<(String, Option<String>, String)>,
652    ) -> bool {
653        let mut state = self.state.write();
654        if !state.serializable.contains_key(&writer) {
655            return false;
656        }
657        let readers = state
658            .serializable
659            .iter()
660            .filter_map(|(&reader, ssi)| {
661                (reader != writer
662                    && ssi.vault_reads.iter().any(|(collection, tenant, key)| {
663                        write_set
664                            .iter()
665                            .any(|(written_collection, written_tenant, written_key)| {
666                                collection == written_collection
667                                    && tenant == written_tenant
668                                    && key.as_ref().is_none_or(|key| key == written_key)
669                            })
670                    }))
671                .then_some(reader)
672            })
673            .collect();
674        Self::serializable_readers_would_be_dangerous(&mut state, writer, readers)
675    }
676
677    pub fn serializable_commit_would_be_dangerous(
678        &self,
679        writer: Xid,
680        write_set: &HashSet<LogicalRowKey>,
681    ) -> bool {
682        if write_set.is_empty() {
683            return false;
684        }
685
686        let mut state = self.state.write();
687        if !state.serializable.contains_key(&writer) {
688            return false;
689        }
690
691        let readers: Vec<Xid> = state
692            .serializable
693            .iter()
694            .filter_map(|(&reader, ssi)| {
695                if reader != writer && !ssi.read_set.is_disjoint(write_set) {
696                    Some(reader)
697                } else {
698                    None
699                }
700            })
701            .collect();
702
703        Self::serializable_readers_would_be_dangerous(&mut state, writer, readers)
704    }
705
706    fn serializable_readers_would_be_dangerous(
707        state: &mut ManagerState,
708        writer: Xid,
709        readers: Vec<Xid>,
710    ) -> bool {
711        for reader in readers {
712            if let Some(reader_state) = state.serializable.get_mut(&reader) {
713                reader_state.outgoing_rw.insert(writer);
714            }
715            if let Some(writer_state) = state.serializable.get_mut(&writer) {
716                writer_state.incoming_rw.insert(reader);
717            }
718        }
719
720        let Some(writer_state) = state.serializable.get(&writer) else {
721            return false;
722        };
723        let has_incoming = !writer_state.incoming_rw.is_empty();
724        let has_outgoing_to_committed = writer_state
725            .outgoing_rw
726            .iter()
727            .any(|xid| state.serializable.get(xid).is_some_and(|ssi| ssi.committed));
728        has_incoming && has_outgoing_to_committed
729    }
730
731    fn prune_serializable_state(state: &mut ManagerState) {
732        if state.active.is_empty() {
733            state.serializable.clear();
734        }
735    }
736
737    /// Is this xid known to have rolled back? Called by the read path to
738    /// skip tuples whose creator never committed.
739    pub fn is_aborted(&self, xid: Xid) -> bool {
740        self.state.read().aborted.contains(&xid)
741    }
742
743    /// Unfinished writers must be rolled back in a crash-recoverable checkpoint,
744    /// without changing their live transaction state or their readers.
745    pub fn checkpoint_excluded_state(&self) -> (u64, HashSet<Xid>) {
746        let (revision, excluded, _) = self.checkpoint_projection_state();
747        (revision, excluded)
748    }
749
750    pub fn checkpoint_projection_state(&self) -> (u64, HashSet<Xid>, u64) {
751        let state = self.state.read();
752        let mut excluded = state.aborted.clone();
753        excluded.extend(state.active.iter().copied());
754        (
755            self.visibility_revision.load(Ordering::Acquire),
756            excluded,
757            state.untracked_visibility_revision,
758        )
759    }
760
761    /// Is this xid still active?
762    pub fn is_active(&self, xid: Xid) -> bool {
763        self.state.read().active.contains(&xid)
764    }
765
766    /// Unique-key admission uses current transaction outcomes, not the
767    /// reader's snapshot. An invisible active/newly committed writer still
768    /// reserves its key; an aborted creator or completed replacement does not.
769    pub fn row_reserves_unique_key(&self, xmin: Xid, xmax: Xid, own_xids: &HashSet<Xid>) -> bool {
770        let state = self.state.read();
771        if state.aborted.contains(&xmin) {
772            return false;
773        }
774        if state.active.contains(&xmin) && !own_xids.contains(&xmin) {
775            return true;
776        }
777        if xmax == 0 || state.aborted.contains(&xmax) {
778            return true;
779        }
780        !own_xids.contains(&xmax) && state.active.contains(&xmax)
781    }
782
783    /// Snapshot of every still-active xid (for VACUUM oldest-active-xid
784    /// calculation — any row with `xmax < min(active)` is reclaimable).
785    pub fn oldest_active_xid(&self) -> Option<Xid> {
786        self.state.read().active.iter().copied().min()
787    }
788
789    /// Whether an active writer lacks the durable result-cache epoch fence.
790    #[doc(hidden)]
791    pub fn has_cache_unsafe_active_xids(&self) -> bool {
792        let state = self.state.read();
793        state.active.len() != state.cache_coherent_updates.len()
794    }
795
796    /// GC must preserve writers excluded by an active reader's snapshot, even
797    /// when those writers have since committed and left the active set.
798    pub fn oldest_required_xid(&self) -> Option<Xid> {
799        let state = self.state.read();
800        state
801            .active
802            .iter()
803            .chain(state.snapshot_horizons.values())
804            .chain(state.statement_horizons.keys())
805            .chain(state.pinned.keys())
806            .copied()
807            .min()
808    }
809
810    /// Like [`oldest_required_xid`](Self::oldest_required_xid), but ignores
811    /// durable pins (VCS commit horizons). Only live transactions and captured
812    /// statement snapshots count. History that no `AS OF` read can address,
813    /// such as rows of a collection outside the VCS, is reclaimable against it.
814    pub fn oldest_live_required_xid(&self) -> Option<Xid> {
815        let state = self.state.read();
816        state
817            .active
818            .iter()
819            .chain(state.snapshot_horizons.values())
820            .chain(state.statement_horizons.keys())
821            .copied()
822            .min()
823    }
824
825    /// Oldest externally pinned xid. Pinned snapshots behave like active
826    /// snapshots for VACUUM: any tuple visible to that xid must survive even
827    /// when no SQL transaction is currently active.
828    pub fn oldest_pinned_xid(&self) -> Option<Xid> {
829        self.state.read().pinned.keys().copied().min()
830    }
831
832    /// Return the next xid that would be allocated. Useful for diagnostics
833    /// and for VACUUM to know the upper bound of aborted-xid retention.
834    pub fn peek_next_xid(&self) -> Xid {
835        self.next_xid.load(Ordering::Relaxed)
836    }
837
838    /// Advance the allocator so future snapshots consider an xid
839    /// recovered from storage/WAL to be in the committed past.
840    pub fn observe_committed_xid(&self, xid: Xid) {
841        if xid == XID_NONE {
842            return;
843        }
844        // Replay can import an xid from our still-unused reservation range.
845        // Retire those slots before publishing the floor: they must neither
846        // hide the recovered row in fresh snapshots nor be allocated again.
847        // Captured snapshots retain their original exclusions.
848        let mut pool = self.autocommit_pool.lock();
849        let target = xid.saturating_add(1);
850        pool.next = pool.next.max(target.min(pool.end));
851        let mut current = self.next_xid.load(Ordering::Relaxed);
852        while current < target {
853            match self.next_xid.compare_exchange(
854                current,
855                target,
856                Ordering::Relaxed,
857                Ordering::Relaxed,
858            ) {
859                Ok(_) => return,
860                Err(actual) => current = actual,
861            }
862        }
863    }
864
865    /// Prune outcomes only after the caller has removed or normalized every
866    /// physical version that references them across all collections and models.
867    /// A snapshot cutoff alone is insufficient: an aborted insert with xmin=x
868    /// becomes visible again if x is forgotten while that version still exists.
869    /// Pinned xids remain retained for higher-level references.
870    pub fn prune_aborted(&self, below: Xid) {
871        let mut state = self.state.write();
872        let ManagerState {
873            aborted, pinned, ..
874        } = &mut *state;
875        let previous = aborted.len();
876        aborted.retain(|&x| x >= below || pinned.contains_key(&x));
877        if previous != aborted.len() {
878            self.visibility_revision.fetch_add(1, Ordering::Release);
879        }
880    }
881
882    /// Pin an xid so its row versions stay reclaim-safe across VACUUM.
883    /// Reference-counted — call `unpin` once per `pin` to release.
884    pub fn pin(&self, xid: Xid) {
885        if xid == XID_NONE {
886            return;
887        }
888        let mut state = self.state.write();
889        *state.pinned.entry(xid).or_insert(0) += 1;
890    }
891
892    /// Decrement an xid's pin count. At zero it is removed and becomes
893    /// VACUUM-eligible again. No-op if the xid was never pinned.
894    pub fn unpin(&self, xid: Xid) {
895        if xid == XID_NONE {
896            return;
897        }
898        let mut state = self.state.write();
899        if let Some(count) = state.pinned.get_mut(&xid) {
900            if *count <= 1 {
901                state.pinned.remove(&xid);
902            } else {
903                *count -= 1;
904            }
905        }
906    }
907
908    /// Is this xid currently pinned?
909    pub fn is_pinned(&self, xid: Xid) -> bool {
910        self.state.read().pinned.contains_key(&xid)
911    }
912
913    /// Current pin count for an xid (0 if not pinned). Diagnostic only.
914    pub fn pin_count(&self, xid: Xid) -> u32 {
915        self.state.read().pinned.get(&xid).copied().unwrap_or(0)
916    }
917}
918
919impl Default for SnapshotManager {
920    fn default() -> Self {
921        Self::new()
922    }
923}
924
925#[cfg(test)]
926mod tests {
927    use super::*;
928
929    #[test]
930    fn xids_are_monotonic() {
931        let m = SnapshotManager::new();
932        let a = m.begin();
933        let b = m.begin();
934        let c = m.begin();
935        assert!(a < b && b < c);
936    }
937
938    #[test]
939    fn snapshot_excludes_concurrent_writers() {
940        let m = SnapshotManager::new();
941        let writer = m.begin();
942        let reader = m.begin();
943        let snap = m.snapshot(reader);
944        // Writer is active from reader's perspective → in_progress set.
945        assert!(snap.in_progress.contains(&writer));
946        // A row written by `writer` with xmin=writer must be invisible.
947        assert!(!snap.sees(writer, XID_NONE));
948    }
949
950    #[test]
951    fn fresh_read_snapshot_sees_latest_committed_hides_active() {
952        let m = SnapshotManager::new();
953        // A committed writer must be visible to a fresh read snapshot; an
954        // xid still active must be hidden. This is the RMW pre-image
955        // contract: latest committed, never an uncommitted sibling.
956        let committed = m.begin();
957        m.commit(committed);
958        let active = m.begin();
959
960        let snap = m.fresh_read_snapshot();
961        assert!(snap.sees(committed, XID_NONE));
962        assert!(!snap.sees(active, XID_NONE));
963        assert!(snap.in_progress.contains(&active));
964    }
965
966    #[test]
967    fn fresh_read_snapshot_refreshes_between_calls() {
968        let m = SnapshotManager::new();
969        // Value committed *after* a first read must be visible to a second
970        // fresh read — proving the snapshot is re-evaluated, not pinned.
971        let later = m.begin();
972        let first = m.fresh_read_snapshot();
973        assert!(!first.sees(later, XID_NONE));
974        m.commit(later);
975        let second = m.fresh_read_snapshot();
976        assert!(second.sees(later, XID_NONE));
977    }
978
979    #[test]
980    fn committed_rows_become_visible() {
981        let m = SnapshotManager::new();
982        let writer = m.begin();
983        m.commit(writer);
984        let reader = m.begin();
985        let snap = m.snapshot(reader);
986        // Row stamped with writer's xid is now visible (writer < reader & committed).
987        assert!(snap.sees(writer, XID_NONE));
988    }
989
990    #[test]
991    fn rolled_back_writers_stay_hidden() {
992        let m = SnapshotManager::new();
993        let writer = m.begin();
994        m.rollback(writer);
995        assert!(m.is_aborted(writer));
996        // Future callers skip tuples with xmin == writer by also consulting is_aborted.
997    }
998
999    #[test]
1000    fn pre_mvcc_rows_always_visible() {
1001        let m = SnapshotManager::new();
1002        let reader = m.begin();
1003        let snap = m.snapshot(reader);
1004        assert!(snap.sees(XID_NONE, XID_NONE));
1005    }
1006
1007    #[test]
1008    fn deletion_xmax_respected() {
1009        let m = SnapshotManager::new();
1010        let creator = m.begin();
1011        m.commit(creator);
1012        let deleter = m.begin();
1013        m.commit(deleter);
1014        let reader = m.begin();
1015        let snap = m.snapshot(reader);
1016        // Reader opens *after* delete → row must be hidden.
1017        assert!(!snap.sees(creator, deleter));
1018    }
1019
1020    #[test]
1021    fn pin_blocks_prune_of_aborted_xid() {
1022        let m = SnapshotManager::new();
1023        let writer = m.begin();
1024        m.rollback(writer);
1025        assert!(m.is_aborted(writer));
1026        m.pin(writer);
1027        // Even with a high watermark, pinned xid survives prune.
1028        m.prune_aborted(writer + 1);
1029        assert!(m.is_aborted(writer));
1030        m.unpin(writer);
1031        m.prune_aborted(writer + 1);
1032        assert!(!m.is_aborted(writer));
1033    }
1034
1035    #[test]
1036    fn pin_is_reference_counted() {
1037        let m = SnapshotManager::new();
1038        let x = m.begin();
1039        m.pin(x);
1040        m.pin(x);
1041        assert_eq!(m.pin_count(x), 2);
1042        m.unpin(x);
1043        assert_eq!(m.pin_count(x), 1);
1044        assert!(m.is_pinned(x));
1045        m.unpin(x);
1046        assert_eq!(m.pin_count(x), 0);
1047        assert!(!m.is_pinned(x));
1048        // Extra unpin is a no-op.
1049        m.unpin(x);
1050        assert_eq!(m.pin_count(x), 0);
1051    }
1052
1053    #[test]
1054    fn pin_xid_none_is_noop() {
1055        let m = SnapshotManager::new();
1056        m.pin(XID_NONE);
1057        assert!(!m.is_pinned(XID_NONE));
1058        assert_eq!(m.pin_count(XID_NONE), 0);
1059    }
1060
1061    #[test]
1062    fn reserved_autocommit_slots_are_not_writers_until_issued() {
1063        let m = SnapshotManager::new();
1064        // An autocommit insert reserves a batch and uses one slot of it.
1065        let insert = m.allocate_committed_xid();
1066        let quiet = m.fresh_read_snapshot();
1067        assert!(
1068            !quiet.in_progress.is_empty(),
1069            "unissued slots stay hidden from the snapshot"
1070        );
1071        assert!(!quiet.in_progress.contains(&insert));
1072        assert!(
1073            !m.snapshot_hides_writers(&quiet),
1074            "slots that wrote nothing must not look like in-flight writers"
1075        );
1076
1077        // Issuing a slot after the snapshot was taken is a concurrent writer.
1078        let later = m.allocate_committed_xid();
1079        assert!(quiet.in_progress.contains(&later));
1080        assert!(m.snapshot_hides_writers(&quiet));
1081
1082        // A transaction in flight when the snapshot is taken always counts,
1083        // also after it commits: the snapshot still must not see its writes.
1084        let writer = m.begin();
1085        let concurrent = m.fresh_read_snapshot();
1086        assert!(m.snapshot_hides_writers(&concurrent));
1087        m.commit(writer);
1088        assert!(m.snapshot_hides_writers(&concurrent));
1089        assert!(!m.snapshot_hides_writers(&m.fresh_read_snapshot()));
1090    }
1091
1092    #[test]
1093    fn autocommit_inserts_are_not_real_writers() {
1094        let m = SnapshotManager::new();
1095        let _insert = m.allocate_committed_xid();
1096        let quiet = m.fresh_read_snapshot();
1097        assert!(!m.snapshot_hides_real_writers(&quiet));
1098        assert!(!m.real_writer_began_after(&quiet));
1099
1100        // Inserts issued after the snapshot, across a pool refill, change
1101        // nothing: they add rows and remove no index entry.
1102        for _ in 0..3 * AUTOCOMMIT_POOL_BATCH {
1103            m.allocate_committed_xid();
1104        }
1105        assert!(!m.snapshot_hides_real_writers(&quiet));
1106        assert!(!m.real_writer_began_after(&quiet));
1107        assert!(!m.snapshot_hides_real_writers(&m.fresh_read_snapshot()));
1108
1109        // A transaction in flight when the snapshot is taken is hidden by
1110        // it, also after it commits.
1111        let writer = m.begin();
1112        let concurrent = m.fresh_read_snapshot();
1113        assert!(m.snapshot_hides_real_writers(&concurrent));
1114        assert!(!m.real_writer_began_after(&concurrent));
1115        // One begun later is not in the older snapshot, but began after it.
1116        assert!(!m.snapshot_hides_real_writers(&quiet));
1117        assert!(m.real_writer_began_after(&quiet));
1118        m.commit(writer);
1119        assert!(m.snapshot_hides_real_writers(&concurrent));
1120        assert!(m.real_writer_began_after(&quiet));
1121        let after = m.fresh_read_snapshot();
1122        assert!(!m.snapshot_hides_real_writers(&after));
1123        assert!(!m.real_writer_began_after(&after));
1124    }
1125
1126    #[test]
1127    fn a_writer_of_one_collection_is_not_a_writer_of_another() {
1128        let m = SnapshotManager::new();
1129        let quiet = m.fresh_read_snapshot();
1130        let update = m.begin_in("orders");
1131        let concurrent = m.fresh_read_snapshot();
1132        // In flight when the snapshot was taken: hidden from it.
1133        assert!(m.snapshot_hides_real_writers_of(&concurrent, "orders"));
1134        assert!(!m.snapshot_hides_real_writers_of(&concurrent, "customers"));
1135        assert!(m.snapshot_hides_real_writers(&concurrent));
1136        // Begun after the older snapshot.
1137        assert!(m.real_writer_of_began_after(&quiet, "orders"));
1138        assert!(!m.real_writer_of_began_after(&quiet, "customers"));
1139        m.commit(update);
1140        assert!(m.snapshot_hides_real_writers_of(&concurrent, "orders"));
1141        assert!(!m.snapshot_hides_real_writers_of(&concurrent, "customers"));
1142
1143        // A transaction that named no collection may change any of them.
1144        let transaction = m.begin();
1145        let during = m.fresh_read_snapshot();
1146        assert!(m.snapshot_hides_real_writers_of(&during, "customers"));
1147        assert!(m.real_writer_of_began_after(&quiet, "customers"));
1148        m.commit(transaction);
1149        let after = m.fresh_read_snapshot();
1150        assert!(!m.snapshot_hides_real_writers_of(&after, "orders"));
1151        assert!(!m.real_writer_of_began_after(&after, "orders"));
1152    }
1153
1154    #[test]
1155    fn waiting_for_writers_of_a_collection_ignores_other_collections() {
1156        let m = Arc::new(SnapshotManager::new());
1157        let orders = m.begin_in("orders");
1158        let short = std::time::Duration::from_millis(5);
1159        assert!(m.await_real_writers_of("customers", short));
1160        assert!(!m.await_real_writers_of("orders", short));
1161        let finisher = {
1162            let m = Arc::clone(&m);
1163            std::thread::spawn(move || {
1164                std::thread::sleep(std::time::Duration::from_millis(20));
1165                m.commit(orders);
1166            })
1167        };
1168        assert!(m.await_real_writers_of("orders", std::time::Duration::from_secs(5)));
1169        finisher.join().expect("finisher");
1170        let transaction = m.begin();
1171        assert!(!m.await_real_writers_of("customers", short));
1172        m.commit(transaction);
1173    }
1174
1175    #[test]
1176    fn a_forgotten_scope_counts_for_every_collection() {
1177        let m = SnapshotManager::new();
1178        let first = m.begin_in("orders");
1179        let during = m.fresh_read_snapshot();
1180        assert!(!m.snapshot_hides_real_writers_of(&during, "customers"));
1181        for _ in 0..SCOPED_WRITER_HISTORY {
1182            let later = m.begin_in("orders");
1183            m.commit(later);
1184        }
1185        assert!(
1186            m.snapshot_hides_real_writers_of(&during, "customers"),
1187            "a writer whose scope left the history must count everywhere"
1188        );
1189        m.commit(first);
1190    }
1191
1192    #[test]
1193    fn a_replayed_change_makes_every_hidden_xid_a_writer() {
1194        let m = SnapshotManager::new();
1195        m.allocate_committed_xid();
1196        let before = m.fresh_read_snapshot();
1197        assert!(!m.snapshot_hides_real_writers(&before));
1198        // A replica replays an update with a pool xid.
1199        let replayed = m.allocate_replayed_xid();
1200        assert!(before.in_progress.contains(&replayed));
1201        assert!(m.snapshot_hides_real_writers(&before));
1202        assert!(m.real_writer_began_after(&before));
1203        let after = m.fresh_read_snapshot();
1204        assert!(!m.snapshot_hides_real_writers(&after));
1205        assert!(!m.real_writer_began_after(&after));
1206    }
1207
1208    #[test]
1209    fn a_forgotten_insert_reservation_counts_as_a_writer() {
1210        let m = SnapshotManager::new();
1211        m.allocate_committed_xid();
1212        let old = m.fresh_read_snapshot();
1213        for _ in 0..(AUTOCOMMIT_POOL_BATCH_HISTORY as u64 + 2) * AUTOCOMMIT_POOL_BATCH {
1214            m.allocate_committed_xid();
1215        }
1216        assert!(
1217            m.snapshot_hides_real_writers(&old),
1218            "a reservation that left the history must err towards a writer"
1219        );
1220    }
1221
1222    #[test]
1223    fn allocate_committed_xid_is_monotonic_and_unique() {
1224        let m = SnapshotManager::new();
1225        let mut seen = HashSet::new();
1226        let mut last = 0u64;
1227        // Drive at least three pool refills (BATCH=16 → 50 covers it).
1228        for _ in 0..50 {
1229            let x = m.allocate_committed_xid();
1230            assert!(x > last, "xids must be strictly increasing: {x} > {last}");
1231            assert!(seen.insert(x), "duplicate xid handed out: {x}");
1232            last = x;
1233        }
1234    }
1235
1236    #[test]
1237    fn mixed_allocations_preserve_transaction_order_and_reclaim_horizon() {
1238        let manager = Arc::new(SnapshotManager::new());
1239        let old = manager.allocate_committed_xid();
1240        let deletion = manager.begin();
1241        manager.commit(deletion);
1242        let next_insert = manager.allocate_committed_xid();
1243        assert!(
1244            next_insert > deletion,
1245            "a later insert cannot reuse an older reserved xid"
1246        );
1247        let (snapshot, _retention) = manager.fresh_retained_snapshot();
1248        assert!(!snapshot.sees(old, deletion));
1249        assert!(snapshot.sees(next_insert, XID_NONE));
1250        assert!(
1251            manager.oldest_required_xid().expect("retained statement") > deletion,
1252            "unused allocator slots cannot keep already visible deletes resident"
1253        );
1254    }
1255
1256    #[test]
1257    fn allocate_committed_xid_skips_active_set() {
1258        let m = SnapshotManager::new();
1259        let _x = m.allocate_committed_xid();
1260        // Pool xids must never appear in the active set — they are
1261        // born committed. `oldest_active_xid` reflects only `begin()`
1262        // callers (real BEGIN-wrapped transactions).
1263        assert_eq!(m.oldest_active_xid(), None);
1264    }
1265
1266    #[test]
1267    fn allocate_committed_xid_visible_to_subsequent_snapshots() {
1268        let m = SnapshotManager::new();
1269        let writer = m.allocate_committed_xid();
1270        let reader = m.begin();
1271        let snap = m.snapshot(reader);
1272        // Pool xid must be invisible to in_progress/aborted (it's in
1273        // neither) and visible because writer < reader. This matches
1274        // the legacy begin()+commit() pair's visibility exactly.
1275        assert!(!snap.in_progress.contains(&writer));
1276        assert!(!m.is_aborted(writer));
1277        assert!(snap.sees(writer, XID_NONE));
1278    }
1279
1280    #[test]
1281    fn allocate_committed_xid_does_not_block_concurrent_begin() {
1282        // Smoke test: an open BEGIN-wrapped tx coexists with pool
1283        // allocation; pool xids end up between the begin and commit
1284        // without being added to `active`.
1285        let m = SnapshotManager::new();
1286        let tx = m.begin();
1287        let auto1 = m.allocate_committed_xid();
1288        let auto2 = m.allocate_committed_xid();
1289        m.commit(tx);
1290        assert!(tx < auto1 && auto1 < auto2);
1291        // `active` should be empty after commit.
1292        assert_eq!(m.oldest_active_xid(), None);
1293    }
1294
1295    #[test]
1296    fn oldest_active_is_min_live_xid() {
1297        let m = SnapshotManager::new();
1298        let a = m.begin();
1299        let b = m.begin();
1300        assert_eq!(m.oldest_active_xid(), Some(a));
1301        m.commit(a);
1302        assert_eq!(m.oldest_active_xid(), Some(b));
1303        m.commit(b);
1304        assert_eq!(m.oldest_active_xid(), None);
1305    }
1306
1307    #[test]
1308    fn cache_coherent_updates_remain_active_without_hiding_other_writers() {
1309        let manager = SnapshotManager::new();
1310        let update = manager.begin_cache_coherent_update();
1311        assert_eq!(manager.oldest_active_xid(), Some(update));
1312        assert!(!manager.has_cache_unsafe_active_xids());
1313        let transaction = manager.begin();
1314        assert!(manager.has_cache_unsafe_active_xids());
1315        manager.commit(transaction);
1316        assert!(!manager.has_cache_unsafe_active_xids());
1317        manager.rollback(update);
1318        assert_eq!(manager.oldest_active_xid(), None);
1319        assert!(!manager.has_cache_unsafe_active_xids());
1320    }
1321    #[test]
1322    fn read_snapshot_excludes_first_future_writer_and_deleter() {
1323        let manager = SnapshotManager::new();
1324        let old = manager.begin();
1325        manager.commit(old);
1326        let snapshot = manager.fresh_read_snapshot();
1327        let future = manager.begin();
1328        manager.commit(future);
1329        assert!(!snapshot.sees(future, XID_NONE));
1330        assert!(snapshot.sees(old, future));
1331        let fresh = manager.fresh_read_snapshot();
1332        assert!(fresh.sees(future, XID_NONE));
1333        assert!(!fresh.sees(old, future));
1334    }
1335
1336    #[test]
1337    fn snapshots_hide_autocommit_writers_allocated_after_begin() {
1338        let manager = SnapshotManager::new();
1339        let old = manager.allocate_committed_xid();
1340        let reader = manager.begin();
1341        let transaction_snapshot = manager.snapshot(reader);
1342        let statement_snapshot = manager.fresh_read_snapshot();
1343        let future = manager.allocate_committed_xid();
1344        assert!(future > reader, "begin retires the older reserved range");
1345        for snapshot in [transaction_snapshot, statement_snapshot] {
1346            assert!(snapshot.sees(old, XID_NONE));
1347            assert!(!snapshot.sees(future, XID_NONE));
1348            assert!(snapshot.sees(old, future));
1349        }
1350        assert!(manager.fresh_read_snapshot().sees(future, XID_NONE));
1351        manager.rollback(reader);
1352    }
1353
1354    #[test]
1355    fn retiring_unused_slots_preserves_an_older_readers_history() {
1356        let manager = Arc::new(SnapshotManager::new());
1357        let old = manager.allocate_committed_xid();
1358        let (snapshot, retention) = manager.fresh_retained_snapshot();
1359        let deletion = manager.begin();
1360        manager.commit(deletion);
1361        let next_insert = manager.allocate_committed_xid();
1362        let (_current, _current_retention) = manager.fresh_retained_snapshot();
1363        assert!(snapshot.sees(old, deletion));
1364        assert!(!snapshot.sees(next_insert, XID_NONE));
1365        assert!(manager.oldest_required_xid().expect("old reader retained") <= deletion);
1366        drop(retention);
1367        assert!(
1368            manager
1369                .oldest_required_xid()
1370                .expect("current reader retained")
1371                > deletion
1372        );
1373    }
1374
1375    #[test]
1376    fn replay_retires_reserved_xids_without_changing_captured_snapshots() {
1377        let manager = SnapshotManager::new();
1378        let first = manager.allocate_committed_xid();
1379        let captured = manager.fresh_read_snapshot();
1380        let replayed = first + 2;
1381        manager.observe_committed_xid(replayed);
1382        assert!(!captured.sees(replayed, XID_NONE));
1383        assert!(manager.fresh_read_snapshot().sees(replayed, XID_NONE));
1384        assert!(manager.allocate_committed_xid() > replayed);
1385
1386        let beyond_pool = manager.peek_next_xid() + 10;
1387        let captured = manager.fresh_read_snapshot();
1388        manager.observe_committed_xid(beyond_pool);
1389        assert!(!captured.sees(beyond_pool, XID_NONE));
1390        assert!(manager.fresh_read_snapshot().sees(beyond_pool, XID_NONE));
1391        assert!(manager.allocate_committed_xid() > beyond_pool);
1392    }
1393}