Multiple versions make concurrent reads and writes possible, but versions aren’t free: who creates them, who can see them, and when they can be dropped all need explicit answers.

Part five of the plan series.

1. TxnMgr holds very little

TxnMgr{
    currentStartTs uint64   // starts at 2, +1 per txn, < 2^62
    currentTxnId   uint64   // starts at 2^62, +1 per txn
    lowestActiveId uint64
    lowestActiveStart uint64
    activeTxns    []Txn     // created, not committed/rolled back
    committedTxns []Txn     // committed, not GC'd
    oldTxns       []Txn     // GC-able, not GC'd
}

The two counters start in different ranges so timestamps and transaction ids never collide:

  • below 2^62 is a timestamp;
  • at or above 2^62 is a transaction id.

Comparing the number alone tells you which it is — no extra tag needed.

2. What a transaction records

FieldPurpose
startTs / commitIdvisibility checks
undoBufferundo log for rollback
local storagewritten but uncommitted data
active query id / highest active query idwhether any query still references it, for GC

3. Lifecycle

  1. Create: allocate start timestamp and id, commitId = 0, join the active queue;
  2. Read: decide visibility by its own startTs;
  3. Write: local storage + undo log, with conflict detection;
  4. Commit: allocate a commit timestamp from currentStartTs, write redo log to disk, maybe trigger a checkpoint;
  5. Rollback: undo via the undo log;
  6. GC: leave the active queue; committed goes to the committed queue, rolled back to the old queue.

4. Two GC conditions

A transaction object can’t be freed at commit — other queries may still reference its versions:

StepConditionMeaning
committed → oldcommitId < lowestActiveStartevery active txn started after it, so nobody will read its old versions
old → freedhighestActiveQueryId < lowestActiveQueryIdno active query can reference it

Why the second condition matters: a long query may still read old versions after a transaction commits. Checking commitId alone would free too early.

5. What this means in practice

  • Long transactions stall GC: they pin lowestActiveStart;
  • Long queries do too: they pin lowestActiveQueryId;
  • So “idle in transaction” and half-hour report queries deserve separate handling in production.

6. Checklist

CheckExpectation
Timestamps and txn ids in separate rangesyes (< 2^62 / ≥ 2^62)
Rollback uses undo logyes
GC checks active queriesyes
Long transactions are monitoredshould be, in production

7. Next

Transactions give consistency; checkpoint and redo give crash recovery. That’s the last post in this series.

Series: Database kernel · Project page

Get the next post

New posts on database kernels and engineering.