Skip to content

Commit 393527f

Browse files
rustyconoverclaude
andcommitted
table_function: add dynamic_to_string hook for EXPLAIN ANALYZE Extra Info
Add a new TableFunctionGenerator.dynamic_to_string(params, execution_id) classmethod that surfaces user-defined diagnostics under EXPLAIN ANALYZE. Workers persist whatever diagnostics they care about (BoundStorage, external systems, etc.) and retrieve them by execution_id from the hook. Wire-side: new TableFunctionDynamicToStringRequest/Response on VgiProtocol plus a Worker dispatcher that catches user exceptions so EA never breaks the query. ProfilingDemoFunction fixture demonstrates the recommended sqlite-shared-storage pattern. Known limitation: DuckDB's dynamic_to_string is only invoked from PhysicalTableScan::ExtraSourceParams, which fires only when the source returns FINISHED. Under LIMIT (and other upstream-FINISHED paths) it is silently skipped — see duckdb/duckdb#22471 for the structural fix. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
1 parent f875682 commit 393527f

10 files changed

Lines changed: 497 additions & 33 deletions

File tree

‎tests/conformance/test_protocol_inventory.py‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,14 @@ class NotExposed:
6262
"Covered by C++ integration/table_function paths."
6363
)
6464
),
65+
"table_function_dynamic_to_string": NotExposed(
66+
reason=(
67+
"DuckDB-only profiler hook. Surfaces user diagnostics under EXPLAIN "
68+
"ANALYZE Extra Info. Non-DuckDB clients have no equivalent surface. "
69+
"Covered by tests/test_table_function_dynamic_to_string.py and "
70+
"C++ integration/table/dynamic_to_string.test."
71+
)
72+
),
6573
# ---------- Aggregate (all unary) ----------
6674
"aggregate_bind": NotExposed(
6775
reason=(

‎tests/conformance/test_table.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
"defaults.test",
1818
"double_sequence.test",
1919
"dynamic_filter.test",
20+
"dynamic_to_string.test",
2021
"expression_filter.test",
2122
"filter_echo.test",
2223
"filter_pushdown.test",
Lines changed: 141 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,141 @@
1+
"""Tests for Worker.table_function_dynamic_to_string()."""
2+
3+
from __future__ import annotations
4+
5+
import logging
6+
from collections.abc import Mapping
7+
from dataclasses import dataclass
8+
from typing import Annotated
9+
10+
import pyarrow as pa
11+
import pytest
12+
from vgi_rpc.rpc import AuthContext, CallContext, OutputCollector
13+
14+
from vgi.arguments import Arg, Arguments
15+
from vgi.invocation import FunctionType
16+
from vgi.protocol import (
17+
BindRequest,
18+
TableFunctionDynamicToStringRequest,
19+
TableFunctionDynamicToStringResponse,
20+
)
21+
from vgi.table_function import (
22+
BindParams,
23+
ProcessParams,
24+
TableFunctionGenerator,
25+
bind_fixed_schema,
26+
init_single_worker,
27+
)
28+
from vgi.worker import Worker
29+
30+
31+
@dataclass(slots=True, frozen=True)
32+
class _Args:
33+
count: Annotated[int, Arg(0, doc="Number of rows")]
34+
35+
36+
@init_single_worker
37+
@bind_fixed_schema
38+
class _OverrideFunc(TableFunctionGenerator[_Args]):
39+
"""Returns a non-empty diagnostic map."""
40+
41+
class Meta:
42+
name = "with_override"
43+
44+
FIXED_SCHEMA = pa.schema([pa.field("n", pa.int64())])
45+
46+
@classmethod
47+
def dynamic_to_string(cls, params: BindParams[_Args], execution_id: bytes) -> Mapping[str, str]:
48+
return {"rows_produced": "42", "execution": execution_id.hex()[:8]}
49+
50+
@classmethod
51+
def process(cls, params: ProcessParams[_Args], state: None, out: OutputCollector) -> None:
52+
out.finish()
53+
54+
55+
@init_single_worker
56+
@bind_fixed_schema
57+
class _DefaultFunc(TableFunctionGenerator[_Args]):
58+
"""Doesn't override dynamic_to_string — base returns {}."""
59+
60+
class Meta:
61+
name = "no_override"
62+
63+
FIXED_SCHEMA = pa.schema([pa.field("n", pa.int64())])
64+
65+
@classmethod
66+
def process(cls, params: ProcessParams[_Args], state: None, out: OutputCollector) -> None:
67+
out.finish()
68+
69+
70+
@init_single_worker
71+
@bind_fixed_schema
72+
class _RaiseFunc(TableFunctionGenerator[_Args]):
73+
"""Raises from the user hook — dispatcher must swallow and return empty."""
74+
75+
class Meta:
76+
name = "raises"
77+
78+
FIXED_SCHEMA = pa.schema([pa.field("n", pa.int64())])
79+
80+
@classmethod
81+
def dynamic_to_string(cls, params: BindParams[_Args], execution_id: bytes) -> Mapping[str, str]:
82+
raise RuntimeError("user hook is broken")
83+
84+
@classmethod
85+
def process(cls, params: ProcessParams[_Args], state: None, out: OutputCollector) -> None:
86+
out.finish()
87+
88+
89+
def _request(function_name: str) -> TableFunctionDynamicToStringRequest:
90+
return TableFunctionDynamicToStringRequest(
91+
bind_call=BindRequest(
92+
function_name=function_name,
93+
arguments=Arguments(positional=(pa.scalar(1),)),
94+
function_type=FunctionType.TABLE,
95+
),
96+
global_execution_id=b"\x01\x02\x03\x04\x05\x06\x07\x08",
97+
)
98+
99+
100+
def _ctx() -> CallContext:
101+
return CallContext(auth=AuthContext.anonymous(), emit_client_log=lambda *a, **kw: None)
102+
103+
104+
class TestTableFunctionDynamicToString:
105+
"""Behavioral cases for the dispatcher."""
106+
107+
def test_override_returns_user_keys(self) -> None:
108+
"""Override returns ordered key/value lists in insertion order."""
109+
110+
class _MyWorker(Worker):
111+
functions = [_OverrideFunc]
112+
113+
result = _MyWorker().table_function_dynamic_to_string(_request("with_override"), _ctx())
114+
assert isinstance(result, TableFunctionDynamicToStringResponse)
115+
assert result.keys == ["rows_produced", "execution"]
116+
assert result.values == ["42", "01020304"]
117+
118+
def test_no_override_returns_empty(self) -> None:
119+
"""Default base implementation returns {}; dispatcher emits empty parallel lists."""
120+
121+
class _MyWorker(Worker):
122+
functions = [_DefaultFunc]
123+
124+
result = _MyWorker().table_function_dynamic_to_string(_request("no_override"), _ctx())
125+
assert result.keys == []
126+
assert result.values == []
127+
128+
def test_user_hook_raises_returns_empty(self, caplog: pytest.LogCaptureFixture) -> None:
129+
"""User hook raising must not propagate; dispatcher logs and returns empty."""
130+
131+
class _MyWorker(Worker):
132+
functions = [_RaiseFunc]
133+
134+
with caplog.at_level(logging.ERROR, logger="vgi.worker"):
135+
result = _MyWorker().table_function_dynamic_to_string(_request("raises"), _ctx())
136+
137+
assert result.keys == []
138+
assert result.values == []
139+
assert any("dynamic_to_string" in rec.message for rec in caplog.records), (
140+
"expected an error log when user hook raises"
141+
)

‎vgi/_test_fixtures/table/__init__.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,9 @@
5656
RepeatValueIntFunction,
5757
RepeatValueStrFunction,
5858
)
59+
from vgi._test_fixtures.table.profiling_example import (
60+
ProfilingDemoFunction,
61+
)
5962
from vgi._test_fixtures.table.sequence import (
6063
DoubleSequenceFunction,
6164
NamedParamsEchoFunction,
@@ -115,6 +118,7 @@
115118
"OrderEchoFunction",
116119
"PartitionedSequenceFunction",
117120
"ProductsScanFunction",
121+
"ProfilingDemoFunction",
118122
"ProjectedDataFunction",
119123
"ProjectsScanFunction",
120124
"RepeatValueIntFunction",
Lines changed: 179 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,179 @@
1+
"""Example function exercising the dynamic_to_string callback.
2+
3+
``ProfilingDemoFunction`` demonstrates the recommended persistence
4+
pattern for diagnostics that should surface under ``EXPLAIN ANALYZE``:
5+
6+
1. ``process()`` keeps per-stream counters in user state (rows,
7+
batches, start time), and after every tick writes a serialized
8+
snapshot via ``params.storage.put(bytes)``.
9+
2. ``dynamic_to_string()`` constructs a ``BoundStorage`` for the
10+
given ``execution_id``, calls ``collect()`` to gather every
11+
worker's last snapshot, and sums them.
12+
13+
``BoundStorage`` defaults to the sqlite-backed shared storage (see
14+
CLAUDE.md → ``VGI_WORKER_SHARED_STORAGE``), so the pattern works across
15+
worker processes — both subprocess transport and HTTP transport with
16+
``max_workers > 1``. No in-memory class state is involved.
17+
"""
18+
19+
from __future__ import annotations
20+
21+
import struct
22+
import time
23+
from collections.abc import Mapping
24+
from dataclasses import dataclass
25+
from typing import Annotated, ClassVar
26+
27+
import numpy as np
28+
import pyarrow as pa
29+
from vgi_rpc import ArrowSerializableDataclass
30+
from vgi_rpc.rpc import OutputCollector
31+
32+
from vgi._test_fixtures.table._common import CountBatchArgs
33+
from vgi.arguments import Arg
34+
from vgi.function_storage import BoundStorage
35+
from vgi.metadata import FunctionExample
36+
from vgi.schema_utils import schema
37+
from vgi.table_function import (
38+
BindParams,
39+
ProcessParams,
40+
TableCardinality,
41+
TableFunctionGenerator,
42+
bind_fixed_schema,
43+
init_single_worker,
44+
)
45+
46+
47+
@dataclass(frozen=True)
48+
class ProfilingDemoArgs(CountBatchArgs):
49+
"""Arguments for ProfilingDemoFunction."""
50+
51+
increment: Annotated[int, Arg("increment", default=1, doc="Step between values", ge=1)]
52+
53+
54+
@dataclass(kw_only=True)
55+
class ProfilingState(ArrowSerializableDataclass):
56+
"""Per-stream counters."""
57+
58+
remaining: int
59+
current_index: int = 0
60+
rows_emitted: int = 0
61+
batches_emitted: int = 0
62+
started_at_ns: int = 0
63+
64+
65+
# Serialized snapshot wire format: three little-endian uint64s
66+
# (rows, batches, elapsed_us). Compact; survives multi-worker collect().
67+
_SNAPSHOT = struct.Struct("<QQQ")
68+
69+
70+
def _pack_snapshot(rows: int, batches: int, elapsed_us: int) -> bytes:
71+
return _SNAPSHOT.pack(rows, batches, elapsed_us)
72+
73+
74+
def _unpack_snapshot(data: bytes) -> tuple[int, int, int]:
75+
return _SNAPSHOT.unpack(data)
76+
77+
78+
@init_single_worker
79+
@bind_fixed_schema
80+
class ProfilingDemoFunction(TableFunctionGenerator[ProfilingDemoArgs, ProfilingState]):
81+
"""Sequence generator that publishes per-execution metrics under EXPLAIN ANALYZE.
82+
83+
Output is identical to ``sequence(count, batch_size, increment)``.
84+
Additionally tracks ``rows_produced``, ``batches_emitted``, and
85+
``elapsed_ms`` and surfaces them via ``dynamic_to_string``.
86+
"""
87+
88+
FunctionArguments = ProfilingDemoArgs
89+
90+
class Meta:
91+
"""Metadata for ProfilingDemoFunction."""
92+
93+
name = "profiling_demo"
94+
description = "Sequence generator publishing diagnostics under EXPLAIN ANALYZE"
95+
categories = ["generator", "utility"]
96+
examples = [
97+
FunctionExample(
98+
sql="EXPLAIN ANALYZE SELECT count(*) FROM profiling_demo(500)",
99+
description="Run with diagnostics surfaced as Extra Info",
100+
),
101+
]
102+
103+
FIXED_SCHEMA: ClassVar[pa.Schema] = schema(n=pa.int64())
104+
NUMPY_DTYPE: ClassVar[type[np.generic]] = np.int64
105+
106+
@classmethod
107+
def cardinality(cls, params: BindParams[ProfilingDemoArgs]) -> TableCardinality:
108+
count = params.args.count
109+
return TableCardinality(estimate=count, max=count)
110+
111+
@classmethod
112+
def initial_state(cls, params: ProcessParams[ProfilingDemoArgs]) -> ProfilingState:
113+
return ProfilingState(
114+
remaining=params.args.count,
115+
started_at_ns=time.monotonic_ns(),
116+
)
117+
118+
@classmethod
119+
def process(
120+
cls,
121+
params: ProcessParams[ProfilingDemoArgs],
122+
state: ProfilingState,
123+
out: OutputCollector,
124+
) -> None:
125+
if state.remaining <= 0:
126+
# Final write so dynamic_to_string sees the totals even after
127+
# the stream finishes.
128+
elapsed_us = (time.monotonic_ns() - state.started_at_ns) // 1000
129+
params.storage.put(_pack_snapshot(state.rows_emitted, state.batches_emitted, elapsed_us))
130+
out.finish()
131+
return
132+
batch_size = params.args.batch_size
133+
size = min(state.remaining, batch_size)
134+
increment = params.args.increment
135+
values = np.arange(
136+
state.current_index * increment,
137+
(state.current_index + size) * increment,
138+
increment,
139+
dtype=cls.NUMPY_DTYPE,
140+
)
141+
out.emit(pa.RecordBatch.from_arrays([pa.array(values)], schema=params.output_schema))
142+
state.current_index += size
143+
state.remaining -= size
144+
state.rows_emitted += size
145+
state.batches_emitted += 1
146+
147+
# Per-tick snapshot — overwrites this worker's slot. The dispatcher's
148+
# collect() on dynamic_to_string sums one snapshot per worker pid.
149+
elapsed_us = (time.monotonic_ns() - state.started_at_ns) // 1000
150+
params.storage.put(_pack_snapshot(state.rows_emitted, state.batches_emitted, elapsed_us))
151+
152+
@classmethod
153+
def dynamic_to_string(
154+
cls,
155+
params: BindParams[ProfilingDemoArgs],
156+
execution_id: bytes,
157+
) -> Mapping[str, str]:
158+
# BindParams doesn't carry a BoundStorage (no execution_id at bind
159+
# time). Construct one with the execution_id we received.
160+
storage = BoundStorage(cls.storage, execution_id)
161+
try:
162+
snapshots = storage.collect()
163+
except Exception:
164+
return {}
165+
if not snapshots:
166+
return {}
167+
rows = 0
168+
batches = 0
169+
elapsed_us = 0
170+
for blob in snapshots:
171+
r, b, e = _unpack_snapshot(blob)
172+
rows += r
173+
batches += b
174+
elapsed_us = max(elapsed_us, e)
175+
return {
176+
"rows_produced": str(rows),
177+
"batches_emitted": str(batches),
178+
"elapsed_ms": f"{elapsed_us / 1000.0:.2f}",
179+
}

‎vgi/_test_fixtures/worker.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,7 @@
120120
OrderEchoFunction,
121121
PartitionedSequenceFunction,
122122
ProductsScanFunction,
123+
ProfilingDemoFunction,
123124
ProjectedDataFunction,
124125
ProjectsScanFunction,
125126
RepeatValueIntFunction,
@@ -288,6 +289,7 @@ def _build_enum_stats() -> dict[str, ColumnStatisticsInput]:
288289
RepeatValueStrFunction,
289290
NamedParamsEchoFunction,
290291
NestedSequenceFunction,
292+
ProfilingDemoFunction,
291293
OrderEchoFunction,
292294
PartitionedSequenceFunction,
293295
ProjectedDataFunction,

‎vgi/meta_worker.py‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -307,6 +307,19 @@ def table_function_statistics(self, request: Any, ctx: CallContext) -> Any:
307307
msg = f"Unknown function '{fn_name}'"
308308
raise ValueError(msg)
309309

310+
def table_function_dynamic_to_string(self, request: Any, ctx: CallContext) -> Any:
311+
"""Dispatch the dynamic_to_string profiler hook to the right worker."""
312+
fn_name = request.bind_call.function_name if request.bind_call else ""
313+
for w in self._workers:
314+
registry = type(w)._build_registry()
315+
if fn_name in registry:
316+
return w.table_function_dynamic_to_string(request, ctx=ctx)
317+
# Function not registered with any worker — return empty rather than
318+
# raising. EXPLAIN ANALYZE must never break the query.
319+
from vgi.protocol import TableFunctionDynamicToStringResponse
320+
321+
return TableFunctionDynamicToStringResponse(keys=[], values=[])
322+
310323
# ========== Aggregate function dispatch ==========
311324

312325
def _dispatch_aggregate(self, request: Any, method_name: str, ctx: CallContext) -> Any:

0 commit comments

Comments
 (0)