Skip to content

Commit 779dc67

Browse files
rustyconoverclaude
andcommitted
fixtures: blob_param_batches, blob_param_streams, blob_param_scalar, blob_param_table
The protocol 3.4 fixtures the extension's arguments_ref*.test files need (vgi docs/testing/blob-test-catalog.md, "Protocol 3.4 large values"): - blob_param_batches(payload, batches): one one-row batch per stream turn; - blob_param_streams(payload, streams): one split per stream, each emitting (stream, strlen, sha256); - blob_param_scalar(i, payload): sha256(payload) per non-NULL i, payload a ConstParam so it rides the bind; - blob_param_table: a catalog table whose scan (blob_param_table_scan, the blob_param_echo twin) binds repeat('t', 65536), reports STABLE_WITHIN_QUERY and is not inline-bound. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 03beaaa commit 779dc67

2 files changed

Lines changed: 250 additions & 3 deletions

File tree

‎tests/test_blob_fixtures.py‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,12 +54,19 @@ def test_catalog_functions_match_the_contract() -> None:
5454
assert names == [
5555
"blob_buffer_echo",
5656
"blob_len",
57+
"blob_param_batches",
5758
"blob_param_echo",
59+
"blob_param_scalar",
60+
"blob_param_streams",
5861
"blob_repeat",
5962
"blob_rows",
6063
"blob_store_values",
6164
"blob_tio",
6265
]
66+
# Protocol 3.4: the catalog table that binds blob_param_echo's twin over RPC.
67+
(table,) = schema.tables
68+
assert table.name == "blob_param_table"
69+
assert not table.inline_bind
6370

6471

6572
@pytest.fixture

‎vgi/_test_fixtures/blob_catalog.py‎

Lines changed: 243 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,8 +25,21 @@
2525
``blob_buffer_echo(t)`` table-buffering stores each input batch raw, replays it
2626
``blob_tio(t)`` table-in-out stores each batch in state, reads back
2727
``blob_store_values(t)`` table-in-out stores each value of column 0 exactly
28+
``blob_param_batches`` table large bind parameter over many turns
29+
``blob_param_streams`` table (one split / stream) large bind parameter, parallel streams
30+
``blob_param_scalar`` scalar (constant param) large constant parameter of a scalar
31+
``blob_param_table`` catalog table a scan binding ``blob_param_echo``
2832
========================= ========================== ========================================
2933
34+
The four ``blob_param_*`` fixtures back the extension's protocol 3.4
35+
argument-reference tests (``test/sql/external_storage/arguments_ref*.test``):
36+
``blob_param_batches(payload, batches)`` emits ``batches`` one-row batches,
37+
one per stream turn; ``blob_param_streams(payload, streams)`` plans ``streams``
38+
splits that each emit one row; ``blob_param_scalar(i, payload)`` returns
39+
``sha256(payload)`` for each non-NULL ``i`` with ``payload`` a constant
40+
parameter; ``blob_param_table`` binds ``repeat('t', 65536)``, reports
41+
``STABLE_WITHIN_QUERY`` and is not inline-bound, so every scan binds over RPC.
42+
3043
``blob_buffer_echo`` and ``blob_tio`` pass every input column through and add
3144
``payload_len`` (UTF-8 byte length) and ``payload_sha256`` (lowercase hex) of
3245
the first column cast to text, matching DuckDB's ``strlen(x)`` and
@@ -49,6 +62,7 @@
4962
from __future__ import annotations
5063

5164
import hashlib
65+
import struct
5266
import uuid
5367
from dataclasses import dataclass
5468
from typing import Annotated, Any, ClassVar
@@ -58,15 +72,17 @@
5872
from vgi_rpc import ArrowSerializableDataclass
5973
from vgi_rpc.rpc import OutputCollector
6074

61-
from vgi.arguments import Arg, Param, Returns, TableInput
62-
from vgi.catalog import Catalog, ReadOnlyCatalogInterface, Schema
63-
from vgi.invocation import BindResponse
75+
from vgi.arguments import Arg, Arguments, ConstParam, Param, Returns, TableInput
76+
from vgi.catalog import Catalog, ReadOnlyCatalogInterface, Schema, Table
77+
from vgi.invocation import BindRepeatability, BindResponse
6478
from vgi.metadata import FunctionExample
79+
from vgi.protocol import PlanResponse, ScanSplit
6580
from vgi.scalar_function import ScalarFunction
6681
from vgi.schema_utils import schema
6782
from vgi.table_buffering_function import TableBufferingFunction, TableBufferingParams
6883
from vgi.table_function import (
6984
BindParams,
85+
InitParams,
7086
ProcessParams,
7187
TableCardinality,
7288
TableFunctionGenerator,
@@ -273,6 +289,219 @@ def process(cls, params: ProcessParams[_BlobParamArgs], state: _EmitOnceState, o
273289
state.emitted = True
274290

275291

292+
def _digest(payload: str) -> tuple[int, str]:
293+
raw = payload.encode()
294+
return len(raw), hashlib.sha256(raw).hexdigest()
295+
296+
297+
@dataclass(slots=True, frozen=True)
298+
class _BlobParamBatchesArgs:
299+
payload: Annotated[str, Arg(0, doc="Parameter to measure")]
300+
batches: Annotated[int, Arg(1, doc="Number of one-row batches", ge=0)]
301+
302+
303+
@dataclass(kw_only=True)
304+
class _BatchCursor(ArrowSerializableDataclass):
305+
next_batch: int = 0
306+
307+
308+
@init_single_worker
309+
@bind_fixed_schema
310+
class BlobParamBatchesFunction(TableFunctionGenerator[_BlobParamBatchesArgs, _BatchCursor]):
311+
"""``blob_param_batches(payload, batches)``: ``batches`` one-row batches, one per stream turn.
312+
313+
Row ``i`` is ``(i, strlen(payload), sha256(payload))``, so a 60-batch call is
314+
at least 60 continuations, each carrying the stream's ``init`` state.
315+
316+
Attributes:
317+
FIXED_SCHEMA: ``(i BIGINT, payload_len BIGINT, payload_sha256 VARCHAR)``.
318+
"""
319+
320+
class Meta:
321+
"""Function metadata."""
322+
323+
name = "blob_param_batches"
324+
description = "Length and SHA-256 of a parameter, once per batch (argument references over many turns)"
325+
examples = [FunctionExample(sql="SELECT * FROM blob_param_batches('abc', 3)", description="3 rows, i = 0..2")]
326+
327+
FIXED_SCHEMA: ClassVar[pa.Schema] = schema(i=pa.int64(), payload_len=pa.int64(), payload_sha256=pa.string())
328+
329+
@classmethod
330+
def cardinality(cls, params: BindParams[_BlobParamBatchesArgs]) -> TableCardinality:
331+
"""Exactly ``batches`` rows."""
332+
return TableCardinality(estimate=params.args.batches, max=params.args.batches)
333+
334+
@classmethod
335+
def initial_state(cls, params: ProcessParams[_BlobParamBatchesArgs]) -> _BatchCursor:
336+
"""Start at batch 0."""
337+
return _BatchCursor()
338+
339+
@classmethod
340+
def process(cls, params: ProcessParams[_BlobParamBatchesArgs], state: _BatchCursor, out: OutputCollector) -> None:
341+
"""Emit one one-row batch per tick."""
342+
if state.next_batch >= params.args.batches:
343+
out.finish()
344+
return
345+
length, digest = _digest(params.args.payload)
346+
out.emit(
347+
pa.RecordBatch.from_pydict(
348+
{"i": [state.next_batch], "payload_len": [length], "payload_sha256": [digest]},
349+
schema=params.output_schema,
350+
)
351+
)
352+
state.next_batch += 1
353+
354+
355+
@dataclass(slots=True, frozen=True)
356+
class _BlobParamStreamsArgs:
357+
payload: Annotated[str, Arg(0, doc="Parameter to measure")]
358+
streams: Annotated[int, Arg(1, doc="Number of parallel streams (one split each)", ge=1)]
359+
360+
361+
@dataclass(kw_only=True)
362+
class _StreamCursor(ArrowSerializableDataclass):
363+
streams: list[int]
364+
next_index: int = 0
365+
366+
367+
@bind_fixed_schema
368+
class BlobParamStreamsFunction(TableFunctionGenerator[_BlobParamStreamsArgs, _StreamCursor]):
369+
"""``blob_param_streams(payload, streams)``: one bind planned as ``streams`` splits.
370+
371+
Each split emits ``(stream index, strlen(payload), sha256(payload))``. Every
372+
split's init embeds the same bind call, so with an argument reference the
373+
worker process fetches the argument once (vgi-rpc's object cache).
374+
375+
Attributes:
376+
FIXED_SCHEMA: ``(stream BIGINT, payload_len BIGINT, payload_sha256 VARCHAR)``.
377+
"""
378+
379+
class Meta:
380+
"""Function metadata."""
381+
382+
name = "blob_param_streams"
383+
description = "Length and SHA-256 of a parameter from parallel streams (argument references)"
384+
supports_splits = True
385+
split_token_ttl_seconds = None
386+
examples = [
387+
FunctionExample(sql="SELECT * FROM blob_param_streams('abc', 4)", description="4 rows, stream = 0..3")
388+
]
389+
390+
FIXED_SCHEMA: ClassVar[pa.Schema] = schema(stream=pa.int64(), payload_len=pa.int64(), payload_sha256=pa.string())
391+
392+
@classmethod
393+
def cardinality(cls, params: BindParams[_BlobParamStreamsArgs]) -> TableCardinality:
394+
"""One row per stream."""
395+
return TableCardinality(estimate=params.args.streams, max=params.args.streams)
396+
397+
@classmethod
398+
def on_plan(cls, params: BindParams[_BlobParamStreamsArgs], request: Any) -> PlanResponse:
399+
"""One split per stream; the payload is the stream index."""
400+
count = params.args.streams
401+
return PlanResponse(
402+
splits=[ScanSplit(payload=struct.pack("<q", i), estimated_rows=1, rows_exact=True) for i in range(count)],
403+
estimated_total_splits=count,
404+
estimated_total_rows=count,
405+
)
406+
407+
@classmethod
408+
def on_split(cls, params: InitParams[_BlobParamStreamsArgs], request: Any, payloads: list[bytes]) -> None:
409+
"""Splits are redeemed from ``params.split_payloads`` in ``initial_state``."""
410+
return None
411+
412+
@classmethod
413+
def initial_state(cls, params: ProcessParams[_BlobParamStreamsArgs]) -> _StreamCursor:
414+
"""The stream indices this reader claimed."""
415+
if getattr(params.init_call, "split_tokens", None) is None:
416+
raise RuntimeError("blob_param_streams is split-only; vgi_split_scans is probably off")
417+
return _StreamCursor(streams=[struct.unpack("<q", p)[0] for p in (params.split_payloads or [])])
418+
419+
@classmethod
420+
def process(cls, params: ProcessParams[_BlobParamStreamsArgs], state: _StreamCursor, out: OutputCollector) -> None:
421+
"""Emit one row per claimed stream, then finish."""
422+
if state.next_index >= len(state.streams):
423+
out.finish()
424+
return
425+
length, digest = _digest(params.args.payload)
426+
out.emit(
427+
pa.RecordBatch.from_pydict(
428+
{"stream": [state.streams[state.next_index]], "payload_len": [length], "payload_sha256": [digest]},
429+
schema=params.output_schema,
430+
)
431+
)
432+
state.next_index += 1
433+
434+
435+
class BlobParamScalarFunction(ScalarFunction):
436+
"""``blob_param_scalar(i, payload)``: ``sha256(payload)`` per non-NULL ``i``.
437+
438+
``payload`` is a constant parameter, so it rides the scalar's bind (and
439+
with it an argument reference), not its input batches.
440+
"""
441+
442+
class Meta:
443+
"""Function metadata."""
444+
445+
name = "blob_param_scalar"
446+
description = "SHA-256 of a constant parameter for every row (argument references for scalars)"
447+
examples = [FunctionExample(sql="SELECT blob_param_scalar(1, 'abc')", description="sha256('abc')")]
448+
449+
@classmethod
450+
def compute(
451+
cls,
452+
i: Annotated[pa.Int64Array, Param(doc="Row value; NULL gives NULL")],
453+
payload: Annotated[str, ConstParam("Constant parameter to hash")],
454+
) -> Annotated[pa.StringArray, Returns()]:
455+
"""``sha256(payload)`` for each row whose ``i`` is not NULL."""
456+
digest = hashlib.sha256(payload.encode()).hexdigest() if payload is not None else None
457+
return pa.array([None if v is None else digest for v in i.to_pylist()], type=pa.string())
458+
459+
460+
#: The fixed argument ``blob_param_table`` binds: ``repeat('t', 65536)``.
461+
BLOB_PARAM_TABLE_ARGUMENT = "t" * 65536
462+
463+
464+
@init_single_worker
465+
class BlobParamTableScan(TableFunctionGenerator[_BlobParamArgs, _EmitOnceState]):
466+
"""The scan behind the ``blob_param_table`` catalog table: ``blob_param_echo`` with a fixed argument.
467+
468+
It reports ``STABLE_WITHIN_QUERY`` and is never inline-bound, so every scan
469+
binds over RPC and a serialized-plan rebind must reproduce the same bind
470+
bytes (the extension's per-query argument-reference memo).
471+
472+
Attributes:
473+
FIXED_SCHEMA: ``(payload_len BIGINT, payload_sha256 VARCHAR)``.
474+
"""
475+
476+
class Meta:
477+
"""Function metadata."""
478+
479+
name = "blob_param_table_scan"
480+
description = "Length and SHA-256 of blob_param_table's fixed parameter (STABLE_WITHIN_QUERY)"
481+
482+
FIXED_SCHEMA: ClassVar[pa.Schema] = BlobParamEchoFunction.FIXED_SCHEMA
483+
484+
@classmethod
485+
def on_bind(cls, params: BindParams[_BlobParamArgs]) -> BindResponse:
486+
"""The echo schema, promising equivalent scans within one query."""
487+
return BindResponse(output_schema=cls.FIXED_SCHEMA, repeatability=BindRepeatability.STABLE_WITHIN_QUERY)
488+
489+
@classmethod
490+
def cardinality(cls, params: BindParams[_BlobParamArgs]) -> TableCardinality:
491+
"""One row."""
492+
return TableCardinality(estimate=1, max=1)
493+
494+
@classmethod
495+
def initial_state(cls, params: ProcessParams[_BlobParamArgs]) -> _EmitOnceState:
496+
"""Not yet emitted."""
497+
return _EmitOnceState()
498+
499+
@classmethod
500+
def process(cls, params: ProcessParams[_BlobParamArgs], state: _EmitOnceState, out: OutputCollector) -> None:
501+
"""Emit the one row, then finish."""
502+
BlobParamEchoFunction.process(params, state, out)
503+
504+
276505
# ---------------------------------------------------------------------------
277506
# Table-buffering and table-in-out
278507
# ---------------------------------------------------------------------------
@@ -473,6 +702,17 @@ def transform(cls, batch: pa.RecordBatch, params: ProcessParams[_TableArgs], sta
473702
BlobBufferEchoFunction,
474703
BlobTioFunction,
475704
BlobStoreValuesFunction,
705+
BlobParamBatchesFunction,
706+
BlobParamStreamsFunction,
707+
BlobParamScalarFunction,
708+
],
709+
tables=[
710+
Table(
711+
name="blob_param_table",
712+
function=BlobParamTableScan,
713+
arguments=Arguments(positional=(pa.scalar(BLOB_PARAM_TABLE_ARGUMENT),)),
714+
comment="blob_param_echo(repeat('t', 65536)), STABLE_WITHIN_QUERY, bound over RPC on every scan",
715+
)
476716
],
477717
)
478718
],

0 commit comments

Comments
 (0)