MVCC: Timestamps, Snapshots and Visibility

This page describes the multi-version concurrency control layer in src/transaction/. It covers transaction identity, the commit clock, read views, the per-transaction write buffer, the commit protocol, statement snapshots and the garbage-collection watermark. Isolation levels and SSI are on Isolation levels. Locks are on Locking. Savepoints and transactional DDL are on Savepoints and transactional DDL. The operator-level summary is in How it works.

Module layout

File Contents
src/transaction/mvcc.rs IsolationLevel, ReadView, VersionInfo, TransactionState, Transaction, Savepoint, TransactionManager, TransactionGuard
src/transaction/ssi.rs SsiTracker (serializable conflict detection)
src/transaction/lock.rs LockManager, LockMode, WaitForGraph, deadlock handling
src/transaction/advisory.rs AdvisoryLockManager (process-global advisory locks)
src/transaction/mod.rs Re-exports of the above

(source: src/transaction/mod.rs, module re-exports)

Third-party crates used here: dashmap (concurrent maps for the active set and lock table), parking_lot (Mutex, RwLock, Condvar), tokio (the mpsc channel type for deadlock events) and serde (lock-mode serialization). (source: src/transaction/mvcc.rs, src/transaction/lock.rs, use lists)

Identifiers and timestamps

Transaction ids and timestamps are both u64 aliases (TxnId, Timestamp). (source: src/types/mod.rs, type aliases Timestamp, TxnId)

The TransactionManager keeps one atomic clock that serves both as the start timestamp of new transactions and as the source of commit timestamps. It is a hybrid logical clock seeded from wall-clock microseconds:

  • next_commit_ts returns max(current, now_micros) and stores that value plus one in the clock, using a compare-and-swap loop, then bumps an allocation epoch used by the statement-snapshot fast path.
  • begin_with_priority for Snapshot Isolation and Serializable also does a fetch_max(now) on the clock before reading start_ts, so a new snapshot is never behind wall time.

Because the clock is seeded from microseconds rather than starting at 1, timestamps survive a restart without going backwards as long as the host clock does not go backwards. (source: src/transaction/mvcc.rs, TransactionManager::next_commit_ts, TransactionManager::begin_with_priority)

Not verified: no test was found that restarts the process and checks that new timestamps are greater than those written before the restart.

Transaction states

State Meaning
Active Running; may read and buffer writes
Preparing Commit in progress
Committed Commit timestamp assigned
Aborted Rolled back

(source: src/transaction/mvcc.rs, TransactionState)

The Transaction struct

Field Purpose
id, start_ts, commit_ts Identity and timestamps
isolation IsolationLevel (see Isolation levels)
read_view Option<ReadView>; built at begin for SI and Serializable
write_buffer BTreeMap<Vec<u8>, Option<Vec<u8>>>; None is a delete
read_set, write_set Keys read and written, for validation
snapshot_instant Wall-clock instant the snapshot was taken
timeout, start_time Transaction lifetime limit
savepoints, undo_log, lock_log Savepoint support (see Savepoints)
ssi_tracker Handle to the shared SsiTracker
current_read_writes When set, commit-time validation is skipped (see below)

(source: src/transaction/mvcc.rs, Transaction)

The struct default timeout is 30 s, but the manager overwrites it with its own default_timeout, which is 600 s. A comment ties the change to separating transaction lifetime from the 30 s lock-wait budget. A transaction past its timeout is aborted at commit. (source: src/transaction/mvcc.rs, Transaction::new, TransactionManager::new, Transaction::is_timed_out)

Tested by test_timed_out_commit_releases_locks... in src/transaction/mvcc.rs tests.

Write buffer and read-your-own-writes

Writes in an explicit transaction go to write_buffer through record_write(key, Some(value)) or record_write(key, None) for a delete. Nothing reaches storage until commit. Table scans inside the transaction overlay the buffer on the storage result with writes_in_range(start, end), an ordered BTreeMap range scan, so a scan touches only that table's buffered keys rather than the whole buffer. (source: src/transaction/mvcc.rs, Transaction::record_write, Transaction::writes_in_range; src/query/engine.rs, overlay_txn_writes call sites)

record_write also pushes the key to the SSI tracker immediately when the transaction is Serializable. (source: src/transaction/mvcc.rs, Transaction::record_write)

Snapshot read bound

snapshot_read_ts() returns Some(start_ts - 1) for Snapshot Isolation and Serializable, and None for Read Committed and Read Uncommitted. Storage reads with Some(ts) see only versions committed at or before ts; None reads the latest committed version. (source: src/transaction/mvcc.rs, Transaction::snapshot_read_ts)

ReadView and visibility

A ReadView has creator_txn_id, min_active_txn_id, max_txn_id, the set of transactions active when the view was built, and snapshot_ts. For SI and Serializable, begin_with_priority builds it with max_txn_id equal to the transaction's own id. (source: src/transaction/mvcc.rs, ReadView, TransactionManager::begin_with_priority)

ReadView::is_visible(txn_id, committed, commit_ts) applies these rules in order:

# Condition Result
1 Version written by the view's own transaction Visible
2 Writer not committed Not visible
3 txn_id > max_txn_id (started after the view) Not visible
4 Writer was in the active set when the view was built Not visible
5 txn_id < min_active_txn_id Visible
6 Otherwise Visible if commit_ts <= snapshot_ts

(source: src/transaction/mvcc.rs, ReadView::is_visible)

Tested by test_visibility in src/transaction/mvcc.rs tests.

VersionInfo (created_by_txn, commit_ts, deleted_at, deleted_by_txn) has its own is_visible. Its deletion check only hides a version deleted by the reading transaction itself; a comment in the code calls this a simplification. The SQL engine relies on storage-level versioned reads with snapshot_read_ts, not on VersionInfo. (source: src/transaction/mvcc.rs, VersionInfo::is_visible)

The module doc comment says the read view "prevents phantom reads". Range predicates are not tracked anywhere in this layer, so do not rely on that statement; see SSI limits.

Version storage

Versions are kept by the storage engine, not by the transaction layer. MemTable::insert_versioned keeps an older version when a newer one is written with a commit_ts above the GC watermark, so a live snapshot can still read it. Compaction keeps only the newest version of a key unconditionally; a code comment documents this as a known gap, and the README states the same caveat. A long-running snapshot can therefore read a newer value than its snapshot after a compaction has run over the key. (source: src/storage/memtable.rs, MemTable::insert_versioned; src/storage/compaction.rs; README.md)

Not verified: no test was found that runs compaction under a live snapshot.

Shared manager

TransactionManager::shared_for(storage) returns one manager per StorageEngine, from a process registry keyed by the storage pointer. Every wire protocol that shares a storage engine therefore shares one clock, one active set, one lock manager and one SSI tracker, so a PostgreSQL session and a MySQL session conflict with each other correctly. (source: src/transaction/mvcc.rs, TransactionManager::shared_for)

Tested by test_mysql_sessions_share_write_conflict_detection in src/protocol/mysql/mod.rs and test_cross_model_txn_invisible_to_concurrent_session_until_commit in src/query/engine.rs.

Begin

begin_with_priority(isolation, priority):

  1. Allocates the id.
  2. For SI and Serializable, inserts a placeholder into the strict_active set before reading the clock, so no committer can miss it, then reads start_ts (after fetch_max(now)), builds the ReadView and replaces the placeholder with start_ts.
  3. Registers Serializable transactions with the SSI tracker.
  4. Registers the transaction with the lock manager (with its priority) and stores it in the active map.
  5. Sets the transaction timeout to the manager's default_timeout (600 s).

(source: src/transaction/mvcc.rs, TransactionManager::begin_with_priority)

Commit protocol

The engine commits in three calls so the storage write happens between validation and lock release:

commit_validate_only(txn)   -> checks, commit_ts, recent_writes
storage.write_batch(...)    -> engine writes the buffered keys
release_locks(txn_id)       -> finish_applying + LockManager::release_all

(source: src/query/engine.rs, commit_transaction; src/transaction/mvcc.rs, commit_validate_only, release_locks)

commit_validate_only runs, in order:

  1. Fails unless the transaction is Active.
  2. If timed out, aborts, cleans up and returns an error.
  3. For Serializable without current_read_writes, runs SsiTracker::check_cycles; a cycle is Error::TransactionConflict with "could not serialize access due to concurrent update".
  4. Runs validate (write-write and, for Serializable, read-write checks).
  5. Under the applying lock, allocates commit_ts with next_commit_ts and registers it as applying.
  6. Records the transaction's keys in recent_writes only when strict_active is non-empty (some SI or Serializable transaction could still conflict with them).
  7. Removes the transaction from the active map, recomputes watermarks and calls retire_committed on the SSI tracker.

On any failure, cleanup_failed_commit releases all locks and removes the transaction from the active set. abort is idempotent and guards its metrics so a second call does not double count. (source: src/transaction/mvcc.rs, commit_validate_only, cleanup_failed_commit, abort)

Tested by test_write_write_conflict, test_failed_commit_releases_locks_and_removes_from_active, test_abort_after_failed_commit_is_idempotent, all_read_committed_commits_skip_recent_writes, strict_txn_active_makes_rc_committer_record_its_writes and rc_writer_after_all_strict_gone_is_not_recorded in src/transaction/mvcc.rs tests.

Conflict checks

Isolation Check Rule
Read Uncommitted, Read Committed none Always passes
any, with current_read_writes none Always passes
Snapshot Isolation check_write_conflicts Conflict if any written key has a recent_writes entry with commit ts >= start_ts (first committer wins)
Serializable above plus check_read_write_conflicts Also conflict if a key read was written by a commit at or after start_ts

(source: src/transaction/mvcc.rs, TransactionManager::validate, check_write_conflicts, check_read_write_conflicts)

current_read_writes is set by the engine for MySQL and SQL Server sessions at REPEATABLE READ or SERIALIZABLE. Those dialects use locking reads for writes (InnoDB style), so a write conflict surfaces as a lock wait rather than a commit-time abort. (source: src/query/engine.rs, mark_mysql_txn; src/transaction/mvcc.rs, Transaction::current_read_writes)

Autocommit applying registry and statement snapshots

Autocommit batches do not create a Transaction. They call begin_applying() to get a commit timestamp and register it as "applying", write their batch, then call end_applying(ts). The registry lets readers wait for a batch to land before they read at a timestamp that includes it. (source: src/transaction/mvcc.rs, begin_applying, end_applying, applied_at)

statement_snapshot() gives a per-statement read timestamp (used for Read Committed statements so one statement sees one consistent cut):

  • The snapshot is the clock minus one, after a fetch_max(now_micros) on the clock.
  • Fast path: if no commit is applying and no commit timestamp was allocated while the snapshot registered (checked through the allocation epoch), return at once without taking the applying lock.
  • Otherwise, wait on the applied condition variable until every applying timestamp at or below the chosen snapshot has finished, for at most 10 s; on expiry it logs a warning and proceeds.

The returned StatementSnapshot is registered in stmt_snapshots so the GC watermark does not pass it while the statement runs, and unregisters itself on drop. (source: src/transaction/mvcc.rs, TransactionManager::statement_snapshot)

Tested by sum_over_concurrent_transfers_sees_whole_transactions in src/query/engine.rs tests. The design note is docs/status/2026-11-24-statement-snapshot.md.

GC watermark

Two watermarks exist:

Watermark Value Consumer
Snapshot (GC) watermark min(start_ts of live SI/Serializable txns) - 1, lowered to the oldest live statement snapshot; u64::MAX when no snapshot is live Storage: versions newer than it are kept in the memtable
watermark() Minimum start_ts of active transactions gc(min_ts) pruning of recent_writes and committed_txns

set_snapshot_watermark_sink(atomic) points the manager at an AtomicU64 owned by storage; every recompute stores into it. (source: src/transaction/mvcc.rs, recompute_snapshot_watermark, set_snapshot_watermark_sink, watermark, update_watermark, gc)

Not verified: no test was found that checks the watermark value directly; it is covered only indirectly by the snapshot-read tests above.

TransactionGuard

TransactionGuard wraps a transaction handle and aborts it on drop unless it was committed, so an early return or panic in Rust code does not leave a transaction active. (source: src/transaction/mvcc.rs, TransactionGuard)

Not verified: no test of the drop path was found.

Engine-level default isolation

The IsolationLevel Rust default is SnapshotIsolation, but a plain SQL BEGIN on the PostgreSQL path starts at Read Committed, because the session's pending isolation defaults to Read Committed. MySQL sessions start at the session isolation, which defaults to Snapshot Isolation (shown as REPEATABLE READ). See Isolation levels. (source: src/transaction/mvcc.rs, impl Default for IsolationLevel; src/query/engine.rs, begin_transaction)