Skip to content

Commit c50e58c

Browse files
rustyconoverclaude
andcommitted
table_filter_pushdown: handle canonical Arrow extension types
Strip extension<arrow.bool8>, extension<arrow.uuid>, and other canonical Arrow extension wrappers from both column and literal before dispatching to pyarrow.compute.equal / is_in. PyArrow's binary-kernel registry has no entry for (bool, extension<arrow.bool8>) or (extension<uuid>, extension<uuid>) even though their storage types do — so any filter literal DuckDB serialized through the canonical extension table would raise ArrowNotImplementedError in the worker. Adds tests/test_filter_pushdown_extension.py pinning bool8, uuid, IN membership, plain-type non-regression, and documents PyArrow's missing equal kernel for INTERVAL types as a separate issue (#35). See follow-up issues #32 #33 #34 for orthogonal bugs surfaced while writing this coverage. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
1 parent 63bf394 commit c50e58c

2 files changed

Lines changed: 352 additions & 9 deletions

File tree

Lines changed: 299 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,299 @@
1+
"""Filter-pushdown evaluation against canonical Arrow extension types.
2+
3+
Regression test for the issue where DuckDB's VGI extension serialises
4+
filter-literal BOOLEAN values as ``extension<arrow.bool8>`` (per
5+
``vgi/duckdb/src/common/arrow/arrow_type_extension.cpp``), and the worker
6+
attempted to compare them directly against a plain ``pa.bool_()`` column.
7+
PyArrow's binary kernels are type-pair-keyed and have no entry for
8+
``equal(bool, extension<arrow.bool8>)``, so the bare ``pc.equal`` call
9+
raised ``ArrowNotImplementedError``.
10+
11+
These tests pin the worker's normalization of canonical extension types
12+
in ``ConstantFilter.evaluate`` and ``InFilter.evaluate`` so the same bug
13+
can't slip back in for ``arrow.bool8``, ``arrow.uuid``, or any future
14+
canonical extension type that wraps a comparable storage type.
15+
"""
16+
17+
from __future__ import annotations
18+
19+
import pyarrow as pa
20+
import pytest
21+
22+
from vgi.table_filter_pushdown import (
23+
ComparisonOp,
24+
ConstantFilter,
25+
InFilter,
26+
)
27+
28+
29+
def _batch_with_bool(name: str, values: list[bool | None]) -> pa.RecordBatch:
30+
"""RecordBatch holding a single plain pa.bool_() column."""
31+
return pa.RecordBatch.from_pydict({name: pa.array(values, type=pa.bool_())})
32+
33+
34+
def _batch_with_bool8(name: str, values: list[bool | None]) -> pa.RecordBatch:
35+
"""RecordBatch holding a single pa.bool8() (canonical extension) column."""
36+
storage = pa.array([None if v is None else int(v) for v in values], type=pa.int8())
37+
ext_arr = pa.ExtensionArray.from_storage(pa.bool8(), storage)
38+
return pa.RecordBatch.from_arrays([ext_arr], names=[name])
39+
40+
41+
# =============================================================================
42+
# ConstantFilter — bool column, bool8 literal (the trains-server case)
43+
# =============================================================================
44+
45+
46+
class TestBoolColumnBool8Literal:
47+
"""Column is plain ``pa.bool_()``; literal arrives as ``pa.bool8()``.
48+
49+
This is the case the trains worker hits when DuckDB serialises a
50+
BOOLEAN constant from ``WHERE has_departures = true``.
51+
"""
52+
53+
def test_eq_true(self) -> None:
54+
batch = _batch_with_bool("flag", [True, False, None, True])
55+
f = ConstantFilter(
56+
column_name="flag",
57+
column_index=0,
58+
op=ComparisonOp.EQ,
59+
value=pa.scalar(1, type=pa.bool8()),
60+
)
61+
result = f.evaluate(batch)
62+
assert result.to_pylist() == [True, False, None, True]
63+
64+
def test_eq_false(self) -> None:
65+
batch = _batch_with_bool("flag", [True, False, None, True])
66+
f = ConstantFilter(
67+
column_name="flag",
68+
column_index=0,
69+
op=ComparisonOp.EQ,
70+
value=pa.scalar(0, type=pa.bool8()),
71+
)
72+
assert f.evaluate(batch).to_pylist() == [False, True, None, False]
73+
74+
def test_ne_true(self) -> None:
75+
batch = _batch_with_bool("flag", [True, False, None, True])
76+
f = ConstantFilter(
77+
column_name="flag",
78+
column_index=0,
79+
op=ComparisonOp.NE,
80+
value=pa.scalar(1, type=pa.bool8()),
81+
)
82+
assert f.evaluate(batch).to_pylist() == [False, True, None, False]
83+
84+
85+
# =============================================================================
86+
# ConstantFilter — bool8 column, bool8 literal (worker-uses-bool8 case)
87+
# =============================================================================
88+
89+
90+
class TestBool8ColumnBool8Literal:
91+
"""Column is also ``pa.bool8()`` — same story on both sides of the kernel.
92+
93+
PyArrow has no ``equal(extension<bool8>, extension<bool8>)`` either, so
94+
we still need to strip the wrapper.
95+
"""
96+
97+
def test_eq_true(self) -> None:
98+
batch = _batch_with_bool8("flag", [True, False, None, True])
99+
f = ConstantFilter(
100+
column_name="flag",
101+
column_index=0,
102+
op=ComparisonOp.EQ,
103+
value=pa.scalar(1, type=pa.bool8()),
104+
)
105+
assert f.evaluate(batch).to_pylist() == [True, False, None, True]
106+
107+
def test_eq_false(self) -> None:
108+
batch = _batch_with_bool8("flag", [True, False, None, True])
109+
f = ConstantFilter(
110+
column_name="flag",
111+
column_index=0,
112+
op=ComparisonOp.EQ,
113+
value=pa.scalar(0, type=pa.bool8()),
114+
)
115+
assert f.evaluate(batch).to_pylist() == [False, True, None, False]
116+
117+
118+
# =============================================================================
119+
# Plain types — sanity that normalisation is a no-op (no regression)
120+
# =============================================================================
121+
122+
123+
class TestPlainTypesUnchanged:
124+
"""Non-extension types still flow through pc.equal unchanged.
125+
126+
The normalisation helper must not break any of the existing happy
127+
paths that ``test_filter_pushdown.py`` already covers in detail.
128+
"""
129+
130+
def test_int32_eq(self) -> None:
131+
batch = pa.RecordBatch.from_pydict({"n": pa.array([1, 2, 3, 4], type=pa.int32())})
132+
f = ConstantFilter(
133+
column_name="n", column_index=0, op=ComparisonOp.EQ, value=pa.scalar(2, type=pa.int32())
134+
)
135+
assert f.evaluate(batch).to_pylist() == [False, True, False, False]
136+
137+
def test_string_eq(self) -> None:
138+
batch = pa.RecordBatch.from_pydict({"s": ["a", "b", "c"]})
139+
f = ConstantFilter(
140+
column_name="s", column_index=0, op=ComparisonOp.EQ, value=pa.scalar("b")
141+
)
142+
assert f.evaluate(batch).to_pylist() == [False, True, False]
143+
144+
def test_plain_bool_eq(self) -> None:
145+
"""No extension on either side — must still work after the fix."""
146+
batch = _batch_with_bool("flag", [True, False, None, True])
147+
f = ConstantFilter(
148+
column_name="flag", column_index=0, op=ComparisonOp.EQ, value=pa.scalar(True)
149+
)
150+
assert f.evaluate(batch).to_pylist() == [True, False, None, True]
151+
152+
153+
# =============================================================================
154+
# InFilter — same kernel-mismatch story applies to pc.is_in
155+
# =============================================================================
156+
157+
158+
class TestInFilterExtension:
159+
"""``WHERE bool_col IN (true)`` hits ``pc.is_in`` with the same type pair.
160+
161+
DuckDB serialises the values list using the canonical extension types,
162+
so InFilter.values arrives as ``extension<arrow.bool8>`` while the
163+
column may be plain ``pa.bool_()``.
164+
"""
165+
166+
def test_in_bool_with_bool8_values(self) -> None:
167+
batch = _batch_with_bool("flag", [True, False, None, True])
168+
# Build the values array as a bool8 extension array
169+
storage = pa.array([1], type=pa.int8())
170+
values = pa.ExtensionArray.from_storage(pa.bool8(), storage)
171+
f = InFilter(column_name="flag", column_index=0, values=values)
172+
assert f.evaluate(batch).to_pylist() == [True, False, False, True]
173+
174+
175+
# =============================================================================
176+
# Symmetry: plain literal against bool8 column (defensive — unlikely but
177+
# easy enough to keep working).
178+
# =============================================================================
179+
180+
181+
class TestPlainLiteralBool8Column:
182+
"""Defensive: if some future code path emits a plain bool literal but
183+
the column happens to be bool8, normalisation should still align them."""
184+
185+
def test_plain_bool_literal_bool8_column(self) -> None:
186+
batch = _batch_with_bool8("flag", [True, False, None, True])
187+
f = ConstantFilter(
188+
column_name="flag",
189+
column_index=0,
190+
op=ComparisonOp.EQ,
191+
value=pa.scalar(True, type=pa.bool_()),
192+
)
193+
assert f.evaluate(batch).to_pylist() == [True, False, None, True]
194+
195+
196+
# =============================================================================
197+
# Pre-fix regression check: ensure the bare pyarrow kernel still raises
198+
# without normalisation. If this stops raising in a future PyArrow version,
199+
# the normalisation helper becomes redundant for that case (good news, not
200+
# a failure) — but flag it so we know to revisit.
201+
# =============================================================================
202+
203+
204+
def test_pyarrow_kernel_gap_still_present() -> None:
205+
"""Documents the underlying PyArrow gap. If this passes in a future
206+
PyArrow release the normalisation helper is over-defensive but harmless."""
207+
import pyarrow.compute as pc
208+
209+
col = pa.array([True, False], type=pa.bool_())
210+
val = pa.scalar(1, type=pa.bool8())
211+
with pytest.raises(pa.lib.ArrowNotImplementedError, match="extension<arrow.bool8>"):
212+
pc.equal(col, val)
213+
214+
215+
# =============================================================================
216+
# UUID — same kernel-mismatch story as bool8; second-most-likely bug in the
217+
# wild because UUID primary keys are everywhere.
218+
# =============================================================================
219+
220+
221+
def _uuid_array(uuids_hex: list[str | None]) -> pa.Array:
222+
"""Build an arrow.uuid extension array from a list of 32-char hex strings."""
223+
storage = pa.array(
224+
[None if u is None else bytes.fromhex(u) for u in uuids_hex],
225+
type=pa.binary(16),
226+
)
227+
return pa.ExtensionArray.from_storage(pa.uuid(), storage)
228+
229+
230+
def _uuid_scalar(uuid_hex: str) -> pa.Scalar:
231+
"""Build an arrow.uuid extension scalar from a 32-char hex string."""
232+
storage = pa.scalar(bytes.fromhex(uuid_hex), type=pa.binary(16))
233+
return storage.cast(pa.uuid())
234+
235+
236+
class TestUuidExtension:
237+
"""Column and literal both arrive as ``extension<arrow.uuid>``.
238+
239+
Both sides are wrapped because DuckDB's UUID type round-trips through
240+
the canonical ``arrow.uuid`` extension on the wire. PyArrow has no
241+
``equal(extension<arrow.uuid>, extension<arrow.uuid>)`` kernel.
242+
"""
243+
244+
UUIDS = [
245+
"00000000000000000000000000000001",
246+
"00000000000000000000000000000002",
247+
None,
248+
"ffffffffffffffffffffffffffffffff",
249+
]
250+
251+
def test_eq(self) -> None:
252+
batch = pa.RecordBatch.from_arrays([_uuid_array(self.UUIDS)], names=["id"])
253+
f = ConstantFilter(
254+
column_name="id", column_index=0, op=ComparisonOp.EQ,
255+
value=_uuid_scalar("00000000000000000000000000000002"),
256+
)
257+
assert f.evaluate(batch).to_pylist() == [False, True, None, False]
258+
259+
def test_ne(self) -> None:
260+
batch = pa.RecordBatch.from_arrays([_uuid_array(self.UUIDS)], names=["id"])
261+
f = ConstantFilter(
262+
column_name="id", column_index=0, op=ComparisonOp.NE,
263+
value=_uuid_scalar("00000000000000000000000000000002"),
264+
)
265+
assert f.evaluate(batch).to_pylist() == [True, False, None, True]
266+
267+
def test_in(self) -> None:
268+
batch = pa.RecordBatch.from_arrays([_uuid_array(self.UUIDS)], names=["id"])
269+
values = _uuid_array([
270+
"00000000000000000000000000000001",
271+
"ffffffffffffffffffffffffffffffff",
272+
])
273+
f = InFilter(column_name="id", column_index=0, values=values)
274+
assert f.evaluate(batch).to_pylist() == [True, False, False, True]
275+
276+
277+
# =============================================================================
278+
# Documented PyArrow gap: no equal kernel for INTERVAL types
279+
# =============================================================================
280+
281+
282+
def test_pyarrow_interval_kernel_gap() -> None:
283+
"""PyArrow has no ``equal`` kernel for any of the interval types
284+
(``month_day_nano_interval``, ``day_time_interval``, ``month_interval``).
285+
286+
This means a filter pushdown like ``WHERE col = INTERVAL '1 day'``
287+
cannot be evaluated on the worker side regardless of whether we strip
288+
extension wrappers — there is simply no kernel to dispatch to. The
289+
pushdown system would need either to refuse INTERVAL filters at
290+
serialisation (DuckDB extension side) or to implement a custom
291+
field-by-field comparison in ``ConstantFilter.evaluate``.
292+
293+
This test documents the gap so we notice if PyArrow ever fills it."""
294+
import pyarrow.compute as pc
295+
296+
arr = pa.array([(1, 1, 1000), (2, 2, 2000)], type=pa.month_day_nano_interval())
297+
val = pa.scalar((1, 1, 1000), type=pa.month_day_nano_interval())
298+
with pytest.raises(pa.lib.ArrowNotImplementedError, match="month_day_nano_interval"):
299+
pc.equal(arr, val)

‎vgi/table_filter_pushdown.py‎

Lines changed: 53 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,50 @@ def _log_debug(event: str, **kwargs: Any) -> None:
5353
_SUPPORTED_VERSION = "1"
5454

5555

56+
def _strip_extension(x: Any) -> Any:
57+
"""Unwrap a canonical Arrow extension wrapper, returning the storage form.
58+
59+
Filter literals serialised by the DuckDB VGI extension carry their
60+
canonical Arrow extension type (e.g. ``arrow.bool8`` for BOOLEAN, see
61+
``vgi/duckdb/src/common/arrow/arrow_type_extension.cpp``). PyArrow's
62+
binary compute kernels are type-pair-keyed and have no entry for
63+
``equal(bool, extension<arrow.bool8>)`` — so we must strip the wrapper
64+
before comparing. Pass the result of this helper to ``pc.equal`` and
65+
friends.
66+
67+
For Arrays / ChunkedArrays, returns the ``.storage`` array. For
68+
Scalars, returns the ``.value`` storage scalar. Plain (non-extension)
69+
inputs are returned unchanged.
70+
71+
Note: the type-check uses ``pa.BaseExtensionType`` rather than
72+
``pa.ExtensionType`` because canonical Arrow extension types like
73+
``Bool8Type`` and ``UuidType`` inherit from ``BaseExtensionType``
74+
directly without going through the user-extension class.
75+
"""
76+
if isinstance(x.type, pa.BaseExtensionType):
77+
if isinstance(x, (pa.Array, pa.ChunkedArray)):
78+
return x.storage
79+
return x.value
80+
return x
81+
82+
83+
def _normalize_for_compare(col: Any, val: Any) -> tuple[Any, Any]:
84+
"""Bring a (column, scalar) pair into a shape pyarrow.compute can compare.
85+
86+
Two transforms in order:
87+
1. Strip canonical Arrow extension wrappers from both sides.
88+
2. If the resulting types still differ (e.g. column is plain
89+
``bool_`` while the literal came over the wire as
90+
``arrow.bool8`` and stripped to ``int8``), cast the literal to
91+
the column's type so the kernel resolves.
92+
"""
93+
col = _strip_extension(col)
94+
val = _strip_extension(val)
95+
if val.type != col.type:
96+
val = val.cast(col.type)
97+
return col, val
98+
99+
56100
def _make_bool_array(value: bool, length: int) -> pa.BooleanArray:
57101
"""Create a boolean array of constant value.
58102
@@ -213,20 +257,20 @@ class ConstantFilter(Filter):
213257

214258
def evaluate(self, batch: pa.RecordBatch) -> pa.BooleanArray:
215259
"""Evaluate comparison against batch column."""
216-
col = batch.column(self.column_index)
260+
col, val = _normalize_for_compare(batch.column(self.column_index), self.value)
217261
match self.op:
218262
case ComparisonOp.EQ:
219-
return pc.equal(col, self.value)
263+
return pc.equal(col, val)
220264
case ComparisonOp.NE:
221-
return pc.not_equal(col, self.value)
265+
return pc.not_equal(col, val)
222266
case ComparisonOp.GT:
223-
return pc.greater(col, self.value)
267+
return pc.greater(col, val)
224268
case ComparisonOp.GE:
225-
return pc.greater_equal(col, self.value)
269+
return pc.greater_equal(col, val)
226270
case ComparisonOp.LT:
227-
return pc.less(col, self.value)
271+
return pc.less(col, val)
228272
case ComparisonOp.LE:
229-
return pc.less_equal(col, self.value)
273+
return pc.less_equal(col, val)
230274
case _:
231275
raise ValueError(f"Unknown comparison operator: {self.op}")
232276

@@ -272,8 +316,8 @@ class InFilter(Filter):
272316

273317
def evaluate(self, batch: pa.RecordBatch) -> pa.BooleanArray:
274318
"""Evaluate IN membership against batch column."""
275-
col = batch.column(self.column_index)
276-
return pc.is_in(col, self.values)
319+
col, vals = _normalize_for_compare(batch.column(self.column_index), self.values)
320+
return pc.is_in(col, vals)
277321

278322
def __repr__(self) -> str:
279323
"""Return string representation for debugging."""

0 commit comments

Comments
 (0)