Skip to main content

SnapshotManager

Struct SnapshotManager 

Source
pub struct SnapshotManager { /* private fields */ }
Expand description

Central allocator and liveness tracker.

Uses an atomic counter for xid allocation and a parking_lot-guarded HashSet for in-progress/aborted bookkeeping. The sets stay small — only unfinished transactions plus a finite rollback history — so a plain HashSet outperforms more complex data structures here.

§Autocommit xid pool

Single-row autocommit writes (MutationEngine::append_one) need an xid that’s “born committed” — they call begin() then commit() back-to-back before the row is even durable. The pre-commit pool (autocommit_pool_*) batches the reservation: one next_xid.fetch_add(BATCH) reserves a contiguous range of xids, each handed out via a single atomic without touching the RwLock<ManagerState>. Pool xids are never inserted into active or aborted so they look like already-committed transactions to every snapshot — identical visibility semantics to the legacy begin()/commit() pair (which also leaves the xid in neither set).

Implementations§

Source§

impl SnapshotManager

Source

pub fn new() -> SnapshotManager

Source

pub fn begin(&self) -> u64

Allocate a new xid and mark it active. Returns the xid for stamping onto UnifiedEntity::xmin/xmax.

Allocation and the active insert happen together under the state write lock. This is load-bearing for first-committer-wins: a concurrent snapshot (state read lock) must never observe a lower-numbered still-running xid as absent from active. Were the fetch_add done outside the lock, a writer that grabbed the smaller xid could still be mid-begin() while a later transaction snapshots a larger xid — the smaller xid would be missing from in_progress, yet xmin <= snapshot.xid, so the snapshot would treat that concurrent (later possibly-committed) writer as visible. That both leaks an uncommitted row into a peer’s read and lets two writers on the same row both commit. Serialising allocation under the lock guarantees any xid smaller than a taken snapshot’s xid is already in active (or already finished), so in_progress is never short a concurrent writer.

Source

pub fn begin_in(&self, collection: &str) -> u64

begin for a writer that changes rows of collection only, such as an autocommit UPDATE or DELETE. A reader of another collection does not have to treat it as a writer that can have left its indexes behind.

Source

pub fn fresh_read_snapshot(&self) -> Snapshot

Capture a fresh read-committed snapshot at this instant: sees every transaction that has committed so far and hides every still-active one. Unlike [snapshot], the caller supplies no xid — the snapshot id is the current allocator high-water mark, read under the same state lock that [begin] holds while it bumps the counter and inserts into active. That mutual exclusion is what makes the read atomic: a concurrent begin() is either wholly visible (counter bumped AND present in active, hence hidden as in-progress) or wholly invisible (neither) — never the torn state where its xid sits below the high-water mark yet is missing from active, which would leak an uncommitted writer as visible.

Used for RMW pre-image reads that must always observe the latest committed row version rather than a pinned statement snapshot.

Source

pub fn snapshot_hides_writers(&self, snapshot: &Snapshot) -> bool

Whether snapshot hides a writer that may already have written.

Every read snapshot lists the reserved-but-unissued autocommit slots in in_progress, so a row written with one of them later stays invisible. Until a slot is issued it has written nothing, and no index can be behind it. A slot issued since the snapshot was taken counts as a writer here, so the answer only errs towards true.

Source

pub fn snapshot_hides_real_writers(&self, snapshot: &Snapshot) -> bool

Whether snapshot hides a transaction that can have removed index entries: one begun with begin and still in flight when the snapshot was taken.

An autocommit INSERT draws its xid from the reserved pool. It adds rows and their index entries and removes none, so it cannot leave an index behind this snapshot whether it ran before or after it was taken.

Once a change was replayed with a pool xid (allocate_replayed_xid) the pool no longer serves inserts alone, and this answers like snapshot_hides_writers.

Source

pub fn real_writer_began_after(&self, snapshot: &Snapshot) -> bool

Whether a transaction was begun with begin after snapshot was taken. Autocommit inserts do not count; see snapshot_hides_real_writers.

Source

pub fn snapshot_hides_real_writers_of( &self, snapshot: &Snapshot, collection: &str, ) -> bool

snapshot_hides_real_writers for a reader of collection: a hidden writer that named another collection when it began (begin_in) does not count.

Source

pub fn await_real_writers_of(&self, collection: &str, wait: Duration) -> bool

Waits, at most wait, until no real writer that can change collection is in flight. Returns whether that was reached. A statement that would otherwise scan the collection because such a writer is hidden from its snapshot can wait the few milliseconds the writer takes and read a fresh snapshot instead.

Source

pub fn real_writer_of_began_after( &self, snapshot: &Snapshot, collection: &str, ) -> bool

Source

pub fn allocate_replayed_xid(&self) -> u64

allocate_committed_xid for a replayed change, which can be an update or a delete. See snapshot_hides_real_writers.

Source

pub fn fresh_retained_snapshot( self: &Arc<SnapshotManager>, ) -> (Snapshot, SnapshotRetentionGuard)

Capture and register under the same lock used by GC cutoff selection. Registering only when the snapshot is installed leaves a capture-to-read interval in which a committed writer’s old versions can be reclaimed.

Source

pub fn retain_snapshot( self: &Arc<SnapshotManager>, snapshot: Snapshot, ) -> (Snapshot, SnapshotRetentionGuard)

Retain a snapshot already protected by its parent transaction, outer statement frame, or historical reference while transferring ownership.

Source

pub fn snapshot(&self, xid: u64) -> Snapshot

Capture a point-in-time snapshot. Must be called after begin() when using SnapshotIsolation/Serializable. ReadCommitted refreshes this per statement via the same call.

Source

pub fn commit(&self, xid: u64)

Mark a transaction as committed. Its writes become visible to future snapshots; earlier snapshots keep their own view.

Source

pub fn allocate_committed_xid(&self) -> u64

Allocate an xid that is born committed — for autocommit callers (MutationEngine::append_one) that previously paid two state.write() lock acquisitions per row to insert-then-remove from the active set.

The returned xid is never inserted into active and never into aborted, which matches the steady state of the legacy begin()/commit() pair when called back-to-back: the xid leaves the manager’s tracking sets unobservably. Concurrent readers therefore see it as an already-committed transaction once xmin <= snapshot.xid, which is exactly the semantics the autocommit path needs.

Implementation: a small reservation pool (AUTOCOMMIT_POOL_BATCH xids) is reserved with one fetch_add. Each caller hands itself the next xid via a single atomic. When the pool drains, the next caller serialises briefly through autocommit_pool_refill to bump the window, then falls back into the lock-free hot path.

Durability note: this method does NOT make the row durable — it only allocates the identifier. The caller must complete the usual WAL-append + fsync cycle before acknowledging the write. Pre-allocating the xid is safe because the xid carries no promise that any row exists; it’s just a number for xmin.

Source

pub fn rollback(&self, xid: u64)

Mark a transaction as rolled back. Its writes MUST stay hidden from every future read — is_visible consults the aborted set before honouring a row’s xmin.

Source

pub fn begin_serializable(&self, xid: u64)

Source

pub fn record_serializable_read( &self, reader: u64, collection: &str, logical_id: EntityId, )

Source

pub fn record_serializable_vault_read( &self, reader: u64, collection: &str, tenant: Option<&str>, key: Option<&str>, )

Source

pub fn serializable_vault_commit_would_be_dangerous( &self, writer: u64, write_set: &HashSet<(String, Option<String>, String)>, ) -> bool

Source

pub fn serializable_commit_would_be_dangerous( &self, writer: u64, write_set: &HashSet<(String, EntityId)>, ) -> bool

Source

pub fn is_aborted(&self, xid: u64) -> bool

Is this xid known to have rolled back? Called by the read path to skip tuples whose creator never committed.

Source

pub fn checkpoint_excluded_state(&self) -> (u64, HashSet<u64>)

Unfinished writers must be rolled back in a crash-recoverable checkpoint, without changing their live transaction state or their readers.

Source

pub fn checkpoint_projection_state(&self) -> (u64, HashSet<u64>, u64)

Source

pub fn is_active(&self, xid: u64) -> bool

Is this xid still active?

Source

pub fn row_reserves_unique_key( &self, xmin: u64, xmax: u64, own_xids: &HashSet<u64>, ) -> bool

Unique-key admission uses current transaction outcomes, not the reader’s snapshot. An invisible active/newly committed writer still reserves its key; an aborted creator or completed replacement does not.

Source

pub fn oldest_active_xid(&self) -> Option<u64>

Snapshot of every still-active xid (for VACUUM oldest-active-xid calculation — any row with xmax < min(active) is reclaimable).

Source

pub fn oldest_required_xid(&self) -> Option<u64>

GC must preserve writers excluded by an active reader’s snapshot, even when those writers have since committed and left the active set.

Source

pub fn oldest_live_required_xid(&self) -> Option<u64>

Like oldest_required_xid, but ignores durable pins (VCS commit horizons). Only live transactions and captured statement snapshots count. History that no AS OF read can address, such as rows of a collection outside the VCS, is reclaimable against it.

Source

pub fn oldest_pinned_xid(&self) -> Option<u64>

Oldest externally pinned xid. Pinned snapshots behave like active snapshots for VACUUM: any tuple visible to that xid must survive even when no SQL transaction is currently active.

Source

pub fn peek_next_xid(&self) -> u64

Return the next xid that would be allocated. Useful for diagnostics and for VACUUM to know the upper bound of aborted-xid retention.

Source

pub fn observe_committed_xid(&self, xid: u64)

Advance the allocator so future snapshots consider an xid recovered from storage/WAL to be in the committed past.

Source

pub fn prune_aborted(&self, below: u64)

Prune outcomes only after the caller has removed or normalized every physical version that references them across all collections and models. A snapshot cutoff alone is insufficient: an aborted insert with xmin=x becomes visible again if x is forgotten while that version still exists. Pinned xids remain retained for higher-level references.

Source

pub fn pin(&self, xid: u64)

Pin an xid so its row versions stay reclaim-safe across VACUUM. Reference-counted — call unpin once per pin to release.

Source

pub fn unpin(&self, xid: u64)

Decrement an xid’s pin count. At zero it is removed and becomes VACUUM-eligible again. No-op if the xid was never pinned.

Source

pub fn is_pinned(&self, xid: u64) -> bool

Is this xid currently pinned?

Source

pub fn pin_count(&self, xid: u64) -> u32

Current pin count for an xid (0 if not pinned). Diagnostic only.

Trait Implementations§

Source§

impl Default for SnapshotManager

Source§

fn default() -> SnapshotManager

Returns the “default value” for a type. Read more

Auto Trait Implementations§

§

impl !Freeze for SnapshotManager

§

impl !RefUnwindSafe for SnapshotManager

§

impl Forget for SnapshotManager

§

impl Move for SnapshotManager

§

impl Send for SnapshotManager
where Atomic<u64>: Send, Atomic<bool>: Send, RwLock<RawRwLock, ManagerState>: Send, Mutex<RawMutex, AutocommitPool>: Send,

§

impl Sync for SnapshotManager
where Atomic<u64>: Sync, Atomic<bool>: Sync, RwLock<RawRwLock, ManagerState>: Sync, Mutex<RawMutex, AutocommitPool>: Sync,

§

impl Unpin for SnapshotManager
where Align8<u64>: Unpin, Align1<u8>: Unpin, Align8<usize>: Unpin, *const u8 is !null: Unpin, *const LeafNode<u64, Arc<str>> is !null: Unpin, Box<(u64, Arc<str>)>: Unpin, Arc<str>: Unpin,

§

impl UnsafeUnpin for SnapshotManager

§

impl UnwindSafe for SnapshotManager

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where T: 'a,

Source§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

Source§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where T: 'a,

Source§

fn implicit( self, class: Class, constructed: bool, tag: u32, ) -> TaggedParser<'a, Implicit, Self, E>

Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> IntoRequest<T> for T

Source§

fn into_request(self) -> Request<T>

Wrap the input message T in a tonic::Request
Source§

impl<L> LayerExt<L> for L

Source§

fn named_layer<S>(&self, service: S) -> Layered<<L as Layer<S>>::Service, S>
where L: Layer<S>,

Applies the layer to a service and wraps it in Layered.
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<G1, G2> Within<G2> for G1
where G2: Contains<G1>,

Source§

fn is_within(&self, b: &G2) -> bool