# CMU 15-445 Bustub Project 3 - Query Execution - 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-proj3/>). I am continuously working to improve the translation.

## Preface

**Wasn't it supposed to be about the same difficulty as P1**?

I worked on it on and off from October 9th to October 17th, at least 4h+ every day, and 7~8h+ when I was relatively free. When I finished, I hadn't done any Leaderboard optimizations, yet my Leaderboard ranking was pretty good (24/140+), which is a bit mysterious.

As usual, at the start I had no idea what to do, and only got a rough picture as I wrote along. Then I discovered my earlier understanding of the concepts was completely off, tore it all down and started over, again and again.

The main reason is that this project's codebase is genuinely huge—there's a lot to read. All the architectural design decisions, the meanings of various data structures and custom types—all of it needs to be crystal clear before you can write appropriate code. And even when it's all clear, you still might not write it correctly, e.g., questions like "which `Schema` exactly am I supposed to pass?"

Starting the blog post only after finishing is also a bit mysterious; I should have been writing notes as I went. That said, this time I put a lot of things into commit messages, and a commit message is usually very long, which makes it convenient for me to review how I was thinking at the time.

At the beginning I didn't know how to proceed, so I referred to these blog posts:

- [CMU15445-2025FALL Personal Ramblings - W3nYui's article - Zhihu](https://zhuanlan.zhihu.com/p/2058632609798923944)
- [Building a Database: 2022 CMU15-445 Project3 Query Execution - Shi Yi's article - Zhihu](https://zhuanlan.zhihu.com/p/587566135)
- [The Making of BusTub: From Course Project to SQL Database](https://zhuanlan.zhihu.com/p/570917775), this one is by the author of this Project.

## Understanding the Core Structure

Let me just briefly go over it, since I'm a bit too lazy to write everything down—here are a few core points:

The full execution flow of a SQL statement, which all three blog posts above cover:

1. Parser: with the help of PostgreSQL's third-party parsing library, produces a Postgres AST

2. Binder: after the AST is produced, the binder rewrites this AST into a higher-level AST that bustub can understand. For example, for `SELECT colA FROM test_1`, it resolves `test_1` to the corresponding `table_oid`.

3. Planner: essentially binds the information in the query statement onto various plan nodes. As for what a plan node is, you'll naturally understand as you write along. Then, it builds a query tree.

4. Optimizer: optimizes the plan nodes

    > [!note]
    >
    > Another thing worth mentioning is that, generally speaking:
    >
    > - The Planner generates Logical Plan Nodes, representing abstract Plans.
    > - The Optimizer generates Physical Plan Nodes, representing concretely executed Plans.
    >
    > A typical example is Join. In the query plan generated by the Planner, a Join is just a Join. In the query plan generated by the Optimizer, the Join will be optimized into a concrete HashJoin or NestedIndexJoin, etc.
    >
    > In Bustub, there is no distinction between Logical Plan Nodes and Physical Plan Nodes. The Planner directly generates Physical Plan Nodes.

5. Executor: based on the Planner's plan, generates the executor corresponding to the plan and carries out the actual execution.

Regarding Executors: the execution models of operators can be roughly divided into three types:

- Iterator Model: has Init and Next, but each Next returns only one tuple
- Materialization Model: one Next returns everything at once (materialization)
- Vectorization Model: one Next returns a certain number of tuples (specified by yourself)

Bustub uses the third one.

In addition, there are two execution directions for operators:

1. Top-to-Bottom. Starting from the root operator, continuously pull data from the operators below.
2. Bottom-to-Top. Starting from the leaf operators, push your own data up to the operators above.

Bustub uses Top-to-Bottom.

That's roughly what you need to know before starting, so let's begin the journey proper. Of course, if this is your first time, after hearing all of the above you're probably still confused. You really have to dig into the code to understand it.

## Task 1

Implement three relatively simple executors, though not understanding the concepts at the start is definitely quite painful.

First look at this image

<img src="https://pica.zhimg.com/v2-9bc6214441f8ca37004ff1389114a692_1440w.jpg" style="zoom: 67%;" />

This image is pretty good; it clarifies a lot of concepts.

### SeqScan

So, to implement SeqScan, you just keep a TableHeap iterator and keep reading Tuples. This way the state of `Next` is also maintained. Remember to check `TupleMeta.is_deleted_`.

Note that you should **not** keep pulling from a child executor, because there is no child executor at all.

### Insert and Delete

I'll discuss these two together, because the general framework is the same: keep pulling tuples from the child executor, modify the TableHeap, and then maintain the indexes on the table. Unlike SeqScan, here there really is a child executor.

But here you need to pay attention to the comment:

> [!important]
>
> ***@param*[out] *tuple_batch* The tuple batch with one integer indicating the number of rows inserted into the table.**
>
> **InsertExecutor::Next() returns true with the number of inserted rows produced only once.**

For example:

```sql
CREATE TABLE t1(id INT, val INT);
INSERT INTO t1 VALUES (1, 10), (2, 20), (3, 30);
```

The child executor provides `(1, 10)`, `(2, 20)`, `(3, 30)`, while the InsertExecutor's output is only one tuple containing a single integer `3`. Delete and Update work the same way.

So my implementation is:

- In the first `Next()`, keep calling the child's `Next()` until all input has been processed
- Then return a count, and use `finished_` to record that execution has already happened
- Subsequent `Next()` calls see `finished_ == true` and directly return `false`.

The code that finally constructs the result, for example for Insert:

```cpp
tuple_batch->emplace_back(
    std::vector<Value>{ValueFactory::GetIntegerValue(insert_cnt)},
    &GetOutputSchema());
finished_ = true;
return true;
```

Note: even if not a single row was inserted, you should still return a tuple with the value `0`.

### Some Notes and Pitfall Records

#### `Next()` Must Clear the Previous Batch's Output

Here's a commit message from back then, `add3064`:

> clear batch before call Next()
>
> **check `ExecutionEngine::PollExecutor` to understand why!!!**

Looking at `ExecutionEngine::PollExecutor()` makes it very clear:

```cpp
std::vector<RID> rids{};
std::vector<Tuple> tuples{};
while (executor->Next(&tuples, &rids, BUSTUB_BATCH_SIZE)) {
  if (result_set != nullptr) {
    result_set->insert(result_set->end(), tuples.begin(), tuples.end());
  }
}
```

The caller repeatedly reuses the same two vectors and **will not clear them for the executor**. So at the beginning of `Next()` you need:

```cpp
tuple_batch->clear();
rid_batch->clear();
```

If you don't clear, the SeqScan test will behave like this: the first batch returns `0`, the second batch becomes `0, 1`, the third batch becomes `0, 1, 2`—all duplicated old results.

#### Insert: The Values Have Already Been Computed by the Child

The original text of the `06278d7` commit message:

> insert doesn't need to evaluate, because its child executor is a value executor, which does the evaluation itself (you can look at the value executor's next function)

This refers to the `INSERT ... VALUES ...` case. Looking at `ValuesExecutor::Next()`, it is already responsible for evaluating column by column and then constructing the tuple:

```cpp
const auto &row_expr = plan_->GetValues()[cursor_];
for (const auto &col : row_expr) {
  values.push_back(col->Evaluate(nullptr, dummy_schema_));
}

tuple_batch->emplace_back(values, &GetOutputSchema());
```

`dummy_schema_` is an empty Schema. For example, for `VALUES (1, 10 + 20)`, these expressions don't depend on the columns of any input tuple, so what's passed here is `nullptr` and an empty Schema.

Of course, Insert's child isn't always Values; it can also come from `INSERT INTO ... SELECT ...`. But for InsertExecutor, the handling is no different: **what the child returns is already a fully evaluated tuple that can be inserted into the table**.

Therefore, the main logic is:

```cpp
auto table_info = exec_ctx_->GetCatalog()->GetTable(plan_->GetTableOid());
auto indexes = exec_ctx_->GetCatalog()->GetTableIndexes(table_info->name_);

// 下面位于消费 child batch 的循环里面。
std::optional<RID> rid = table_info->table_->InsertTuple({0, false}, tuple);
if (rid.has_value()) {
  for (auto &index_info : indexes) {
    Tuple key = tuple.KeyFromTuple(
        table_info->schema_, index_info->key_schema_,
        index_info->index_->GetKeyAttrs());
    index_info->index_->InsertEntry(key, rid.value(), exec_ctx_->GetTransaction());
  }
  insert_cnt += 1;
}
```

`{0, false}` is `TupleMeta`, where `false` means not deleted. `InsertTuple()` returns a `std::optional<RID>`, and on success you get the location of this new record in the TableHeap. **Note that the RID used to insert into the index here is this new RID**, not the RID returned by the child, because tuples produced by Values never had a corresponding location in the table in the first place.

One more point: updating the table does not automatically maintain the indexes for us. However many indexes the table has, you need to extract the key and insert into each one separately.

#### Why Is the Index's Key Also a Tuple?

I didn't understand this at the time either.

For example, if the table's Schema is `(id INT, val INT)`, a row is `(2, 20)`, and the index is only built on `id`:

- Full tuple: (2, 20)
- key attrs: \[0]
- key schema: (id INT)
- key tuple: (2)
- Mapping stored in the index: (2) -> the RID of this row

The three parameters of `KeyFromTuple()` then correspond:

- `table_info->schema_`: what structure to use to read the original full tuple.
- `index_info->key_schema_`: what structure the extracted index key has.
- `GetKeyAttrs()`: which columns to take from the full tuple, and in what order.

Although this key is also of type Tuple, it **only contains the columns the index needs**.

Actually, I think designing it as `vector<Value>` would be more reasonable; I don't know why it's like this. In any case, keep this in mind.

### Delete: Logical Deletion and Deleting Index Entries

Delete's input is the records already filtered out by the child for deletion. Once you get the tuple and the corresponding RID, just delete them directly.

However, although it's called deletion, this doesn't erase the tuple's bytes from the page; it only sets `TupleMeta.is_deleted_` to `true`. Then, delete the corresponding entry in each index.

### Update

Although it's essentially Insert and Delete stitched together, I actually hit more pitfalls here than in both of them combined. The [Fall 2025 spec](https://15445.courses.cs.cmu.edu/fall2025/project3/#update) requires deleting the old record first, then inserting the new record.

First, let me paste the `7ed57b8` commit message verbatim; this one basically records all the problems I had at the time:

> Refactor update_executor, lots of pitfalls
>
> 1. You must look at the fields of the plan and the executor; don't assume they're all the same. The update executor has `const TableInfo *table_info_`, but I didn't notice it when writing code, so I first defined a local variable `table_info`, and then later when using it, because of autocomplete, I used `table_info_` everywhere, and they were all null pointers, causing errors... Actually I think this field isn't very useful either; getting it locally is the same. But since it's given, initialize it in the constructor.
>
> 2. Next is another field, but this one is on the plan node: `std::vector<AbstractExpressionRef> target_expressions_;`. **I actually didn't use this at first, which means my update updated nothing at all**. Here we need to evaluate this vector one by one
>
>     - Note that tidy requires reserving in advance and forbids push_back inside loops, so we can refer to the reserve in value_executor
>
>     Then we get new_tuple and new_rid. Then we also need to delete the old index entries and update the new index entries. Note that the index key here is very important. This key means the index's key, the key for looking up the index. Note that the key and rid used for deleting the old index entry and building the new one must each be the corresponding one; don't mix them up!

#### `target_expressions_` Determines the Updated Values

At first, unfamiliar with the API, what I did was "delete the old tuple, then insert the same tuple back"—pulling your pants down just to put them back on.

For example:

```sql
UPDATE t1 SET val = val + 5 WHERE id = 2;
```

Suppose the old tuple is `(2, 20)`. The `target_expressions_` given by the Planner can be understood as an array whose length is the number of columns of the final returned tuple, where each column corresponds to a computation. For columns that weren't modified, the Planner fills in a `ColumnValueExpression` that reads the old column:

```text
Column 0: #0.0        reads the id of the old tuple
Column 1: #0.1 + 5    reads the val of the old tuple, then adds 5
```

Here `#0.1` means the 1st column of the 0th input, with indices starting from 0.

Therefore, you need to call `Evaluate()` one by one to get all the Values for constructing the new tuple:

```cpp
std::vector<Value> values;
values.reserve(plan_->target_expressions_.size());
for (const auto &expr : plan_->target_expressions_) {
  values.push_back(expr->Evaluate(&old_tuple, child_executor_->GetOutputSchema()));
}
Tuple new_tuple{values, &table_info_->schema_};
```

What you get is `(2, 25)`. Each expression is evaluated against the same `old_tuple`; it's not "modify one column, then use the modified tuple to compute the next column."

#### Which Schema Should Actually Be Passed?

- The current executor's `GetOutputSchema()` represents what the current executor outputs to its parent node, not the structure of the table it operates on

- The `child_executor`'s Schema works the same way

- `plan_->output_schema_` is actually the same as the current executor's, mainly because this line of the function is the same:

    ```cpp
    auto GetOutputSchema() const -> const Schema & override { return plan_->OutputSchema(); };
    ```

#### Old Key, Old RID and New Key, New RID

After computing the new values, the operations on the table are:

```cpp
table_info_->table_->UpdateTupleMeta({0, true}, old_rid);
std::optional<RID> new_rid = table_info_->table_->InsertTuple({0, false}, new_tuple);
```

The operations on the indexes require extracting the old key and the new key separately:

```cpp
if (new_rid.has_value()) {
  for (auto &index_info : indexes) {
    Tuple old_key = old_tuple.KeyFromTuple(
        table_info_->schema_, index_info->key_schema_,
        index_info->index_->GetKeyAttrs());
    Tuple new_key = new_tuple.KeyFromTuple(
        table_info_->schema_, index_info->key_schema_,
        index_info->index_->GetKeyAttrs());

    index_info->index_->DeleteEntry(old_key, old_rid, exec_ctx_->GetTransaction());
    index_info->index_->InsertEntry(new_key, new_rid.value(), exec_ctx_->GetTransaction());
  }
  updated_cnt += 1;
}
```

For example, if the index is built on `id`, the old record `(2, 20)` is located at the hypothetical `RID(10, 0)`, and after updating to `(8, 20)` it's located at the hypothetical `RID(11, 0)`. That means deleting `2 -> RID(10, 0)` and inserting `8 -> RID(11, 0)`. The key and the RID must each correspond; you can't stitch a new key together with an old RID.

Even if you only modify `val` and `id` doesn't change, the index still needs to be maintained. Because P3 here does delete-then-insert, **the key can be the same, but the record's location has already changed to the new RID**. If the original index still points to the old record, a lookup would find the record that has already been marked as deleted.

#### Could You Update a Record You Just Inserted Yourself?

This question relates to which kind of iterator SeqScan chooses: the difference between `MakeIterator()` and `MakeEagerIterator()`.

For example, with `UPDATE t1 SET val = val + 1`, if you insert new records while scanning, and the iterator keeps moving toward the new end of the table, you might end up updating the just-inserted records again. This is the Halloween problem that needs to be avoided here.

`MakeIterator()` records the current end-of-table stopping position when created, so subsequent scans won't cross this boundary to chase newly inserted records.

### Optimizing SeqScan to IndexScan

Although in the spec, the order is to implement IndexScan first and then this optimizer rule, the spec also says implementing the latter first helps you better understand the former, so I did it that way, and that was indeed the case.

But since this was my first encounter with an optimizer, let's first understand the basic structure of the optimizer:

#### What Is the Optimizer Actually Changing?

> The BusTub optimizer is a rule-based optimizer. Most optimizer rules construct optimized plans in a bottom-up way. Because the query plan has this tree structure, before applying the optimizer rules to the current plan node, you want to first recursively apply the rules to its children.
>
> At each plan node, you should determine if the source plan structure matches the one you are trying to optimize, and then check the attributes in that plan to see if it can be optimized into the target optimized plan structure.
>
> In the public BusTub repository, we already provide the implementation of several optimizer rules. Please take a look at them as reference.

The optimizer takes in an execution plan tree and returns an optimized execution plan tree.

> [!note]
>
> A trick for writing the optimizer is to notice what type the finally returned plan node actually is, then look at its constructor to determine what we need to obtain, and use that as a clue for coding.

For example, if table `t1(id INT, val INT)` has an index on `id`, the query `WHERE id = 2` can simplify the plan into the following transformation:

```text
Filter(id = 2)                 SeqScan(filter = id = 2)
  └── SeqScan(t1)       ->              ↓
                              IndexScan(key = 2)
```

This is actually two rules: `OptimizeMergeFilterScan()` is responsible for merging the Filter into the SeqScan, and `OptimizeSeqScanAsIndexScan()` then tries to replace this SeqScan with a predicate.

The former's skeleton code is already implemented; only the latter is something we need to write.

> [!note]
>
> Reading the source code of `OptimizeMergeFilterScan()` is of great benefit for implementing this problem.

Look at `optimizer.cpp` and `optimizer_custom_rules.cpp`; they simply call these optimization functions in sequence. **The order matters**: our rule reads `SeqScanPlanNode::filter_predicate_`, which presupposes that `OptimizeMergeFilterScan()` has been implemented.

Then, almost every optimization rule begins with something like this:

```cpp
std::vector<AbstractPlanNodeRef> children;
for (const auto &child : plan->GetChildren()) {
  children.emplace_back(OptimizeSeqScanAsIndexScan(child));
}
auto optimized_plan = plan->CloneWithChildren(std::move(children));
```

That is, first recursively optimize each child, then put the optimized children back into a new current node, and finally determine whether the current node can be optimized. For example, if the root node is a Projection with the SeqScan below it, checking only the root node would never find the SeqScan below.

The meaning of `CloneWithChildren()`: keep the current node's other information and only replace its children. It's like keeping the subtree's root node while grafting on entirely new children.

#### So My SeqScan Was Also Implemented Wrong Before

Because we noticed that `OptimizeMergeFilterScan()` merges the predicate into the `SeqScanPlanNode`, but **our SeqScan Executor seemingly never handled the predicate at all**!

Here's the original text of the `3bf6908` commit message:

> fully refactor seq_scan_executor
>
> SeqScanExecutor::Next() has 3 bugs.
> 1. It completely fails to handle filter_predicate_: so DELETE WHERE id = 1 would delete all records it reads.
> 2. It directly returns false upon encountering a deleted Tuple: but it should skip it and continue scanning.
> 3. Each Next() returns only one Tuple: it doesn't actually read in batches according to batch_size.
>
> Mainly because I didn't understand many concepts at the very beginning, this part was completely wrong

The first pitfall is directly related to this optimization process. **The Filter node has already been merged away, so the responsibility for evaluating the condition has been handed to the SeqScan**. If SeqScan doesn't handle `filter_predicate_`, it's as if the `WHERE` condition simply vanished.

Handling it like this is enough:

```cpp
if (plan_->filter_predicate_ != nullptr &&
    !plan_->filter_predicate_->Evaluate(&tuple, plan_->OutputSchema()).GetAs<bool>()) {
  continue;
}
```

#### Parsing the Expression Tree of the Filter Condition

The key to cracking this problem is understanding what the expression tree inside `filter_predicate_` looks like. Note that this is a different thing from the execution plan tree above:

- The nodes in the execution plan tree are operators like SeqScan, Filter, Projection, etc.
- The nodes in the expression tree are expressions like `LogicExpression`, `ComparisonExpression`, `ColumnValueExpression`, etc.

For example, for `WHERE id = 1 OR id = 4 OR 7 = id`, one possible expression structure is:

```text
                OR
              /    \
            OR      =
           /  \    / \
          =    =  7   id
         / \  / \
        id 1 id 4
```

So, for the conditions specified in the spec here (conversion to IndexScan), you can understand it as:

- A binary tree.
- Looking at each comparison condition as a whole, at the bottom they are all `=` comparisons of `ComparisonExpression`.
- Above them is a bunch of possible `LogicExpression`s; as the spec says, only `or` multi-condition matching is accepted.
- Below the comparison nodes are the two real kinds of leaf nodes: **columns** and **constants**.

So design two handler functions: `handle_cmp_expr` handles a single comparison condition, and `handle_expr` recursively processes the whole expression tree.

> [!note]
>
> This pattern was used again later; it's very handy.

What `handle_cmp_expr` needs to confirm:

1. Whether it's a `ComparisonExpression`, and the comparison type is `ComparisonType::Equal`.
2. Whether one side is a `ColumnValueExpression` and the other side is a `ConstantValueExpression`
    - The logic here is a bit annoying, because the left side could be a constant and the right side a column, so you have to go through if-else repeatedly to determine which is which. So if the first match fails, swap left and right and try again.
3. For the integer indexes supported here, check that the column type is `INTEGER` and the constant is not NULL.

On success, return the column index and the constant expression for the outer function to construct with; on failure, return `std::nullopt`.

`handle_expr` checks whether the logic node is an OR, then recursively checks both sides:

```cpp
auto handle_expr = [&](auto &&self, const AbstractExpressionRef &expr) -> bool {
  if (auto logic_expr = dynamic_cast<const LogicExpression *>(expr.get())) {
    if (logic_expr->logic_type_ != LogicType::Or) {
      return false;
    }
    return self(self, logic_expr->GetChildAt(0)) &&
           self(self, logic_expr->GetChildAt(1));
  }
  // 下面调用 handle_cmp_expr，检查并收集单个比较条件。
  // ...
};
```

This return value determines "whether both sides can be parsed into the point-query conditions we support."

There's also a restriction: all comparisons must target the same column. `id = 1 OR val = 4` is not optimized.

#### Deduplication and Index Selection

`WHERE id = 1 OR id = 1` should only return the corresponding record once. So when collecting constants, use an `unordered_set<int32_t>` for deduplication, and use `pred_keys` to store the deduplicated constant expressions:

```cpp
if (uset.insert(value).second) {
  pred_keys.push_back(pred_key);
}
```

> [!note]
>
> The `.second` in `insert()`'s return value indicates whether a new element was actually inserted this time.

Duplicate values are no longer added to `pred_keys`, but the whole condition is still valid; you can't return a parse failure just because of duplicates. I encountered this distinction again later with the Hash Join optimizer.

After confirming the whole expression can be handled, go look up the table's indexes in the Catalog. My implementation only selects OR conditions joined on single-column integer indexes, and requires `GetKeyAttrs().front()` to equal the column index just extracted. If not found, return the original plan; if found, construct:

```cpp
return std::make_shared<IndexScanPlanNode>(
    seq_scan_plan->output_schema_, table_info->oid_, index_oid.value(),
    seq_scan_plan->filter_predicate_, pred_keys);
```

That is, hand the output Schema, the table's OID, the index's OID, the original predicate, and the constants to query over to the IndexScan.

### IndexScan

After finishing the optimizer above, this part actually isn't hard anymore.

There's no child executor here; the data comes from the index and the TableHeap. **Note that what you find in the index is a RID, not a complete tuple**; after getting the RID, you still need to go back to the table:

```cpp
auto [meta, tuple] = table_info->table_->GetTuple(rid);
```

Then, just like SeqScan, check `meta.is_deleted_`, skip deleted records, and put valid tuples and their corresponding RIDs into the output batch.

#### Point Lookup and Ordered Scan

The spec says two kinds of queries need to be implemented:

> 1. Point Lookup: `SELECT FROM <table> WHERE <index column> = <val>`. You will implement the optimizer rule to transform a `SeqScan` into an `IndexScan` in the next section.
> 2. Ordered Scan: `SELECT FROM <table> ORDER BY <index column>`. The optimizer rule to generate an `IndexScan` for queries with `ORDER BY` on an index column has been implemented for you. Your task is to handle `ASC` (or default) ordering only in `IndexScan`.

That is:

| Query Type | Who Generates the IndexScan Plan | How the Executor Reads |
| --- | --- | --- |
| `WHERE id = 1 OR id = 4` | The `OptimizeSeqScanAsIndexScan()` implemented above | Iterate over `pred_keys_`, calling `ScanKey()` one by one |
| `ORDER BY id ASC`, or ASC omitted | The existing `OptimizeOrderByAsIndexScan()` | Traverse in order starting from the index's beginning iterator |

Here, `pred_keys_.empty()` distinguishes the two branches. When empty, do an ordered scan; when not empty, do point lookups. This is the convention of how these rules currently generate plans.

For point lookup, first evaluate the constant expression, then construct the key tuple using the **index's key Schema**:

```cpp
const AbstractExpressionRef &expr = plan_->pred_keys_[now_key_idx_];
Value val = expr->Evaluate(nullptr, Schema({}));
Tuple key{{val}, &index_info->key_schema_};

std::vector<RID> rids;
index_info->index_->ScanKey(key, &rids, exec_ctx_->GetTransaction());
if (rids.empty()) {
  continue;
}
RID rid = rids.back();
```

What's evaluated here is a constant, so no input tuple or Schema is needed; empty arguments suffice.

When constructing the key tuple, however, you need the real `key_schema_`, for the same reason as extracting the index key during Insert earlier.

The ordered scan part is just the P2 iterator; the B+ tree is already sorted by key, so just traverse along the leaf pages.

These two branches each need to save state:

- The ordered scan saves `it_`, stopping at the next index entry to process when a batch is full.
- The point lookup saves `now_key_idx_`, indicating which position in `pred_keys_` has been processed.

> [!note]
>
> #### \[LLM] The spec clearly allows the cast, so why does `dynamic_cast` still fail?
>
> I also ran into a version problem here. Following the spec, I wrote:
>
> ```cpp
> auto tree = dynamic_cast<BPlusTreeIndexForTwoIntegerColumn *>(
>     index_info->index_.get());
> ```
>
> But the cast produced a null pointer. Here's what I asked Codex verbatim at the time:
>
> > I don't understand the second point—doesn't the spec say this cast can be used freely?
>
> After investigating, I found that the local code had mixed in Spring 2026's index creation changes. Single-column integer indexes were actually created as `GenericKey<4>` template instantiations, while Fall 2025's `BPlusTreeIndexForTwoIntegerColumn` uses `GenericKey<8>`; these are different C++ types.
>
> Although the name contains TwoIntegerColumn, it **doesn't mean we're querying two integer columns**; rather, it's that an 8-byte key template is fixed here. An INT column is only 4 bytes, and it can also be placed inside this 8-byte key. `dynamic_cast` won't automatically convert between two different template instantiations just because they're both called B+ trees.
>
> In the end, I only reverted the corresponding base code and tests to Fall 2025, keeping the other implementations. The original text of the `b7975d8` commit message:
>
> > revert(p3): restore Fall 2025 index templates and tests
> >
> > This reverts commit c26d28cf07acbbdc8b5a46ae6efa1cafb4a7bed2
> > (s26 p3: added support for composite key indexes in DDL).
> >
> > Spring 2026 DDL creates `GenericKey<4>` indexes for single integer columns,
> > while Fall 2025 specifies BPlusTreeIndexForTwoIntegerColumn, which uses
> > `GenericKey<8>`. The mismatch makes the prescribed dynamic_cast fail.
> >
> > Restore fixed 8-byte index creation for primary keys and CREATE INDEX,
> > including the original one-or-two-column limit. Remove the Spring 2026
> > composite-key index scan test and retain the existing Fall 2025 P3 tests.
> >
> > Validation in Ubuntu with clang 15, using the current working tree:
> >
> > - sqllogictest builds successfully.
> > - clang-format and clang-tidy pass for bustub_ddl.cpp.
> > - P3.01-06: 5/6 pass. P3.05 gets past the original type assertion but
> >     still fails on index ordering after UPDATE in the executor implementation.
>
> The 5/6 here was the intermediate result right after the revert, not the result after the later fixes. One more point: a 4-byte column doesn't mean a 4-byte index template was actually created, so you can't determine which C++ type it is just by looking at the column's size.

## Task 2

Task 2 includes 3 operators: Aggregation, NestedLoopJoin, and NestedIndexJoin.
### Aggregation

The difficulty of Aggregation lies in understanding a large pile of concepts that are all coupled together, which is quite annoying. Here, let's take a single SQL query and walk through the whole process of how the input becomes the result.

```sql
SELECT department, COUNT(*), SUM(salary)
FROM employee
GROUP BY department;
```

Suppose the child executor produces `(CS, 5000)`, `(Math, 7000)`, `(CS, 6000)` in order; the final result should be two rows: CS has 2 people with a total salary of 11000, and Math has 1 person with a total salary of 7000.

> [!important]
>
> Aggregation means **one output record per group**.

First read this diagram; it's very valuable.

<img src="https://image.wendaining.top/20261018151622507.png" style="zoom:50%;" />

> [!note]
>
> The prompt for this diagram was: "Referring to the diagram above that describes the logical relationships between data structures like the table heap, draw a similar-style diagram explaining the data structures and APIs related to aggregation."

#### First find the group, then prepare this row's aggregate input

To complete this query, we need to maintain a headcount and a salary sum for each department.

`SimpleAggregationHashTable` is internally just an `unordered_map`: the key indicates which group, and the value holds the accumulated state for that group.

Next, we need to compute the group key and the aggregate input provided by each row from every input, then update the accumulated state of the corresponding group.

Having decided to aggregate by department, first look at how the Plan describes this. It contains three groups of information:

```cpp
/** The GROUP BY expressions */
std::vector<AbstractExpressionRef> group_bys_;
/** The aggregation expressions */
std::vector<AbstractExpressionRef> aggregates_;
/** The aggregation types */
std::vector<AggregationType> agg_types_;
```

| Method in the Plan | Content in this example | Purpose |
| --- | --- | --- |
| `GetGroupBys()` | `department` | Computes the group key, e.g. `[CS]` |
| `GetAggregates()` | constant `1`, `salary` | Computes the value each input row contributes to the aggregation, e.g. `[1, 5000]` |
| `GetAggregateTypes()` | `CountStarAggregate`, `SumAggregate` | Determines how each of these two items is accumulated |

**The expressions `std::vector<AbstractExpressionRef> aggregates_` are responsible for computing this row's input values, while the aggregate types `std::vector<AggregationType> agg_types_` are responsible for deciding how to accumulate them**.

Then the two helper functions map onto this:

- `MakeAggregateKey(&tuple)`: evaluates `group_bys_` one by one to determine which group this tuple belongs to.
- `MakeAggregateValue(&tuple)`: evaluates `aggregates_` one by one to get this row's aggregate input.

> [!caution]
>
> Note that the `AggregateValue` type can represent both **the input values provided by one row** and **the accumulated result of a group so far**.

With this, the hash table stores:

```text
AggregateKey -> AggregateValue
[CS]         -> [2, 11000]
[Math]       -> [1, 7000]
```

> [!note]
>
> If there is no GROUP BY, `MakeAggregateKey()` produces an empty group key, and all inputs go into the same group.
>
> In other words, having no grouping columns doesn't mean there are no aggregate items.
>
> For example, `select count(*) from t` has no `group by`.

#### How are results accumulated within the same group?

The hash table provides an `InsertCombine()` method, which calls two methods we need to implement: `GenerateInitialAggregateValue()` and `CombineAggregateValues()`.

The general idea is that with the group key and this row's input values, you can call `InsertCombine()`: first find the group in the hash table; if it doesn't exist, use `GenerateInitialAggregateValue()` to create the initial value, then call `CombineAggregateValues()` to update it.

For example, CS's initial value is `[0, NULL]`. Merging the first `(CS, 5000)` gives `[1, 5000]`; merging `(CS, 6000)` then gives `[2, 11000]`. Math updates its own entry, accumulated separately from CS.

`CombineAggregateValues()` updates `result->aggregates_[i]` for each aggregate item according to `agg_types_[i]`:

- `COUNT(*)`: add one for every row, regardless of whether other columns in the row are NULL.
- `COUNT(expr)`: add one only if the input value is not NULL.
- `SUM`, `MIN`, `MAX`: skip NULLs; when the result doesn't yet have a valid value, first accept the first non-NULL input, then perform the addition or comparison.

The group key may also contain NULLs; when both corresponding positions are NULL, they should be considered as belonging to the same group, so `AggregateKey::operator==()` has this special handling:

```cpp
if (val.IsNull() && other_val.IsNull()) {
  continue;
}
```

> [!note]
>
> Also, here's a mistake I made at the beginning; the original text of the `e75f409` commit message:
>
> > Fixed an error in the aggregation executor constructor
> >
> > The main thing here is to clarify the difference between the plan's two `std::vector<AbstractExpressionRef>`:
> >
> > - `std::vector<AbstractExpressionRef> group_bys_` contains the group by fields; for example, if it's group by salary, then this expression is a ColumnValueExpression
> > - `std::vector<AbstractExpressionRef> aggregates_` contains the concrete aggregate computations, like SUM() and so on
> >
> > The latter is passed in here, because
> >
> > 1. There may be no group by logic at all
> > 2. `SimpleAggregationHashTable` requires the latter, for incremental aggregation; moreover, the count of this corresponds to the number of columns to output in the Schema, so iterating over this one by one to compute is reasonable. Passing the former might give 0, and the loop wouldn't even run
>
> The correct initialization is:
>
> ```cpp
> aht_(plan_->GetAggregates(), plan_->GetAggregateTypes())
> ```
>
> At the time, the first `SELECT COUNT(*) ...` returned `0`. The reason was that without GROUP BY, `GetGroupBys().size()` was 0, and my `CombineAggregateValues()` used `agg_exprs_.size()` to control the loop, so nothing was ever accumulated.

#### Pipeline Breaker

Hash aggregation is a **pipeline breaker**: the input must be fully consumed before the final grouped results can be output; the intermediate hash table holds the accumulated state of each group.

Therefore, the build phase goes in `Init()`, and `Next()` is only responsible for fetching results.

`Init()` first clears the previous hash table, initializes the child, then keeps pulling inputs:

```cpp
while (child_executor_->Next(
    &tmp_tuple_batch, &tmp_rid_batch, BUSTUB_BATCH_SIZE)) {
  for (const Tuple &tuple : tmp_tuple_batch) {
    aht_.InsertCombine(
        MakeAggregateKey(&tuple), MakeAggregateValue(&tuple));
  }
}
```

> [!caution]
>
> Note an edge case; the original text of the commit message:
>
> > Fixed an edge case
> >
> > Failed test 7; took a look and it's a special case
> >
> > The table is an empty table, but the input is `select count(*) from table`
> >
> > Because the table is empty, `Init()` inserts nothing. But actually we need to insert the initial value. Added a function to insert the initial value — even if there's nothing to do, we should still run that `Generate` once.
> >
> > Worth noting is the additional condition `&& plan_->GetGroupBys().empty()`.
> >
> > Because if we only check is_table_empty, then for SQL like this
> >
> > ```sql
> > SELECT v1, COUNT(*) FROM t1 GROUP BY v1;
> > ```
> >
> > Since v1 doesn't actually appear, nothing should be output — the output should just be nothing. Without this condition, the output would be
> >
> > ```
> > NULL 0
> > ```
> >
> > which doesn't meet the requirement.
> >
> > Anyway, it's a rather tricky edge case, and it involves annoying NULLs, so no need to worry too much about it.
>
> So the added condition is: **the input is empty AND there is no GROUP BY**. Without GROUP BY, the entire input forms one group; with GROUP BY, empty input produces no groups at all.
>
> ```cpp
> if (is_table_empty && plan_->GetGroupBys().empty()) {
>   aht_.InsertInitialValue(AggregateKey{});
> }
> ```
>
> Also, this doesn't only handle a standalone `COUNT(*)`: for example, `SELECT COUNT(*), SUM(v1) FROM t1`, empty input still needs to return one row of initial values. According to this Project's initial values and the `p3.07` test, `COUNT(*)` returns 0, and the other aggregate items return `integer_null`, including `COUNT(v1)`. This is handled per the project's requirements.

Once the empty-input case is handled, that's mostly it; finally execute `aht_iterator_ = aht_.Begin()`.

#### `Next()`

The thing to note here is the format of the returned tuple: **each time you traverse a hash table entry, create a new `values` and construct a result tuple**:

```text
A -> (2, 400)    yields (A, 2, 400)
B -> (3, 600)    yields (B, 3, 600)
```

What's generated here is an in-memory aggregation result with no corresponding TableHeap record location, so `rid_batch` gets a placeholder `RID{}`.

Also, HAVING is the job of an upper-level Filter; there's no need to implement it again inside AggregationExecutor.
### Nested Loop Join

So-called NLJ:

- Fix one left-table record and scan the right table from beginning to end;

- Then move to the next left-table record and rescan the right table.

- One left row may match multiple right rows, and every match must be output.

    > [!note]
    >
    > Fixing either the left or the right table actually works. But fixing the right table and probing with the left table is the better choice, because it makes Left Join easier.

Here the plan node provides `left_executor_` and `right_executor`, i.e., the sources for obtaining each table's tuples.

We need to support INNER JOIN and LEFT JOIN:

- INNER JOIN only outputs successfully matched combinations
- LEFT JOIN must also keep left rows with no matches at all, filling the right-side columns with NULL

Each check of a pair of left/right tuples uses `EvaluateJoin()`:

```cpp
const Value &val = filter_expr->EvaluateJoin(
    &left_tuple, left_schema, &right_tuple, right_schema);
bool has_value = !val.IsNull() && val.GetAs<bool>();
```

Only a non-NULL true result is output.

If the left side has been fully scanned, no match was found, and it's a LEFT JOIN, fill the right side with NULLs according to the right table Schema's column types.

Initially, I materialized the entire right table into memory in `Init()`, and then each left row traversed this cache. But this implementation couldn't pass the tests. The original text of the `6c6df25` commit message:

> The implementation that materializes the entire right table in Init() cannot pass the tests
>
> ```cpp
> BUSTUB_ASSERT(
>     casted_right_executor->GetInitCount() + 1 >=
>         casted_left_executor->GetNextCount(),
>     "nlj check failed, are you initializing the right executor every time when there is a left tuple? "
>     "(off-by-one is okay)");
> ```
>
> It should be changed to: for each new left tuple processed, re-initialize the right table via right_executor_->Init() to rescan the right side, and in Next() read the right-side tuples in batches, rather than pre-caching everything.

Then `6509c81` changed it to "implement partial loading of the right table", restarting the right-side scan for each new left row. The following flow needs to be followed:

- Take one left tuple
- The right executor starts from the beginning
- Read right tuples batch by batch, checking the join condition for each
- When the table is exhausted, move to the next left tuple

However, maintaining state here is troublesome; the state I maintained:

| Member | Meaning |
| --- | --- |
| `left_tuples_`, `left_cursor_` | The current left-table input batch, and the row currently being processed |
| `right_tuples_`, `right_cursor_` | The current right-table input batch, and the next position to compare |
| `matched_` | Whether the current left-table record ever matched during this round of right-table scanning |

Honestly, I feel this kind of trivial detail isn't very important; just have an agent or a plain chat LLM write it.

> [!note]
>
> Later, when implementing Hash Join, the same problem came up again, and it was even more complicated — maintaining variables alone was too hard. So I wrote a class to maintain this kind of state, which is much simpler. Of course, NLJ here wasn't implemented that way, probably because it wasn't hard enough yet xD

### Nested Index Join

After implementing the former, it actually didn't feel that complicated anymore.

A regular NLJ takes one outer-table record and scans the entire inner table, while Nested Index Join directly uses the outer table's join key to look up the inner table's index. After finding the RID, it goes back to the table to construct the join result; for LEFT JOIN rows with no match, the right side is still filled with NULLs.

## Task 3

Implement Hash Join, Optimizing NestedLoopJoin to HashJoin.

I feel these are the two hardest problems... especially the implementation of Grace Hash Join.

### Hash Join

Although the task is to implement Grace Hash Join, I first implemented a version without considering Grace.

So-called Hash Join:

- First, based on the join predicate, compute the hash row by row
    - For example, `table A(a, b, c), table B(e, f)`, and I want to `join A, B on A.a = B.e and A.b = B.f`
    - Then I traverse table B, computing the hash of each row's combination of e and f; the value is the key, and I build a hash table mapping from key to each actual row of table B
- Then, I traverse table A row by row, computing the hash of the a and b combination; if this hash value exists in the hash table above, the join rows are found, and those rows are pulled out
- The combinations of the above rows are the result

This implementation isn't actually that troublesome.

First, according to:

> **Hint:** You will need a way to hash a tuple with multiple attributes in order to construct a unique key. As a starting point, take a look at how the `SimpleAggregationHashTable` in the `AggregationExecutor` implements this functionality.

Following this, write a hash; the key point is really writing the Key — imitate it and write a `HashJoinKey`, and the Value is just a Tuple.

Imitating it isn't troublesome; the core requirement is satisfying the hash table's required **reflexivity**, i.e., any key satisfies `k == k`. This really means specially handling the case where both keys are NULL — in that case `operator==` returns true, but `NULL = NULL` must not produce a JOIN result. So we also need to skip right-table rows whose join keys contain NULL during the build phase. LEFT JOIN's left-table rows must be kept; when no match is found later, a result with the right side filled with NULLs still needs to be output.

Then just write it normally; note that since Hash Join is a pipeline breaker, the entire hash table needs to be built during Init, and then you just match against the iterator.

Note that the hash table we use here is actually `std::unordered_multimap`, so one key can match multiple values. When traversing, you need to record two iterators, using `equal_range()` to get the begin and end iterators of all values for a key and traverse them.

> [!note]
>
> Although the spec says that even if the hash values are equal, you must check whether the Values are actually equal, to guard against hash collisions.
>
> But actually, the STL requires the hashmap's key to implement `operator==`; internally it uses this operator overload to do real comparisons during lookup, thereby handling hash collisions internally, so we don't need to worry about this.

### Grace Hash Join

The previous regular Hash Join has a problem:

- Because table B may be very large, the hash table may not fit in memory at all

The solution: partitioned hash join

- Set a partitioning constant, e.g., PART_COUNT = 4, effectively splitting each of the two tables into 4 parts
- The partitioning principle is: at initialization, hash each of the two tables separately
    - For table A, for example, hashing the first row gives 101; mod 4 gives 1, so this row's content is recorded into partition 1
    - Same for table B
    - Note that what's stored above is effectively `vector<Row>`, and the array's index is the partition number. Moreover, this data is stored on disk
- When traversing, go through the partitions one by one
    - When traversing partition 0, first build the hash table for table B's partition 0
    - Then traverse all rows of table A's partition 0 and match them, just like the naive Hash Join above
- Finally, aggregate to get the result

The most important point here is that **both sides must use the same partitioning rule**. Identical join keys produce identical hash values, so they must land in the same numbered partition. This way, processing `A[i]` and `B[i]` is enough; there's no need to look at other partitions. Of course, this is now effectively a hash with very high collision rate, so you need to check equality yourself.

> [!note]
>
> The modulo operation is the most naive, and also a rather poor, hash function

This way, what needs to be loaded into memory each time is smaller. After processing one partition, you can clear the hash table and continue with the next.

However, the fact that this executor is a pipeline breaker doesn't change, so we still need to compute all the hashes during Init. How do we load them? We need an **Intermediate Result Page**.

#### Intermediate Result Page

> [!note]
>
> The `vector<Row>` written above is just for ease of understanding; what's actually kept in memory is the page id, and the Tuples are placed in Intermediate Result Pages managed by the BufferPoolManager. Essentially, you need to (temporarily) persist the Tuples into pages.

First, about this `Intermediate Result Page`; the most valuable references are `table_page.h` and `table_page.cpp` — the core design is basically identical!

The spec mentions that you can go read the external merge sort section; after reading it, the most core sentence is this:

> Also, your `IntermediateResultPage` layout should be compact, i.e. as little fragmentation as possible. You should also make sure that the pages are actually deleted after the merge sort is done.

So we need a compact implementation, meaning the previous tuple should be adjacent to the next tuple.

Referring to the source code, apart from not needing to store Meta, remove that part. The rest can be said to be exactly the same.

So designing a page really means: first make a fixed-length header storing some basic meta data, and then the dynamic part follows. At the very beginning, use a `char*` pointer to pin down the position.

Specifically here, it reuses TablePage's slotted page idea. However, intermediate results don't need `TupleMeta`, and the order of pages is managed by the outer page id array, so not even a next page id needs to be stored. In the end, only these things remain:

- At the beginning, `num_tuples_`, occupying 2 bytes, records how many Tuples this page has.
- Following that are each Tuple's offset and size, two `uint16_t`s, 4 bytes per Tuple.
- The actual Tuple data is placed from the end of the page toward the front, while the slot array at the front grows toward the back; the space between the two is the remaining space.

When inserting, besides the Tuple itself, you also need to reserve space for a new slot. If the two sides collide, `InsertTuple()` returns `std::nullopt`, letting the outer executor switch to another page.

This design also satisfies the spec's requirement of supporting `VARCHAR`, obviously.

Also, regarding the `char*` mentioned above, the actual code writes `char page_start_[0]`, placed at the very beginning of the class, used to obtain the starting address of the data within the page — no pointer is actually stored in the page. This is clang's idiom, copied from the source code; I didn't really look into why it doesn't occupy space itself, but it works anyway)

> [!note]
>
> You can't stuff a `std::vector<Tuple>` into the page; otherwise what's stored is just an in-process pointer, and the Tuple data never gets written into the page.

#### Initializing partitions

Then comes the core part of Grace Hash Join.

Initially I defined the constant `static constexpr size_t PARTITION_COUNT = 16;`; the value was chosen by the LLM. Later it was changed to 32, with the reason explained later.

The general purpose is that at initialization, all left and right inputs must be initialized and written to disk, and the form of persistence is through the intermediate pages just written. Manipulating pages also requires going through the context's BufferPoolManager and using some PageGuard APIs; I hadn't written it in a while and had somewhat forgotten, but the writing style is just like that anyway. The core is in the `initialize_partitions` Lambda function.

Specifically, define a data structure like this:

```cpp
using Partitions = std::vector<std::pair<std::vector<page_id_t>, std::vector<page_id_t>>>;
```

The general idea is that `first` is `left` and `second` is `right`; then for a specific `partition_idx`, which is really `partition_idx = std::hash<bustub::HashJoinKey>{}(hjk) % PARTITION_COUNT`, write the Tuple into a page; if the page is full, create a new page and continue writing.

So it looks like there are three layers, which is really just:

```cpp
partitions_[分区编号].first   // 这个分区的左表有哪些页
partitions_[分区编号].second  // 这个分区的右表有哪些页
```

Each time a Tuple is read, first compute the `HashJoinKey` using the corresponding side's key expressions from the plan, then decide the partition. Then try to write into the last page of this partition; if there's no page, or the last page can't fit it, call `NewPage()`, get a WritePageGuard, `Init()` it, and then insert.

The NULL filtering mentioned earlier also goes in this step:

- For INNER JOIN, rows on either side whose **join keys** contain NULL can be skipped;
- For LEFT JOIN, only the right side's NULLs are skipped.

> [!caution]
>
> Note that here you check the **join keys**, not any arbitrary column of the Tuple; NULLs in other columns don't affect this row's participation in the JOIN.

This part is fine, no big deal.

#### Managing traversal with PagesReader

Then, the most important thing is still `Next()`. The key is understanding the essence of Grace Hash Join. The point is that for a specific partition idx, we build (build) the right table's hash table, then use the left table to probe — remember to select the left table of the same partition — then traverse the tuples inside; for each tuple, compute its key, then find all matching right-table tuples from the hash table just built, reusing the emit logic.

But actually writing it is quite painful. Previously you only needed to manage the left table's batch and the cursor within the batch; now there's an extra layer of partitions, each partition has several pages, each page has several Tuples, and after getting a left Tuple, you still have to continue traversing all matching right Tuples. And at any time you may return because the output batch is full, and the next call must resume from the last position.

Writing this was painful for me, so I had the AI try to propose a simplified logic; unexpectedly, it proposed an intermediate-layer Class that manages reading Tuples page by page and Tuple by Tuple from a partition. This is really clever, as exquisite as the PageGuard design; learned something.

This class is `PagesReader`. The outside only needs to tell it this group of page ids, and then repeatedly call `Next()`. Implement these interfaces:

- `Reset(pages)`: switch to a new group of pages and start reading from the beginning of this group.
- `Next()`: take out the next Tuple; when the current page is exhausted, move to the next page, and only return false when all pages are exhausted.
- `GetCurrentTuple()`: get the currently retrieved Tuple.
- `ClearCurrentTuple()`: when the current Tuple is done being processed, clear it, but keep the position for the next read.

The purpose of the last interface is in the so-called nested fallback, i.e., when the inner side has no match and we check for left join. Because if the current left tuple has ever matched, the left join logic doesn't need to run. Executing `ClearCurrentTuple()` indicates that the current tuple has matched.

#### Moving from one partition to the next

With this encapsulation, the outside only needs to consider:

- Whether the current left Tuple still has unmatched matches
- Whether the left partition still has Tuples
- Whether there is a next partition

First write a `LoadPartition()`, responsible for building the hash table for the right partition of the current number, and resetting `left_reader_` to the left partition of the same number. `NextPartition()` is responsible for advancing the partition number, then calling `LoadPartition()`.

At initialization, `part_cursor_` is 0, so just calling `LoadPartition()` is enough. If `NextPartition()` is called at this point, it will first increment, directly skipping partition 0...

`Next()`'s logic is written in this order:

1. If the current left Tuple still has matches that haven't been output, i.e., `begin_ != end_`, emit one, advance `begin_`, then continue.
2. If there are no remaining matches, let `left_reader_` take the next left Tuple.
    - If successfully retrieved, re-run `equal_range()` and save the new `begin_` and `end_`.
    - If nothing matched at all, and it's a LEFT JOIN, emit one result with the right side filled with NULLs.
3. If the left partition is exhausted, call `NextPartition()` and continue.
4. Only when all partitions are processed is it truly finished.

Wrap it in an outer `while (tuple_batch->size() < batch_size && part_cursor_ < PARTITION_COUNT)`. **And inside, write no loops at all — write only `if`s**. This is also a lesson: with an outer loop, if the inner `if`s can let the outer loop handle the inner loop's needs, don't write loops inside.

At this point, I had painfully more or less implemented the Grace Hash Join part, but there was still one TODO left.

The missing TODO was that the right side might not fit entirely into one hash table, so it needs to be split into multiple.

#### What if a partition still doesn't fit?

I feel this was quite an ordeal, mentally.

We partitioned earlier, but a problem remains:

- The partitioning constant might be too small; after one round of partitioning, the table still doesn't fit
- Or all the table's keys might be identical (e.g., the table's matching key is `1` for a million rows)

The solution to the former is to partition again, recursively, and each level of partitioning uses a different hash function.

But the latter poses another problem: in the latter's case, the former would keep recursing down to one tuple per hash index, which is meaningless.

Therefore, you can set a limit of at most two or three levels of partitioning.

But how should this data structure be designed? At first I thought it was like this:

First, when traversing Tuples, keep a counter, accumulating the Tuple sizes; when about to exceed 4KB (PAGE SIZE), start splitting.

Obviously, this splitting process can be recursive. If the limit is exceeded, I keep probing one level deeper, and only after the memory-loading requirement is satisfied do I execute the Next() logic of selecting the two partitions and using the left table's tuples to probe the right table.

Then clearly, our current code organization differs too much from this idea. First, `left_reader_` is locked into reading first-level partitions; there's no such thing as second-level partitions. Also, the logic of Next and NextPartition is completely decoupled, but now they'd have to be coupled together, requiring a complete rewrite.

If a complete rewrite is needed, it would be better to just stuff the previously written LoadPartition logic back into Next, and that's the only way to do it.

But anyway, recursion can't go on forever; the depth can't be too deep. I think at most the second or third level is enough — after all, one level has a full 16 fanout, and if that doesn't work, fall back to Nested Loop Join, just a Nested Hash variant.

So the rough idea was to stuff LoadPartition() and NextPartition() entirely back into Next()'s logic, and the hash table's data structure would have to be rewritten as a recursive tree structure, wrapped in a struct providing some nicely encapsulated functions, so it's as transparent as possible to the user.

At this point, I suddenly thought of the page table and file system tree structures learned in Operating Systems.

What I was thinking at the time was: could we also split the hash value into several segments, with each segment used to select one level of partitioning? Since we only plan to do a limited number of levels, falling back when insufficient, maybe there's no need to actually maintain a recursive tree — just fix it at two levels. I think this borrowing from OS is quite clever.

Then, as I kept thinking — mainly considering that if the right side gets small partitions but the left side can't do the same, since the left side's partitions were locked in at the start —

I suddenly realized: if I only planned to split into two levels, why didn't I just partition into 256 partitions from the very beginning... Then, the later hash-table loading logic still loads as if there's only one level, and if one level fails, fall back to the nested version. I feel this layering makes no essential difference at all; it's even better and simpler.

Then I felt 256 wasn't quite right either, so it became 32. Anyway, in short, I discovered that the problem can be solved completely without layering — total overkill on my part.

#### Nested fallback within a partition

The nested logic isn't complicated either; with PagesReader managing the tuples on both sides, it's really quite simple. It's just a naive double loop within one partition.

First, when `LoadPartition()` builds the table, maintain a `tuple_bytes`, adding each inserted tuple's `GetLength()`. If inserting the next one would exceed `BUSTUB_PAGE_SIZE / 2`, i.e., 4096 bytes, set `use_nested_ = true`, clear the partially built hash table, and exit the table-building process.

Note that this doesn't discard the right partition's remaining data. All Tuples were already written into temporary pages during `Init()`; now we're just deciding not to use this hash table that can't fit everything, and instead scanning the original right partition from the beginning.

> [!note]
>
> This counting is actually rather crude.

Then in `Next()`, choose between the two sets of logic based on `use_nested_`. The nested side's steps aren't complicated; just use `PageReader` well.

Finally, the temporary pages' release must also be handled. I centralized it in `ClearPartitions()`: first clear both readers' states, then traverse all partitions, `DeletePage()` the left and right page ids one by one, and finally clear the arrays.

### Optimizing NestedLoopJoin to HashJoin

First is recursive analysis: if it's a `LogicExpression`, only handle the and case, then recurse on the left and right sides respectively.

The recursion's endpoint is handling `ComparisionExpression`; the left and right sides of a `ComparisionExpression` are `ConstantColumnExpression`s, and the requirement here is, for example, an Equal operator.

First, the ultimate goal is to return a HashJoinPlan; the core elements are these constructor parameters of HashJoinPlanNode:

- `left` `right`: the plan nodes for obtaining the left and right tuples; the simplest case is a seq scan. Just pass in the left and right from the original nlj node
- `left_key_expressions` `right_key_expressions`. This is the more troublesome part
- `join_type`: also just copied from the nlj plan node

Let's focus on the two `key_expressions`:

- Create two usets and two `std::vector<AbstractExpressionRef>`; the usets store `col_id`s
- For the function handling `ComparisonExpression`:
    - When recursing into a `ComparisonExpression`, parse out the `ConstantColumnExpression`s on both sides of this `ComparisonExpression`. If they're not, terminate and fall back to the regular case
        - Also consider the possible case where the left side of the expression is a column of the right table and the right side is a column of the left table — but that's a detail, handled later
    - Then return the left `ConstantColumnExpression`, the right `ConstantColumnExpression`, and both sides' `GetColIdx()`
- Then, when the outer main recursive function gets the return values, process them one by one; if a col_id doesn't exist in the uset, append it to the end of those two arrays
- Finally, construct the appropriate `key_expressions` and return the answer.

So really, just clarifying the思路 is enough. The most valuable references are `nlj_as_index_join.cpp` and the previously self-written `seqscan_as_indexscan.cpp`; the former clarifies how this join should be written, and the latter clarifies reusing the previous recursive expression approach.

## Task 4

Need to implement External Merge Sort + Limit Executors + Window Functions.

I feel External Merge Sort is about as hard as Hash Join, whereas Window Functions are really just a comprehensive combination of previous logic — since I was more or less familiar with it all by then, writing it was actually less complicated.

### External Merge Sort

So-called external merge sort is a merge sort that caches intermediate results.

The core elements are:

- Since the sort executor is a pipeline breaker, most of the logic should be implemented in Init; Next just fetches the results.
- There are individual `MergeSortRun`s, whose core data structure is `vector<page_id_t> pages_`, storing a series of Intermediate Result Pages, in order, with the tuples sorted
    - "In order" means: traversing `pages_`, the last tuple of each page and the first tuple of the next satisfy the partial order we need, and the tuples within each page also satisfy it
    - Therefore, there's also an iterator class for conveniently reading a run's tuples.
- In the end, a single run is obtained, and the tuples within it are sorted.

So, first, according to the spec, implement the `TupleComparator` logic. This really means implementing two functions (operator overloads):

```cpp
auto GenerateSortKey(const Tuple &tuple, const std::vector<OrderBy> &order_bys, const Schema &schema) -> SortKey;
```

and

```cpp
auto TupleComparator::operator()(const SortKey &key_a, const SortKey &key_b) const -> bool;
```

Nothing much to say about either; just get the logic control right.

Then, implement the concrete functions inside the executor.
#### Init and Next

Specifically, what Init should do is:

- Obtain all the tuples that need to be sorted via the `child_executor`'s `Next()`
- However, our TupleComparator actually compares `SortEntry = std::pair<SortKey, Tuple>;`, while `SortKey = std::vector<Value>;`, so no matter what, we first need to get the SortKey corresponding to a Tuple — this is where the `GenerateSortKey` function comes in. It's a bit long and ugly, but it works
- Write these tuples into a series of Intermediate Result Pages, and according to the spec, only sort the tuples within a single page (ensuring this fits in memory)
- At the beginning, one Page is one Run, which is also the constraint from the spec above

After that, the formal merge sort process begins:

- First, the merge process handles k runs at a time; initially, traverse the first k of `std::vector<MergeSortRun> runs`.
- Since it's k-way, set up a min-heap, and each time select the smallest (in the tuple comparison sense) from the current run's iterator. But again, back to the problem that the comparator can only compare `SortEntry` — you have to carry along some other inexplicable stuff, and then I realized that what actually needs to be stored here is the iterator.
- Each time, take the top of the heap, pop it, insert the successor iterator of this iterator, and write a new page. The write logic can just follow the above, reusing the same tracker — when full, write a page. Here you can open an array of `page_id`s to keep track. If this iterator has been fully traversed, don't put it back into the heap.
- Until the heap is empty, which means the merge is completely done. At this point, construct a new run; we can directly use the array we just recorded to construct it.
- How to handle the newly obtained run? We use a `while(runs.size() > 1)` approach, constructing new next_runs each time and appending to the next_runs we obtained. After finishing one round, `runs = std::move(next_runs)`, so the old runs get released on their own
- However, the pages inside the released runs are no longer useful, but still need to be manually released; so I changed the run into an RAII object that automatically releases all resources upon destruction, which is very convenient. Note that the RAII object must also forbid copying, and overload the move-semantics operators and so on

> [!note]
>
> About the RAII implementation here:
>
> The key point here is that **a run owns a set of temporary pages**:
>
> - Upon destruction, `Cleanup()` traverses these page ids and calls `DeletePage()` on each one.
> - Copying is forbidden. Otherwise, two runs would both hold the same set of page ids, resulting in double release at the end.
> - The move constructor moves `pages_` over, then uses `std::exchange(other.bpm_, nullptr)` to make the original object give up its cleanup responsibility.
> - The move assignment must first `Cleanup()` the pages it originally owned, then take over the new pages.
>
> This way, each round of `runs = std::move(next_runs)`, the old run's pages are automatically reclaimed; the final run is moved into the executor's member, waiting for the next Init to replace it, or for the executor's destructor, at which point it is automatically released.

Then the Next is extremely simple — just read all the way through the iterator.

#### A Few Bugs

I ran into a few bugs along the way.

- When all the data doesn't fill a page, the "can't fit any more, write a page" branch was never triggered, so there was still data in `to_sort` while `runs` was empty. So after finishing reading the input, you need to check whether there are still Tuples in `to_sort`, and call `flush_run()` one last time; inside, if the buffer is found to be empty, just return directly without creating an empty page.
- Then I also fixed a bug where, after the heap was emptied, a new run was constructed while the remaining data in `to_sort` hadn't yet been written to pages. This is the same situation as above, except it happens at the end of each group's merge. The heap being empty only means the input has been fully read; it doesn't mean the output buffer is also empty. If this group's result doesn't even fill one page, a run with no pages would be constructed, and the next round would crash as soon as it's dereferenced. So in the end I split the two pieces of logic into `flush_page()` and `flush_run()`: the former is responsible for writing pages, and the initial run sorts first and then calls it; during merging the data is already sorted, so just write pages directly. Both at the end of input and at the end of each group's merge, the tail page must be flushed.

One more thing to note: after creating a new page, you should first take the guard and then call `As<>`; otherwise the guard is a temporary object that will be destructed, and subsequent access to the page is not guaranteed to be safe.

> [!note]
>
> At the time I even asked: is this page guard thing real? I had written a lot of code like this before and it seemed fine?
>
> For example, `auto page = bpm->WritePage(page_id).AsMut<IntermediateResultPage>();` — after the semicolon, the temporary guard is destructed. The `page` pointer may not become invalid immediately, but the corresponding page is no longer protected by the guard; once the frame is evicted and reused, you might later be accessing data from a different page. It only seemed fine before because this situation never came up.

### Limit

Actually there's not much to say; let me summarize the pitfalls:

There's this edge case where the number of tuples in the table is less than the limit. For example, the table only has 10 rows, but `LIMIT 15` — after outputting 10 rows, it will still keep fetching data from the child executor.

The child executor clears `tuples_` after finishing reading, but `cursor_ ` is still 10. On the next call:

- `cursor_ == tuples_.size()`: 10 == 0, not satisfied.
- `cursor_ < tuples_.size()`: 10 < 0, not satisfied.
- `outputed_ < limit`: 10 < 15, always satisfied.

So the loop keeps spinning idly.

There are two termination conditions here: either the limit has already been output, or the child has no more data.

### Window Functions

Before implementing window functions, I read through the spec and felt like I had a bunch of questions but remembered nothing, and the source code was just an ordinary plan and executor with nothing special about it — I didn't even know what to look at.

At the start, a few things need to be determined:

- If there's an order by, although you could output row by row, because of the sorting, it has to become a pipeline breaker.
- If there's no order by, then although no sorting is needed, the aggregation is computed over the entire partition, which effectively makes it a pipeline breaker anyway.
- `window_func_indexes` is the source of the keys of `window_functions_`, corresponding to the column indices of the output Tuple. When traversing `columns_`, if this index is in `window_functions_`, you can't directly evaluate that placeholder; you have to get the result through the corresponding WindowFunction.

Whether or not there's an order by actually has a huge impact on the code logic. Although the code is highly similar, there are inseparable couplings that make it hard to keep the logic clear — it's better to just write the similar code as two copies.

So split Next into two functions, using a condition to go down each path:

- `NextWithOrderBy()`: Init sorts first, then reads in order; each row read updates the corresponding partition's state, then outputs the current window value.
- `NextWithoutOrderBy()`: Init computes the entire partition's aggregate value up front, and Next only reads the final aggregate value, without accumulating again.

#### Reusing the Sort

The problem states that window functions in a query share the same set of order bys, so the whole table should be sorted first and then output. Basically all the logic is identical — you can even directly copy the logic from the external merge sort executor's `Init()`, just maintaining the pages in the final run and an iterator.

If sorting is needed, you have to end up with a set of intermediate pages storing the sorted tuples; if sorting isn't needed, you still have to save the original rows and output them after the entire partition's aggregate value is computed. So the insertion process logic can be reused; the only difference is whether the tuples within a page are sorted.

So really, the sorting is basically just reused.

#### Each Window Function, Each Partition Has Its Own State

Then, I read through the previous Aggregation-related code and conversation, and found that there, in `Init`, a `plan_executor_` only has one hash table (because a statement has only one group bys).

But here, for window functions, there should be a hash table corresponding to each entry in the window_functions hashmap.

But here the smallest unit is a window function, and a window function's type cannot be an array — it's unique.

Essentially, one `group_bys` condition (one `agg_key`) can only correspond to one `agg_val`, corresponding to a unique type. But to locate this state, you still need to know both which window function and which partition:

```cpp
using PartitionHashTable = std::unordered_map<AggregateKey, WindowState>;
std::unordered_map<uint32_t, PartitionHashTable> ht_;
```

In short, locating a specific WindowState depends on both the idx and the AggregateKey — you can't rely on the former alone, **otherwise it's equivalent to having no partition by**.

#### RANK and State Initialization

I asked AI and it said to write a RankState struct.

But I wanted to reuse the previous logic, so I introduced `std::variant`: `using WindowState = std::variant<Value, RankState>;`

Ordinary aggregations store a Value, while RANK needs to store how many rows have been read, the current rank, and the previous SortKey.

But after using `std::variant`, a lot of the previous code seemingly couldn't be reused anymore, and I didn't know what to do — for example, `InitVal(Value &val, WindowFunctionType type)`; changing the function signature to WindowState didn't help either.

The solution is, well, just to use the `get<T>` approach.

Also, I defined InitVal() but the Init logic needs `wf.partition_by_` which couldn't be obtained, so I integrated it into the first insertion, using `try_emplace()` to confirm whether it's the first time.

One last thing to note: what's output at the end is a new Tuple — that is, the result obtained from the window function — not, like aggregation, some semantically dubious concatenation.
