Skip to content

Commit 8bec8a6

Browse files
rustyconoverclaude
andcommitted
fix(filters): register intersects_extent UDF lazily; declare numpy in engine extras
0.51.0 registered the duckdb.spatial/intersects_extent@1 UDF on every filter-evaluator connection. create_function needs numpy in both Haybarn and DuckDB, and neither the haybarn nor the duckdb extra declared it (only dev did), so a worker installed as vgi-python[haybarn] failed every pushed-down filter: "predicate does not bind ... numpy is required". Register the UDF only when the predicate calls intersects_extent, and add numpy>=2.4.1 to the haybarn and duckdb extras for that case. Filter evaluation cannot run without one of those extras, so numpy stays out of the core dependencies. A new CI job installs the built wheel with only [haybarn] or [duckdb], evaluates pushed-down filters (plain and intersects_extent) through deserialize_filters, then removes numpy and evaluates the plain one again. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 5c424f9 commit 8bec8a6

7 files changed

Lines changed: 282 additions & 7 deletions

File tree

‎.github/workflows/ci.yml‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,40 @@ jobs:
4646
- name: Run tests
4747
run: uv run --python ${{ matrix.python-version }} pytest
4848

49+
# The test job syncs --all-extras, whose dev extra pulls numpy in. That hid
50+
# the 0.51.0 bug where every filter evaluation needed numpy but neither engine
51+
# extra declared it. Here the built wheel gets only one user-facing extra.
52+
packaging:
53+
name: Wheel with only [${{ matrix.extra }}]
54+
runs-on: ubuntu-latest
55+
strategy:
56+
fail-fast: false
57+
matrix:
58+
extra: [haybarn, duckdb]
59+
steps:
60+
- uses: actions/checkout@v7
61+
62+
- name: Install uv
63+
uses: astral-sh/setup-uv@v10.3.3
64+
65+
- name: Build wheel
66+
run: uv build --wheel --out-dir dist .
67+
68+
- name: Install the wheel with only [${{ matrix.extra }}]
69+
run: |
70+
uv venv --python 3.13 "$RUNNER_TEMP/venv"
71+
VIRTUAL_ENV="$RUNNER_TEMP/venv" uv pip install "$(ls dist/vgi_python-*.whl)[${{ matrix.extra }}]"
72+
73+
- name: Evaluate pushed-down filters (plain and intersects_extent)
74+
working-directory: ${{ runner.temp }}
75+
run: '"$RUNNER_TEMP/venv/bin/python" -I "$GITHUB_WORKSPACE/tests/packaging/check_filter_evaluation.py"'
76+
77+
- name: Evaluate an ordinary filter without numpy
78+
working-directory: ${{ runner.temp }}
79+
run: |
80+
VIRTUAL_ENV="$RUNNER_TEMP/venv" uv pip uninstall numpy
81+
"$RUNNER_TEMP/venv/bin/python" -I "$GITHUB_WORKSPACE/tests/packaging/check_filter_evaluation.py" --plain-only
82+
4983
lint:
5084
name: Lint
5185
runs-on: ubuntu-latest

‎CHANGELOG.md‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,19 @@
11
# Changelog
22

3+
## Unreleased
4+
5+
### Fixes
6+
7+
- **Pushed-down filters no longer need numpy.** In 0.51.0 every expression-filter evaluator connection registered
8+
the `duckdb.spatial/intersects_extent@1` UDF up front, and the engine's `create_function` needs numpy, which no
9+
user-facing extra declared. A worker installed as `vgi-python[haybarn]` (or `[duckdb]`) therefore failed every
10+
pushed-down filter with `FilterDeserializationError: ... predicate does not bind under vgi.duckdb.standard.v1:
11+
Invalid Input Error: 'numpy' is required for this operation`. The UDF is now registered only on the first
12+
predicate that calls `intersects_extent`, so ordinary filters never call `create_function`. The `haybarn` and
13+
`duckdb` extras now also declare `numpy>=2.4.1`, which that function does need; filter evaluation cannot run
14+
without one of those extras, so numpy stays out of the core dependencies. A new CI job installs the built wheel
15+
with only one engine extra and evaluates pushed-down filters, with and without numpy.
16+
317
## 0.51.0 (2026-11-11)
418

519
### Fixes

‎pyproject.toml‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -59,8 +59,12 @@ dependencies = [
5959
# (STANDARD_V1_ENGINE_VERSIONS). A looser range lets a resolver pick e.g.
6060
# duckdb 1.5.6, and every pushed-down filter then fails to bind. Change these
6161
# only together with STANDARD_V1_ENGINE_VERSIONS (a test keeps them in step).
62-
haybarn = ["haybarn==1.5.5rc1"]
63-
duckdb = ["duckdb==1.5.5"]
62+
# numpy: the engine's create_function needs it, and the evaluator registers the
63+
# duckdb.spatial/intersects_extent@1 UDF with it (only for predicates that call
64+
# that function). Filter evaluation never runs without one of these extras, so
65+
# numpy belongs here rather than in the core dependencies.
66+
haybarn = ["haybarn==1.5.5rc1", "numpy>=2.4.1"]
67+
duckdb = ["duckdb==1.5.5", "numpy>=2.4.1"]
6468
http = ["vgi-rpc[http]"]
6569
# Publishing and resolving immutable external catalog results needs the RPC
6670
# download/compression dependencies on every transport, including subprocess.
Lines changed: 127 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,127 @@
1+
"""Decode and evaluate pushed-down filters with an installed vgi-python wheel.
2+
3+
The ``packaging`` CI job runs this against the built wheel installed with only
4+
a user-facing engine extra (``haybarn`` or ``duckdb``). The dev extra and dev
5+
group pull numpy in, which hid the 0.51.0 bug: every filter evaluation called
6+
the engine's ``create_function``, which needs numpy, and neither engine extra
7+
declared it, so any pushed-down filter failed to bind.
8+
9+
python -I tests/packaging/check_filter_evaluation.py [--plain-only]
10+
11+
``--plain-only`` skips the intersects_extent case; CI uses it after removing
12+
numpy, to prove an ordinary filter does not need numpy at all. Run it with
13+
``-I`` from outside the checkout so it imports the installed package.
14+
"""
15+
16+
from __future__ import annotations
17+
18+
import json
19+
import sys
20+
from collections.abc import Mapping
21+
from typing import Any
22+
23+
import pyarrow as pa
24+
25+
import vgi
26+
from vgi import deserialize_filters
27+
28+
_METADATA = {
29+
b"vgi_filter_encoding": b"vgi.filters.v2",
30+
b"vgi_filter_version": b"2",
31+
b"vgi_evaluation_context": b"vgi.none.v1",
32+
}
33+
_WKB = {b"ARROW:extension:name": b"geoarrow.wkb", b"ARROW:extension:metadata": b"{}"}
34+
35+
36+
def _column(name: str, index: int) -> dict[str, object]:
37+
return {"node": "column_ref", "column_index": index, "column_name": name}
38+
39+
40+
def _snapshot(expression: Mapping[str, object], mode: str, *payload: tuple[pa.Field[Any], object]) -> pa.RecordBatch:
41+
document = {
42+
"encoding": "vgi.filters.v2",
43+
"semantics": "vgi.duckdb.standard.v1",
44+
"kind": "snapshot",
45+
"predicates": [
46+
{"id": "query:0", "revision": 0, "mode": mode, "source": "query", "expression": dict(expression)}
47+
],
48+
}
49+
fields: list[pa.Field[Any]] = [
50+
pa.field("filter_spec", pa.string(), nullable=False),
51+
*(field for field, _ in payload),
52+
]
53+
arrays = [pa.array([json.dumps(document)]), *(pa.array([value], type=field.type) for field, value in payload)]
54+
return pa.RecordBatch.from_arrays(arrays, schema=pa.schema(fields, metadata=_METADATA)) # type: ignore[arg-type]
55+
56+
57+
def check_plain() -> None:
58+
"""``WHERE region = 'west' AND amount > 900``, as the pushdown_sqlite starter receives it."""
59+
columns: list[pa.Field[Any]] = [pa.field("region", pa.string()), pa.field("amount", pa.int64())]
60+
schema = pa.schema(columns)
61+
expression: dict[str, object] = {
62+
"node": "and",
63+
"children": [
64+
{
65+
"node": "comparison",
66+
"op": "eq",
67+
"left": _column("region", 0),
68+
"right": {"node": "literal", "value_ref": 0},
69+
},
70+
{
71+
"node": "comparison",
72+
"op": "gt",
73+
"left": _column("amount", 1),
74+
"right": {"node": "literal", "value_ref": 1},
75+
},
76+
],
77+
}
78+
filters = deserialize_filters(
79+
_snapshot(
80+
expression,
81+
"required",
82+
(pa.field("value_0", pa.string()), "west"),
83+
(pa.field("value_1", pa.int64()), 900),
84+
),
85+
output_schema=schema,
86+
)
87+
data = pa.RecordBatch.from_pydict(
88+
{"region": ["west", "west", "east"], "amount": [950, 100, 1000]},
89+
schema=schema,
90+
)
91+
got = filters.evaluate(data).to_pylist()
92+
assert got == [True, False, False], got
93+
print("plain filter ok:", got)
94+
95+
96+
def check_intersects_extent() -> None:
97+
"""``geom && POINT(1 1)``: the duckdb.spatial/intersects_extent@1 UDF, which needs numpy."""
98+
point = bytes.fromhex("0101000000000000000000f03f000000000000f03f") # POINT(1 1)
99+
far = bytes.fromhex("010100000000000000000024400000000000002440") # POINT(10 10)
100+
schema = pa.schema([pa.field("geom", pa.binary(), metadata=_WKB)])
101+
expression: dict[str, object] = {
102+
"node": "call",
103+
"function": {"namespace": "duckdb.spatial", "name": "intersects_extent", "version": 1},
104+
"arguments": [_column("geom", 0), {"node": "literal", "value_ref": 0}],
105+
}
106+
filters = deserialize_filters(
107+
_snapshot(expression, "advisory", (pa.field("value_0", pa.binary(), metadata=_WKB), point)),
108+
output_schema=schema,
109+
extension_functions=frozenset({("duckdb.spatial", "intersects_extent", 1)}),
110+
)
111+
data = pa.RecordBatch.from_arrays([pa.array([point, far, None], pa.binary())], schema=schema)
112+
got = filters.evaluate(data).to_pylist()
113+
assert got == [True, False, None], got
114+
print("intersects_extent filter ok:", got)
115+
116+
117+
def main() -> None:
118+
"""Run the checks against the installed wheel."""
119+
if "site-packages" not in (vgi.__file__ or ""):
120+
raise SystemExit(f"vgi imported from {vgi.__file__}, not an installed wheel; run with -I outside the checkout")
121+
check_plain()
122+
if "--plain-only" not in sys.argv:
123+
check_intersects_extent()
124+
125+
126+
if __name__ == "__main__":
127+
main()

‎tests/test_filter_v2.py‎

Lines changed: 54 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -720,7 +720,9 @@ def test_engine_pins_match_standard_v1_oracle() -> None:
720720
assert match, f"{engine} extra must pin an exact version, got {specs[0]!r}"
721721
assert match.group(1) in STANDARD_V1_ENGINE_VERSIONS[engine]
722722
dev_duckdb = [spec for spec in extras["dev"] if re.match(r"duckdb\b", spec)]
723-
assert [spec.replace(" ", "") for spec in dev_duckdb] == list(extras["duckdb"])
723+
assert [spec.replace(" ", "") for spec in dev_duckdb] == [
724+
spec for spec in extras["duckdb"] if re.match(r"duckdb\b", spec)
725+
]
724726

725727

726728
@pytest.mark.parametrize(
@@ -773,6 +775,57 @@ def _connect(**_kw: object) -> _Connection:
773775
assert opened == []
774776

775777

778+
def test_intersects_extent_udf_is_registered_only_when_used(monkeypatch: pytest.MonkeyPatch) -> None:
779+
"""Ordinary filters never call ``create_function`` (it needs numpy); intersects_extent registers once.
780+
781+
0.51.0 registered the UDF on every evaluator connection, so a worker
782+
installed with only the ``haybarn`` extra (no numpy) failed to bind any
783+
pushed-down filter.
784+
"""
785+
import threading
786+
787+
from vgi import filter_v2
788+
789+
registered: list[object] = []
790+
real_register = filter_v2._register_intersects_extent
791+
792+
def counting_register(connection: object) -> None:
793+
registered.append(connection)
794+
real_register(connection)
795+
796+
monkeypatch.setattr(filter_v2, "_register_intersects_extent", counting_register)
797+
monkeypatch.setattr(filter_v2, "_evaluation_local", threading.local())
798+
context = filter_v2.EvaluationContext(profile=filter_v2.NO_EVALUATION_CONTEXT)
799+
amount = pa.RecordBatch.from_pydict({"amount": pa.array([100, 950], pa.int64())})
800+
plain = filter_v2.Comparison(
801+
filter_v2.ComparisonOperator.GT,
802+
filter_v2.ColumnRef(0, "amount", pa.int64()),
803+
filter_v2.Literal(0, pa.field("value_0", pa.int64()), pa.scalar(900, pa.int64())),
804+
)
805+
assert filter_v2.evaluate_expression(plain, amount, context).to_pylist() == [False, True]
806+
assert registered == []
807+
808+
wkb = {b"ARROW:extension:name": b"geoarrow.wkb", b"ARROW:extension:metadata": b"{}"}
809+
point = bytes.fromhex("0101000000000000000000f03f000000000000f03f") # POINT(1 1)
810+
geom = pa.RecordBatch.from_arrays(
811+
[pa.array([point], pa.binary())], schema=pa.schema([pa.field("geom", pa.binary(), metadata=wkb)])
812+
)
813+
call = filter_v2.Call(
814+
filter_v2.FunctionIdentity("duckdb.spatial", "intersects_extent", 1),
815+
(
816+
filter_v2.ColumnRef(0, "geom", pa.binary()),
817+
filter_v2.Literal(0, pa.field("value_0", pa.binary(), metadata=wkb), pa.scalar(point, pa.binary())),
818+
),
819+
)
820+
# Nested under NOT / OR: the walk must still find the call.
821+
nested = filter_v2.Not(filter_v2.BooleanExpression("or", (filter_v2.Not(call), filter_v2.Not(call))))
822+
assert filter_v2.evaluate_expression(nested, geom, context).to_pylist() == [True]
823+
assert len(registered) == 1
824+
assert filter_v2.evaluate_expression(call, geom, context).to_pylist() == [True]
825+
assert filter_v2.evaluate_expression(plain, amount, context).to_pylist() == [False, True]
826+
assert len(registered) == 1
827+
828+
776829
class _NoNbytes:
777830
"""Stands in for a view-typed batch under pyarrow < 19, where ``nbytes`` raises."""
778831

‎uv.lock‎

Lines changed: 4 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎vgi/filter_v2.py‎

Lines changed: 43 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1193,7 +1193,13 @@ def _quote_string(value: str) -> str:
11931193
return "'" + value.replace("'", "''") + "'"
11941194

11951195

1196-
def _get_evaluation_connection(context: EvaluationContext) -> Any:
1196+
def _get_evaluation_connection(context: EvaluationContext, *, intersects_extent: bool = False) -> Any:
1197+
"""Return this thread's evaluator connection for ``context``.
1198+
1199+
``intersects_extent`` first registers the duckdb.spatial/intersects_extent@1
1200+
UDF on the connection (once per connection). It is opt-in because DuckDB and
1201+
Haybarn need numpy for ``create_function``, and ordinary filters must not.
1202+
"""
11971203
connections = getattr(_evaluation_local, "connections", None)
11981204
if connections is None:
11991205
connections = {}
@@ -1226,9 +1232,16 @@ def _get_evaluation_connection(context: EvaluationContext) -> Any:
12261232
# core, a waitress worker on a 48-core host carried ~290 threads, and
12271233
# every evaluation paid to dispatch onto that pool.
12281234
connection = connect(config={"threads": 1})
1229-
_register_intersects_extent(connection)
12301235
_apply_context(connection, context)
12311236
connections[key] = connection
1237+
if intersects_extent:
1238+
registered = getattr(_evaluation_local, "intersects_extent_registered", None)
1239+
if registered is None:
1240+
registered = set()
1241+
_evaluation_local.intersects_extent_registered = registered
1242+
if key not in registered:
1243+
_register_intersects_extent(connection)
1244+
registered.add(key)
12321245
return connection
12331246

12341247

@@ -1250,8 +1263,34 @@ def as_list(values: Any) -> list[Any]:
12501263
)
12511264

12521265

1266+
def _uses_intersects_extent(expression: FilterExpression) -> bool:
1267+
"""Whether ``expression`` calls duckdb.spatial/intersects_extent@1 anywhere."""
1268+
if isinstance(expression, Call):
1269+
identity = expression.function
1270+
if isinstance(identity, FunctionIdentity) and (identity.namespace, identity.name, identity.version) == (
1271+
"duckdb.spatial",
1272+
"intersects_extent",
1273+
1,
1274+
):
1275+
return True
1276+
return any(_uses_intersects_extent(argument) for argument in expression.arguments)
1277+
if isinstance(expression, (Comparison, Arithmetic)):
1278+
return _uses_intersects_extent(expression.left) or _uses_intersects_extent(expression.right)
1279+
if isinstance(expression, BooleanExpression):
1280+
return any(_uses_intersects_extent(child) for child in expression.children)
1281+
if isinstance(expression, (FieldRef, Not, IsNull, Cast, Negate, In)):
1282+
return _uses_intersects_extent(expression.expression)
1283+
if isinstance(expression, RuntimeFilter):
1284+
return _uses_intersects_extent(expression.input)
1285+
return False
1286+
1287+
12531288
def _register_intersects_extent(connection: Any) -> None:
1254-
"""duckdb.spatial/intersects_extent@1 with the specified semantics (vgi/_wkb_extent.py)."""
1289+
"""duckdb.spatial/intersects_extent@1 with the specified semantics (vgi/_wkb_extent.py).
1290+
1291+
``create_function`` needs numpy, which the ``haybarn`` and ``duckdb`` extras
1292+
declare for this one function.
1293+
"""
12551294
connection.create_function(
12561295
_INTERSECTS_EXTENT_UDF,
12571296
_intersects_extent_udf,
@@ -1294,7 +1333,7 @@ def _evaluate_expression(
12941333
batch: pa.RecordBatch,
12951334
context: EvaluationContext,
12961335
) -> pa.BooleanArray:
1297-
connection = _get_evaluation_connection(context)
1336+
connection = _get_evaluation_connection(context, intersects_extent=_uses_intersects_extent(expression))
12981337
referenced = expression_columns(expression)
12991338
input_fields: list[pa.Field[Any]] = []
13001339
input_arrays: list[pa.Array[Any]] = []

0 commit comments

Comments
 (0)