Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 31 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
53 changes: 53 additions & 0 deletions benchmarks/join_benchmark.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -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


Expand Down
188 changes: 188 additions & 0 deletions tests/test_join_order.py
Original file line number Diff line number Diff line change
@@ -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
Loading