Skip to content

Commit 54627ed

Browse files
rustyconoverclaude
andcommitted
catalog: inline bind_result on TableInfo for @bind_fixed_schema functions
Add a `bind_result: bytes | None` field at the tail of TableInfo. When populated, the C++ extension uses these bytes verbatim and skips the per-scan `bind` RPC for catalog-routed scans. Pre-binding lives in the catalog framework's schema_contents post-pass (not in Table.to_table_info, which lacks the live request context). The post-pass is restricted to functions decorated with @bind_fixed_schema: the decorator's contract — output is exactly cls.FIXED_SCHEMA, no kwargs, no per-call state — matches what's safe to freeze for the catalog cache lifetime. The decorator now sets two markers: - cls._inline_bind_safe = True (class level, only when injection actually happened — i.e., the existing "on_bind not in __dict__" guard succeeded) - on_bind_impl._is_bind_fixed_schema = True (function level, lets us distinguish decorator-installed on_bind from a subclass override) Table.inline_bind=True is the descriptor opt-in. The validator rejects descriptors whose function isn't @bind_fixed_schema-decorated, or whose function class overrides on_bind (escaping the decorator's contract). The schema_contents post-pass synthesizes BindResponse(output_schema=cls.FIXED_SCHEMA) directly — no func_cls.bind() call. This sidesteps the entire class of "bind succeeded with garbage inputs because the catalog request didn't carry real settings/secrets" failures because the decorator's bind has no inputs. The serialized blob is cached lazily on a private class attribute (FIXED_SCHEMA never changes) so repeated schema_contents calls reuse it. Tests cover round-trip, schema-shape positional invariant, descriptor validation paths, and end-to-end populate-on-schema_contents. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
1 parent 7ebbe19 commit 54627ed

5 files changed

Lines changed: 272 additions & 4 deletions

File tree

‎tests/catalog/test_declarative.py‎

Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -308,6 +308,64 @@ def test_table_without_statistics_omits_column_statistics(self) -> None:
308308
assert info.supports_column_statistics is False
309309
assert info.column_statistics is None
310310

311+
def test_table_inline_bind_default_false(self) -> None:
312+
"""``inline_bind`` defaults to False and stays out of TableInfo.
313+
314+
Pre-binding only fires through the catalog framework's schema_contents
315+
post-pass for inline_bind=True tables.
316+
"""
317+
table = Table(name="users", function=UsersFunction)
318+
assert table.inline_bind is False
319+
info = table.to_table_info("main")
320+
assert info.bind_result is None
321+
322+
def test_table_inline_bind_requires_function(self) -> None:
323+
"""``inline_bind=True`` with no function raises at descriptor build."""
324+
cols = pa.schema([pa.field("id", pa.int64())])
325+
with pytest.raises(ValueError, match="requires function="):
326+
Table(name="t", columns=cols, inline_bind=True)
327+
328+
def test_table_inline_bind_requires_bind_fixed_schema(self) -> None:
329+
"""``inline_bind=True`` with a non-decorated function raises.
330+
331+
UsersFunction uses ``@bind_fixed_schema`` already, so build a one-off
332+
subclass with a manual on_bind to exercise the rejection path.
333+
"""
334+
from typing import Any as _Any
335+
336+
from vgi.invocation import BindResponse
337+
from vgi.table_function import BindParams
338+
339+
@init_single_worker
340+
class _ManualBindFn(TableFunctionGenerator[EmptyArgs]):
341+
class Meta: # noqa: D106
342+
name = "manual"
343+
344+
FIXED_SCHEMA = schema({"x": pa.int64()})
345+
346+
@classmethod
347+
def on_bind(cls, params: BindParams[EmptyArgs]) -> BindResponse: # noqa: D102
348+
return BindResponse(output_schema=cls.FIXED_SCHEMA)
349+
350+
@classmethod
351+
def process(cls, params: ProcessParams[EmptyArgs], state: None, out: _Any) -> None: # noqa: D102
352+
out.finish()
353+
354+
with pytest.raises(ValueError, match="@bind_fixed_schema"):
355+
Table(name="t", function=_ManualBindFn, inline_bind=True)
356+
357+
def test_table_inline_bind_decorated_function_validates(self) -> None:
358+
"""``Table(inline_bind=True, function=DecoratedFn)`` builds cleanly.
359+
360+
The descriptor accepts the configuration but does not pre-bind in
361+
``to_table_info`` — that's the catalog framework's job. Verify
362+
bind_result stays None at the descriptor level.
363+
"""
364+
table = Table(name="users", function=UsersFunction, inline_bind=True)
365+
assert table.inline_bind is True
366+
info = table.to_table_info("main")
367+
assert info.bind_result is None # pre-bind is the framework's job
368+
311369

312370
class TestTableValidation:
313371
"""Tests for Table validation errors."""
@@ -1377,6 +1435,48 @@ def test_schema_contents_tables(self, catalog_interface: ReadOnlyCatalogInterfac
13771435
names = {c.name for c in contents}
13781436
assert names == {"users", "events"}
13791437

1438+
def test_schema_contents_inline_bind_post_pass(self) -> None:
1439+
"""schema_contents post-pass populates bind_result for inline_bind=True tables.
1440+
1441+
The framework checks Table.inline_bind, walks to the function class
1442+
(UsersFunction is @bind_fixed_schema-decorated), and inlines a
1443+
serialized BindResponse(output_schema=cls.FIXED_SCHEMA) on TableInfo.
1444+
"""
1445+
from vgi.invocation import BindResponse
1446+
1447+
class _InlineBindCatalog(ReadOnlyCatalogInterface):
1448+
catalog = Catalog(
1449+
name="ib",
1450+
default_schema="main",
1451+
schemas=[
1452+
Schema(
1453+
name="main",
1454+
tables=[
1455+
# Inline-bind opted in.
1456+
Table(name="u_inline", function=UsersFunction, inline_bind=True),
1457+
# No opt-in — bind_result stays null.
1458+
Table(name="u_normal", function=UsersFunction),
1459+
],
1460+
functions=[UsersFunction],
1461+
),
1462+
],
1463+
)
1464+
1465+
contents = _InlineBindCatalog().schema_contents(
1466+
attach_id=AttachId(b"test"),
1467+
transaction_id=None,
1468+
name="main",
1469+
type=SchemaObjectType.TABLE,
1470+
)
1471+
by_name = {c.name: c for c in contents}
1472+
assert by_name["u_inline"].bind_result is not None
1473+
# The inlined bytes are a real BindResponse — round-trip and confirm.
1474+
bind_resp = BindResponse.deserialize_from_bytes(by_name["u_inline"].bind_result)
1475+
assert bind_resp.output_schema.equals(UsersFunction.FIXED_SCHEMA)
1476+
assert bind_resp.opaque_data is None
1477+
# Non-opted-in table stays null.
1478+
assert by_name["u_normal"].bind_result is None
1479+
13801480
def test_schema_contents_views(self, catalog_interface: ReadOnlyCatalogInterface) -> None:
13811481
"""schema_contents returns views for VIEW type."""
13821482
attach_id = AttachId(b"test")

‎tests/catalog/test_serialization.py‎

Lines changed: 39 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -379,6 +379,42 @@ def test_omitted_inline_fields_default_to_none(self) -> None:
379379
assert restored.cardinality_estimate is None
380380
assert restored.cardinality_max is None
381381
assert restored.column_statistics is None
382+
assert restored.bind_result is None
383+
384+
def test_inlined_bind_result_round_trip(self) -> None:
385+
"""``bind_result`` IPC bytes round-trip through TableInfo.
386+
387+
The C++ extension reads this field (when populated) and skips the
388+
per-scan ``bind`` RPC.
389+
"""
390+
from vgi.invocation import BindResponse
391+
392+
columns_schema = schema(id=pa.int64())
393+
columns_bytes = SerializedSchema(columns_schema.serialize().to_pybytes())
394+
# The inlined bytes are an actual BindResponse — not a synthetic blob —
395+
# so we deserialize it back at the end to confirm shape.
396+
output_schema = pa.schema([pa.field("x", pa.int32(), nullable=False)])
397+
bind_blob = BindResponse(output_schema=output_schema, opaque_data=None).serialize_to_bytes()
398+
original = TableInfo(
399+
name="t",
400+
schema_name="s",
401+
columns=columns_bytes,
402+
not_null_constraints=[],
403+
unique_constraints=[],
404+
check_constraints=[],
405+
comment=None,
406+
tags={},
407+
bind_result=bind_blob,
408+
)
409+
serialized = original.serialize_to_bytes()
410+
batch, _ = deserialize_record_batch(serialized)
411+
restored = TableInfo.deserialize_from_batch(batch)
412+
assert restored.bind_result is not None
413+
assert restored.bind_result == bind_blob
414+
# Round-trip the inner BindResponse so we know the bytes are valid.
415+
restored_bind = BindResponse.deserialize_from_bytes(restored.bind_result)
416+
assert restored_bind.output_schema.equals(output_schema)
417+
assert restored_bind.opaque_data is None
382418

383419
def test_inlined_column_statistics_round_trip(self) -> None:
384420
"""``column_statistics`` IPC bytes round-trip through TableInfo.
@@ -975,9 +1011,10 @@ def test_table_info_schema(self) -> None:
9751011
assert schema.field("scan_function").type == pa.binary()
9761012
assert schema.field("cardinality_estimate").type == pa.int64()
9771013
assert schema.field("column_statistics").type == pa.binary()
978-
# column_statistics is the LAST field (positional schema compatibility:
1014+
assert schema.field("bind_result").type == pa.binary()
1015+
# bind_result is the LAST field (positional schema compatibility:
9791016
# old C++ extensions ignore-by-position trailing fields).
980-
assert schema.field(len(schema) - 1).name == "column_statistics"
1017+
assert schema.field(len(schema) - 1).name == "bind_result"
9811018

9821019
def test_view_info_schema(self) -> None:
9831020
"""Verify ViewInfo Arrow schema."""

‎vgi/catalog/catalog_interface.py‎

Lines changed: 63 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
catalog interfaces in VGI workers, enabling DuckDB ATTACH support.
55
"""
66

7+
import dataclasses
78
from abc import ABC, abstractmethod
89
from collections.abc import Mapping, Sequence
910
from dataclasses import dataclass, field
@@ -281,6 +282,22 @@ class TableInfo(CatalogSchemaObject, ArrowSerializableDataclass):
281282
# RPC continues to fire.
282283
column_statistics: Annotated[bytes | None, ArrowType(pa.binary())] = None
283284

285+
# Optional inlined bind result. Bytes are the IPC payload of
286+
# ``BindResponse.serialize_to_bytes()``. When populated, the C++
287+
# extension uses these bytes verbatim and skips the per-scan ``bind``
288+
# RPC, threading the deserialized BindResult straight into bind_data.
289+
#
290+
# The catalog framework only populates this for tables marked
291+
# ``Table(inline_bind=True)`` whose function class is
292+
# ``@bind_fixed_schema``-decorated — the decorator's contract (output is
293+
# exactly ``cls.FIXED_SCHEMA``, no per-call inputs, no opaque_data)
294+
# matches what's safe to freeze for the catalog cache lifetime.
295+
# Functions with custom ``on_bind`` are not eligible via the framework
296+
# path; workers can still inline manually inside their own
297+
# ``schema_contents`` override when the bind output is independently
298+
# known to be stable.
299+
bind_result: Annotated[bytes | None, ArrowType(pa.binary())] = None
300+
284301

285302
@dataclass(frozen=True)
286303
class ViewInfo(CatalogSchemaObject, ArrowSerializableDataclass):
@@ -1533,6 +1550,41 @@ def method(self: Any, **kwargs: Any) -> Any:
15331550
return method
15341551

15351552

1553+
def _inline_bind_result_for(func_cls: type) -> bytes | None:
1554+
"""Pre-built ``bind_result`` bytes for a ``@bind_fixed_schema`` function.
1555+
1556+
Returns the IPC-serialized ``BindResponse(output_schema=cls.FIXED_SCHEMA)``
1557+
that the worker would have produced from a regular bind RPC. Cached on a
1558+
private class attribute so subsequent ``schema_contents`` calls (per
1559+
attach, per cache invalidation) reuse the bytes instead of re-serializing.
1560+
1561+
Returns ``None`` if the class isn't safely pre-bind-able — either it
1562+
isn't ``@bind_fixed_schema``-decorated (no ``_inline_bind_safe`` marker),
1563+
or a subclass has overridden ``on_bind`` (escaping the decorator's
1564+
contract — see the eligibility comment on ``bind_fixed_schema``).
1565+
"""
1566+
if not getattr(func_cls, "_inline_bind_safe", False):
1567+
return None
1568+
# If the class has its own on_bind in __dict__, it's either the decorator's
1569+
# injection (marked) or a subclass override (unmarked). Reject overrides.
1570+
on_bind_attr = func_cls.__dict__.get("on_bind")
1571+
if on_bind_attr is not None:
1572+
underlying = getattr(on_bind_attr, "__func__", on_bind_attr)
1573+
if not getattr(underlying, "_is_bind_fixed_schema", False):
1574+
return None
1575+
cached = func_cls.__dict__.get("_cached_inline_bind_result")
1576+
if cached is not None:
1577+
return cached # type: ignore[no-any-return]
1578+
from vgi.invocation import BindResponse
1579+
1580+
response = BindResponse(output_schema=func_cls.FIXED_SCHEMA, opaque_data=None)
1581+
blob = response.serialize_to_bytes()
1582+
# Set on the class itself so subclasses don't pollute their parents'
1583+
# cache with each other's serialized blobs (FIXED_SCHEMA may differ).
1584+
func_cls._cached_inline_bind_result = blob # type: ignore[attr-defined]
1585+
return blob
1586+
1587+
15361588
class ReadOnlyCatalogInterface(CatalogInterface):
15371589
"""A read-only catalog interface that does not support DDL operations.
15381590
@@ -2096,7 +2148,17 @@ def schema_contents(
20962148
if type_enum == SchemaObjectType.TABLE:
20972149
for (sn, _), table in self._table_registry.items():
20982150
if sn == name_lower:
2099-
results.append(table.to_table_info(schema_name))
2151+
info = table.to_table_info(schema_name)
2152+
# Inline-bind post-pass: descriptors with inline_bind=True
2153+
# backed by @bind_fixed_schema-decorated functions get a
2154+
# pre-built BindResponse inlined onto TableInfo.bind_result.
2155+
# The C++ extension uses these bytes verbatim and skips
2156+
# the per-scan bind RPC.
2157+
if table.inline_bind and table.function is not None:
2158+
bind_bytes = _inline_bind_result_for(table.function)
2159+
if bind_bytes is not None:
2160+
info = dataclasses.replace(info, bind_result=bind_bytes)
2161+
results.append(info)
21002162
elif type_enum == SchemaObjectType.VIEW:
21012163
for (sn, _), view in self._view_registry.items():
21022164
if sn == name_lower:

‎vgi/catalog/descriptors.py‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -255,6 +255,16 @@ class Table:
255255
# to keep the existing per-bind RPC behavior.
256256
cardinality_estimate: int | None = None
257257
cardinality_max: int | None = None
258+
# Opt into pre-binding the function during ``schema_contents`` and
259+
# inlining the result on ``TableInfo.bind_result``. The C++ extension
260+
# then skips the per-scan ``bind`` RPC.
261+
#
262+
# Only valid when ``function`` is a ``@bind_fixed_schema``-decorated
263+
# ``TableFunctionGenerator`` subclass — the decorator's contract (output
264+
# is exactly ``cls.FIXED_SCHEMA``, no per-call inputs) matches what's
265+
# safe to freeze for the catalog cache lifetime. Setting this on a
266+
# descriptor whose function is not decorated raises at descriptor build.
267+
inline_bind: bool = False
258268
comment: str | None = None
259269
tags: dict[str, str] = field(default_factory=dict)
260270

@@ -266,6 +276,39 @@ def __post_init__(self) -> None:
266276
if self.columns is not None and self.function is not None:
267277
raise ValueError(f"Table '{self.name}': cannot specify both 'columns' and 'function'")
268278

279+
# Validate inline_bind contract: only @bind_fixed_schema-decorated
280+
# functions qualify for the catalog framework's pre-bind path. The
281+
# decorator marks both the class (_inline_bind_safe=True) and the
282+
# installed on_bind function (_is_bind_fixed_schema=True). The
283+
# function-level marker lets us reject subclasses that overrode
284+
# on_bind even though they inherit _inline_bind_safe via MRO.
285+
if self.inline_bind:
286+
if self.function is None:
287+
raise ValueError(
288+
f"Table '{self.name}': inline_bind=True requires function= to be set"
289+
)
290+
if not getattr(self.function, "_inline_bind_safe", False):
291+
raise ValueError(
292+
f"Table '{self.name}': inline_bind=True requires the function class "
293+
f"to be decorated with @bind_fixed_schema. Got {self.function.__name__}, "
294+
f"which has a custom on_bind. Either decorate it (deleting the manual "
295+
f"on_bind) or leave inline_bind=False."
296+
)
297+
on_bind_attr = self.function.__dict__.get("on_bind")
298+
if on_bind_attr is not None:
299+
# The class has its own on_bind in __dict__. Either the
300+
# decorator installed it (good — has _is_bind_fixed_schema
301+
# marker on the underlying function) or a subclass overrode
302+
# it (bad — escapes the decorator's contract).
303+
underlying = getattr(on_bind_attr, "__func__", on_bind_attr)
304+
if not getattr(underlying, "_is_bind_fixed_schema", False):
305+
raise ValueError(
306+
f"Table '{self.name}': inline_bind=True is not safe for "
307+
f"{self.function.__name__} because it overrides on_bind, "
308+
f"escaping @bind_fixed_schema's contract. Either remove the "
309+
f"override or leave inline_bind=False."
310+
)
311+
269312
# Resolve columns to validate constraints
270313
resolved = self._get_resolved_columns()
271314
column_names = {f.name for f in resolved}

‎vgi/table_function.py‎

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -937,7 +937,22 @@ def on_init_impl(cls_: type[T], params: Any) -> GlobalInitResponse:
937937

938938

939939
def bind_fixed_schema[T: TableFunctionGenerator[Any, Any]](cls: type[T]) -> type[T]:
940-
"""Class decorator to return FIXED_SCHEMA from on_bind for a TableFunctionGenerator subclass."""
940+
"""Class decorator to return FIXED_SCHEMA from on_bind for a TableFunctionGenerator subclass.
941+
942+
Sets ``cls._inline_bind_safe = True`` *only when* the decorator actually
943+
installs its own ``on_bind``. The catalog framework reads this marker to
944+
decide whether `Table(inline_bind=True)` is allowed — the contract is "the
945+
decorator's bind is in control, output is exactly ``cls.FIXED_SCHEMA``,
946+
no kwargs inspected." If the class already defined its own ``on_bind``,
947+
the decorator silently leaves it alone and we *must not* set the marker;
948+
otherwise the framework would inline a bind it doesn't actually control.
949+
950+
Subclasses inherit the marker via Python attribute lookup. A subclass
951+
that overrides ``on_bind`` adds it to its own ``__dict__``; the catalog
952+
framework's eligibility check is
953+
``getattr(cls, "_inline_bind_safe", False) and "on_bind" not in cls.__dict__``,
954+
which correctly excludes such subclasses.
955+
"""
941956
if "on_bind" not in cls.__dict__: # only inject if subclass hasn't overridden
942957
if not hasattr(cls, "FIXED_SCHEMA"):
943958
raise ValueError(f"Class {cls.__name__} must define FIXED_SCHEMA to use @bind_fixed_schema")
@@ -949,6 +964,12 @@ def on_bind_impl(cls_: type[T], params: Any) -> BindResponse:
949964
raise TypeError(f"Class {cls_.__name__}.FIXED_SCHEMA must be a pyarrow.Schema")
950965
return BindResponse(output_schema=value)
951966

967+
# Mark the function itself so we can later distinguish "decorator
968+
# installed this on_bind" from "user overrode on_bind" — useful for
969+
# downstream callers (e.g. catalog inline-bind) that need to confirm
970+
# the bind logic in effect is the decorator's, not a subclass override.
971+
on_bind_impl._is_bind_fixed_schema = True # type: ignore[attr-defined]
972+
952973
# assign as classmethod
953974
cls.on_bind = classmethod(on_bind_impl) # type: ignore[assignment]
954975

@@ -957,4 +978,9 @@ def on_bind_impl(cls_: type[T], params: Any) -> BindResponse:
957978
if hasattr(cls, "__abstractmethods__") and "on_bind" in cls.__abstractmethods__:
958979
cls.__abstractmethods__ = cls.__abstractmethods__ - {"on_bind"}
959980

981+
# Mark the class as inline-bind-safe *only when* we actually installed
982+
# the on_bind. If the class had a pre-existing custom on_bind, we left
983+
# it alone and have no claim about its purity — the marker stays unset.
984+
cls._inline_bind_safe = True # type: ignore[attr-defined]
985+
960986
return cls

0 commit comments

Comments
 (0)