Skip to content

Commit 5e85bc2

Browse files
rustyconoverclaude
andcommitted
feat(scan-planning): recursive may_match, flat fixture paths, comma branch_filter fixture
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 7e1f6ea commit 5e85bc2

3 files changed

Lines changed: 107 additions & 43 deletions

File tree

‎tests/test_scan_planning.py‎

Lines changed: 37 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -200,6 +200,38 @@ def test_may_match_prunes_by_min_max(predicates: Any, matching_days: list[int])
200200
assert days == matching_days
201201

202202

203+
def test_may_match_or_and_in() -> None:
204+
def or_filters(*days: int) -> ScanPlanningFilters:
205+
exprs = [
206+
{
207+
"node": "comparison",
208+
"op": "eq",
209+
"left": {"node": "column_ref", "column_index": 0, "column_name": "event_date"},
210+
"right": {"node": "literal", "value_ref": i},
211+
}
212+
for i in range(len(days))
213+
]
214+
document = {
215+
"encoding": "vgi.filters.v2",
216+
"semantics": "vgi.duckdb.standard.v1",
217+
"kind": "snapshot",
218+
"predicates": [
219+
{
220+
"id": "query:0",
221+
"revision": 0,
222+
"mode": "advisory",
223+
"source": "query",
224+
"expression": {"node": "or", "children": exprs},
225+
}
226+
],
227+
}
228+
payloads = [value_payload(i, D(2026, 10, d), pa.date32()) for i, d in enumerate(days)]
229+
return ScanPlanningFilters(serialize_filter_batch(build_filter_batch(document, payloads)), lambda: COLUMNS)
230+
231+
filters = or_filters(1, 3)
232+
assert [d for d in range(1, 6) if filters.may_match(_day_stats(D(2026, 10, d)))] == [1, 3]
233+
234+
203235
def test_may_match_keeps_candidates_without_bounds() -> None:
204236
filters = _filters(("event_date", "eq", D(2026, 10, 4)))
205237
assert filters.may_match([ColumnStatistics("event_date")])
@@ -233,7 +265,7 @@ def _attach(client: Any) -> Any:
233265

234266

235267
def _last_plan(tmp_dir: str) -> dict[str, Any]:
236-
with open(f"{tmp_dir}/planned_days/last_plan.json", encoding="utf-8") as fh:
268+
with open(f"{tmp_dir}/planned_days_last_plan.json", encoding="utf-8") as fh:
237269
return json.load(fh) # type: ignore[no-any-return]
238270

239271

@@ -255,7 +287,10 @@ def test_worker_hook_receives_filters_and_prunes(client: Any) -> None:
255287
)
256288
assert len(result.branches) == 1
257289
files = result.branches[0].positional_arguments[0].as_py()
258-
assert [f.rsplit("/", 1)[1] for f in files] == ["2026-10-04.parquet", "2026-10-05.parquet"]
290+
assert [f.rsplit("/", 1)[1] for f in files] == [
291+
"planned_days_2026-10-04.parquet",
292+
"planned_days_2026-10-05.parquet",
293+
]
259294
assert result.branches[0].row_count == 20
260295
plan = _last_plan(_BRANCH_DIR)
261296
assert plan == {"received_filters": True, "days": ["2026-10-04", "2026-10-05"]}

‎vgi/_test_fixtures/worker.py‎

Lines changed: 23 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -371,15 +371,14 @@
371371
_BRANCH_DIR = (os.environ.get("VGI_TEST_BRANCH_DIR") or tempfile.gettempdir()).replace("\\", "/").rstrip("/")
372372

373373
# Protocol 3.2 filtered scan planning fixtures (test/sql/integration/catalog/scan_planning_*.test).
374-
# Five days of data, one parquet file per day under {_BRANCH_DIR}/planned_days/. The tests create
374+
# Five days of data, one parquet file per day: {_BRANCH_DIR}/planned_days_<day>.parquet. The tests create
375375
# the files for the first four days only: the 2026-10-05 file never exists, so any scan that fails
376376
# to prune that day errors with "No files found" — a passing query proves the pruning happened.
377377
_PLANNED_DAYS: tuple[datetime.date, ...] = tuple(datetime.date(2026, 10, d) for d in range(1, 6))
378-
_PLANNED_DIR = f"{_BRANCH_DIR}/planned_days"
379378

380379

381380
def _planned_day_file(day: datetime.date) -> str:
382-
return f"{_PLANNED_DIR}/{day.isoformat()}.parquet"
381+
return f"{_BRANCH_DIR}/planned_days_{day.isoformat()}.parquet"
383382

384383

385384
def _planned_day_stats(day: datetime.date) -> list[ColumnStatistics]:
@@ -1166,6 +1165,13 @@ def _fixture_columns(name: str, columns: pa.Schema, version: int = 3) -> pa.Sche
11661165
columns=schema(event_date=pa.date32(), n=pa.int64()),
11671166
comment="Protocol 3.2: pruning by branch_filter contradiction — scan_planning_branch_filter.test",
11681167
),
1168+
# Protocol 3.2: branch_filter must be ONE expression. "n < 5, n > 2"
1169+
# parses as two; 3.1 clients silently kept the first.
1170+
Table(
1171+
name="multi_branch_comma_filter",
1172+
columns=schema(n=pa.int64()),
1173+
comment="Protocol 3.2: multi-expression branch_filter is rejected",
1174+
),
11691175
Table(
11701176
name="multi_branch_numbers",
11711177
columns=schema(n=pa.int64()),
@@ -1773,6 +1779,19 @@ def table_scan_branches_get(
17731779

17741780
if [component.lower() for component in schema_path] == ["data"] and name.lower().startswith("planned_days"):
17751781
return _planned_days_branches(name.lower(), None)
1782+
if [component.lower() for component in schema_path] == ["data"] and name.lower() == "multi_branch_comma_filter":
1783+
return ScanBranchesResult(
1784+
branches=[
1785+
ScanBranch(
1786+
function_name="sequence",
1787+
positional_arguments=[pa.scalar(10)],
1788+
named_arguments={},
1789+
branch_filter="n < 5, n > 2",
1790+
schema_path=["main"],
1791+
)
1792+
],
1793+
required_extensions=[],
1794+
)
17761795

17771796
# multi_branch_numbers: two arms, each sequence(50). Union size = 100.
17781797
if [component.lower() for component in schema_path] == ["data"] and name.lower() == "multi_branch_numbers":
@@ -2370,8 +2389,7 @@ def _planned_days_branches(name: str, filters: ScanPlanningFilters | None) -> Sc
23702389
if name == "planned_days":
23712390
days = [d for d in _PLANNED_DAYS if filters is None or filters.may_match(_planned_day_stats(d))]
23722391
# Record what the worker saw so tests can assert the predicates arrived.
2373-
os.makedirs(_PLANNED_DIR, exist_ok=True)
2374-
with open(f"{_PLANNED_DIR}/last_plan.json", "w", encoding="utf-8") as fh:
2392+
with open(f"{_BRANCH_DIR}/planned_days_last_plan.json", "w", encoding="utf-8") as fh:
23752393
json.dump({"received_filters": filters is not None, "days": [d.isoformat() for d in days]}, fh)
23762394
if not days:
23772395
return ScanBranchesResult(branches=[], required_extensions=["parquet"])

‎vgi/scan_planning.py‎

Lines changed: 47 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -61,8 +61,8 @@ def may_match(self, statistics: Iterable[ColumnStatistics]) -> bool:
6161
returning branches. Columns or predicates this helper cannot reason
6262
about count as "may match", so the answer errs towards keeping data.
6363
"""
64-
filters = self.decode()
65-
return all(_column_may_match(filters, stat) for stat in statistics)
64+
by_name = {stat.column_name: stat for stat in statistics}
65+
return all(_filter_may_match(f, by_name) for f in self.decode().filters)
6666

6767

6868
def _as_py(value: pa.Scalar[Any] | None) -> Any:
@@ -71,43 +71,54 @@ def _as_py(value: pa.Scalar[Any] | None) -> Any:
7171
return value.as_py()
7272

7373

74-
def _column_may_match(filters: PushdownFilters, stat: ColumnStatistics) -> bool:
75-
lo, hi = _as_py(stat.min), _as_py(stat.max)
76-
if not stat.has_not_null:
77-
# Entirely NULL: comparison, equality and IN predicates never match.
78-
return not _has_value_predicate(filters, stat.column_name)
79-
if lo is None and hi is None:
74+
def _filter_may_match(f: Any, stats: dict[str, ColumnStatistics]) -> bool:
75+
"""Whether filter ``f`` can be true for some row described by ``stats``; unknown shapes return True."""
76+
from vgi.table_filter_pushdown import (
77+
AndFilter,
78+
ComparisonOp,
79+
ConstantFilter,
80+
InFilter,
81+
IsNotNullFilter,
82+
IsNullFilter,
83+
OrFilter,
84+
)
85+
86+
if isinstance(f, AndFilter):
87+
return all(_filter_may_match(child, stats) for child in f.children)
88+
if isinstance(f, OrFilter):
89+
return any(_filter_may_match(child, stats) for child in f.children)
90+
stat = stats.get(f.column_name)
91+
if stat is None:
8092
return True
93+
if isinstance(f, IsNullFilter):
94+
return stat.has_null
95+
if isinstance(f, IsNotNullFilter):
96+
return stat.has_not_null
97+
if not stat.has_not_null:
98+
# Entirely NULL: comparisons and IN never match.
99+
return not isinstance(f, ConstantFilter | InFilter)
100+
lo, hi = _as_py(stat.min), _as_py(stat.max)
81101
try:
82-
constant = filters.get_column_constant(stat.column_name)
83-
if constant is not None:
84-
c = _as_py(constant)
85-
if c is not None and ((lo is not None and c < lo) or (hi is not None and c > hi)):
86-
return False
87-
in_values = filters.get_column_in_values(stat.column_name)
88-
if in_values is not None:
89-
values = [v for v in in_values.to_pylist() if v is not None]
90-
if values and all((lo is not None and v < lo) or (hi is not None and v > hi) for v in values):
91-
return False
92-
bounds = filters.get_column_bounds(stat.column_name)
93-
if bounds is not None:
94-
bmin, bmax = _as_py(bounds.min_value), _as_py(bounds.max_value)
95-
if bmin is not None and hi is not None and (hi < bmin or (hi == bmin and not bounds.min_inclusive)):
96-
return False
97-
if bmax is not None and lo is not None and (lo > bmax or (lo == bmax and not bounds.max_inclusive)):
98-
return False
102+
if isinstance(f, InFilter):
103+
values = [v for v in f.values.to_pylist() if v is not None]
104+
return any((lo is None or v >= lo) and (hi is None or v <= hi) for v in values)
105+
if isinstance(f, ConstantFilter):
106+
c = _as_py(f.value)
107+
if c is None:
108+
return True
109+
if f.op == ComparisonOp.EQ:
110+
return (lo is None or c >= lo) and (hi is None or c <= hi)
111+
if f.op == ComparisonOp.NE:
112+
return not (lo is not None and hi is not None and lo == hi == c)
113+
if f.op == ComparisonOp.GT:
114+
return hi is None or hi > c
115+
if f.op == ComparisonOp.GE:
116+
return hi is None or hi >= c
117+
if f.op == ComparisonOp.LT:
118+
return lo is None or lo < c
119+
if f.op == ComparisonOp.LE:
120+
return lo is None or lo <= c
99121
except TypeError:
100122
# Incomparable types (e.g. a predicate literal of another type): keep the candidate.
101123
return True
102124
return True
103-
104-
105-
def _has_value_predicate(filters: PushdownFilters, column_name: str) -> bool:
106-
try:
107-
return (
108-
filters.get_column_constant(column_name) is not None
109-
or filters.get_column_in_values(column_name) is not None
110-
or filters.get_column_bounds(column_name) is not None
111-
)
112-
except TypeError:
113-
return False

0 commit comments

Comments
 (0)