Skip to content

Commit acee931

Browse files
rustyconoverclaude
andcommitted
buffered table: add sink_order_dependent + requires_input_batch_index
Two new metadata flags for the buffered_table contract, completing the ordering-knob 2x2 over input (Sink) and output (Source) phases. Meta.sink_order_dependent — when True (only meaningful with buffered_table=True), the C++ Sink operator will declare ParallelSink=false. All process() calls land on one worker in source order; combine() sees a single state_id. Use when the function's correctness depends on ingest order under a source that DuckDB might otherwise parallelize. Meta.requires_input_batch_index — when True (only meaningful with buffered_table=True), the C++ Sink operator declares RequiredPartitionInfo()=BatchIndex(). DuckDB threads a globally-unique monotonic batch_index from the source into every Sink call; each buffered_table_process RPC carries it through to params.batch_index on the worker side. Workers can sort by batch_index in combine() to reconstruct source order under parallel ingest. Requires a source that supports batch_index (TEMP TABLE / parquet / CSV; range() / VALUES don't, DuckDB rejects at scheduling time). The two flags are mutually exclusive (single-thread sink already orders; batch_index would be redundant noise) — rejected at metadata-resolve time with a clear TypeError. ProcessParams gains a `batch_index: int | None` field, populated only when requires_input_batch_index=True. None for every other call path. Two new fixtures exercise the flags: - OrderedBufferInputFunction (sink_order_dependent=True) - BatchIndexBufferInputFunction (requires_input_batch_index=True) accumulates IndexedBatch(batch_index, batch_bytes) tuples, sorts in combine(), yields in source order from finalize(). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
1 parent 5b5ef92 commit acee931

7 files changed

Lines changed: 222 additions & 1 deletion

File tree

‎vgi/_test_fixtures/table_in_out.py‎

Lines changed: 134 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,8 @@
7272
"CrashOnFinalizeFunction",
7373
"HangOnProcessFunction",
7474
"LargeStateFunction",
75+
"OrderedBufferInputFunction",
76+
"BatchIndexBufferInputFunction",
7577
]
7678

7779

@@ -961,3 +963,135 @@ def finalize(
961963
{name: [len(state.payload)] for name in params.output_schema.names},
962964
schema=params.output_schema,
963965
)
966+
967+
968+
# ============================================================================
969+
# Ordering knobs (sink_order_dependent, requires_input_batch_index)
970+
# ============================================================================
971+
972+
973+
class OrderedBufferInputFunction(BufferInputFunction):
974+
"""Buffered table function with single-threaded ingest.
975+
976+
Uses ``Meta.sink_order_dependent=True`` to force ``ParallelSink=false`` on
977+
the C++ operator. Every ``process()`` call arrives on the same worker in
978+
source order — verifying this works correctly is the integration test's
979+
job (assert distinct ``conn=`` count is exactly 1).
980+
981+
Output is identical to ``BufferInputFunction``: passthrough of all
982+
buffered rows. Because there's only one Sink thread there's only one
983+
state_id; combine returns ``[0]`` and finalize yields the buffer.
984+
"""
985+
986+
class Meta(BufferInputFunction.Meta):
987+
name = "ordered_buffer_input"
988+
description = "buffer_input variant with sink_order_dependent=True"
989+
categories = ["test", "ordering"]
990+
sink_order_dependent = True
991+
992+
993+
@dataclass(kw_only=True)
994+
class IndexedBatch(ArrowSerializableDataclass):
995+
"""One (batch_index, batch_bytes) pair stored per process() call.
996+
997+
The Arrow schema generator can't infer a heterogeneous tuple type, so
998+
pairs are wrapped in a named dataclass with explicit fields.
999+
"""
1000+
1001+
batch_index: int
1002+
batch_bytes: bytes
1003+
1004+
1005+
@dataclass(kw_only=True)
1006+
class BatchIndexBufferInputState(ArrowSerializableDataclass):
1007+
"""Accumulates IndexedBatch entries for later ordering.
1008+
1009+
Each Sink thread keeps its own slice keyed by batch_index. combine()
1010+
merges all slices, sorts by batch_index globally, and writes the
1011+
ordered buffer to slot 0 for finalize() to yield in source order.
1012+
"""
1013+
1014+
pairs: list[IndexedBatch] = field(default_factory=list)
1015+
1016+
1017+
class BatchIndexBufferInputFunction(TableInOutGenerator[SingleTableArguments, BatchIndexBufferInputState]):
1018+
"""Buffered table function that demands ``batch_index`` per ``process()``.
1019+
1020+
Uses ``Meta.requires_input_batch_index=True`` so the C++ operator
1021+
declares ``RequiredPartitionInfo()=BatchIndex()`` and threads DuckDB's
1022+
per-chunk batch_index into every ``process()`` call. The worker stores
1023+
``(batch_index, ipc_bytes)`` per Sink thread; combine() merges and
1024+
sorts globally; finalize() yields in source order under parallel ingest.
1025+
"""
1026+
1027+
state_class = BatchIndexBufferInputState
1028+
1029+
class Meta:
1030+
# Declared standalone (not inheriting from BufferInputFunction.Meta)
1031+
# because resolve_metadata's vars(meta_class) only sees directly-set
1032+
# attributes — Python class attribute inheritance on Meta doesn't
1033+
# carry through. Explicit beats implicit here.
1034+
name = "batch_index_buffer_input"
1035+
description = "buffer_input variant using batch_index to reconstruct order"
1036+
categories = ["test", "ordering"]
1037+
buffered_table = True
1038+
requires_input_batch_index = True
1039+
1040+
@classmethod
1041+
def initial_state(
1042+
cls, params: ProcessParams[SingleTableArguments]
1043+
) -> BatchIndexBufferInputState:
1044+
return BatchIndexBufferInputState()
1045+
1046+
@classmethod
1047+
def process(
1048+
cls,
1049+
params: ProcessParams[SingleTableArguments],
1050+
state: BatchIndexBufferInputState,
1051+
batch: pa.RecordBatch,
1052+
out: OutputCollector,
1053+
) -> None:
1054+
# batch_index must be present when Meta.requires_input_batch_index=True;
1055+
# if it's None the C++ side failed to thread it through.
1056+
if params.batch_index is None:
1057+
raise RuntimeError(
1058+
"batch_index_buffer_input.process() received batch_index=None "
1059+
"— Meta.requires_input_batch_index plumbing is broken"
1060+
)
1061+
sink = pa.BufferOutputStream()
1062+
with pa.ipc.new_stream(sink, batch.schema) as writer:
1063+
writer.write_batch(batch)
1064+
state.pairs.append(
1065+
IndexedBatch(batch_index=params.batch_index, batch_bytes=sink.getvalue().to_pybytes())
1066+
)
1067+
out.emit(empty_batch(params.output_schema))
1068+
1069+
@classmethod
1070+
def combine(
1071+
cls, state_ids: list[int], params: ProcessParams[SingleTableArguments]
1072+
) -> list[int]:
1073+
"""Merge per-state buffers, sort by batch_index, write to slot 0."""
1074+
if not state_ids:
1075+
return []
1076+
stored = params.storage.aggregate_get(state_ids)
1077+
all_pairs: list[IndexedBatch] = []
1078+
for entry in stored:
1079+
if entry is None:
1080+
continue
1081+
partial = BatchIndexBufferInputState.deserialize_from_bytes(entry[1])
1082+
all_pairs.extend(partial.pairs)
1083+
all_pairs.sort(key=lambda p: p.batch_index)
1084+
merged = BatchIndexBufferInputState(pairs=all_pairs)
1085+
params.storage.aggregate_put([(0, merged.serialize_to_bytes())])
1086+
return [0]
1087+
1088+
@classmethod
1089+
def finalize(
1090+
cls, finalize_state_id: int, params: ProcessParams[SingleTableArguments]
1091+
) -> Iterator[pa.RecordBatch]:
1092+
stored = params.storage.aggregate_get([finalize_state_id])
1093+
if not stored or stored[0] is None:
1094+
return
1095+
state = BatchIndexBufferInputState.deserialize_from_bytes(stored[0][1])
1096+
for entry in state.pairs:
1097+
yield pa.ipc.open_stream(entry.batch_bytes).read_next_batch()

‎vgi/_test_fixtures/worker.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -158,6 +158,7 @@
158158
resolve_versioned_constraints_version,
159159
)
160160
from vgi._test_fixtures.table_in_out import (
161+
BatchIndexBufferInputFunction,
161162
BufferInputFunction,
162163
CrashOnCombineFunction,
163164
CrashOnFinalizeFunction,
@@ -168,6 +169,7 @@
168169
FilterBySettingFunction,
169170
HangOnProcessFunction,
170171
LargeStateFunction,
172+
OrderedBufferInputFunction,
171173
RepeatInputsFunction,
172174
SumAllColumnsFunction,
173175
SumAllColumnsSimpleDistributed,
@@ -296,6 +298,8 @@ def _build_enum_stats() -> dict[str, ColumnStatisticsInput]:
296298
CrashOnFinalizeFunction,
297299
HangOnProcessFunction,
298300
LargeStateFunction,
301+
OrderedBufferInputFunction,
302+
BatchIndexBufferInputFunction,
299303
# TableFunctionGenerator - generate output without input
300304
ConstantColumnsFunction,
301305
SlowCancellableFunction,

‎vgi/catalog/catalog_interface.py‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -490,6 +490,19 @@ class FunctionInfo(CatalogSchemaObject, ArrowSerializableDataclass):
490490
# combine-returned order. Default false enables parallel finalize.
491491
source_order_dependent: bool = False
492492

493+
# Only meaningful when ``buffered_table`` is true. When true, the SINK
494+
# phase runs single-threaded — every process() call arrives in source
495+
# order on one worker. Mutually exclusive with requires_input_batch_index.
496+
sink_order_dependent: bool = False
497+
498+
# Only meaningful when ``buffered_table`` is true. When true, the C++
499+
# Sink operator declares RequiredPartitionInfo()=BatchIndex(); each
500+
# process() RPC carries a globally-unique monotonic batch_index from
501+
# DuckDB's source. Workers can sort by it in combine() to reconstruct
502+
# source order under parallel ingest. Mutually exclusive with
503+
# sink_order_dependent.
504+
requires_input_batch_index: bool = False
505+
493506
# Settings required by the function
494507
required_settings: list[str] = field(default_factory=list)
495508

@@ -2308,6 +2321,8 @@ def _function_to_info(self, func_cls: type, schema_name: str) -> FunctionInfo:
23082321
has_finalize=meta.has_finalize,
23092322
buffered_table=meta.buffered_table,
23102323
source_order_dependent=meta.source_order_dependent,
2324+
sink_order_dependent=meta.sink_order_dependent,
2325+
requires_input_batch_index=meta.requires_input_batch_index,
23112326
# Settings
23122327
required_settings=meta.required_settings,
23132328
# Secrets

‎vgi/metadata.py‎

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -405,6 +405,23 @@ class ResolvedMetadata:
405405
# combine() returned them. The default (False) enables parallel finalize.
406406
source_order_dependent: bool = False
407407

408+
# When True (only meaningful with buffered_table=True), the SINK phase
409+
# runs single-threaded — every process() call arrives in source order on
410+
# one worker. The default (False) parallelizes ingest. Mutually
411+
# exclusive with requires_input_batch_index (single-thread already
412+
# orders; no batch_index needed).
413+
sink_order_dependent: bool = False
414+
415+
# When True (only meaningful with buffered_table=True), the C++ Sink
416+
# operator declares RequiredPartitionInfo()=BatchIndex(), causing DuckDB
417+
# to thread a globally-unique monotonic batch_index from the source
418+
# into every process() call. Workers can accumulate (batch_index,
419+
# payload) tuples and sort in combine() to reconstruct source order
420+
# under parallel ingest. Requires the source to support batch_index
421+
# (parquet/csv/temp-table-scan do; range() does not — bind fails).
422+
# Mutually exclusive with sink_order_dependent.
423+
requires_input_batch_index: bool = False
424+
408425
def to_dict(self) -> dict[str, Any]:
409426
"""Convert to dictionary for JSON serialization."""
410427
return {
@@ -435,6 +452,8 @@ def to_dict(self) -> dict[str, Any]:
435452
"has_finalize": self.has_finalize,
436453
"buffered_table": self.buffered_table,
437454
"source_order_dependent": self.source_order_dependent,
455+
"sink_order_dependent": self.sink_order_dependent,
456+
"requires_input_batch_index": self.requires_input_batch_index,
438457
}
439458

440459
@staticmethod
@@ -468,6 +487,8 @@ def from_dict(d: dict[str, Any]) -> ResolvedMetadata:
468487
has_finalize=d.get("has_finalize", False),
469488
buffered_table=d.get("buffered_table", False),
470489
source_order_dependent=d.get("source_order_dependent", False),
490+
sink_order_dependent=d.get("sink_order_dependent", False),
491+
requires_input_batch_index=d.get("requires_input_batch_index", False),
471492
)
472493

473494

@@ -860,6 +881,14 @@ def _normalize_examples(
860881
# When True (only with buffered_table), source phase is single-threaded
861882
# and finalize_state_ids drain in combine-returned order.
862883
"source_order_dependent",
884+
# When True (only with buffered_table), the SINK phase runs single-
885+
# threaded — process() calls arrive in source order on one worker.
886+
"sink_order_dependent",
887+
# When True (only with buffered_table), DuckDB threads a globally-
888+
# unique monotonic batch_index from the source into every process()
889+
# call. Worker can reconstruct source order in combine() by sorting
890+
# accumulated (batch_index, payload) tuples.
891+
"requires_input_batch_index",
863892
# Aggregate function specific
864893
"order_dependent",
865894
"distinct_dependent",
@@ -951,6 +980,23 @@ def resolve_metadata(cls: type) -> ResolvedMetadata:
951980
f"{cls.__name__}: Meta.source_order_dependent is only meaningful when "
952981
f"Meta.buffered_table = True"
953982
)
983+
if attrs.get("sink_order_dependent") and not attrs.get("buffered_table"):
984+
raise TypeError(
985+
f"{cls.__name__}: Meta.sink_order_dependent is only meaningful when "
986+
f"Meta.buffered_table = True"
987+
)
988+
if attrs.get("requires_input_batch_index") and not attrs.get("buffered_table"):
989+
raise TypeError(
990+
f"{cls.__name__}: Meta.requires_input_batch_index is only meaningful when "
991+
f"Meta.buffered_table = True"
992+
)
993+
if attrs.get("sink_order_dependent") and attrs.get("requires_input_batch_index"):
994+
raise TypeError(
995+
f"{cls.__name__}: Meta.sink_order_dependent and "
996+
f"Meta.requires_input_batch_index are mutually exclusive — "
997+
f"single-threaded sink already orders process() calls; "
998+
f"batch_index is only useful under parallel ingest"
999+
)
9541000

9551001
# Use class name as default name, converting to snake_case
9561002
class_name = cls.__name__
@@ -1045,6 +1091,8 @@ def resolve_metadata(cls: type) -> ResolvedMetadata:
10451091
or bool(attrs.get("buffered_table", False))),
10461092
buffered_table=bool(attrs.get("buffered_table", False)),
10471093
source_order_dependent=bool(attrs.get("source_order_dependent", False)),
1094+
sink_order_dependent=bool(attrs.get("sink_order_dependent", False)),
1095+
requires_input_batch_index=bool(attrs.get("requires_input_batch_index", False)),
10481096
)
10491097

10501098

@@ -1193,6 +1241,8 @@ def _detect_has_finalize(cls: type, function_type: CatalogFunctionType) -> bool:
11931241
pa.field("has_finalize", pa.bool_()),
11941242
pa.field("buffered_table", pa.bool_()),
11951243
pa.field("source_order_dependent", pa.bool_()),
1244+
pa.field("sink_order_dependent", pa.bool_()),
1245+
pa.field("requires_input_batch_index", pa.bool_()),
11961246
]
11971247
)
11981248

‎vgi/protocol.py‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1335,6 +1335,12 @@ class BufferedTableProcessRequest(ArrowSerializableDataclass):
13351335
state_id: int # int64; assigned by C++ atomic counter per Sink thread
13361336
input_batch: bytes # Full IPC stream bytes
13371337
attach_opaque_data: bytes | None = None
1338+
# Globally-unique monotonic position from DuckDB's source-side batch
1339+
# tagging, populated only when Meta.requires_input_batch_index=True
1340+
# (operator advertises RequiredPartitionInfo()=BatchIndex()). Workers
1341+
# that need source-order ordering accumulate (batch_index, payload)
1342+
# tuples and sort in combine().
1343+
batch_index: int | None = None
13381344

13391345

13401346
@dataclass(frozen=True, slots=True, kw_only=True)

‎vgi/table_function.py‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -358,6 +358,14 @@ class ProcessParams[TArgs]:
358358
# None if no filters have been received. Updated before each process() call.
359359
current_pushdown_filters: Any = None # PushdownFilters | None
360360

361+
# Globally-unique monotonic batch index for this process() call. Populated
362+
# ONLY for buffered_table functions with Meta.requires_input_batch_index=True
363+
# — the C++ Sink reads it from DuckDB's per-chunk OperatorPartitionInfo
364+
# and forwards it. Workers can accumulate (batch_index, payload) tuples
365+
# and sort in combine() to reconstruct source order under parallel ingest.
366+
# None for every other call path.
367+
batch_index: int | None = None
368+
361369

362370
class TableFunctionBase[TArgs](vgi.function.Function):
363371
"""Base class for table functions with cardinality and schema validation.

‎vgi/worker.py‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2402,13 +2402,17 @@ def buffered_table_process(
24022402
)
24032403
func_cls, params = cached
24042404
# Rebuild storage with this request's auth context so the storage
2405-
# layer's request-scoped fields stay consistent.
2405+
# layer's request-scoped fields stay consistent. Forward the
2406+
# per-call batch_index (only set when Meta.requires_input_batch_index
2407+
# = True; otherwise None). ProcessParams is otherwise immutable
2408+
# across process() calls within one execution.
24062409
params = _dataclass_replace(
24072410
params,
24082411
storage=BoundStorage(
24092412
func_cls.storage, request.execution_id, request=request, auth=ctx.auth
24102413
),
24112414
auth_context=ctx.auth,
2415+
batch_index=request.batch_index,
24122416
)
24132417

24142418
batch = pa.ipc.open_stream(request.input_batch).read_next_batch()

0 commit comments

Comments
 (0)