CMU 15-445 Bustub Project 4 - Concurrency Control - Note
Last updated on November 2, 2026 pm
This article is currently an experimental machine translation and may contain errors. If anything is unclear, please refer to original Chinese version. I am continuously working to improve the translation.
Preface
This time I'm opening a document to record things before writing, so that I won't forget everything later)
After all, a quick glance shows that the spec for P4 is quite long — if I don't take notes, I'll definitely end up writing the later parts while forgetting the earlier ones.
Actually, I haven't watched the corresponding lectures yet, so I'll also record some notes on the knowledge here.
This time I tried using an LLM purely, but combined with the course's high-quality resources, giving it this prompt:
I'm a bit too lazy to watch the videos, so please help me speedrun it like this:
- Learn unit by unit, with each section within each lecture as the unit, using the slides and notes as the main thread to assist my learning
- For the original text above, try to translate it verbatim; add as little embellishment of your own as possible
- However, you are encouraged to use intelligent UI diagrams to help me understand
- After learning each chunk of knowledge, use the corresponding problems from the homework to build a Q&A system paired with intelligent UI for me to practice with
That's it. Start with Lecture 17 first — try outputting how you would divide up Lecture 17. Once you've divided it, I'll say "start," and then we'll begin learning bit by bit.
There are quite a few files you need to read, so be a bit careful with reading them.
Let's see how it works.
Second edit: the result was really good.
Lec 17 Concurrency Control Theory
Why we need concurrency control and Recovery:
- Lost Update Problem (Concurrency Control): when two or more transactions try to update the same data simultaneously, how should we handle it?
- Durability Problem (Recovery): when a power outage occurs, how do we ensure the database is in a correct state?
The basic requirement of a Transaction: either complete all steps, or execute none of them.
A simple way to handle transactions:
- Serialize everything, with a single worker thread executing one transaction at a time.
- Before a transaction begins, the DBMS copies the entire database to a new file and makes all modifications on that file.
- If the transaction succeeds, the new file becomes the current database file; if the transaction fails, the DBMS discards the modified copy and none of the transaction's changes are saved.
This approach is called The Strawman System or Shadow Paging; it gives up all concurrency and doesn't work well.
If concurrent execution is needed, we must guarantee:
- Correctness: ensure execution meets requirements without errors
- Fairness: ensure no transaction starves
Moreover, transactions can only constrain things within the DBMS. Suppose a transaction modifies the database and sends an email to an external mailbox, and then the transaction aborts — the DBMS has no way to recall the email.
Therefore, we need Formal Correctness Criteria to judge whether a certain interleaved execution is valid. Specifically:
Formally, a database can be represented as a fixed set of named data objects (A, B, C, ...).
These objects can be Attributes, Tuples, Pages, Tables, or even the entire database.
The algorithms we will discuss apply to any type of object, but all objects must be of the same type.
A Transaction is a series of read/write operations performed on these objects, such as R(A), W(B). This is the DBMS's abstract view of the user program.
The boundaries of a transaction are defined by the client.
In SQL, a new transaction begins with the BEGIN command and ends with COMMIT or ABORT / ROLLBACK.
For COMMIT, either all of the transaction's modifications are saved to the database, or the DBMS overrides this decision and aborts the transaction instead.
For ABORT, all of the transaction's modifications are undone, making it as if the transaction never happened.
A transaction's abort can be initiated proactively by the transaction itself, or caused by the DBMS.
Correctness specification: ACID
Atomic
The possible outcomes of a transaction's commit:
- Commit
- Abort / Rollback
Methods to guarantee Atomicity:
- Logging: the DBMS records all operations in a log in order, maintaining undo logs on both disk and in memory
- Shadow Paging: mentioned above. Runtime performance is worse than logging
The key difference between the two approaches:
Logging: allows modifying data, then undoing the modifications using the recorded information.
Shadow Paging: keeps the original pages, makes modifications on a copy, and only adopts the new pages after commit.
Two concurrent transactions interfere with each other, causing the final database state to not correspond to the result of any serial execution. Which property is primarily violated?: Isolation.
Consistency
Integrity Constraints
Constraints at the SQL level, such as a certain field not being allowed to be negative.
Eventual Consistency
Eventual consistency: a committed transaction may see inconsistent results
For example, a committed transaction may not immediately see the updates made by an earlier committed transaction.
So, eventual consistency isn't great.
Isolation
Isolation of Transactions: the DBMS provides transactions with the illusion that "each transaction is the only one running in the system," unable to see the effects of other transactions.
This is equivalent to: transactions running serially. But truly serial execution is impossible. So we need a way to let transactions execute interleaved while still appearing to execute one at a time.
Concurrency Control Protocol
A concurrency control protocol is the method by which the DBMS decides at runtime how to correctly interleave the operations of multiple transactions.
It falls into two categories:
- Pessimistic concurrency control: the DBMS assumes transactions will conflict, so it prevents problems from the start;
- Optimistic concurrency control: the DBMS optimistically assumes conflicts between transactions are rare, so it chooses to handle them after they occur.
Execution Schedule
The order in which the DBMS executes transactions is called the execution schedule.
Goal: interleave transactions to maximize concurrency while remaining equivalent to some serial execution.
Formal Properties of Schedules
We can think of before and after execution as state transitions, with the entire database being a state machine.
- Serial schedule: literally what it says
- Equivalent schedules: two schedules that produce exactly the same final state
- Serializable schedule: if a schedule is equivalent to some serial execution of these transactions, then it is a serializable schedule
Conflicting Operations
Let's define a few concepts.
Two operations are said to conflict if they satisfy the following conditions:
- They belong to different transactions.
- They act on the same data object.
- At least one of the operations is a write.
Different types of conflicts lead to different types of anomalies, such as:
Read-write conflicts lead to unrepeatable reads, i.e., a transaction reads the same data object multiple times but cannot get the same value. A simple example: transaction T1 has two read tasks, with a complete transaction T2 sandwiched between them, which has an RW conflict with T1.
Write-read conflicts lead to dirty reads, i.e., a transaction reads data written by another transaction that has not yet been committed.

Write-write conflicts lead to lost updates, i.e., one transaction overwrites data written by another transaction that has not yet committed. Essentially, T1 writes first, and T2 writes later, overwriting T1's write.
There is one more anomaly, the phantom read, which we'll discuss later.
Distinguish between conflicts and anomalies:
A conflict is a relationship between operations; an anomaly is an abnormal phenomenon that appears during execution.
Conflict Serializability
Two schedules are conflict equivalent if and only if both of these conditions hold:
- They contain the same operations of the same transactions.
- In both schedules, every pair of conflicting operations has the same relative order.
If a schedule S is conflict equivalent to some serial schedule, then S is conflict serializable.
Intuitively, this means schedule S can be transformed into a serial schedule by swapping adjacent, non-conflicting operations between different transactions.
Example:

Dependency Graph
Use a dependency graph to verify whether a schedule is conflict serializable.
In the dependency graph:
- Each transaction is a node in the graph
- There is a directed edge from $T_i$ to $O_i$ if and only if operation $T_j$ of transaction $O_j$ conflicts with operation $O_i$ of transaction $O_j$, and $T_i$ appears before $T_j$ in the schedule
A schedule is conflict serializable if and only if its dependency graph is acyclic.
Understanding: if the dependency graph has no cycles, we can find a topological ordering and execute the transactions serially in that order, while satisfying the ordering constraints between all conflicting operations.
View Serializability
View serializability is a weaker definition of serializability than conflict serializability.
View serializability is difficult to enforce efficiently, because the DBMS does not know how the application will interpret these values. Therefore, real systems do not adopt this approach.
So I was too lazy to read it; skipping.
Durability
Transaction durability: all modifications of committed transactions must be durable after a system crash or restart, i.e., the following two situations are not allowed:
- Incomplete updates are not allowed: after crash recovery, only part of a transaction's modifications must not remain.
- Modifications of failed transactions must not be retained: the modifications of a transaction that did not successfully commit must not become part of the database's valid state after recovery.
This is achieved through appropriate redo logs.
An example problem:

Lec 18 Two-Phase Locking
Transaction Locks
Serializability and its related theory carry an assumption: at scheduling time, all read and write operations are known.
But in practice, we need a method that maintains correctness dynamically during execution.
Therefore, the DBMS uses locks to dynamically produce serializable transaction execution schedules, with an internal lock manager responsible for deciding whether a transaction can acquire a lock on a particular object.
That sentence above is a bit convoluted. A simple example: suppose Ta and Tb want to access the same object — the Lock Manager coordinates the lock requests.
The difference between Locks and Latches:
- Lock: protects the database's data values (isolates transactions), avoiding conflicts between concurrent transactions
- Latch: protects the DBMS's internal data structures (isolates threads), avoiding errors caused by multi-threaded concurrent access
Locks are usually held for the entire transaction, while Latches are only held for short critical sections.
Two basic kinds of locks:
- Shared Lock: allows multiple transactions to read the same object simultaneously
- Exclusive Lock: while held, no other transaction may hold a lock on that object
It's basically just a reader-writer lock, right?
How the Lock Manager works: it maintains an internal Lock Table, recording which transactions hold which locks, and which transactions are waiting to acquire locks.
Basic Two-Phase Locking
Two-Phase Locking: a pessimistic concurrency control protocol that uses locks to dynamically decide whether a transaction is allowed to access objects in the database.
Phase 1: Growing — each transaction requests the locks it needs from the DBMS's Lock Manager. The Lock Manager grants or denies these requests.
Phase 2: Shrinking — after a transaction releases its first lock, it immediately enters the shrinking phase. In this phase, the transaction can only release previously acquired locks and cannot acquire new ones.
Core rule: once you start releasing locks, you cannot acquire new locks, nor upgrade existing locks.
2PL guarantees conflict serializability, because the dependency graph produced by the schedule contains no cycles.
Simple explanation: under 2PL, the conflict ordering between transactions must be consistent with the order of their last successful lock acquisitions; a cycle is impossible because locks cannot be re-acquired.
2PL has the Cascading Abort problem: after one transaction aborts, other transactions must also roll back, wasting already-completed computation work.
A simple example: T1 finishes its writes and enters the shrink phase; T2 acquires the lock but then something goes wrong and it aborts — then T1's completed work must also abort.
2PL can also produce dirty reads.
Strong Strict 2PL
Definition of a Strict Schedule: a schedule is Strict if any value written by a transaction is not read or overwritten by another transaction until that transaction commits.
So SS2PL: a variant of 2PL in which a transaction must finish (Commit or Abort) before it can release locks.
Advantages:
- No cascading aborts
- The DBMS can undo an aborted transaction's modifications by restoring the dependent values of the recovered tuples.
- Avoids dirty reads
Disadvantages:
- Poor concurrency performance
- Cannot prevent deadlocks
Strict 2PL: must hold all X-Locks until the transaction ends, but allows releasing S-Locks early (provided the 2PL phase restrictions are still respected).
Deadlock
Two approaches 2PL uses to handle deadlocks: detection and prevention
Detection
The DBMS can build a Waits-for Graph to track which locks each transaction is waiting to acquire.
The graph is defined as follows:
- Nodes represent transactions.
- If transaction $T_i$ is waiting for transaction $T_j$ to release some lock, there is a directed edge $T_i\rightarrow T_j$ (waiter -> holder)
- The system periodically checks the wait-for graph for cycles and decides how to break them.
The system usually uses a background thread to periodically check the Waits-for Graph for cycles. If one check misses a deadlock, subsequent checks still have a chance to find it, so there are trade-offs in detection frequency.
Handling
When the DBMS detects a deadlock, it selects a Victim Transaction, rolls it back, and thereby breaks the wait-for cycle.
There are many selection strategies, such as age, proportion of execution, etc.
Prevention
Unlike Detection, deadlock prevention stops any transaction from entering a deadlock before it happens.
That is: when a transaction tries to acquire a lock held by another transaction, the DBMS can abort one of them.
To achieve this, the DBMS assigns priorities to transactions; for example, one scheme is "the older, the higher the priority."
For example, Wait-Die:
- An old transaction requests a new transaction's lock: the old transaction waits
- A new transaction requests an old transaction's lock: the old transaction dies
Wound-Die:
- An old transaction requests a new transaction's lock: the new transaction dies
- A new transaction requests an old transaction's lock: the new transaction waits
Both protocols guarantee no deadlocks; both schemes only allow transactions to wait for locks in one direction, so cycles are impossible in the graph.
If a transaction is restarted after being aborted, the DBMS lets it keep using its original timestamp rather than assigning a new one.
This avoids the transaction becoming ever younger and lower in priority, being repeatedly aborted, and thus causing Starvation.
Note: this is a measure to avoid starvation; it does not mean starvation is absolutely impossible under any scheduling conditions.
Lock Hierarchy
This is essentially about distinguishing lock granularity.
Trade-offs:
- Coarse-grained locks reduce lock management overhead, but limit concurrency;
- Fine-grained locks improve potential concurrency, but require managing more locks.
Database Lock Hierarchy
| Level | Frequency of Use |
|---|---|
| Database | Slightly Rare |
| Table | Very Common |
| Page | Common |
| Tuple | Very Common |
| Attribute | Rare |
Intention Locks
Suppose T1 already holds an exclusive lock on some tuple in table P. If T2 wants to acquire a shared lock on the entire table, the DBMS must know that a finer-grained exclusive lock exists on this table; otherwise it might incorrectly approve the request.
Checking tuple by tuple is too expensive.
Hence intention locks are introduced, allowing the system to determine whether a lock can be granted to a higher-level node without checking all lower-level nodes.
If a node has an intention lock on it, it means some transaction is locking at that lower level.
So, for the example above, T1 would add an IX(TableP) to the table; since S(TableP) conflicts with IX, the lock cannot be acquired.
IX(Table P) means the transaction intends to use exclusive locks at a lower level of P; it is not itself equivalent to X(Table P).
Three kinds of intention locks:
- Intention Shared: indicates the transaction is currently or about to explicitly acquire an S-Lock at a lower level.
- Intention-Exclusive: indicates the transaction is currently or about to explicitly acquire an X-Lock at a lower level.
- Shared + Intention-Exclusive: the entire subtree rooted at this node is explicitly locked in shared mode, while the transaction will also explicitly acquire exclusive locks at lower levels. (read the whole, write parts)
A counterintuitive conclusion: IX is compatible with IX. Because they only declare that there are writes at a lower level; it doesn't mean both parties will modify the same tuple. Real conflicts still need to be determined at the lower level.
Hierarchical Locking
This subsection focuses on how transactions acquire locks along the hierarchy.
In general: acquiring S/IS or X/IX/SIX on a child node requires holding the corresponding lock on the parent node.
Therefore, one should usually acquire locks top-down and release locks bottom-up.
When is SIX needed: scanning the entire table while modifying a single tuple.
As long as locks are compatible, different transactions can concurrently access the same element.
Lock Escalation
When a transaction holds a large number of low-level locks, the DBMS can automatically convert them to a coarser-grained lock, reducing the number of lock requests the Lock Manager needs to maintain and process.
Explicit Locking
Most databases support explicit locking via SQL, bypassing the Lock Manager. I won't go into detail here.
A simple example: before performing a large number of writes to a table, proactively acquire an exclusive lock first, to prevent two transactions later both wanting to upgrade and causing a deadlock, forcing an abort.
Lec 19 Timestamp Ordering Concurrency Control
As for why Timestamp Ordering (TO) is introduced, we first need to review 2PL.
2PL is a pessimistic protocol, in that: it requires transactions to acquire locks before accessing database objects.
But if in fact conflicts between transactions are rare, an optimistic protocol is better.
TO is a class of optimistic concurrency control protocols; specifically:
- The DBMS uses timestamps to determine the serializability order of transactions
- Each transaction $T_i$ is assigned a unique, fixed, monotonically increasing timestamp, denoted $TS(T_i)$
- If $TS(T_i) < TS(T_j)$, then the DBMS must ensure that the execution schedule is equivalent to the serial schedule in which $T_i$ executes before $T_j$.
Timestamp allocation strategies:
- System clock (UNIX TIME)
- Logical counter (increment +1)
OCC Basic Protocol
OCC - Optimistic Concurrency Protocol
Optimistic Concurrency Control (OCC) is an optimistic concurrency control protocol that uses timestamps to validate transactions.
OCC works best when the number of conflicts is small. For example:
- All transactions are read-only.
- The data subsets accessed by transactions do not overlap.
If the database is large and the workload has no obvious skew, the probability of conflicts between transactions is low, so OCC is a good choice.
In OCC, the DBMS creates a Private Workspace for each transaction:
- All of a transaction's modifications are done in its own Workspace;
- Objects being written are copied into the Workspace for modification;
- If the isolation level needs to guarantee Repeatable Read, read objects are also copied into the Workspace.
- Note that other transactions cannot read the modifications a transaction produces in its Private Workspace.
- When a transaction is ready to commit, the DBMS checks whether its Write Set conflicts with other transactions.
The three phases of OCC:
- Read Phase: the DBMS tracks the transaction's Read Set and Write Set, and stores the transaction's writes in the Private Workspace
- Validation Phase: when the transaction is ready to commit, the DBMS assigns the transaction a unique timestamp (TS), then checks whether the transaction conflicts with other transactions.
- Write Phase:
- If validation succeeds, the DBMS sets write timestamps (W-TS) on all modified objects in the Private Workspace and applies the modifications atomically to the global database.
- If validation fails, the transaction aborts and restarts.
The Read Phase is when the transaction does its actual work; the Validation and Write Phases together form the Commit Protocol.
OCC Validation
In the Validation Phase, how do we determine whether the transaction to be committed will conflict with other transactions? It's simply a matter of validating the Read / Write Sets of other in-progress transactions; there are two methods.
- Forward Validation: check active transactions that have not yet committed.
- Backward Validation: check transactions that have already committed.
Three conditions to guarantee serializability:
Assume the timestamp order is $TS(T_i)<TS(T_j)$; satisfying at least one of the three conditions is sufficient:
- Fully serial: $T_i$ completed its Write Phase before $T_j$ entered its Read Phase.
- Overlapping read phases, ordered writes: $T_i$'s Write Phase must be earlier than $T_j$'s Write Phase, and $W_i\cap R_j=\varnothing$
- Larger overlap: $T_i$'s Read Phase must end before $T_j$'s Read Phase ends, and $W_i\cap R_j=\varnothing$ and $W_i\cap W_j=\varnothing$
OCC Performance and Limitations
OCC's ideal scenarios:
- All transactions are read-only
- Transactions access non-overlapping data subsets
Potential problems:
- The Private Workspace is obviously problematic
- Validation and the Write Phase's verification are bottlenecks
- Aborts are wasteful
- Timestamp Allocation Bottleneck
Aborts are fairly serious, because with OCC, in high-conflict scenarios a large number of transactions will roll back. Moreover, aborts happen only after the transaction has already finished executing, causing a lot of waste.
Phantom Reads
Phantom read: when a transaction scans a range multiple times, and another transaction inserts or deletes tuples belonging to that range between the two scans, the scanning transaction may get different results.
The phantom read problem arises because transactions only lock existing records, ignoring records that other transactions are creating.
Phantom Prevention
| Method | Core Idea | Usage in the Course |
|---|---|---|
| Lock Everything | Lock the entire table or all relevant pages | Common, but coarse-grained |
| Re-Execute Scans | Re-scan the predicate before commit, checking whether the results are still the same | Rarely used |
| Predicate Locking | Lock the WHERE predicate; if another transaction tries to acquire a lock on the same predicate and it conflicts with an existing predicate lock, a lock conflict occurs | Rarely used |
| Index Locking | Use index keys to lock ranges | Common |
Let's focus on the last one; it is in fact a special case of predicate locking: using Key Ranges in the index to protect the query range.
It divides into these four types:
| Type | Protected Object |
|---|---|
| Key-Value | A single Key. To protect a Key that does not yet exist, Virtual Keys need to be introduced. |
| Gap | Locks the Gap between index key values, preventing other transactions from inserting new records into the protected gap. |
| Key-Range | Locks the interval from one existing Key to the next Key, thereby protecting both existing key values and the corresponding insertion range. |
| Hierarchical | Allows transactions to hold larger Key Ranges in different lock modes, reducing the overhead of accessing the Lock Manager. |
Isolation Levels
We've been talking about: serializability, conflict serializability, etc.
But forcibly enforcing serializability makes the system's concurrency too low and performance poor.
Therefore, the DBMS may want to use weaker consistency levels to improve scalability.
Four anomalies:
| Anomaly | Original Definition |
|---|---|
| Dirty Read | Reading data that has not yet been committed |
| Unrepeatable Read | Re-reading the same data yields different results |
| Lost Update | One transaction overwrites another concurrent transaction's update |
| Phantom Read | Inserting or deleting records causes the same range scan to yield different results |
Four isolation levels, from strongest to weakest:
- Serializable: phantom reads not allowed, all reads are repeatable, and dirty reads are also not allowed.
- Repeatable Read: phantom reads may occur.
- Read Committed: phantom reads, unrepeatable reads, and lost updates may occur.
- Read Uncommitted: all of the above anomalies can occur.
Actually, the definitions corresponding to these names are easy to remember. For example, why doesn't Read Committed have dirty reads? Because the definition of a dirty read is precisely "reading uncommitted data." And Repeatable Read means multiple reads return the same data, i.e., it solves the unrepeatable read and lost update problems. Why does it solve lost updates? Because a lost update can also be seen as repeatedly reading inconsistent data.
How to implement different isolation levels? Taking 2PL as an example:
| Isolation Level | Implementation Idea |
|---|---|
| Serializable | Strong Strict 2PL + Phantom Protection |
| Repeatable Read | Strong Strict 2PL, but without Phantom Protection |
| Read Committed | Exclusive locks held until transaction end; shared locks released immediately after reading |
| Read Uncommitted | Exclusive locks held until transaction end; no shared locks acquired when reading |
Lec 20 MVCC
MVCC Fundamentals
Multi-Version Control System MVCC is a broader concept than a mere Concurrency Control Protocol, touching every aspect of the DBMS's design and implementation.
MVCC's core idea: one logical object, multiple physical versions.
MVCC's core benefit: write transactions don't block read transactions, and read transactions don't block write transactions.
Note that MVCC allows reads and writes to not block each other, but it does not automatically eliminate write-write conflicts.
It means one transaction can modify an object while other transactions read the object's old version.
Read-only transactions can, without using any locks, access the Consistent Snapshots provided by the DBMS.
Snapshot Isolation
Snapshot Isolation: at the start of a transaction, the transaction is given a consistent snapshot of the database, where the data values in the snapshot only include values produced by transactions committed at that time. The entire complete transaction runs within this snapshot.
Solutions for Write-Write Conflicts: First Writer Wins or Last Writer Wins.
For example, with the former: if the earlier transaction writes but hasn't committed, the later transaction writing the same object will be aborted.
Write Skew Anomaly
Under Snapshot Isolation, when two concurrent transactions modify different objects, a Write Skew Anomaly may occur, producing a non-serializable schedule.
To explain this problem, here's an example:
- Suppose the database initially has two marbles, one black and one white; the former is A, the latter is B.
- T1 turns all black marbles white, T2 turns all white marbles black.
- Serialized results:
- If the order is T1 - T2, everything ends up black;
- If the order is T2 - T1, everything ends up white.
- These two cases correspond to the only possibilities under serializability.
- But under snapshot isolation, both transactions execute on snapshots with the same initial conditions;
- T1 only modifies A, T2 only modifies B
- Since they don't write the same object, no WW conflict occurs
- Then, the final result: A is white, B is black, corresponding to no serial result whatsoever.
The essential reason is that there is a cycle in the dependency graph.

Strictly speaking, this uses the Read-Write Antidependency from multi-version serialization graphs; you can't simply treat it as a single-version schedule and apply the ordinary conflict graph directly.
Project 4's Snapshot Isolation only needs to check write-write conflicts, so in the marble example above, both transactions might successfully commit.
But Task 4.4's Serializable Verification also needs to check the data that was read, to determine whether concurrent transactions' writes invalidate those reads.
For example, when T1 commits, if it finds that T2 has already committed, and:
$$ R_1\cap W_2\ne\varnothing $$
then T1 may need to be aborted to avoid a non-serializable execution.
Version Chains
Version storage: the DBMS uses the pointer field in a Tuple to create a Version Chain for each logical Tuple. Essentially, it is a linked list ordered by timestamp. At runtime, a transaction traverses along the version chain until it finds the correct version visible to itself.
Version Chain Ordering
- Oldest-to-Newest (O2N):
- New versions are appended to the end of the version chain. Lookups must traverse the version chain.
- Newest-to-Oldest (N2O):
- Each time a new version is created, the index pointer must be updated to point to the new chain head.
- Reading the latest version requires no traversal of the version chain.
- This is usually the better approach, because most transactions only care about the latest version.
Note the actual approach in the BusTub project:
BusTub does not append the complete updated Tuple to the main table on every update; instead it uses a Delta Storage-like scheme: current physical values -> Undo Log chain. More on this later.
Append-Only Storage
Append-Only Storage
- All physical versions of a logical Tuple are kept in the same table space.
- Different versions are stored mixed together in the table.
- On each update, the DBMS only needs to append the Tuple's new version to free space in the table, then update the version chain.
Time-Travel Storage
This is the counterpart to Append-Only Storage, the second version storage scheme. Specifically:
- The DBMS maintains a separate table, called the Time-Travel Table, which stores old versions of Tuples.
- On each update, the DBMS copies the old version to the Time-Travel Table, then overwrites the Tuple in the Main Table with the new data.
- The Tuple's pointer in the Main Table points to the historical version in the Time-Travel Table.
It is still the pointer-linked-list logical structure; it's just that all historical versions are in the Time-Travel Table.
The direct benefit is that the main table doesn't have to mix in a large number of historical Tuples.
Delta Storage
Time-Travel Storage has this problem: if you only change one column of a tuple with many columns, you end up recording the entire historical information in full.
Delta Storage is similar to Time-Travel Storage, but the DBMS no longer stores complete historical Tuples; instead it stores only the differences or changes (Deltas) between Tuples in a Delta Storage Segment.
Afterwards, a transaction can traverse these Deltas in reverse order and apply them to recreate old versions.
Therefore, compared to Time-Travel Storage, Delta Storage writes faster but reads slower.
A Delta stores the value before the modification, not the value after.
Note that for Tuples that have been logically deleted and are no longer needed by any active transaction, the physical records in the main table can eventually also be reclaimed.
That is the GC to be discussed below.
Tuple-Level Garbage Collection
A version can be reclaimed if any of the following conditions is met:
- No active transaction can see this version.
- This version was created by a transaction that has already Aborted.
There are two main implementation approaches to garbage collection: Tuple-Level GC and Transaction-Level GC.
Regarding the first point, an example: version A0 has timestamp 10, but all currently active transactions have timestamps > 10, and it has been logically deleted — then this version can be reclaimed.
Let's focus on the principle of what we call Tuple-Level GC: the DBMS discovers old versions by directly inspecting Tuples.
Two implementation schemes:
- Background Vacuuming
- A separate background thread periodically scans tables, looking for versions that can be reclaimed.
- A simple optimization is to maintain a Dirty Page Bitmap, recording which Pages have been modified since the last scan. This way, the background thread can skip Pages that haven't changed.
- Cooperative Cleaning
- Worker Threads identify reclaimable versions while traversing version chains
- Only applicable to Oldest-to-Newest (O2N) version chains, because the traversal order must be old -> new so that cleanup can be done along the way
Transaction-Level Garbage Collection
In transaction-level garbage collection, each transaction is responsible for tracking its own old versions, so the DBMS doesn't need to scan Tuples to find them.
- Each transaction maintains its own Read Set and Write Set.
- When a transaction ends, the garbage collector can use these sets to determine which Tuples can be reclaimed.
Simply put: maintain a set of Old Versions and determine whether these old versions are still needed.
However, BusTub's implementation differs greatly from this; more on that later.
Logical vs. Physical Pointers
Understanding how MVCC indexes locate version chains.
For the primary key index, which points to the head of the version chain: if a transaction modifies a Tuple's primary key attributes, that modification is treated as a DELETE followed by an INSERT. If Time-Travel or Delta Storage is used, the latest Tuple may always be kept in the same physical slot, in which case ordinary column updates don't necessarily require modifying the index pointer.
Updating a Tuple's contents does not necessarily mean changing the Tuple's physical address.
For secondary indexes, it's more complicated. There are two management schemes:
- Using Logical Pointers:
- The DBMS uses a fixed, unchanging identifier for each Tuple.
- This requires an additional Indirection Layer to map logical IDs to the Tuple's physical location.
- Afterwards, a Tuple update only needs to modify the mapping in the indirection layer.
- Physical Pointers
- The DBMS directly uses the physical address of the version chain head.
- Whenever the version chain head changes, all related indexes need to be updated. This can be very expensive.
MVCC Duplicate Key Problem
Indexes in MVCC databases usually don't store a Tuple's version information together with the index key. The same Key in different snapshots may point to different logical Tuples. Therefore, the index needs to support duplicate Keys. This is the MVCC Duplicate Key Problem.
Three requirements are proposed:
- The index's underlying data structure needs to be able to store non-unique keys.
- Primary key indexes and unique indexes need additional execution logic for conditional inserts. It must atomically check whether the Key exists before deciding whether to insert.
- A Worker may get multiple entries from a single index query, so it needs to follow the pointers to find the correct physical version.
Allowing the index's underlying layer to store duplicate Keys does not mean allowing two visible records that violate the uniqueness constraint to appear in the database.
However, bustub's constraint is that an index always points to the same RID.
Deleted
- Logical Delete means that, for a particular snapshot, the record no longer exists.
- Physical Delete means the database actually releases the storage space occupied by the record.
The method of logical deletion: actually, we've already done this in the projects:
- Maintain an
is_deleted_in the metadata - Set a tombstone
Preface About the Spec
Recording some miscellaneous things to know.
- Use undo logs and undo links. The former is bound to transactions
- Depends on the correct implementation of p2 and p3
- Need to modify on top of this
Also: this diagram is very useful:

Task 1
Timestamp Allocation
First, understand bustub's timestamp allocation mechanism:
- Each transaction is assigned two timestamps: read ts and commit ts
- When a transaction begins, it is assigned a read ts whose value equals the commit timestamp of the most recently committed transaction
- When a transaction commits, it uses the most recently committed transaction's commit timestamp + 1
- Why is this OK? Because the read ts is fixed once assigned, but afterwards the last commit ts only increases monotonically
- Visible version = the latest version with (timestamp <= read ts)
- Remember to update
last_commit_ts_
Here you need to implement the corresponding todo comments in TransactionManager::Commit and TransactionManager::Begin.
Actually, if you just follow what's said above, there's not much to say. Note that for this task, you only need to modify the corresponding parts.
Watermark
The so-called watermark is:
- Among all transactions that have not yet been Committed or Aborted, the smallest read timestamp (
read_ts). - If no such transaction exists, then the Watermark equals the last commit ts.
The meaning of the Watermark is: current and future transactions never need to read snapshots earlier than the Watermark.
The most naive way to obtain it is obviously to traverse everything (the manager has a std::unordered_map<txn_id_t, std::shared_ptr<Transaction>> txn_map_, so just scan it all).
But this is too inefficient, so the spec requires us to implement a watermark algorithm that is at least $O(logN)$.
Anyway, first read the code. watermark.h contains these three fields:
timestamp_t commit_ts_;
timestamp_t watermark_;
std::unordered_map<timestamp_t, int> current_reads_;| Member | Meaning |
|---|---|
commit_ts_ |
The latest commit timestamp recorded inside Watermark |
watermark_ |
The cached minimum active read timestamp |
current_reads_ |
Records active read timestamps and their occurrence counts |
Then we need to implement these two functions:
auto Watermark::AddTxn(timestamp_t read_ts) -> void;
auto Watermark::RemoveTxn(timestamp_t read_ts) -> void;Actually, we also need to combine this with the functions in TransactionManager; Begin(), Commit(), and Abort() all need to correctly call AddTxn() and RemoveTxn().
We can then realize that we can exploit the monotonically non-decreasing property of the watermark, using the existing hash table data structure to achieve amortized $O(1)$.
Roughly speaking:
- If the hash table is non-empty, then at the position keyed by the watermark there must be a value, and everything before the watermark is empty
- When deleting a txn, if the value doesn't become 0, nothing happens
- If the entire hash table becomes empty, set watermark = commit_ts
- But if the hash table is not empty, then check whether the deleted one is exactly the one at the watermark position
- If so, keep moving forward until reaching a non-empty position.
- This only traverses once, amortized $O(1)$.
Task 2
The preceding introduction covers the storage mechanism for version data.
BusTub stores transaction data in three places: the Table Heap, the Transaction Manager, and each transaction's own Workspace:
- The Table Heap always contains the latest Tuple data.
- The Transaction Manager keeps, for each Tuple, a link pointing to the latest Undo Log (
PageVersionInfo). - Transactions keep the Undo Logs they created themselves, recording how the transaction modified the Tuple.
The connections are roughly:
- You can get Tuple + Metadata from the TableHeap via RID
- You can get an UndoLink from the Transaction Manager via RID, which is essentially
txn_id+log_idx. AnUndoLinkis a link pointing to an Undo Log, used to chain together all the Undo Logs of a Tuple.- If this txn id is invalid, then the undo link is invalid. Before obtaining undo logs, you need to first confirm validity
- Via the Undo Link you can get undo logs from the Transaction and traverse them one by one
The way to obtain historical versions:
- First, get all modifications that occurred after this timestamp
- Starting from the latest version, undo these modifications one by one
Tuple Reconstruction
Goal: given the latest Tuple and a set of Undo Logs, reconstruct the historical Tuple.
(The next small task: finding the appropriate undo logs)
Implement this function:
auto ReconstructTuple(
const Schema *schema,
const Tuple &base_tuple,
const TupleMeta &base_meta,
const std::vector<UndoLog> &undo_logs
) -> std::optional<Tuple>;Note that the undo logs here:
- Are applied in order from newest to oldest
- All passed-in Undo Logs should be applied; you must ensure the arguments don't pass in too many undo logs
Also, if the result is deleted, return std::nullopt.
Another thing to note: the meanings of the fields of the undo log class are all easy to understand, except for the tuple — this tuple uses a partial schema, containing only the columns that were changed.
So we need to use Schema::CopySchema() to construct a partial schema, so that we can get the values we need from this tuple, and finally construct the returned tuple.
When constructing, we need an array std::vector<uint32_t> attrs, which can be obtained by iterating over the undo log's modified_fields_ (by index).
Sequential Scan (Tuple Retrieval)
This section is essentially about collecting the undo logs that are actually needed.
We need to rewrite the SeqScanExecutor from Project 3 so that it can obtain the corresponding version based on the transaction's read ts. We also need to implement CollectUndoLogs() in execution_common.cpp:
auto CollectUndoLogs(
RID rid,
const TupleMeta &base_meta,
const Tuple &base_tuple,
std::optional<UndoLink> undo_link,
Transaction *txn,
TransactionManager *txn_mgr
) -> std::optional<std::vector<UndoLog>>;Pay attention to the return values:
- Returning an empty vector: there is a value but no rollback is needed; the current version can be used directly.
- Returning
std::nullopt: at the current transaction's read point in time, this Tuple does not yet exist, and there are not enough historical versions to reconstruct it.
So we can divide into three cases:
-
If the base tuple is new enough for the current snapshot, i.e.
base_meta.ts < = txn.read_ts, then it's case 1 -
If the base tuple is too new, i.e.
base_meta.ts > txn.read_ts, or the Tuple was modified by another transaction that has not yet committed, then we need to traverse the version chain and collect all undo logs aftertxn.read_ts. -
If the Tuple in the Table Heap contains the current transaction's own modifications, i.e. the current transaction is reading data it previously modified itself, then special handling is needed, using a temporary timestamp.
Even if a transaction's
read_tsis earlier than its own modifications, the transaction should be able to read its own latest uncommitted modifications.For case 3, if it's the transaction's own modification, the handling is actually the same as case 1.
Here let me explain the temporary timestamp in detail:
- Both
timestamp_tandtxn_idareint64_t - It is stipulated that
txn_idstarts from 1LL << 62, i.e. only values with bit 62 set to 1 are transaction IDs (bit 63 is the sign bit, unused) - And it is stipulated that
0 <= ts < 1LL << 62, so anything with bit 62 equal to 0 is a timestamp - The temporary timestamp directly uses the current transaction's ID
- As long as bit 62 is 1 when scanning, it means this is a temporary timestamp
However, bustub provides human-friendly interfaces:
using txn_id_t = int64_t;
const txn_id_t TXN_START_ID = 1LL << 62;
auto GetTransactionTempTs() const -> timestamp_t {
return txn_id_;
}
auto GetTransactionIdHumanReadable() const -> txn_id_t {
return txn_id_ ^ TXN_START_ID;
}You can use GetTupleAndUndoLink() to get the Base Tuple, TupleMeta, and the link pointing to the first Undo Log all at once.
When traversing the version chain, the loop termination condition is finding the first log with log.ts < txn.ts.
CollectUndoLogs is responsible for determining the rollback path; ReconstructTuple is responsible for applying the logs and determining whether the target version was deleted.
The collection phase should not prematurely determine deletion.
Task 3
In this section, you will need to implement the data modification executors. This includes the insert executor, delete executor, and update executor.
Insert Executor
Roughly these points:
- Create a new tuple in the table heap, correctly constructing the tuple meta
- Set the timestamp in the tuple heap to the current transaction's temporary timestamp
- Also add the new Tuple's RID to the Write Set via
AppendWriteSet()
For Task 4.2, when re-inserting, you need to consider reusing an existing RID.
Note the two functions TableHeap::UpdateTupleInPlace() and TransactionManager::UpdateUndoLink():
- They work similarly to CAS: check first, then decide whether to execute
- Use these two functions together with
GetTupleAndUndoLink()andUpdateTupleAndUndoLink()to atomically update the Tuple and UndoLink. This only needs to be considered in Task 4.2; the current tests are all single-threaded.
Commit
Convert the tuples modified by the transaction from temporary versions to committed versions.
Roughly there are six elements:
-
Acquire
commit_mutex_to ensure only one transaction performs a commit at a time -
Obtain the Commit Timestamp; it is recommended to use
last_commit_ts_.load() + 1rather thanfetch_add(1)Essentially, you must not update the global TS prematurely, otherwise the new read ts would be wrong
-
Update the timestamps of all base tuples in the write set
-
Set the transaction state to
COMMITTED -
Update the transaction's own
commit_ts_ -
Update the global
last_commit_ts_; here you can usefetch_add(1)
You also need to implement TxnMgrDbg, used to print the contents of the Table Heap and each Tuple's version chain. This is a bit annoying, so I had an LLM write it (after all, I'm not really good at debugging it myself).
Generate Undo Logs
The core point is: when the same transaction modifies the tuple corresponding to the same RID multiple times, only one undo log is kept in the end.
You need to implement GenerateNewUndoLog() and GenerateUpdatedUndoLog().
Why two functions are needed:
- When a transaction modifies a tuple for the first time, use
GenerateNewUndoLog() - For subsequent modifications, use
GenerateUpdatedUndoLog()
Three cases need to be considered:
-
Update — the key point is to only update the values that weren't updated, keeping the original values from the very beginning
-
Delete — the complete tuple needs to be kept in the undo log. You should also consider: how to handle the case where the same transaction has already performed multiple modifications on it before.
Note that
UndoLog::is_deleted_indicates whether the historical version to be restored was deleted! -
Insert — in Task 4.2, you need to deal with the case of inserting a new tuple into the position of a previously deleted tuple
Note that you may use two functions:
Tuple::IsTupleContentEqual(): directly compares whether the serialized values of two Tuples are equal, without comparing RIDsValue::CompareExactlyEquals(): compares whether two fields are equal; note this function treats two NULLs as equal. Because for an undo log, going from null to null is also no change.
You must be clear about what the undo log is for:
- Be clear about what the undo log's
is_deleted_is actually for — it indicates that historically this tuple did not exist, that it was deleted - If we are currently performing a delete operation, then on the contrary
is_deleted_should be set to false, and the log's tuple should be set to the previous tuple. This represents what the tuple looked like at that time
Update & Delete Executor
Actually wire the previously implemented undo log reading and undo log generation into the update and delete logic, so that the database can correctly modify versions.
For each rid to be modified:
- Check for write-write conflicts
- Handle the undo log and version chain
- Update the table heap
Detecting write-write conflicts: mainly divided into two categories:
- This tuple was modified by a transaction that has not yet committed, so other transactions are forbidden from modifying this tuple, otherwise they will be aborted
- This tuple was deleted and committed by a transaction, but an earlier-started transaction attempts to delete it again after that commit
- Note: a transaction's own modifications to itself should not be considered a write-write conflict
The sole condition for detecting a write-write conflict is checking the base tuple metadata's timestamp.
When a write-write conflict is detected:
- Set the transaction state to
TAINTED - Throw an
ExecutionException
The Update Executor should act as a pipeline breaker:
- First pull down and cache all tuples from the child executor, then read tuples from the cache and update them
- Reason: for example, if the child executor is a seq scan executor, scanning below while modifying above would affect the scan below
The core modifications needed for update and delete:
- Use the Generate series of functions from the previous task to generate the latest undo log
- Use
UpdateTupleAndUndoLink()to update
But actually, after reading the spec above I still didn't know what to do; it took several rounds of grilling an LLM to roughly understand. To summarize:
-
First, since update needs to be a pipeline breaker, i.e. caching all tuples and rids, we just do that. Although I suspect memory won't fit, the tests don't seem to check this, so whatever.
-
Use
auto [base_meta, base_tuple, undo_link] = GetTupleAndUndoLink(txn_mgr, table_info_->table_.get(), old_rid);to get the base meta and base tuple; the so-called base tuple is the tuple currently pointed to by this rid -
Then, check for write-write conflicts. If the write-write conflict check passes, then the base tuple should be the same as the old tuple (since currently there are only single-threaded tests); if it doesn't pass, handle it as described above
-
Then, as before, keep evaluating to get the new_tuple
-
Case analysis on the base meta:
- If it's the first modification, call
GenerateNewUndoLog(), then calltxn->AppendUndoLog()to get the new_link, which will be needed later when callingUpdateTupleAndUndoLink() - If it was previously modified by ourselves, then use
GenerateUpdatedUndoLog(); no need to worry about the undo link and such - In all other cases, the timestamp is our own + no previously created undo -> this tuple was newly inserted within this transaction, no need to worry, just modify it directly
- If it's the first modification, call
-
Finally,
if (UpdateTupleAndUndoLink(txn_mgr, old_rid, new_link, table_info_->table_.get(), txn, {txn->GetTransactionTempTs(), false}, new_tuple)) { txn->AppendWriteSet(plan_->GetTableOid(), old_rid); updated_cnt += 1; }
Here, this new_link is the previous undo link if it's not the first modification.
Handling the delete executor is similar.
Stop-the-world Garbage Collection
Abort
Implement the abort logic. The spec gives two implementation approaches, but I feel the first one is utterly baffling — it says it can be done this way to save time, but actually implementing the second one isn't much more complicated...
First, why abort is needed:
- When a transaction encounters a write-write conflict, it is set to the TAINTED state
- It needs to be aborted to eliminate the transaction's effects on the database, so that writing can continue;
- Otherwise, when other transactions try to write this tuple, checking the meta reveals it's all temp ts, always a write-write conflict, and they simply can't write
The abort logic is actually not hard:
- Our goal is to restore the tuple to its state before this transaction modified it
- Based on our earlier implementation, a transaction's modifications to a tuple result in at most one undolog, repeatedly modified on a single log; or it's newly created, or previously deleted
- So, use
GetTupleAndUndoLink()to get it - Then, check the
UndoLink; if it doesn't exist, it's a newly inserted tuple. In this case the spec says to set the meta's ts to 0 — this is a special case — then callUpdateTupleAndUndoLink() - If it exists, just restore accordingly; note that the meta afterwards should have parameters matching those in the log
Task 4
Task 4 requires making the current MVCC system support primary key indexes and extending it to the serializable isolation level.
The main issue is that the earlier parts didn't touch indexes at all (or rather, the parts of the update/insert/delete executors that involved indexes were removed), and now we need to implement this:
- The index is responsible for finding the RID
- MVCC decides whether this RID exists in the current snapshot
Worth noting is that the tests only test the primary key index. The primary key index can have more than one column, but in any case secondary indexes won't be tested.
Index Insert
Core task: modify InsertExecutor so that Insert operations correctly maintain the primary key index.
Elements of the primary key index:
- A table has at most one primary key index
- The primary key index is created automatically based on the table's schema
- The primary key can be a composite primary key
Operation flow:
- Check whether the primary key already exists in the index; if it exists, set TAINTED + throw an ExcutionException
- Insert into the TableHeap
- Insert into the index, mapping the new primary key to the RID; on failure, set TAINTED + throw an ExcutionException
Actually, just implement it according to this. To check whether the primary key exists, use tuple.KeyFromTuple() to get the primary-key-related key, then use the primary key index's ScanKey().
Index Scan, Delete & Update
Solve three problems:
- After IndexScanExecutor finds the RID via the index, it needs to return the appropriate historical version based on the current transaction
- For InsertExecutor, how to handle the case where the primary key exists in the index but the Tuple has been deleted (reuse the RID)
- How UpdateExecutor / DeleteExecutor can modify tuples without breaking the index mapping
Essence: the key in the Index always points to the same RID, and remains unchanged once created.
The tuple pointed to by the RID can change; MVCC is responsible for maintaining history.
So, for IndexScanExecutor, it's basically just reusing the previous handling logic for SeqScanExecutor, migrating it over with minor tweaks — not hard.
For InsertExecutor, it's a bit more complicated. Roughly these elements:
- Simply put, after
ScanKey()finds something, instead of directly throwing an exception, you should reuse the original RID, i.e. modify on top of the previous sub-task (modify inside that if) - But here it's essentially an Update (though an Update of something that was originally deleted), which is actually pretty much the same as Task 3.6; just reuse the various logic
- However, the difference from Task 3.6 is that concurrency needs to be considered, i.e.
UpdateTupleAndUndoLink()needs to consider thecheck()callback. If the check fails, you also need to set TAINTED and throw an exception - It's actually a bit complicated.
Then the Update and Delete Executors are basically the same as above — just add a check, and there's not much to say: just check whether the ts relative to the base meta has changed.
Why do neither Update nor Delete need to handle the index anymore? Because the index is not bound to any specific tuple or anything like that, but only bound to the RID!
In the end, I found that the core logic chain in these three Executors — first get the meta tuple link, then branch based on whether it was modified by the current transaction — can be extracted into execution common as a Modify function.
Primary Key Updates
Simply put:
- When the primary key is updated, the implementation is: first delete the old key, then do an insert for the new key
- The execution order is: first insert the tuple with the new primary key into the table heap, then delete all the old tuples that will be updated, and finally insert the updated tuple back with the new primary key
- The new key creates a new index entry; the old key is left untouched and kept.
Translating this into code:
- Originally, when the UpdateExecutor called
Modify(), it did so without any conditions - But in this task, you need to first determine whether the primary key's column values have changed
- If they have changed, you can't go directly through Modify; instead you must split it into delete + insert
First use Tuple::KeyFromTuple and IsTupleContentEqual to determine whether the primary key has changed.
Then, inserting the tuple with the new primary key into the table heap is nothing special — just pass nullptr as the target parameter of Modify. Actually, this can be combined with the unchanged case using a ternary expression: if changed, pass nullptr.
Afterwards, for the part of inserting back, I found it's exactly the same logic as InsertExecutor, also needing to consider RID reuse, so I extracted the logic there into a function and put it in execution common.
Up to here it's fine, but there's a problem: the spec requires deleting all the old tuples that will be updated first.
So, Next() uses two loops: the first loop does pure reading + deletion first, also implementing the previous logic, but keeps an array to temporarily store all the tuples that changed. Then, the second loop iterates over the just-stashed array and Inserts them one by one.
Serializable Verification
Serializability depends on Snapshot Isolation, but the write skew problem exists; this Task is about solving that problem.
It's about performing an OCC (Optimistic Concurrency Control) Backward Validation before each transaction commits.
Simply put, it's a scan: whether the range read by the current transaction was modified by other transactions after the read and before the commit.
The so-called "range read" is essentially recording the predicates.
The spec says:
- Each time SeqScan or IndexScan is called, use
Transaction::AppendScanPredicate(table_oid, predicate)to record the predicate;predicate == nullptrmeans a full table scan - Also implement
VerifyTxn, which makes the judgment in the context of the current transaction's information.
Specifically, the rules of VerifyTxn are:
- Read-only transactions don't need verification.
- Collect all conflicting transactions. A conflicting transaction is one that committed after the current transaction's read ts.
- Collect the RIDs from the WriteSets of all conflicting transactions, grouped by table oid
- For each RID, use
CollectUndoLogs, then restore versions one by one, as follows:- The so-called "restoring versions one by one" means traversing the entire version chain starting from the base tuple, verifying one by one
- For each version, get the before image and after image, i.e. what the row looked like before and after the change
- If it's an insert, i.e. before doesn't exist but after does, abort if the after image hits the predicate
- If it's a delete, abort if the before image hits the predicate
- If it's an update, i.e. both exist, check both; abort if either hits
- Actually I feel the division given in the spec isn't very meaningful; just compute both before and after as optionals and test them
- Note that the so-called hitting the predicate is obtained via
GetScanPredicates() -> const std::unordered_map<table_oid_t, std::vector<AbstractExpressionRef>> &
However, there are a few edge cases:
- If it's insert followed by delete, just ignore it, as if nothing happened
- If something was changed and then changed back, the above logic also needs to be used to judge
- If tupleA and tupleB "swap", both need to be checked
There are also a few points to note when coding:
- You need to traverse
txn_map_to get all the conflict txns, but this step requires acquiring the shared lock of the txn map. However, if you handle other core logic inside the traversal loop, the call chain insideCollectUndoLogswill callGetUndoLogOptional, which acquires the map's shared lock again — but repeatedly acquiring the same shared lock in the same thread is UB. So the solution is to first store all the conflicting transactions. - If
CollectUndoLogsreturns no value, it actually means this is a newly inserted tuple; don't just ignore it directly.
The end.

