From b3d1766f302a2f6f10b27fe5f6264247b27895f0 Mon Sep 17 00:00:00 2001 From: SpookyJumpyBeans <116844292+SpookyJumpyBeans@users.noreply.github.com> Date: Sat, 3 Oct 2026 21:57:33 -0400 Subject: [PATCH] Add a pushdown toggle, and name each operator in the plan JSON --no-pushdown (pushdown=False in the engine) keeps every WHERE predicate in one Filter above the joins. The cost model then sees each table at full size too, which is the honest comparison: without pushdown the planner has no filtered row counts to order joins by. PlanStats now records the operator class, so a frontend can style a node by type without parsing labels like "Reorder to declared column order". --- README.md | 5 +-- tests/test_explain_analyze.py | 12 ++++++- tests/test_pushdown.py | 64 +++++++++++++++++++++++++++++++++++ tinyquery/cli.py | 12 +++++-- tinyquery/engine.py | 24 ++++++++----- tinyquery/planner.py | 17 +++++++--- tinyquery/profiler.py | 3 ++ 7 files changed, 119 insertions(+), 18 deletions(-) diff --git a/README.md b/README.md index 2038ecf..25bbe41 100644 --- a/README.md +++ b/README.md @@ -172,7 +172,7 @@ Filter t.k = 1 (rows est=25 actual=1 time=0.02ms self=0.01ms) <-- estimate o Estimates are recomputed bottom-up over the finished plan using the same statistics and formulas the join orderer uses. Timing is inclusive of children, and `self` subtracts them. `--analyze --json` emits the plan and rows -as JSON. +as JSON, with each node's operator class alongside its label. Profiling works from outside the operators: for one run, each instance gets its `open`, `next_row`, and `close` wrapped with counters, and the originals @@ -197,7 +197,8 @@ python -m tinyquery --analyze "SELECT o.region, SUM(l.revenue) AS total FROM ord `--explain` prints the plan without running it. `--analyze` runs it and reports estimated vs actual rows per operator. `--no-reorder` turns off the cost-based -join order, for comparison. +join order, and `--no-pushdown` keeps every `WHERE` filter above the joins, for +comparison. `--data examples` is the default. Each `*.csv` becomes a table named after the file. diff --git a/tests/test_explain_analyze.py b/tests/test_explain_analyze.py index eb0e30a..f3136ff 100644 --- a/tests/test_explain_analyze.py +++ b/tests/test_explain_analyze.py @@ -135,7 +135,17 @@ def test_plan_serialises_to_json(): plan = explain_analyze(star_catalog(), THREE_TABLE_SQL).plan data = json.loads(json.dumps(plan.to_dict())) assert data["actual_rows"] == plan.actual_rows - assert {"label", "estimated_rows", "actual_rows", "total_ms", "self_ms", "children"} <= set(data) + assert { + "label", "operator", "estimated_rows", "actual_rows", "total_ms", "self_ms", "children" + } <= set(data) + operators = {node["operator"] for node in _json_nodes(data)} + assert {"Project", "Reorder", "HashJoin", "Filter", "Scan"} <= operators + + +def _json_nodes(data): + yield data + for child in data["children"]: + yield from _json_nodes(child) def test_cli_analyze_prints_estimates_and_actuals(capsys): diff --git a/tests/test_pushdown.py b/tests/test_pushdown.py index 828c638..dffb1fb 100644 --- a/tests/test_pushdown.py +++ b/tests/test_pushdown.py @@ -64,3 +64,67 @@ def test_pushdown_does_not_change_results(): ) by_region = {row[0]: row[1] for row in rows} assert by_region == {"west": 10, "east": 20, "north": 3} + + +def test_without_pushdown_the_filter_stays_above_the_join(): + plan = explain( + sample_catalog(), + """ + SELECT o.region, l.revenue + FROM orders o + JOIN lineitem l ON o.id = l.order_id + WHERE o.year = 2024 AND l.sku = 'widget' + """, + pushdown=False, + ) + lines = plan.splitlines() + filter_idx = next(i for i, line in enumerate(lines) if "Filter" in line) + join_idx = next(i for i, line in enumerate(lines) if "HashJoin" in line) + assert filter_idx < join_idx + assert "Filter o.year = 2024 AND l.sku = 'widget'" in plan + assert sum("Filter" in line for line in lines) == 1 + + +def test_pushdown_off_returns_the_same_rows(): + sql = """ + SELECT o.region, SUM(l.revenue) AS total + FROM orders o + JOIN lineitem l ON o.id = l.order_id + WHERE o.year = 2024 AND l.sku = 'widget' + GROUP BY o.region + """ + on, _ = execute(sample_catalog(), sql) + off, _ = execute(sample_catalog(), sql, pushdown=False) + assert sorted(on) == sorted(off) + + +def test_pushdown_off_feeds_the_join_more_rows(): + from tinyquery.engine import explain_analyze + + sql = """ + SELECT o.region, l.revenue + FROM orders o + JOIN lineitem l ON o.id = l.order_id + WHERE o.year = 2024 + """ + + def join_input_rows(pushdown): + plan = explain_analyze(sample_catalog(), sql, pushdown=pushdown).plan + join = plan + while join.operator != "HashJoin": + join = join.children[0] + return sum(child.actual_rows for child in join.children) + + assert join_input_rows(pushdown=True) < join_input_rows(pushdown=False) + + +def test_cli_no_pushdown_flag(capsys): + from tinyquery.cli import main + + sql = ( + "SELECT o.region, l.revenue FROM orders o " + "JOIN lineitem l ON o.id = l.order_id WHERE o.year = 2024" + ) + assert main(["--explain", "--no-pushdown", sql]) == 0 + lines = capsys.readouterr().out.splitlines() + assert lines[1].strip().startswith("Filter o.year = 2024") diff --git a/tinyquery/cli.py b/tinyquery/cli.py index c8857f1..46e0036 100644 --- a/tinyquery/cli.py +++ b/tinyquery/cli.py @@ -56,6 +56,11 @@ def main(argv: list[str] | None = None) -> int: action="store_true", help="join tables in the order written instead of asking the cost model", ) + parser.add_argument( + "--no-pushdown", + action="store_true", + help="keep WHERE filters above the joins instead of pushing them down", + ) args = parser.parse_args(argv) catalog = Catalog() @@ -81,9 +86,10 @@ def main(argv: list[str] | None = None) -> int: print(f"-- {name.strip()} at version {version}", file=sys.stderr) reorder = not args.no_reorder + pushdown = not args.no_pushdown try: if args.analyze: - result = explain_analyze(catalog, args.sql, reorder=reorder) + result = explain_analyze(catalog, args.sql, reorder=reorder, pushdown=pushdown) if args.json: print(json.dumps({ "columns": result.schema.names(), @@ -96,9 +102,9 @@ def main(argv: list[str] | None = None) -> int: print(f"({n} row{'s' if n != 1 else ''})") return 0 if args.explain: - print(explain(catalog, args.sql, reorder=reorder)) + print(explain(catalog, args.sql, reorder=reorder, pushdown=pushdown)) return 0 - rows, schema = execute(catalog, args.sql, reorder=reorder) + rows, schema = execute(catalog, args.sql, reorder=reorder, pushdown=pushdown) print(_format_table(rows, schema)) return 0 except TinyQueryError as exc: diff --git a/tinyquery/engine.py b/tinyquery/engine.py index 0a77f60..7b13b52 100644 --- a/tinyquery/engine.py +++ b/tinyquery/engine.py @@ -8,8 +8,10 @@ from tinyquery.schema import Row, Schema -def compile_sql(catalog: Catalog, sql: str, reorder: bool = True) -> Operator: - return plan(catalog, parse(sql), reorder=reorder) +def compile_sql( + catalog: Catalog, sql: str, reorder: bool = True, pushdown: bool = True +) -> Operator: + return plan(catalog, parse(sql), reorder=reorder, pushdown=pushdown) def collect(operator: Operator) -> tuple[list[Row], Schema]: @@ -26,12 +28,16 @@ def collect(operator: Operator) -> tuple[list[Row], Schema]: return rows, operator.schema -def execute(catalog: Catalog, sql: str, reorder: bool = True) -> tuple[list[Row], Schema]: - return collect(compile_sql(catalog, sql, reorder=reorder)) +def execute( + catalog: Catalog, sql: str, reorder: bool = True, pushdown: bool = True +) -> tuple[list[Row], Schema]: + return collect(compile_sql(catalog, sql, reorder=reorder, pushdown=pushdown)) -def explain(catalog: Catalog, sql: str, reorder: bool = True) -> str: - return format_explain(compile_sql(catalog, sql, reorder=reorder)) +def explain( + catalog: Catalog, sql: str, reorder: bool = True, pushdown: bool = True +) -> str: + return format_explain(compile_sql(catalog, sql, reorder=reorder, pushdown=pushdown)) def format_explain(operator: Operator, indent: int = 0) -> str: @@ -41,6 +47,8 @@ def format_explain(operator: Operator, indent: int = 0) -> str: return "\n".join(lines) -def explain_analyze(catalog: Catalog, sql: str, reorder: bool = True) -> AnalyzeResult: +def explain_analyze( + catalog: Catalog, sql: str, reorder: bool = True, pushdown: bool = True +) -> AnalyzeResult: """Run the query and return its rows plus per-operator estimates and timings.""" - return profile_plan(compile_sql(catalog, sql, reorder=reorder)) + return profile_plan(compile_sql(catalog, sql, reorder=reorder, pushdown=pushdown)) diff --git a/tinyquery/planner.py b/tinyquery/planner.py index c956ece..f0912ae 100644 --- a/tinyquery/planner.py +++ b/tinyquery/planner.py @@ -28,12 +28,17 @@ class Planner: - def __init__(self, catalog: Catalog, reorder: bool = True) -> None: + def __init__( + self, catalog: Catalog, reorder: bool = True, pushdown: 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 + # Off means every WHERE predicate stays in one Filter above the joins, + # so the cost model also sees each table at its full size. + self.pushdown = pushdown def plan(self, query: Query) -> Operator: # Validate WHERE against the full joined schema first so ambiguous @@ -105,7 +110,9 @@ def _plan_joins( filters: dict[str, list[Expr]] = {} for ref in refs: scan = self._scan(ref) - pushed, conjuncts = _take_resolvable(conjuncts, scan.schema) + pushed: list[Expr] = [] + if self.pushdown: + pushed, conjuncts = _take_resolvable(conjuncts, scan.schema) filters[ref.alias] = pushed inputs[ref.alias] = _with_filter(scan, pushed) @@ -300,8 +307,10 @@ def _restore_declared_order( return Reorder(node, indices, schema) -def plan(catalog: Catalog, query: Query, reorder: bool = True) -> Operator: - return Planner(catalog, reorder=reorder).plan(query) +def plan( + catalog: Catalog, query: Query, reorder: bool = True, pushdown: bool = True +) -> Operator: + return Planner(catalog, reorder=reorder, pushdown=pushdown).plan(query) def _alias_schema(table: Table, alias: str) -> Schema: diff --git a/tinyquery/profiler.py b/tinyquery/profiler.py index f547e82..57c58c8 100644 --- a/tinyquery/profiler.py +++ b/tinyquery/profiler.py @@ -51,6 +51,7 @@ class PlanStats: """One operator's numbers, with its children's beneath it.""" label: str + operator: str # class name, e.g. "HashJoin", so a frontend need not parse labels estimated_rows: float actual_rows: int total_ms: float # this operator plus everything beneath it @@ -67,6 +68,7 @@ def misestimate(self) -> float: def to_dict(self) -> dict[str, Any]: return { "label": self.label, + "operator": self.operator, "estimated_rows": round(self.estimated_rows, 1), "actual_rows": self.actual_rows, "total_ms": round(self.total_ms, 3), @@ -165,6 +167,7 @@ def _build( self_ms = max(0.0, total_ms - sum(child.total_ms for child in children)) return PlanStats( label=op.explain_label(), + operator=type(op).__name__, estimated_rows=estimates[id(op)], actual_rows=rows, total_ms=total_ms,