From 6c6a36b8a1eaf7d1eddd905c456ee80de494c5b8 Mon Sep 17 00:00:00 2001 From: SpookyJumpyBeans <116844292+SpookyJumpyBeans@users.noreply.github.com> Date: Mon, 7 Sep 2026 22:47:54 -0400 Subject: [PATCH] Choose join order from a cost model instead of the written order Joins ran in the order they appeared in the query. That is fine until it isn't: a query that joins a fact table to a wide dimension before applying a filter that leaves one row carries every fact row through the wide join for nothing. Adds tinyquery/cost.py. `analyze` walks a table once for row count and per-column distinct values, which is what ANALYZE collects, except this one can look at everything because the table is already in memory. Selectivity and join cardinality use the textbook formulas, and `choose_join_order` runs the Selinger subset DP over left-deep plans, costing each join as build side plus probe side. Reordering moves columns around inside the row, so SELECT * would have started reporting a different column order. Project cannot fix that because it flattens qualifiers and would break o.region further up, so this adds a Reorder operator that permutes back to the declared order and keeps the schema intact. The planner takes reorder=True, threaded through plan/compile_sql/execute/ explain. Turning it off restores the previous behaviour exactly, which is how the tests compare the two plans on identical data and how the benchmark measures the difference. On a fact table joined to a 200 row dimension and a 50 row table filtered to one, the reordered plan runs 1.30x faster at 1,000 facts and 2.19x at 100,000. The gap widens because the cost of a bad order scales with the intermediate result, the same shape as hash join versus nested loop and unlike pushdown, which stays flat. 27 new tests, 76 total. --- README.md | 32 ++++- benchmarks/join_benchmark.py | 53 ++++++++ tests/test_join_order.py | 188 ++++++++++++++++++++++++++ tinyquery/cost.py | 247 +++++++++++++++++++++++++++++++++++ tinyquery/engine.py | 12 +- tinyquery/operators.py | 37 ++++++ tinyquery/planner.py | 139 +++++++++++++++++--- 7 files changed, 686 insertions(+), 22 deletions(-) create mode 100644 tests/test_join_order.py create mode 100644 tinyquery/cost.py diff --git a/README.md b/README.md index 54470f8..0b3e991 100644 --- a/README.md +++ b/README.md @@ -101,13 +101,43 @@ should expect. The filter keeps about half the orders, so the build side is half as large and half as many probes find a match. It changes the constant, not the complexity. +**Cost-based join ordering**, a fact table joined to a 200 row dimension and a +50 row table filtered down to one: + +| facts | rows out | cost-based | as written | speedup | +| --- | --- | --- | --- | --- | +| 1,000 | 20 | 0.004s | 0.006s | 1.30x | +| 5,000 | 100 | 0.018s | 0.024s | 1.35x | +| 20,000 | 400 | 0.073s | 0.108s | 1.48x | +| 100,000 | 2,000 | 0.324s | 0.711s | **2.19x** | + +Written order joins the facts to the dimension first, which means carrying +every fact row through a wide join before anything filters it down. The cost +model starts from the filtered table instead: + +``` +HashJoin f.dim_id = d.id + HashJoin t.id = f.tiny_id + Filter t.id = 1 + Scan t + Scan f + Scan d +``` + +That one row leads, the join to `f` collapses the fact table immediately, and +`d` joins against something small. Like hash join and unlike pushdown, the win +grows with size, because the cost of getting the order wrong is proportional to +how big the intermediate result gets. + Measured on CPython 3.13, best of three runs. ## What it does not do No nested queries, no outer joins, no disk spill. NULL join keys never match. NULLs in `ORDER BY` sort last. -No cost-based join reordering: joins execute in the order written. AND-clauses in `WHERE` that only mention one table are pushed below the join (so `o.year = 2024` filters orders before the hash table is built). Predicates that mention both sides, and `OR`s we cannot split, stay above the join. +AND-clauses in `WHERE` that only mention one table are pushed below the join (so `o.year = 2024` filters orders before the hash table is built). Predicates that mention both sides, and `OR`s we cannot split, stay above the join. + +Join ordering searches left-deep plans only, using the Selinger dynamic program over subsets, and gives up above 10 tables. Statistics come from a full scan rather than a sample, which is honest only because the tables are already in memory. Estimates use the usual independence assumptions, so correlated predicates will mislead it in exactly the way they mislead every other optimiser. ## Run diff --git a/benchmarks/join_benchmark.py b/benchmarks/join_benchmark.py index 76de827..c25fd55 100644 --- a/benchmarks/join_benchmark.py +++ b/benchmarks/join_benchmark.py @@ -93,6 +93,51 @@ def time_pushdown(orders: Scan, lineitems: Scan, repeat: int) -> tuple[float, fl return below, above, count +def time_join_order(n_facts: int, n_dim: int, n_tiny: int, repeat: int) -> tuple[float, float, int]: + """Cost-based join order versus joining in the order written. + + A fact table joined to a wide dimension and a heavily filtered tiny one. + Written order pays for the wide join across every fact row; the cost model + joins the filtered table first and shrinks the input to everything after. + """ + from tinyquery.catalog import Catalog + from tinyquery.engine import execute + from tinyquery.schema import Column, Schema + + catalog = Catalog() + for name, columns, rows in ( + ("f", ["id", "dim_id", "tiny_id", "amount"], + [(i, i % n_dim, i % n_tiny, i) for i in range(n_facts)]), + ("d", ["id", "label"], [(i, f"d{i}") for i in range(n_dim)]), + ("t", ["id", "label"], [(i, f"t{i}") for i in range(n_tiny)]), + ): + catalog.register( + name, Schema(tuple(Column(c, table=name) for c in columns)), rows + ) + + sql = """ + SELECT f.id, d.label, t.label + FROM f + JOIN d ON f.dim_id = d.id + JOIN t ON f.tiny_id = t.id + WHERE t.id = 1 + """ + best_on = float("inf") + best_off = float("inf") + count = -1 + for _ in range(repeat): + start = time.perf_counter() + rows, _ = execute(catalog, sql) + best_on = min(best_on, time.perf_counter() - start) + count = len(rows) + + start = time.perf_counter() + rows_off, _ = execute(catalog, sql, reorder=False) + best_off = min(best_off, time.perf_counter() - start) + assert len(rows_off) == count, "reordering changed the row count" + return best_on, best_off, count + + def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( @@ -136,6 +181,14 @@ def main() -> int: below, above, rows = time_pushdown(orders, lineitems, args.repeat) print(f"{n:>8,} {rows:>10,} {below:>12.3f}s {above:>11.3f}s " f"{above / below:>8.2f}x") + + print() + print(f"{'facts':>8} {'rows out':>10} {'cost-based':>12} " + f"{'as written':>12} {'speedup':>9}") + print("-" * 56) + for n in args.sizes: + on, off, rows = time_join_order(n, n_dim=200, n_tiny=50, repeat=args.repeat) + print(f"{n:>8,} {rows:>10,} {on:>11.3f}s {off:>11.3f}s {off / on:>8.2f}x") return 0 diff --git a/tests/test_join_order.py b/tests/test_join_order.py new file mode 100644 index 0000000..693f1ed --- /dev/null +++ b/tests/test_join_order.py @@ -0,0 +1,188 @@ +"""The optimiser may change the join order but never the answer. + +Every test here compares `reorder=True` against `reorder=False` on the same +data, so a reordering bug shows up as a difference rather than as a plausible +looking wrong result. +""" + +import random + +import pytest + +from tinyquery.catalog import Catalog +from tinyquery.cost import analyze, estimate_join_rows, estimate_selectivity +from tinyquery.engine import execute, explain +from tinyquery.expr import BinaryOp, ColumnRef, Literal +from tinyquery.schema import Column, Schema + + +def catalog_with(**tables): + """Build a catalog from {name: (columns, rows)}.""" + catalog = Catalog() + for name, (columns, rows) in tables.items(): + schema = Schema(tuple(Column(c, table=name) for c in columns)) + catalog.register(name, schema, rows) + return catalog + + +def star_catalog(n_facts=400, n_dim=40, n_tiny=3): + """A fact table joined to a big dimension and a very small one. + + Joining the tiny table first shrinks the intermediate result immediately; + joining it last means carrying every fact row through the wide join. Same + answer either way, very different amount of work. + """ + facts = [(i, i % n_dim, i % n_tiny, i) for i in range(n_facts)] + dims = [(i, f"d{i}") for i in range(n_dim)] + tinies = [(i, f"t{i}") for i in range(n_tiny)] + return catalog_with( + f=(["id", "dim_id", "tiny_id", "amount"], facts), + d=(["id", "label"], dims), + t=(["id", "label"], tinies), + ) + + +THREE_TABLE_SQL = """ + SELECT f.id, d.label, t.label + FROM f + JOIN d ON f.dim_id = d.id + JOIN t ON f.tiny_id = t.id + WHERE t.id = 1 +""" + + +def test_same_rows_with_and_without_reordering(): + catalog = star_catalog() + reordered, _ = execute(catalog, THREE_TABLE_SQL) + written, _ = execute(catalog, THREE_TABLE_SQL, reorder=False) + assert sorted(reordered) == sorted(written) + assert reordered # and it is not trivially empty + + +def test_reordering_actually_changes_the_plan(): + """If the plan never changes, the rest of these tests prove nothing.""" + catalog = star_catalog() + assert explain(catalog, THREE_TABLE_SQL) != explain( + catalog, THREE_TABLE_SQL, reorder=False + ) + + +def test_select_star_keeps_declared_column_order(): + """Executing joins out of order moves columns; the output must not show it.""" + catalog = star_catalog() + sql = "SELECT * FROM f JOIN d ON f.dim_id = d.id JOIN t ON f.tiny_id = t.id" + reordered, schema_a = execute(catalog, sql) + written, schema_b = execute(catalog, sql, reorder=False) + assert schema_a.names() == schema_b.names() + assert schema_a.names()[:4] == ["f.id", "f.dim_id", "f.tiny_id", "f.amount"] + assert sorted(reordered) == sorted(written) + + +def test_aggregates_survive_reordering(): + catalog = star_catalog() + sql = """ + SELECT d.label, SUM(f.amount) AS total + FROM f + JOIN d ON f.dim_id = d.id + JOIN t ON f.tiny_id = t.id + GROUP BY d.label + """ + assert sorted(execute(catalog, sql)[0]) == sorted( + execute(catalog, sql, reorder=False)[0] + ) + + +def test_two_table_joins_are_left_alone(): + """One join has only one left-deep shape, so there is nothing to choose.""" + catalog = star_catalog() + sql = "SELECT f.id FROM f JOIN d ON f.dim_id = d.id" + assert explain(catalog, sql) == explain(catalog, sql, reorder=False) + + +def test_chain_join_agrees(): + """f to d to t, rather than both joins hanging off f.""" + catalog = star_catalog() + sql = """ + SELECT f.id + FROM f + JOIN d ON f.dim_id = d.id + JOIN t ON d.id = t.id + """ + assert sorted(execute(catalog, sql)[0]) == sorted( + execute(catalog, sql, reorder=False)[0] + ) + + +def test_the_filtered_table_is_joined_first(): + """The whole point: a filter that leaves one row should lead the plan.""" + catalog = star_catalog() + plan = explain(catalog, THREE_TABLE_SQL) + # The filtered scan of t sits at the bottom, inside the innermost join. + assert plan.index("Filter t.id = 1") > plan.index("HashJoin") + assert plan.rindex("Scan d") > plan.index("Filter t.id = 1") + + +@pytest.mark.parametrize("seed", range(15)) +def test_random_three_table_joins_agree(seed): + rng = random.Random(seed) + n_dim = rng.randint(2, 12) + n_tiny = rng.randint(1, 5) + n_facts = rng.randint(0, 120) + facts = [ + (i, rng.randrange(n_dim + 2), rng.randrange(n_tiny + 2), rng.randrange(50)) + for i in range(n_facts) + ] + catalog = catalog_with( + f=(["id", "dim_id", "tiny_id", "amount"], facts), + d=(["id", "label"], [(i, f"d{i}") for i in range(n_dim)]), + t=(["id", "label"], [(i, f"t{i}") for i in range(n_tiny)]), + ) + sql = """ + SELECT f.id, d.label, t.label + FROM f + JOIN d ON f.dim_id = d.id + JOIN t ON f.tiny_id = t.id + """ + assert sorted(execute(catalog, sql)[0]) == sorted( + execute(catalog, sql, reorder=False)[0] + ) + + +# ----------------------------------------------------------- cost model units + + +def test_analyze_counts_rows_and_distinct_values(): + schema = Schema((Column("a"), Column("b"))) + stats = analyze(schema, [(1, "x"), (1, "y"), (2, "x"), (None, "x")]) + assert stats.row_count == 4 + assert stats.distinct("a") == 2 # NULL is not a distinct value + assert stats.distinct("b") == 2 + + +def test_equality_selectivity_follows_distinct_count(): + schema = Schema((Column("a"),)) + stats = analyze(schema, [(i % 10,) for i in range(100)]) + predicate = BinaryOp("=", ColumnRef("a"), Literal(3)) + assert estimate_selectivity(predicate, stats) == pytest.approx(0.1) + + +def test_and_multiplies_selectivity(): + schema = Schema((Column("a"), Column("b"))) + stats = analyze(schema, [(i % 10, i % 4) for i in range(100)]) + both = BinaryOp( + "AND", + BinaryOp("=", ColumnRef("a"), Literal(1)), + BinaryOp("=", ColumnRef("b"), Literal(1)), + ) + assert estimate_selectivity(both, stats) == pytest.approx(0.1 * 0.25) + + +def test_join_estimate_divides_by_the_wider_key(): + # 100 rows joined to 10 rows on a key with 10 distinct values -> 100. + assert estimate_join_rows(100, 10, 10, 10) == pytest.approx(100) + # A more selective key on either side means fewer matches. + assert estimate_join_rows(100, 100, 100, 10) == pytest.approx(100) + + +def test_join_estimate_never_returns_zero(): + assert estimate_join_rows(0, 0, 1, 1) >= 1.0 diff --git a/tinyquery/cost.py b/tinyquery/cost.py new file mode 100644 index 0000000..b1ac77d --- /dev/null +++ b/tinyquery/cost.py @@ -0,0 +1,247 @@ +"""Table statistics and a cost model for choosing a join order. + +The planner used to join tables in the order they were written. That is fine +until the order is wrong, at which point an intermediate result blows up and +every later join pays for it. This module decides the order instead. + +Three pieces: + + * `analyze` walks a table once and records its row count and how many + distinct values each column holds. That is what a real engine gets from + ANALYZE, except a real engine samples and this one can afford to look at + everything, because the table is already in memory. + + * `estimate_*` turns those counts into a guess at how many rows a filter or + a join will produce. Textbook formulas, and they are guesses: the point of + a cost model is to rank plans, not to be right. + + * `choose_join_order` searches left-deep plans with the Selinger dynamic + program, keeping the cheapest way to produce each subset of tables. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from itertools import combinations +from typing import Iterable, Sequence + +from tinyquery.expr import BinaryOp, ColumnRef, Expr, Literal, NotOp +from tinyquery.schema import Row, Schema + +# Used when we have no basis for a guess. Postgres uses a similar constant. +DEFAULT_SELECTIVITY = 0.1 +# Range comparisons against an unknown distribution. +RANGE_SELECTIVITY = 1.0 / 3.0 +# Beyond this many tables the subset DP costs more than the plan it saves. +MAX_TABLES_TO_REORDER = 10 + + +@dataclass(frozen=True) +class TableStats: + """What ANALYZE would record for one table.""" + + row_count: int + ndv: dict[str, int] # column name -> number of distinct non-null values + + def distinct(self, column: str) -> int: + """Distinct values in a column, falling back to "all rows differ".""" + return max(1, self.ndv.get(column, self.row_count)) + + +def analyze(schema: Schema, rows: Sequence[Row]) -> TableStats: + """One pass over the table, counting rows and distinct values per column.""" + seen: list[set] = [set() for _ in schema.columns] + for row in rows: + for i, value in enumerate(row): + if value is not None: + seen[i].add(value) + return TableStats( + row_count=len(rows), + ndv={col.name: len(seen[i]) for i, col in enumerate(schema.columns)}, + ) + + +def estimate_selectivity(predicate: Expr, stats: TableStats) -> float: + """Fraction of rows a predicate is expected to keep, in [0, 1].""" + if isinstance(predicate, BinaryOp): + if predicate.op == "AND": + return estimate_selectivity(predicate.left, stats) * estimate_selectivity( + predicate.right, stats + ) + if predicate.op == "OR": + left = estimate_selectivity(predicate.left, stats) + right = estimate_selectivity(predicate.right, stats) + # Inclusion-exclusion, assuming the two are independent. + return min(1.0, left + right - left * right) + if predicate.op in ("=", "!=", "<>"): + column = _column_of(predicate) + if column is None: + return DEFAULT_SELECTIVITY + equality = 1.0 / stats.distinct(column) + return equality if predicate.op == "=" else 1.0 - equality + if predicate.op in ("<", "<=", ">", ">="): + return RANGE_SELECTIVITY + if isinstance(predicate, NotOp): + return 1.0 - estimate_selectivity(predicate.expr, stats) + return DEFAULT_SELECTIVITY + + +def estimate_filtered_rows(predicates: Iterable[Expr], stats: TableStats) -> float: + rows = float(stats.row_count) + for predicate in predicates: + rows *= estimate_selectivity(predicate, stats) + return max(1.0, rows) + + +def estimate_join_rows( + left_rows: float, right_rows: float, left_ndv: int, right_ndv: int +) -> float: + """Textbook equijoin estimate: |A| * |B| / max(distinct keys on either side). + + The intuition is that the side with more distinct keys spreads its rows + thinner, so it decides how many matches an average row on the other side + finds. Assumes keys on the smaller side all appear on the larger one, which + is exactly the assumption that makes estimates drift on real data. + """ + return max(1.0, left_rows * right_rows / max(1, left_ndv, right_ndv)) + + +@dataclass(frozen=True) +class JoinEdge: + """An equijoin predicate, as a link between two table aliases.""" + + left_alias: str + left_key: Expr + right_alias: str + right_key: Expr + + def other(self, alias: str) -> str: + return self.right_alias if alias == self.left_alias else self.left_alias + + def touches(self, alias: str) -> bool: + return alias in (self.left_alias, self.right_alias) + + def key_for(self, alias: str) -> Expr: + return self.left_key if alias == self.left_alias else self.right_key + + +@dataclass(frozen=True) +class JoinStep: + """One join in the chosen order: add `alias` to what we already have.""" + + alias: str + edge: JoinEdge + + +@dataclass(frozen=True) +class JoinPlan: + order: tuple[str, ...] + steps: tuple[JoinStep, ...] + estimated_rows: float + cost: float + + +def choose_join_order( + aliases: Sequence[str], + base_rows: dict[str, float], + key_ndv: dict[tuple[str, str], int], + edges: Sequence[JoinEdge], +) -> JoinPlan | None: + """Cheapest left-deep join order, or None if we should not reorder. + + `key_ndv` maps (alias, column) to distinct values in that base column, used + to estimate how many rows a join produces. + + Cost is the number of rows a hash join has to touch, which is the build + side plus the probe side. Summing that over the whole plan rewards orders + that keep intermediate results small, which is the entire point. + + Returns None when there is nothing to decide (fewer than two joins) or when + the search would be too large to be worth it. + """ + n = len(aliases) + if n < 3 or n > MAX_TABLES_TO_REORDER: + # With two tables there is only one left-deep shape, so nothing to pick. + return None + if not _is_connected(aliases, edges): + # A cross product somewhere; leave the written order alone. + return None + + # best[subset] = (cost so far, estimated rows, order, steps) + best: dict[frozenset[str], tuple[float, float, tuple[str, ...], tuple[JoinStep, ...]]] = {} + for alias in aliases: + best[frozenset([alias])] = (0.0, base_rows[alias], (alias,), ()) + + for size in range(2, n + 1): + for subset in combinations(aliases, size): + key = frozenset(subset) + for alias in subset: + prefix = key - {alias} + if prefix not in best: + continue + edge = _connecting_edge(prefix, alias, edges) + if edge is None: + continue # would be a cross product at this step + prefix_cost, prefix_rows, order, steps = best[prefix] + left_alias = edge.other(alias) + rows = estimate_join_rows( + prefix_rows, + base_rows[alias], + key_ndv.get((left_alias, _column_name(edge.key_for(left_alias))), 1), + key_ndv.get((alias, _column_name(edge.key_for(alias))), 1), + ) + cost = prefix_cost + prefix_rows + base_rows[alias] + current = best.get(key) + if current is None or cost < current[0]: + best[key] = ( + cost, + rows, + order + (alias,), + steps + (JoinStep(alias, edge),), + ) + + final = best.get(frozenset(aliases)) + if final is None: + return None + cost, rows, order, steps = final + return JoinPlan(order=order, steps=steps, estimated_rows=rows, cost=cost) + + +def _connecting_edge( + have: frozenset[str], alias: str, edges: Sequence[JoinEdge] +) -> JoinEdge | None: + for edge in edges: + if edge.touches(alias) and edge.other(alias) in have: + return edge + return None + + +def _is_connected(aliases: Sequence[str], edges: Sequence[JoinEdge]) -> bool: + if not aliases: + return False + reached = {aliases[0]} + changed = True + while changed: + changed = False + for edge in edges: + for a, b in ( + (edge.left_alias, edge.right_alias), + (edge.right_alias, edge.left_alias), + ): + if a in reached and b not in reached: + reached.add(b) + changed = True + return reached.issuperset(aliases) + + +def _column_of(predicate: BinaryOp) -> str | None: + """Column name in a `column literal` comparison, if it is one.""" + if isinstance(predicate.left, ColumnRef) and isinstance(predicate.right, Literal): + return predicate.left.name + if isinstance(predicate.right, ColumnRef) and isinstance(predicate.left, Literal): + return predicate.right.name + return None + + +def _column_name(expr: Expr) -> str: + return expr.name if isinstance(expr, ColumnRef) else str(expr) diff --git a/tinyquery/engine.py b/tinyquery/engine.py index 5793cf8..37677d9 100644 --- a/tinyquery/engine.py +++ b/tinyquery/engine.py @@ -7,8 +7,8 @@ from tinyquery.schema import Row, Schema -def compile_sql(catalog: Catalog, sql: str) -> Operator: - return plan(catalog, parse(sql)) +def compile_sql(catalog: Catalog, sql: str, reorder: bool = True) -> Operator: + return plan(catalog, parse(sql), reorder=reorder) def collect(operator: Operator) -> tuple[list[Row], Schema]: @@ -25,12 +25,12 @@ def collect(operator: Operator) -> tuple[list[Row], Schema]: return rows, operator.schema -def execute(catalog: Catalog, sql: str) -> tuple[list[Row], Schema]: - return collect(compile_sql(catalog, sql)) +def execute(catalog: Catalog, sql: str, reorder: bool = True) -> tuple[list[Row], Schema]: + return collect(compile_sql(catalog, sql, reorder=reorder)) -def explain(catalog: Catalog, sql: str) -> str: - return format_explain(compile_sql(catalog, sql)) +def explain(catalog: Catalog, sql: str, reorder: bool = True) -> str: + return format_explain(compile_sql(catalog, sql, reorder=reorder)) def format_explain(operator: Operator, indent: int = 0) -> str: diff --git a/tinyquery/operators.py b/tinyquery/operators.py index 7f0a5ab..3355c1b 100644 --- a/tinyquery/operators.py +++ b/tinyquery/operators.py @@ -179,6 +179,43 @@ def children(self) -> list[Operator]: return [self.left, self.right] +class Reorder(Operator): + """Permute columns back into the order the query declared them. + + The join optimiser is free to execute joins in whatever order is cheapest, + which moves columns around: joining c before b puts c's columns in the + middle of the row. Everything above the join still expects `FROM a JOIN b + JOIN c` to produce a's columns, then b's, then c's, and SELECT * reads the + schema positionally. + + Project cannot do this job because it flattens columns to bare names and + drops the table qualifier, which would break `o.region` further up. + """ + + def __init__(self, child: Operator, indices: list[int], schema: Schema) -> None: + self.child = child + self.indices = indices + self.schema = schema + + def open(self) -> None: + self.child.open() + + def next_row(self) -> Row | None: + row = self.child.next_row() + if row is None: + return None + return tuple(row[i] for i in self.indices) + + def close(self) -> None: + self.child.close() + + def explain_label(self) -> str: + return "Reorder to declared column order" + + def children(self) -> list[Operator]: + return [self.child] + + class NestedLoopJoin(Operator): """Inner equijoin that rescans the right side for every left row. diff --git a/tinyquery/planner.py b/tinyquery/planner.py index 669d9c4..c956ece 100644 --- a/tinyquery/planner.py +++ b/tinyquery/planner.py @@ -3,6 +3,13 @@ from tinyquery.catalog import Catalog, Table from tinyquery.errors import TinyQueryError from tinyquery.expr import Aggregate, BinaryOp, ColumnRef, Expr +from tinyquery.cost import ( + JoinEdge, + JoinPlan, + analyze, + choose_join_order, + estimate_filtered_rows, +) from tinyquery.operators import ( Distinct, Filter, @@ -11,6 +18,7 @@ Limit, Operator, Project, + Reorder, Scan, Sort, TopK, @@ -20,8 +28,12 @@ class Planner: - def __init__(self, catalog: Catalog) -> None: + def __init__(self, catalog: Catalog, reorder: bool = True) -> None: self.catalog = catalog + # Off means "join in the order written", which is what the planner did + # before the cost model existed. Tests and the benchmark use it to + # compare the two plans on identical inputs. + self.reorder = reorder def plan(self, query: Query) -> Operator: # Validate WHERE against the full joined schema first so ambiguous @@ -33,18 +45,7 @@ def plan(self, query: Query) -> Operator: for pred in conjuncts: _require_resolvable(pred, full_schema) - node = self._scan(query.from_table) - pushed, conjuncts = _take_resolvable(conjuncts, node.schema) - node = _with_filter(node, pushed) - - for join in query.joins: - right = self._scan(join.table) - pushed, conjuncts = _take_resolvable(conjuncts, right.schema) - right = _with_filter(right, pushed) - left_key, right_key = self._bind_join_keys( - node.schema, right.schema, join.left_key, join.right_key - ) - node = HashJoin(node, right, left_key, right_key) + node, conjuncts = self._plan_joins(query, conjuncts) # Cross-table predicates (and ORs we could not split) stay above the join. node = _with_filter(node, conjuncts) @@ -91,6 +92,83 @@ def plan(self, query: Query) -> Operator: node = Limit(node, query.limit) return node + def _plan_joins( + self, query: Query, conjuncts: list[Expr] + ) -> tuple[Operator, list[Expr]]: + """Build the join tree, reordering it when the cost model says to. + + Filters are pushed onto each base table first, because a filter that + removes 90% of a table changes which join order is cheapest. + """ + refs = [query.from_table] + [join.table for join in query.joins] + inputs: dict[str, Operator] = {} + filters: dict[str, list[Expr]] = {} + for ref in refs: + scan = self._scan(ref) + pushed, conjuncts = _take_resolvable(conjuncts, scan.schema) + filters[ref.alias] = pushed + inputs[ref.alias] = _with_filter(scan, pushed) + + plan = self._choose_order(query, refs, filters) + if plan is None: + node = self._join_in_written_order(query, inputs) + return node, conjuncts + + node = self._join_in_plan_order(query, inputs, plan) + return _restore_declared_order(node, refs, inputs), conjuncts + + def _join_in_written_order( + self, query: Query, inputs: dict[str, Operator] + ) -> Operator: + node = inputs[query.from_table.alias] + for join in query.joins: + right = inputs[join.table.alias] + left_key, right_key = self._bind_join_keys( + node.schema, right.schema, join.left_key, join.right_key + ) + node = HashJoin(node, right, left_key, right_key) + return node + + def _join_in_plan_order( + self, query: Query, inputs: dict[str, Operator], plan: JoinPlan + ) -> Operator: + node = inputs[plan.order[0]] + for step in plan.steps: + right = inputs[step.alias] + left_key, right_key = self._bind_join_keys( + node.schema, right.schema, step.edge.left_key, step.edge.right_key + ) + node = HashJoin(node, right, left_key, right_key) + return node + + def _choose_order( + self, query: Query, refs: list[TableRef], filters: dict[str, list[Expr]] + ) -> JoinPlan | None: + """Ask the cost model for an order, or None to keep the written one.""" + if not self.reorder: + return None + edges: list[JoinEdge] = [] + for join in query.joins: + left = _qualified_ref(join.left_key) + right = _qualified_ref(join.right_key) + if left is None or right is None: + # A key we cannot attribute to one table; do not reorder. + return None + edges.append( + JoinEdge(left[0], join.left_key, right[0], join.right_key) + ) + + base_rows: dict[str, float] = {} + key_ndv: dict[tuple[str, str], int] = {} + for ref in refs: + table = self.catalog.get(ref.name) + stats = analyze(table.schema, table.rows) + base_rows[ref.alias] = estimate_filtered_rows(filters[ref.alias], stats) + for column in table.schema.columns: + key_ndv[(ref.alias, column.name)] = stats.distinct(column.name) + + return choose_join_order([ref.alias for ref in refs], base_rows, key_ndv, edges) + def _scan(self, ref: TableRef) -> Scan: table = self.catalog.get(ref.name) schema = _alias_schema(table, ref.alias) @@ -191,8 +269,39 @@ def _apply_distinct_order_limit(self, node: Operator, query: Query) -> Operator: return self._apply_order_limit(node, query) -def plan(catalog: Catalog, query: Query) -> Operator: - return Planner(catalog).plan(query) +def _qualified_ref(expr: Expr) -> tuple[str, str] | None: + """(table alias, column) for a qualified column reference, else None.""" + if isinstance(expr, ColumnRef) and expr.table is not None: + return expr.table, expr.name + return None + + +def _restore_declared_order( + node: Operator, refs: list[TableRef], inputs: dict[str, Operator] +) -> Operator: + """Put columns back where `FROM a JOIN b JOIN c` says they belong. + + Executing joins out of order moves columns around inside the row. Anything + reading positionally above this point, SELECT * in particular, expects the + declared order, so undo the permutation before handing the rows up. + """ + declared: list[tuple[str | None, str]] = [] + for ref in refs: + for column in inputs[ref.alias].schema.columns: + declared.append((column.table, column.name)) + + executed = [(column.table, column.name) for column in node.schema.columns] + if executed == declared: + return node + + positions = {key: i for i, key in enumerate(executed)} + indices = [positions[key] for key in declared] + schema = Schema(tuple(Column(name, table=table) for table, name in declared)) + return Reorder(node, indices, schema) + + +def plan(catalog: Catalog, query: Query, reorder: bool = True) -> Operator: + return Planner(catalog, reorder=reorder).plan(query) def _alias_schema(table: Table, alias: str) -> Schema: