Skip to content

Commit dcb9339

Browse files
rustyconoverclaude
andcommitted
catalog: inline scan_function and cardinality on declarative Table
Add four function-discovery fields and two cardinality fields to TableInfo, and populate them from the declarative Table descriptor in to_table_info. The C++ extension reads these and skips: - catalog_table_{scan,insert,update,delete}_function_get RPCs when the matching ``*_function`` is set (one RPC saved per scan/write) - table_function_cardinality RPC when cardinality_estimate / cardinality_max is set (one RPC saved per bind) The auto-impl mirrors ReadOnlyCatalogInterface.table_scan_function_get's shape: function_name from get_metadata(), empty positional/named args, no required extensions. Workers whose function args change more frequently than catalog_version (rotating credentials, presigned URLs, per-transaction snapshots) keep the per-bind RPC by leaving the descriptor's function= unset or by overriding to_table_info themselves. Tests: round-trip serialization for both groups of fields, descriptor behavior (defaults, partial population, explicit-columns tables remain empty). Updates test_schema_info_schema for the field count bump on SchemaInfo (estimated_object_count from a prior commit). Also adds two function-backed tables to the example fixture worker covering the scan_function and cardinality inlining paths under integration testing. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
1 parent 89772c9 commit dcb9339

5 files changed

Lines changed: 277 additions & 1 deletion

File tree

‎tests/catalog/test_declarative.py‎

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -195,6 +195,81 @@ def test_table_function_backed_with_constraints(self) -> None:
195195
assert table.not_null == ("id",)
196196
assert table.unique == (("id",),)
197197

198+
def test_function_backed_table_inlines_scan_function(self) -> None:
199+
"""Inline a serialized ScanFunctionResult on function-backed tables.
200+
201+
The C++ extension reads ``TableInfo.scan_function`` and skips the
202+
per-bind ``catalog_table_scan_function_get`` RPC.
203+
"""
204+
from vgi_rpc.utils import deserialize_record_batch
205+
206+
table = Table(name="users", function=UsersFunction)
207+
info = table.to_table_info("main")
208+
assert info.scan_function is not None
209+
batch, _ = deserialize_record_batch(info.scan_function)
210+
sfr = ScanFunctionResult.deserialize(batch)
211+
# The inlined function name must match the function's metadata so
212+
# the C++ extension can route the bind correctly.
213+
assert sfr.function_name == UsersFunction.get_metadata().name
214+
# Auto-impl mirrors ``ReadOnlyCatalogInterface.table_scan_function_get``:
215+
# empty positional/named args, no required extensions.
216+
assert sfr.positional_arguments == []
217+
assert sfr.named_arguments == {}
218+
assert sfr.required_extensions == []
219+
# Write functions remain null because this Table has none.
220+
assert info.insert_function is None
221+
assert info.update_function is None
222+
assert info.delete_function is None
223+
224+
def test_table_propagates_cardinality_to_table_info(self) -> None:
225+
"""``Table.cardinality_estimate`` / ``cardinality_max`` flow into TableInfo.
226+
227+
The C++ extension reads these and skips the per-bind
228+
``table_function_cardinality`` RPC for read-only / slow-changing tables.
229+
"""
230+
table = Table(
231+
name="users",
232+
function=UsersFunction,
233+
cardinality_estimate=42,
234+
cardinality_max=100,
235+
)
236+
info = table.to_table_info("main")
237+
assert info.cardinality_estimate == 42
238+
assert info.cardinality_max == 100
239+
240+
def test_table_cardinality_defaults_to_none(self) -> None:
241+
"""Default to None so the per-bind RPC behavior is preserved.
242+
243+
Tables without explicit cardinality propagate None, which keeps the
244+
existing per-bind ``table_function_cardinality`` RPC path.
245+
"""
246+
table = Table(name="users", function=UsersFunction)
247+
info = table.to_table_info("main")
248+
assert info.cardinality_estimate is None
249+
assert info.cardinality_max is None
250+
251+
def test_table_cardinality_estimate_only(self) -> None:
252+
"""Estimate-only is a valid configuration — DuckDB gets a point estimate."""
253+
table = Table(name="users", function=UsersFunction, cardinality_estimate=500)
254+
info = table.to_table_info("main")
255+
assert info.cardinality_estimate == 500
256+
assert info.cardinality_max is None
257+
258+
def test_explicit_columns_table_omits_scan_function(self) -> None:
259+
"""Leave scan_function null for explicit-columns tables.
260+
261+
These tables have no declarative ``function=...`` so the C++ extension
262+
falls back to ``catalog_table_scan_function_get`` — which the worker
263+
may resolve via custom logic (e.g. ``read_parquet`` against S3).
264+
"""
265+
cols = pa.schema([pa.field("id", pa.int64())])
266+
table = Table(name="t", columns=cols)
267+
info = table.to_table_info("main")
268+
assert info.scan_function is None
269+
assert info.insert_function is None
270+
assert info.update_function is None
271+
assert info.delete_function is None
272+
198273

199274
class TestTableValidation:
200275
"""Tests for Table validation errors."""

‎tests/catalog/test_serialization.py‎

Lines changed: 119 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -262,6 +262,123 @@ def test_multiple_unique_constraints(self) -> None:
262262

263263
assert restored.unique_constraints == [[0], [1, 2]]
264264

265+
def test_inlined_scan_function_round_trip(self) -> None:
266+
"""``scan_function`` IPC bytes round-trip through TableInfo serialize/deserialize.
267+
268+
The C++ extension reads this field (when populated) and skips the
269+
per-bind ``catalog_table_scan_function_get`` RPC.
270+
"""
271+
columns_schema = schema(id=pa.int64())
272+
columns_bytes = SerializedSchema(columns_schema.serialize().to_pybytes())
273+
sfr = ScanFunctionResult(
274+
function_name="read_parquet",
275+
positional_arguments=[pa.scalar("s3://bucket/x.parquet", pa.string())],
276+
named_arguments={"hive_partitioning": pa.scalar(True, pa.bool_())},
277+
required_extensions=["parquet"],
278+
)
279+
original = TableInfo(
280+
name="t",
281+
schema_name="s",
282+
columns=columns_bytes,
283+
not_null_constraints=[],
284+
unique_constraints=[],
285+
check_constraints=[],
286+
comment=None,
287+
tags={},
288+
scan_function=sfr.serialize(),
289+
)
290+
serialized = original.serialize_to_bytes()
291+
batch, _ = deserialize_record_batch(serialized)
292+
restored = TableInfo.deserialize_from_batch(batch)
293+
294+
assert restored.scan_function is not None
295+
nested, _ = deserialize_record_batch(restored.scan_function)
296+
restored_sfr = ScanFunctionResult.deserialize(nested)
297+
assert restored_sfr.function_name == "read_parquet"
298+
assert [s.as_py() for s in restored_sfr.positional_arguments] == ["s3://bucket/x.parquet"]
299+
assert restored_sfr.named_arguments["hive_partitioning"].as_py() is True
300+
assert restored_sfr.required_extensions == ["parquet"]
301+
# Other inline fields default to None when not populated.
302+
assert restored.insert_function is None
303+
assert restored.update_function is None
304+
assert restored.delete_function is None
305+
306+
def test_inlined_cardinality_round_trip(self) -> None:
307+
"""``cardinality_estimate`` and ``cardinality_max`` round-trip on TableInfo.
308+
309+
The C++ extension reads these (when populated) and skips the per-bind
310+
``table_function_cardinality`` RPC.
311+
"""
312+
columns_schema = schema(id=pa.int64())
313+
columns_bytes = SerializedSchema(columns_schema.serialize().to_pybytes())
314+
original = TableInfo(
315+
name="t",
316+
schema_name="s",
317+
columns=columns_bytes,
318+
not_null_constraints=[],
319+
unique_constraints=[],
320+
check_constraints=[],
321+
comment=None,
322+
tags={},
323+
cardinality_estimate=12345,
324+
cardinality_max=99999,
325+
)
326+
serialized = original.serialize_to_bytes()
327+
batch, _ = deserialize_record_batch(serialized)
328+
restored = TableInfo.deserialize_from_batch(batch)
329+
assert restored.cardinality_estimate == 12345
330+
assert restored.cardinality_max == 99999
331+
332+
def test_inlined_cardinality_partial(self) -> None:
333+
"""Partial population (estimate-only or max-only) round-trips correctly."""
334+
columns_schema = schema(id=pa.int64())
335+
columns_bytes = SerializedSchema(columns_schema.serialize().to_pybytes())
336+
for estimate, max_ in [(1000, None), (None, 5000)]:
337+
original = TableInfo(
338+
name="t",
339+
schema_name="s",
340+
columns=columns_bytes,
341+
not_null_constraints=[],
342+
unique_constraints=[],
343+
check_constraints=[],
344+
comment=None,
345+
tags={},
346+
cardinality_estimate=estimate,
347+
cardinality_max=max_,
348+
)
349+
data = original.serialize_to_bytes()
350+
batch, _ = deserialize_record_batch(data)
351+
restored = TableInfo.deserialize_from_batch(batch)
352+
assert restored.cardinality_estimate == estimate
353+
assert restored.cardinality_max == max_
354+
355+
def test_omitted_inline_fields_default_to_none(self) -> None:
356+
"""A TableInfo without inline fields round-trips with None values.
357+
358+
Models the backward-compat path: an old worker omits these fields,
359+
the C++ extension sees None and falls back to the per-bind RPC.
360+
"""
361+
columns_schema = schema(id=pa.int64())
362+
original = TableInfo(
363+
name="t",
364+
schema_name="s",
365+
columns=SerializedSchema(columns_schema.serialize().to_pybytes()),
366+
not_null_constraints=[],
367+
unique_constraints=[],
368+
check_constraints=[],
369+
comment=None,
370+
tags={},
371+
)
372+
serialized = original.serialize_to_bytes()
373+
batch, _ = deserialize_record_batch(serialized)
374+
restored = TableInfo.deserialize_from_batch(batch)
375+
assert restored.scan_function is None
376+
assert restored.insert_function is None
377+
assert restored.update_function is None
378+
assert restored.delete_function is None
379+
assert restored.cardinality_estimate is None
380+
assert restored.cardinality_max is None
381+
265382

266383
class TestViewInfoSerialization:
267384
"""Test ViewInfo serialization round-trip."""
@@ -792,12 +909,13 @@ def test_catalog_attach_result_schema(self) -> None:
792909
def test_schema_info_schema(self) -> None:
793910
"""Verify SchemaInfo Arrow schema."""
794911
schema = SchemaInfo.ARROW_SCHEMA
795-
assert len(schema) == 4
912+
assert len(schema) == 5
796913
assert schema.field("attach_id").type == pa.binary()
797914
assert schema.field("name").type == pa.string()
798915
assert schema.field("comment").type == pa.string()
799916
assert schema.field("comment").nullable is True
800917
assert schema.field("tags").type == pa.map_(pa.string(), pa.string())
918+
assert schema.field("estimated_object_count").type == pa.map_(pa.string(), pa.int64())
801919

802920
def test_table_info_schema(self) -> None:
803921
"""Verify TableInfo Arrow schema."""

‎vgi/_test_fixtures/worker.py‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -424,6 +424,27 @@ def _build_enum_stats() -> dict[str, ColumnStatisticsInput]:
424424
statistics_cache_max_age_seconds=3600,
425425
comment="A large sequence of integers from 0 to 1,000,000",
426426
),
427+
# Function-backed table with a no-arg function. Used by the
428+
# ``inlined_scan_function.test`` integration test to verify
429+
# the C++ extension reads the inlined ``scan_function`` from
430+
# ``TableInfo`` and skips ``catalog_table_scan_function_get``.
431+
Table(
432+
name="ten_thousand_table",
433+
function=TenThousandFunction,
434+
comment="Function-backed table over the no-arg ten_thousand function",
435+
),
436+
# Function-backed table with inlined cardinality. Used by the
437+
# ``inlined_cardinality.test`` integration test to verify the
438+
# C++ extension uses ``Table.cardinality_estimate`` /
439+
# ``cardinality_max`` from ``TableInfo`` and skips the per-bind
440+
# ``table_function_cardinality`` RPC.
441+
Table(
442+
name="cardinality_inlined_table",
443+
function=TenThousandFunction,
444+
cardinality_estimate=10000,
445+
cardinality_max=10000,
446+
comment="Function-backed table with inlined cardinality (10000 rows)",
447+
),
427448
# Time-travel table: version-specific schema
428449
Table(
429450
name="versioned_data",

‎vgi/catalog/catalog_interface.py‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -241,6 +241,33 @@ class TableInfo(CatalogSchemaObject, ArrowSerializableDataclass):
241241
# Statistics capability flag — indicates this table can provide column statistics.
242242
supports_column_statistics: bool = False
243243

244+
# Optional inlined function-discovery results. When populated, the C++
245+
# extension uses the cached value and skips the corresponding
246+
# ``catalog_table_{scan,insert,update,delete}_function_get`` RPC. Bytes are
247+
# the IPC payload from ``ScanFunctionResult.serialize()``.
248+
#
249+
# Populating these fields freezes the function args for the lifetime of the
250+
# catalog cache (until ``catalog_version`` bumps). Workers whose function
251+
# args change more frequently than ``catalog_version`` (rotating
252+
# credentials, presigned URLs, per-transaction snapshots) MUST leave these
253+
# null so the per-bind RPC continues to fire.
254+
scan_function: Annotated[bytes | None, ArrowType(pa.binary())] = None
255+
insert_function: Annotated[bytes | None, ArrowType(pa.binary())] = None
256+
update_function: Annotated[bytes | None, ArrowType(pa.binary())] = None
257+
delete_function: Annotated[bytes | None, ArrowType(pa.binary())] = None
258+
259+
# Optional inlined cardinality. When populated, the C++ extension uses
260+
# these values directly and skips the ``table_function_cardinality`` RPC
261+
# — saving one round-trip per bind. Use for read-only or slow-changing
262+
# tables where cardinality is statically known.
263+
#
264+
# Populating these fields freezes the cardinality for the lifetime of
265+
# the catalog cache (until ``catalog_version`` bumps). Workers whose
266+
# cardinality changes faster (e.g. live counters) MUST leave them null
267+
# so the per-bind RPC continues to fire.
268+
cardinality_estimate: Annotated[int | None, ArrowType(pa.int64())] = None
269+
cardinality_max: Annotated[int | None, ArrowType(pa.int64())] = None
270+
244271

245272
@dataclass(frozen=True)
246273
class ViewInfo(CatalogSchemaObject, ArrowSerializableDataclass):

‎vgi/catalog/descriptors.py‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
IndexInfo,
2525
MacroInfo,
2626
MacroType,
27+
ScanFunctionResult,
2728
SchemaInfo,
2829
SerializedSchema,
2930
TableColumnStatisticsResult,
@@ -151,6 +152,28 @@ def _default_to_sql(value: DefaultValue) -> str:
151152
return f"'{escaped}'"
152153

153154

155+
def _inline_function_result(
156+
func: type[Function] | None,
157+
) -> bytes | None:
158+
"""Build inlined ``ScanFunctionResult`` IPC bytes for a function-backed table.
159+
160+
Returns ``None`` when the table is not function-backed for that operation.
161+
Mirrors ``ReadOnlyCatalogInterface._write_function_get`` /
162+
``table_scan_function_get`` auto-impl: empty positional/named arguments,
163+
no required extensions. The C++ extension uses these bytes verbatim and
164+
skips the corresponding ``catalog_table_*_function_get`` RPC.
165+
"""
166+
if func is None:
167+
return None
168+
func_meta = func.get_metadata()
169+
return ScanFunctionResult(
170+
function_name=func_meta.name,
171+
positional_arguments=[],
172+
named_arguments={},
173+
required_extensions=[],
174+
).serialize()
175+
176+
154177
@dataclass(frozen=True, slots=True)
155178
class ForeignKeyDef:
156179
"""A foreign key constraint definition.
@@ -225,6 +248,12 @@ class Table:
225248
column_comments: dict[str, str] = field(default_factory=dict)
226249
statistics: dict[str, ColumnStatisticsInput] = field(default_factory=dict)
227250
statistics_cache_max_age_seconds: int | None = None
251+
# Optional inlined cardinality. When set, the C++ extension uses these
252+
# values directly and skips the per-bind ``table_function_cardinality``
253+
# RPC. Use for read-only or slow-changing tables. Leave both as ``None``
254+
# to keep the existing per-bind RPC behavior.
255+
cardinality_estimate: int | None = None
256+
cardinality_max: int | None = None
228257
comment: str | None = None
229258
tags: dict[str, str] = field(default_factory=dict)
230259

@@ -471,6 +500,12 @@ def to_table_info(self, schema_name: str) -> TableInfo:
471500
supports_column_statistics=bool(self.statistics),
472501
comment=self.comment,
473502
tags=dict(self.tags),
503+
scan_function=_inline_function_result(self.function),
504+
insert_function=_inline_function_result(self.insert_function),
505+
update_function=_inline_function_result(self.update_function),
506+
delete_function=_inline_function_result(self.delete_function),
507+
cardinality_estimate=self.cardinality_estimate,
508+
cardinality_max=self.cardinality_max,
474509
)
475510

476511
def resolve_column_statistics(self) -> TableColumnStatisticsResult | None:

0 commit comments

Comments
 (0)