Locking: Lock Manager, Deadlocks, Timeouts and Advisory Locks

SynergyDB uses locks for three purposes: row locks that stop lost updates, key locks that make concurrent INSERTs of one unique key behave like PostgreSQL, and advisory locks that applications take explicitly. The first two go through LockManager in src/transaction/lock.rs. Advisory locks have their own process-global manager in src/transaction/advisory.rs. The isolation levels that rely on these locks are on Isolation levels.

Lock manager structure

LockManager holds:

Field Type Purpose
locks DashMap<Vec<u8>, Arc<Mutex<LockState>>> One entry per locked resource key
txn_locks DashMap<TxnId, HashSet<Vec<u8>>> Keys held per owner, for release_all
wait_graph WaitForGraph Wait-for edges and per-transaction metadata
config LockManagerConfig Timeouts and policies
stats LockManagerStats Counters (acquired, released, waits, timeouts, deadlocks)

Each LockState has granted: Vec<LockRequest>, waiting: VecDeque<LockRequest> (FIFO) and a parking_lot::Condvar. (source: src/transaction/lock.rs, LockManager, LockState, LockRequest)

There is one LockManager per TransactionManager, and one TransactionManager per storage engine, so every wire protocol shares the same lock table. (source: src/transaction/mvcc.rs, TransactionManager::shared_for, TransactionManager::lock_manager)

Lock modes

Mode Strength
IntentionShared (IS) 1
Shared (S) 2
IntentionExclusive (IX) 3
Update (U) 4
SharedIntentionExclusive (SIX) 5
Exclusive (X) 6

Compatibility matrix (held mode in rows, requested mode in columns; Y means compatible):

  IS S IX U SIX X
IS Y Y Y Y - -
S Y Y - Y - -
IX Y - Y - - -
U Y Y - - - -
SIX - - - - - -
X - - - - - -

SIX is incompatible with every mode, including IS. The textbook matrix makes SIX compatible with IS. (source: src/transaction/lock.rs, LockMode::is_compatible)

Allowed upgrades: S to X, S to U, U to X, IS to IX, IS to SIX, IX to SIX. (source: src/transaction/lock.rs, LockMode::can_upgrade_to, LockMode::strength)

The SQL engine only requests Shared (for SELECT ... FOR SHARE / FOR KEY SHARE) and Exclusive (everything else). The intention and update modes are used only by the lock manager's own tests and tests/concurrency.rs. (source: src/query/engine.rs, LockMode:: call sites)

Tested by lock_mode_compatibility, lock_shared_concurrent_reads, lock_exclusive_blocks_shared, lock_upgrade_shared_to_exclusive and lock_release_all in tests/concurrency.rs.

Acquire algorithm

acquire_with_deadlock_timeout(txn_id, key, mode, timeout, deadlock_timeout):

  1. Clamp timeout to config.max_timeout (300 s).
  2. Run the configured prevention scheme (default None, which does nothing).
  3. Get or create the LockState for key and lock its mutex.
  4. If the caller already holds the key: same mode returns at once; an allowed upgrade is applied in place when the caller is the only holder or the new mode is compatible with the other holders; a request for a mode that is not an upgrade (for example S while holding X) returns at once.
  5. If can_grant (compatible with every other granted holder, and compatible with every waiter queued ahead of it), grant.
  6. Otherwise, append to waiting and add a wait-for edge to each granted holder whose mode conflicts.
  7. If deadlock_timeout is zero, check for a cycle now; if the caller is in one, remove it from the queue and return Error::Deadlock.
  8. Loop: wait on the condition variable for at most 50 ms (a guard against lost wakeups), rebuild this waiter's out-edges from the current holders, run the cycle check once when deadlock_timeout has elapsed and the lock still cannot be granted, grant when can_grant passes, and return Error::LockTimeout at the deadline.

(source: src/transaction/lock.rs, LockManager::acquire_with_deadlock_timeout, LockState::can_grant)

acquire(txn_id, key, mode, timeout) is the same call with DEFAULT_DEADLOCK_TIMEOUT (1 s). try_acquire never waits; it returns Ok(false) when the lock is not available. (source: src/transaction/lock.rs, LockManager::acquire, LockManager::try_acquire)

Wait-for edges are added only toward granted holders. A waiter that is blocked only by an incompatible waiter queued ahead of it (FIFO fairness) has no edge for that wait, so a cycle that passes through queue order alone is not detected and ends at the lock timeout instead. (source: src/transaction/lock.rs, acquire_with_deadlock_timeout) Not verified: no test covers this case.

Release

  • release(txn_id, key) removes the owner's granted entries, wakes all waiters, and removes the resource entry when it has no holders, no waiters and no other Arc reference.
  • release_all(txn_id) releases every key in txn_locks and unregisters the owner from the wait graph. Commit, rollback and session drop all end here.
  • release_prefix(prefix) releases every lock on keys with a given prefix; DROP TABLE uses it.
  • is_locked_by_other(key, txn_id) reports whether anyone else holds the key.

(source: src/transaction/lock.rs, release, release_all, release_prefix, is_locked_by_other)

Tested by test_session_drop_mid_transaction_releases_row_locks, failed_statement_releases_the_transactions_row_locks and insert_locks_are_released_and_forgotten in src/query/engine.rs tests, and test_failed_commit_releases_locks_and_removes_from_active in src/transaction/mvcc.rs tests.

Deadlock detection

The detection that runs in practice is on-demand, inside the waiter. Each waiter checks once whether it is in a cycle, after deadlock_timeout of waiting. If it is, it aborts itself with Error::Deadlock. The other members of the cycle continue. This is the PostgreSQL scheme: the earliest waiter in the cycle reaches its check first and fails. (source: src/transaction/lock.rs, acquire_with_deadlock_timeout)

Session dialect deadlock_timeout Effect
PostgreSQL and others 1 s (DEFAULT_DEADLOCK_TIMEOUT) Earliest waiter in the cycle fails
MySQL, SQL Server 0 The request that closes the cycle fails at once, as in InnoDB and SQL Server

(source: src/query/engine.rs, QueryEngine::deadlock_timeout)

WaitForGraph provides has_cycle (recursive DFS), is_in_cycle (iterative search, used by acquire), detect_all_cycles (Tarjan strongly connected components), find_cycle and select_victim. (source: src/transaction/lock.rs, WaitForGraph)

Tested by test_deadlock_detected_after_waiter_granted and test_deadlock_detected_after_lock_handoff in src/transaction/lock.rs tests, and deadlock_detection_two_cycle, deadlock_detection_three_cycle and deadlock_no_false_positive in tests/concurrency.rs.

Background detection, victim policies and prevention schemes

Feature Default Status
start_background_detection (tokio task, every detection_interval = 100 ms) background_detection: true in config Not wired: TransactionManager::start_deadlock_detection is its only caller and nothing in src/ calls that. When run, it selects and marks a victim but does not abort it.
VictimSelectionPolicy: Youngest (default), Oldest, LowestPriority, FewestLocks, LeastVictimized, Weighted (weights age 0.3, priority 0.4, locks 0.2, victim count 0.1) Youngest Used only by select_victim, which only the background task and tests call. On-demand detection always aborts the waiter that found the cycle.
DeadlockPreventionScheme: None (default), WaitDie, WoundWait, LockOrdering, TimeoutBased None Not wired: no code outside lock.rs sets a non-default scheme. WoundWait only increments a counter; it never wounds a holder. WaitDie and LockOrdering return Error::Deadlock.
set_deadlock_channel (tokio::sync::mpsc sender for DeadlockEvent) unset Not wired: never called; deadlock events go to tracing only.
max_deadlock_retries 3 No reader found.

(source: src/transaction/lock.rs, LockManagerConfig::default, start_background_detection, apply_prevention_scheme, apply_wound_wait, set_deadlock_channel; src/transaction/mvcc.rs, start_deadlock_detection)

Victim selection is tested by deadlock_victim_selection_youngest and deadlock_victim_selection_fewest_locks in tests/concurrency.rs, which call the graph directly.

TransactionPriority (Low 0, Normal 1, High 2, Critical 3) is recorded in the graph metadata at begin and used only by victim selection. (source: src/transaction/lock.rs, TransactionPriority, TransactionMetadata)

Timeouts

Setting Default Source
LockManagerConfig::default_timeout 30 s src/transaction/lock.rs, LockManagerConfig::default
LockManagerConfig::max_timeout (cap on every wait) 300 s same
PostgreSQL lock_timeout GUC Unset means wait up to max_timeout src/query/engine.rs, lock_wait_timeout, parse_guc_duration_ms
MySQL innodb_lock_wait_timeout 50 s, minimum 1 s, capped at max_timeout src/query/engine.rs, lock_wait_timeout, set_lock_wait_timeout_secs
SQL Server SET LOCK_TIMEOUT n (ms) Unset or negative means max_timeout; @@LOCK_TIMEOUT reports -1 when unset src/query/engine.rs, set_lock_timeout_ms, lock_timeout_ms
SELECT ... FOR UPDATE/SHARE blocking wait inside a transaction Fixed 5 s, with the 1 s deadlock check src/query/engine.rs, lock_one_row_for_select
Transaction lifetime 600 s src/transaction/mvcc.rs, TransactionManager::new

parse_guc_duration_ms accepts a number with an optional unit ms, us, s, min, h or d; a bare number is milliseconds. (source: src/query/engine.rs, parse_guc_duration_ms)

A lock timeout returns Error::LockTimeout ("canceling statement due to lock timeout"). See Errors for wire codes. Tested by test_lock_timeout in src/transaction/lock.rs tests.

The SELECT ... FOR UPDATE wait uses the fixed 5 s timeout rather than lock_wait_timeout(), so lock_timeout and innodb_lock_wait_timeout do not apply to it. (source: src/query/engine.rs, lock_one_row_for_select) Not verified: no test checks this interaction.

How the engine uses locks

Row locks for UPDATE and DELETE

Inside an explicit transaction, UPDATE and DELETE take an Exclusive lock on the row's storage key ({table}:{pk}) through acquire_row_lock, then pass once through the storage row latch so that any autocommit write already in progress on that row finishes before the transaction reads it. Locks are held until commit or rollback. (source: src/query/engine.rs, acquire_row_lock)

Autocommit UPDATE and DELETE take no row lock. Under the storage row latch, they check whether another owner holds the row (wait_row_unlocked_latched). If one does, they queue for an Exclusive lock under a transient statement owner, then re-check. The transient owner id comes from next_transient_lock_id, which counts up from 1 << 63, a range real transaction ids never reach. The statement releases it at its end (release_stmt_locks). (source: src/query/engine.rs, wait_row_unlocked_latched, key_lock_owner, release_stmt_locks; src/transaction/lock.rs, next_transient_lock_id)

Tested by test_concurrent_update_same_row_no_lost_updates_or_vanish and test_concurrent_autocommit_delete_not_lost_to_update in src/query/engine.rs tests. The design note is docs/status/2026-11-24-concurrent-write-locks.md.

Key locks for INSERT

Before an INSERT (or the conflict probe of ON CONFLICT) checks for duplicates, lock_insert_keys takes an Exclusive lock on every uniqueness key the row would claim: the primary-key row key, each UNIQUE column value and each UNIQUE column group. Unique keys have the form \u{0}ukey:{table}:{cols}:{vals}, and citext values are lowercased first. A second session inserting the same key blocks until the first commits (then gets 23505) or rolls back (then succeeds). UPDATEs that change a unique value lock the new key through lock_changed_unique_keys. (source: src/query/engine.rs, lock_insert_key, lock_insert_keys, unique_lock_keys, lock_changed_unique_keys)

Tested by concurrent_inserts_of_one_unique_key_keep_one_row and insert_locks_are_released_and_forgotten in src/query/engine.rs tests.

SELECT … FOR UPDATE / FOR SHARE

apply_select_row_locks resolves the single base table of the SELECT, scans it with the WHERE predicate, and locks each matching row: Exclusive for FOR UPDATE and FOR NO KEY UPDATE, Shared for FOR SHARE and FOR KEY SHARE.

Wait mode Behaviour
default Blocking acquire, 5 s timeout
NOWAIT try_acquire; on contention Error::LockNotAvailable("could not obtain lock on row in relation \"t\""), SQLSTATE 55P03
SKIP LOCKED try_acquire; rows that cannot be locked are dropped by injecting a pk IN (...) filter

Limits: a SELECT whose source is not a single base table runs without row locks, and a table without a primary key also runs unlocked. In autocommit, the locks are probed with a transient id and released at once. (source: src/query/engine.rs, apply_select_row_locks, lock_one_row_for_select)

Tested by test_select_for_update_skip_locked_and_nowait, test_select_for_update_blocks_then_proceeds and test_select_for_update_composite_pk in src/query/engine.rs tests.

Stall diagnostics

When the environment variable SYNERGYDB_STALL_DUMP is set to 1, dbg_stage records the last lock-manager stage each transaction reached, and stall_dump / stall_diag_dump render the lock table, waiters and stages for a watchdog. When the variable is unset, dbg_stage is a cached no-op. (source: src/transaction/lock.rs, stall_dump_enabled, dbg_stage, stall_diag_dump)

Advisory locks

Manager

AdvisoryLockManager::global() returns one process-wide manager: a std::sync::Mutex over HashMap<i64, Holder { session, count }> and a std::sync::Condvar. Advisory locks are exclusive and re-entrant: the holding session may take the same key again, and each acquisition needs a matching unlock. They are not part of LockManager and do not take part in deadlock detection. (source: src/transaction/advisory.rs, AdvisoryLockManager)

Method Behaviour
try_acquire(session, key) Takes the lock if free or already held by session; returns bool
acquire_blocking(session, key, timeout) Waits on the condvar until free or the timeout passes
release(session, key) Decrements the count; returns false if session is not the holder
release_all_for_session(session) Drops every lock the session holds
release_keys_for_session(session, keys) Removes the session's entry for each listed key, whatever its count (used for transaction-scoped locks); returns the number of counts dropped
is_held_by(session, key) Test helper
holder(key) Current holder, if any
fold_two_int(a, b) (a as i64) << 32 \| (b as u32 as i64), the PostgreSQL two-key layout

(source: src/transaction/advisory.rs)

Tests in src/transaction/advisory.rs: try_acquire_excludes_other_session, unlock_returns_false_when_not_held, reentrant_requires_matching_unlocks, release_all_drops_session_locks, fold_two_int_matches_pg_layout, blocking_acquire_times_out_when_held_by_other.

PostgreSQL functions

try_handle_advisory_lock intercepts SELECT pg_advisory_*(...) and SELECT pg_try_advisory_*(...) before planning. The session id is the engine id.

Function Scope Returns
pg_advisory_lock(k) / (a, b) Session void (OID 2278)
pg_try_advisory_lock(...) Session bool (OID 16)
pg_advisory_xact_lock(...) Transaction void
pg_try_advisory_xact_lock(...) Transaction bool
pg_advisory_unlock(...) Session bool, true if this session held it
pg_advisory_unlock_all() Session void

Arguments may be integer literals (a ::int or ::bigint suffix is ignored) or $N parameters. Two arguments are folded with fold_two_int. The blocking forms wait up to 60 s, then fail with Error::QueryExecution("advisory lock N not available within timeout"). Transaction-scoped locks are released at COMMIT and ROLLBACK (release_xact_advisory_locks). Session locks are released when the session ends (release_session_advisory_locks). (source: src/query/engine.rs, try_handle_advisory_lock, release_xact_advisory_locks, release_session_advisory_locks)

Function names are matched by prefix. pg_advisory_lock_shared therefore matches pg_advisory_lock and takes an exclusive lock, and the same applies to the other _shared forms. (source: src/query/engine.rs, try_handle_advisory_lock) Not verified: no test was found for the _shared variants.

Tested by test_advisory_lock_acquire_try_unlock_two_sessions, test_advisory_lock_two_int_overload, test_advisory_xact_lock_released_on_commit and test_advisory_lock_released_on_session_end in src/query/engine.rs tests.

MySQL named locks

GET_LOCK(name, timeout), RELEASE_LOCK(name), IS_FREE_LOCK(name), IS_USED_LOCK(name) and RELEASE_ALL_LOCKS() use the same manager. The key is the FNV-1a hash of the lowercased name with the top bit set, which keeps named locks apart from small pg_advisory_lock integers. A negative timeout waits 365 days. (source: src/query/engine.rs, mysql_named_lock)

Tested by mysql_named_locks_across_sessions in src/query/engine.rs tests.