# CMU 15-445 Bustub Project 2 - B+Tree - Note

> This article is currently an experimental machine translation and may contain errors. If anything is unclear, please refer to [original Chinese version](<https://blog.wendain.ing/posts/cmu-15-445-bustub-proj2/>). I am continuously working to improve the translation.

## Preface

**How can a single Lab be this hard...**

Task 2's difficulty was unbelievable — it gave me depression just writing it. As a result, I barely hand-wrote anything afterward and mostly directed the Agent (though I'd like to think I was still fairly fine-grained about it), which isn't exactly something to be proud of.

So since I finished it with only a half-understanding, this note is basically a list of the points that left an impression on me, rather than a systematic, linear walkthrough of each Task with detailed explanations of the implementations.

## Task 1

Although this is called Task 1, some concepts that absolutely need to be clarified will also be covered here.

### The correspondence between keys and children in an internal page

- The first key is invalid, but the first child is valid;
- When searching for a key equal to a separator key, go to the **right child**
- Therefore, the `int KeyIndex(const KeyType& key)` function cannot reuse the same binary search logic:
    - internal page needs `std::upper_bound()` followed by -1
    - leaf page can directly use `std::lower_bound()`

### Tombstones separate "logical deletion" from "physical deletion"

- Recording a deletion does not necessarily decrease `GetSize()`;
- Only when the buffer is full (`GetTombstoneSize() == TOMBSTONE_CNT`) is the oldest slot cleaned up (overwritten).

## Task 2

### The difference between the header page and the root page

`header_page_id_` points to the page holding the tree's metadata, and the `root_page_id_` inside it is what points to the tree root.

- An empty tree can still have a header;
- The root can also be a leaf page.

### `Init()` must be passed the size from the tree configuration

The default parameters cannot be used directly; they differ depending on the node type.

### Using `SplitResult` to express the split result

Put the left page ID, the promoted key, and the right page ID into a single struct to reduce scattered temporary variables.

**The promoted key always corresponds to the right side** (i.e., the indices are consistent)

### The difference between leaf page splits and internal page splits

- For a leaf page, the separator key comes from the right page, and the records still **remain** in the leaf;
- An internal page must **promote** the separator key to the parent, and must also correctly handle the first invalid key of the right page (i.e., `IsTombstone()`

### Internal page borrowing and merging must go through the parent's separator key

Because both operations necessarily involve changes to the parent page, they are pessimistic.

### Incoming tombstones are always treated as updates, while preserving each side's internal order

Per the spec, the receiving page's existing pending-deletion records should be processed first, and the incoming page's pending-deletion records processed afterward.

Therefore, `MergeFrom(right)` works as follows:

1. First compute the total number of tombstones on both pages. If it exceeds the buffer capacity, process the **oldest few tombstones at the head of the receiving page's queue** in advance to make room for the right page's tombstones.
2. Compact the receiving page's key/value arrays in one pass, build a mapping from old indices to new indices, and fix the indices of the remaining tombstones. This avoids repeatedly calling `EraseAt()` and shifting the arrays many times.
3. Append the right page's records, then append the markers in the right page's original tombstone queue order; uniformly add the receiving page's post-cleanup length to the indices.

The final queue is "the receiving page's remaining tombstones → the incoming page's tombstones," with both sides' internal ordering preserved. **You must not re-register tombstones in key order**, because a key's magnitude has nothing to do with when it was deleted.

Borrowing moves only a single entry: `MoveEntryTo()` first records whether the entry is already deleted, then moves it to the receiving page; if it is a tombstone, it calls the receiving page's `RemoveAt()` to register it as the newest pending-deletion record.

### The root node and single-child parent pages are special cases

- The root is allowed to be below the minimum size of ordinary nodes;
- The header needs updating: when a root leaf page is emptied by deletion, or when an internal root is left with only one child (upfloat).

## Task 3

### Iterating across pages is not just jumping to the next page

You also have to skip tombstones, empty pages, and pages whose entries have all been deleted.

### Adding `prev_page_id_`

Maintaining it alone is fine, but horizontal scans are prone to deadlock (see the last point in Lect 10).

After adding the backward pointer, splits and merges also need to modify the successor page. For example, merging `L ↔ R ↔ S` into `L ↔ S` requires changing `S.prev` to L.

This introduces **horizontal lock acquisition**: one thread holds L and waits for R, while another holds R and waits for L, and they can deadlock each other. The original top-down lock acquisition order does not cover accesses between adjacent leaf pages.

The solution is no-wait: try to acquire the adjacent page's latch, and if it fails, end the current attempt. The underlying API used is:

```cpp
std::unique_lock<std::shared_mutex> lock(latch, std::try_to_lock);
if (!lock.owns_lock()) {
  // 没有取得写锁，不能继续访问页面。
}
```

The read lock corresponds to `std::shared_lock`. On success, `std::move()` this already-lock-holding object into the PageGuard — the guard must not acquire the lock a second time; on failure, undo the pin.

There is also a submission constraint: the original submission list (`CMakeList.txt`) does not include `TracedBufferPoolManager`, so you cannot rely on adding `TryReadPage()` / `TryWritePage()` to it.

**Therefore, leverage the `AccessType` parameter that it already forwards**, and add `IndexNoWait`:

```cpp
bpm_->ReadPage(next_page_id, AccessType::IndexNoWait);
```

The call still goes through TracedBPM, and read/write counts are still tracked as usual; the actual try-lock is done in the underlying BPM. This mode throws `PageLatchUnavailable` on latch conflicts, which inherits from `std::runtime_error`, and is thus a kind of `std::exception`.

The iterator's `++` and `--` handle cross-page movement this way: on failure, call `guard_.reset()`, set the current iterator to end, and then propagate the exception to the caller.

Because the guard is shared, you cannot directly `Drop()` it here, or you would release the lock that other iterator copies are still using.

> [!important]
>
> To summarize when to use `AccessType::IndexNoWait`:
>
> **When acquiring leaf locks horizontally rather than through the parent page**.
>
> Acquiring ordinary child locks downward can still wait; no-wait is used for these horizontal leaf page accesses.

## Task 4

### An indirect way to upgrade a read lock to a write lock

When reaching the leaf, keep the parent page's read lock, release the leaf page's read lock, acquire the leaf page's write lock, and finally release the parent page's read lock.

The key point is that there is no "in-place upgrade" API, and you cannot hold your own read lock while waiting for a write lock on the same page.

During the descent, alternate between `parent_guard` and `guard` to hold the parent page and the current page. After reaching the leaf:

```cpp
page_id_t leaf_page_id = guard.GetPageId();
guard.Drop();
auto leaf_guard = bpm_->WritePage(leaf_page_id);
parent_guard.Drop();
```

Although the leaf page lock is temporarily absent in between, **the parent page's read lock is still held**: other threads cannot acquire the parent page's write lock to modify the structural relationships here. When the root itself is a leaf page, this parent is the header.

For optimistic Remove:

- If the tombstone buffer still has space, the deletion does not reduce physical slots and can be handled directly;
- If a physical deletion is needed, check whether the minimum size is still satisfied after the deletion.
- If an underflow is possible, return `false`, release the locks, and take the pessimistic path from the root.

### The pessimistic Remove's `pop_ancestors_if_safe()`

This lambda determines: **whether the current node can absorb one deletion effect coming from below, guaranteeing that the change will not propagate further to its parent page.**

First compute the minimum size, then check `GetSize() > min_size`:

| Node | `min_size` used in the check | Reason |
| --- | --- | --- |
| Ordinary node | `GetMinSize()` | After losing one slot or child, it still must not underflow |
| Root leaf page | 1 | Deleting from 1 to 0 requires updating the header |
| Internal root page | 2 | Going from 2 children to 1 requires shrinking the root and updating the header |

Leaf pages have one extra condition: **when the tombstone buffer is not full, it also counts as safe**. Because this deletion only registers a tombstone and does not reduce physical slots. When there is no tombstone buffer, this special case is not taken.

If safe, first release `header_page_`, then release the ancestors from the front of `write_set_` while popping the corresponding `child_idx_`, leaving only the current node's write lock. Afterwards, continue acquiring child locks downward and perform the same check.

> [!note]
>
> So `write_set_` may only hold the latter part of the path. You can no longer use "only one guard left" to determine whether the current page is the root; instead, compare the actual page ID via `ctx.IsRootPage(page_id)`.
>

### Lock acquisition failures that allow retrying must happen before modifying the page

If you execute `RemoveAt()` first and only try to lock the sibling after deleting down to an underflow, then on failure you cannot simply "start over": the key is already deleted, but the tree has not been repaired yet.

Therefore, after confirming that this deletion may cause a leaf page underflow, the pessimistic Remove first prepares the horizontal leaf page locks:

1. Prefer the left sibling; when the current page is the leftmost child, choose the right sibling.
2. Use `IndexNoWait` to acquire the sibling's write lock and put it into the Context.
3. Then acquire the write lock of the successor page that may need modification: when merging with the left sibling, it is the current page's next page; when merging with the right sibling, it is the right sibling's next page.
4. Only after all succeed, execute `RemoveAt()`, then borrow or merge per the original logic.

Here the **successor page that might be needed for a merge** is locked in advance, even if borrowing ultimately succeeds and no merge is needed.

A lock acquisition failure throws `PageLatchUnavailable`; the Context's destructor releases the locks along the path, and the outermost `Remove()` catches this specific exception and retries from the root.

Insert works the same way: when a leaf page is about to split, first try to lock the old successor, then insert and split, and only afterwards can you safely modify the old successor's `prev_page_id_`.
