Search RU
Tasks / SQL / Query plan regression
Statement hard

Query plan regression

`detect_plan_regression(baseline, candidate, *, rows_growth_factor=2.0)`
compares two query plans and reports whether the plan got worse.

A plan is a list of scan nodes in traversal order (a teaching format, not raw
`EXPLAIN`):

```python
[
{"node": "Index Scan", "relation": "orders", "rows": 100},
{"node": "Seq Scan", "relation": "customers", "rows": 5000},
]
```

Allowed `node` values: `"Seq Scan"`, `"Index Scan"`, `"Index Only Scan"`,
`"Bitmap Index Scan"`, `"Bitmap Heap Scan"`.

The report:

```python
{
"regressed": True,
"findings": [
{
"kind": "scan",
"relation": "orders",
"baseline": "Index Scan",
"candidate": "Seq Scan",
},
{
"kind": "rows",
"relation": "customers",
"baseline": 1000,
"candidate": 5000,
"factor": 5.0,
},
{
"kind": "join_order",
"baseline": ["orders", "customers"],
"candidate": ["customers", "orders"],
},
],
}
```

Contract:

- `kind: "scan"` — the table had index access in baseline (any node except
`Seq Scan`) and has `Seq Scan` in candidate;
- `kind: "rows"` — the table's row estimate grew strictly more than
`rows_growth_factor` times: `candidate_rows > baseline_rows * factor`; the
`factor` in the finding is `round(candidate_rows / baseline_rows, 2)`;
- `kind: "join_order"` — the relative order of the common tables changed;
adding a new table alone is not a regression; the finding carries the full
table lists in plan order;
- `join_order` is added at most once and last;
- finding order: `scan` in baseline order, then `rows` in baseline order, then
`join_order`;
- `regressed` is `True` when `findings` is non-empty;
- empty plans, or plans without common tables, return
`{"regressed": False, "findings": []}`;
- `rows_growth_factor` is a number strictly greater than zero, not `bool`;
- invalid input raises `ValueError`: a plan is not a list, a node is not a
dict, an unknown `node`, an empty `relation`, `rows` is not a positive
integer, a table repeats within one plan.

Write tests for: an index turning into `Seq Scan`, row estimate growth above
and below the threshold, exactly on the threshold, a change of index access
type, a changed join order, a new table at the end, finding order, empty plans,
and invalid input.

Python · SQLite
sqlexplainquery-planregression
test_solution.py Python 3.14 · SQLite
AI mentor

The AI mentor is available after you log in: it sees your attempt history and does not spend resources on anonymous requests.

Log in and ask
Hints 1 of 3 unlocked · attempts: 0
Hint 1

How is "the plan changed" different from "the plan got worse"? And is a
`Seq Scan` on a table that was already read sequentially a regression?

Hint 2 — unlocks after 1 attempt
Hint 3 — unlocks after 3 attempts