|
25 | 25 | ``blob_buffer_echo(t)`` table-buffering stores each input batch raw, replays it |
26 | 26 | ``blob_tio(t)`` table-in-out stores each batch in state, reads back |
27 | 27 | ``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`` |
28 | 32 | ========================= ========================== ======================================== |
29 | 33 |
|
| 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 | +
|
30 | 43 | ``blob_buffer_echo`` and ``blob_tio`` pass every input column through and add |
31 | 44 | ``payload_len`` (UTF-8 byte length) and ``payload_sha256`` (lowercase hex) of |
32 | 45 | the first column cast to text, matching DuckDB's ``strlen(x)`` and |
|
49 | 62 | from __future__ import annotations |
50 | 63 |
|
51 | 64 | import hashlib |
| 65 | +import struct |
52 | 66 | import uuid |
53 | 67 | from dataclasses import dataclass |
54 | 68 | from typing import Annotated, Any, ClassVar |
|
58 | 72 | from vgi_rpc import ArrowSerializableDataclass |
59 | 73 | from vgi_rpc.rpc import OutputCollector |
60 | 74 |
|
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 |
64 | 78 | from vgi.metadata import FunctionExample |
| 79 | +from vgi.protocol import PlanResponse, ScanSplit |
65 | 80 | from vgi.scalar_function import ScalarFunction |
66 | 81 | from vgi.schema_utils import schema |
67 | 82 | from vgi.table_buffering_function import TableBufferingFunction, TableBufferingParams |
68 | 83 | from vgi.table_function import ( |
69 | 84 | BindParams, |
| 85 | + InitParams, |
70 | 86 | ProcessParams, |
71 | 87 | TableCardinality, |
72 | 88 | TableFunctionGenerator, |
@@ -273,6 +289,219 @@ def process(cls, params: ProcessParams[_BlobParamArgs], state: _EmitOnceState, o |
273 | 289 | state.emitted = True |
274 | 290 |
|
275 | 291 |
|
| 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 | + |
276 | 505 | # --------------------------------------------------------------------------- |
277 | 506 | # Table-buffering and table-in-out |
278 | 507 | # --------------------------------------------------------------------------- |
@@ -473,6 +702,17 @@ def transform(cls, batch: pa.RecordBatch, params: ProcessParams[_TableArgs], sta |
473 | 702 | BlobBufferEchoFunction, |
474 | 703 | BlobTioFunction, |
475 | 704 | 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 | + ) |
476 | 716 | ], |
477 | 717 | ) |
478 | 718 | ], |
|
0 commit comments