2929
3030from __future__ import annotations
3131
32- from dataclasses import dataclass
32+ from dataclasses import dataclass , field
33+ from collections .abc import Iterator
3334from typing import Annotated , Any
3435
3536import pyarrow as pa
@@ -117,44 +118,46 @@ def on_bind(cls, params: BindParams[SingleTableArguments]) -> BindResponse:
117118 return BindResponse (output_schema = params .bind_call .input_schema )
118119
119120
120- class BufferInputFunction (TableInOutGenerator [SingleTableArguments ]):
121- """Buffering function that collects all input and emits during finalization.
121+ @dataclass (kw_only = True )
122+ class BufferInputState (ArrowSerializableDataclass ):
123+ """Per-state_id buffer of IPC-encoded record batches.
122124
123- USE CASE
124- --------
125- When you need to see all data before producing output, or when you want to
126- delay output until the stream is complete. Useful for sorting, deduplication,
127- or operations that need the full dataset.
125+ Each entry is one input batch serialized as IPC stream bytes — bytes
126+ rather than ``pa.RecordBatch`` objects so the state round-trips cleanly
127+ through ``ArrowSerializableDataclass.serialize_to_bytes``.
128+ """
128129
129- BEHAVIOR
130- --------
131- - output_schema: Returns input schema unchanged (default)
132- - process(): Stores batches in buffer and emits empty results
133- - finalize(): Returns buffered batches
130+ batches : Annotated [list [bytes ], ArrowType (pa .list_ (pa .binary ()))] = field (default_factory = list )
134131
135- SCHEMA TRANSFORMATION
136- ---------------------
137- Input: any schema
138- Output: same schema (passthrough)
139132
140- Note:
141- ----
142- This is a test/example function for protocol validation.
133+ class BufferInputFunction (TableInOutGenerator [SingleTableArguments , BufferInputState ]):
134+ """Buffering function — collects all input, emits during finalize.
143135
144- Example:
145- -------
146- Input stream: batch1, batch2, batch3
147- During processing: (empty), (empty), (empty)
148- On finalize: batch1, batch2, batch3
136+ Uses the buffered table function path (``Meta.buffered_table = True``):
137+ each parallel Sink thread accumulates into its own ``state_id``,
138+ ``combine`` returns those state_ids as-is (pass-through partitioning),
139+ and ``finalize`` yields the buffered batches for one state_id per RPC.
140+ Under UNION ALL the inputs are distributed across Sink threads and the
141+ combined output is the union of every buffer.
149142
143+ Schema:
144+ Input: any schema
145+ Output: same schema (passthrough)
150146 """
151147
148+ # Explicit state_class — TableInOutGenerator's generic param isn't auto-
149+ # reflected onto the class today (only TableInOutFunction has that
150+ # __init_subclass__ hook). The buffered_table_process worker handler
151+ # uses this to deserialize the per-state_id state.
152+ state_class = BufferInputState
153+
152154 class Meta :
153155 """Metadata for BufferInputFunction."""
154156
155157 name = "buffer_input"
156158 description = "Collects all input batches and emits during finalization"
157159 categories = ["utility" , "buffer" ]
160+ buffered_table = True
158161 examples = [
159162 FunctionExample (
160163 sql = "SELECT * FROM buffer_input((SELECT * FROM input_table))" ,
@@ -163,29 +166,58 @@ class Meta:
163166 ]
164167
165168 @classmethod
166- def on_init (cls , params : InitParams [SingleTableArguments ]) -> GlobalInitResponse :
167- """Enforce single-worker execution."""
168- return GlobalInitResponse (max_workers = 1 )
169+ def initial_state (cls , params : ProcessParams [SingleTableArguments ]) -> BufferInputState :
170+ return BufferInputState ()
169171
170172 @classmethod
171173 def process (
172174 cls ,
173175 params : ProcessParams [SingleTableArguments ],
174- state : None ,
176+ state : BufferInputState ,
175177 batch : pa .RecordBatch ,
176178 out : OutputCollector ,
177179 ) -> None :
178- """Buffer each input batch in storage queue and emit empty."""
179- params .storage .queue_push_batches ([batch ])
180+ """Serialize the batch and append to this state_id's buffer.
181+
182+ Under the buffered_table path ``out`` is a NoOpCollector that
183+ silently accepts the trailing zero-row emit but would raise on any
184+ non-empty emit — process() is sink-only.
185+ """
186+ sink = pa .BufferOutputStream ()
187+ with pa .ipc .new_stream (sink , batch .schema ) as writer :
188+ writer .write_batch (batch )
189+ state .batches .append (sink .getvalue ().to_pybytes ())
180190 out .emit (empty_batch (params .output_schema ))
181191
182192 @classmethod
183- def finalize (cls , params : ProcessParams [SingleTableArguments ]) -> list [pa .RecordBatch ]:
184- """Return all buffered batches."""
185- batches : list [pa .RecordBatch ] = []
186- while batch := params .storage .queue_pop_batch ():
187- batches .append (batch )
188- return batches
193+ def combine (
194+ cls , state_ids : list [int ], params : ProcessParams [SingleTableArguments ]
195+ ) -> list [int ]:
196+ """Pass-through partitioning: each state_id is its own finalize key.
197+
198+ No cross-state merging is needed — each thread's buffer is already a
199+ complete, ordered slice of the rows that landed on that thread.
200+ Returning ``state_ids`` lets DuckDB's parallel Source phase drain all
201+ buffers concurrently.
202+ """
203+ return state_ids
204+
205+ @classmethod
206+ def finalize (
207+ cls , finalize_state_id : int , params : ProcessParams [SingleTableArguments ]
208+ ) -> Iterator [pa .RecordBatch ]:
209+ """Yield the buffered batches for one finalize_state_id, one per RPC.
210+
211+ The framework wraps this generator at the worker side: each
212+ ``buffered_table_finalize`` RPC consumes one ``yield`` and reports
213+ ``has_more`` based on whether the iterator is exhausted.
214+ """
215+ stored = params .storage .aggregate_get ([finalize_state_id ])
216+ if not stored or stored [0 ] is None :
217+ return
218+ state = BufferInputState .deserialize_from_bytes (stored [0 ][1 ])
219+ for batch_bytes in state .batches :
220+ yield pa .ipc .open_stream (batch_bytes ).read_next_batch ()
189221
190222
191223class FilterBySettingFunction (TableInOutGenerator [SingleTableArguments ]):
@@ -391,6 +423,10 @@ class Meta:
391423 name = "sum_all_columns"
392424 description = "Computes column-wise sums across all batches"
393425 categories = ["aggregation" , "numeric" ]
426+ # Uses the buffered table function path: each parallel Sink thread
427+ # accumulates per-thread sums, combine reduces them to a single
428+ # partition, finalize yields one row with the total.
429+ buffered_table = True
394430 examples = [
395431 FunctionExample (
396432 sql = "SELECT * FROM sum_all_columns((SELECT * FROM input_table))" ,
@@ -434,6 +470,12 @@ def initial_state(cls, params: ProcessParams[SumAllColumnsFunctionArguments]) ->
434470 )
435471 )
436472
473+ # The state class must be a dataclass-style class for the framework's
474+ # auto-detection from TableInOutGenerator[..., TState], but the
475+ # generic-param plumbing on TableInOutGenerator doesn't auto-populate
476+ # state_class (only TableInOutFunction does). Set it explicitly.
477+ state_class = SumAllColumnsState
478+
437479 @classmethod
438480 def process (
439481 cls ,
@@ -442,7 +484,7 @@ def process(
442484 batch : pa .RecordBatch ,
443485 out : OutputCollector ,
444486 ) -> None :
445- """Accumulate column sums across all batches ."""
487+ """Accumulate this batch into the per-state_id partial_sums ."""
446488 if params .args .logging :
447489 out .client_log (
448490 Level .INFO ,
@@ -459,40 +501,56 @@ def process(
459501 sums [name ] = prev
460502
461503 state .partial_sums = cls ._scalars_to_single_row_batch (sums )
462-
463- # Save running sums to storage for finalize (upsert per worker)
464- params .storage .put (params .storage .serialize_record_batch (state .partial_sums ))
465-
466- out .emit (empty_batch (params .output_schema ))
504+ # No out.emit needed — the buffered NoOpCollector swallows zero-row
505+ # emits but emitting nothing is the cleanest signal that process is
506+ # sink-only here.
467507
468508 @classmethod
469- def finalize (cls , params : ProcessParams [SumAllColumnsFunctionArguments ]) -> list [pa .RecordBatch ]:
470- """Return single row containing the column sums."""
471- sums : dict [str , pa .Scalar [Any ]] = {}
472-
473- # Initialize sums to zero in case no data was processed
474- for field in params .output_schema :
475- sums [field .name ] = pa .scalar (0 , type = field .type )
476-
477- # Retrieve the accumulated sums from function storage and merge.
478- # When process() never stored anything (empty input, or a subclass
479- # like ExceptionProcessFunction that doesn't call super().process()),
480- # storage.collect() returns []. pa.Table.from_batches([]) requires a
481- # schema, so pass it explicitly to avoid a confusing ValueError.
482- batches = [params .storage .deserialize_record_batch (item ) for item in params .storage .collect ()]
483- all_tables = pa .Table .from_batches (batches , schema = params .output_schema )
484-
485- for field in params .output_schema :
486- col_sum = pc .sum (all_tables .column (field .name ))
487- if col_sum .is_valid :
488- sums [field .name ] = col_sum
509+ def combine (
510+ cls , state_ids : list [int ], params : ProcessParams [SumAllColumnsFunctionArguments ]
511+ ) -> list [int ]:
512+ """Merge every per-thread state into a single coordinator state.
513+
514+ Reads each per-state_id ``partial_sums`` from shared BoundStorage,
515+ column-sums them across states, writes the merged result back to
516+ slot 0, and returns ``[0]`` as the only finalize partition. The
517+ finalize phase will yield one row total.
518+ """
519+ if not state_ids :
520+ return []
521+ stored = params .storage .aggregate_get (state_ids )
522+ merged : dict [str , pa .Scalar [Any ]] = {name : pa .scalar (0 , type = field .type )
523+ for name , field in zip (params .output_schema .names ,
524+ params .output_schema )}
525+ for entry in stored :
526+ if entry is None :
527+ continue
528+ partial = SumAllColumnsState .deserialize_from_bytes (entry [1 ]).partial_sums
529+ for name in params .output_schema .names :
530+ merged [name ] = pc .add (merged [name ], partial .column (name )[0 ])
531+ merged_state = SumAllColumnsState (partial_sums = cls ._scalars_to_single_row_batch (merged ))
532+ params .storage .aggregate_put ([(0 , merged_state .serialize_to_bytes ())])
533+ return [0 ]
489534
490- return [
491- pa .RecordBatch .from_pydict (
492- {name : [val ] for name , val in sums .items ()},
493- schema = params .output_schema ,
494- )
495- ]
535+ @classmethod
536+ def finalize (
537+ cls , finalize_state_id : int , params : ProcessParams [SumAllColumnsFunctionArguments ]
538+ ) -> Iterator [pa .RecordBatch ]:
539+ """Yield one row carrying the merged column sums."""
540+ stored = params .storage .aggregate_get ([finalize_state_id ])
541+ if not stored or stored [0 ] is None :
542+ # No data at all — emit zeros so SQL like
543+ # `SELECT * FROM sum_all_columns((SELECT 1 WHERE 1=0))` still
544+ # produces a row with the expected shape.
545+ sums = {name : pa .scalar (0 , type = field .type )
546+ for name , field in zip (params .output_schema .names , params .output_schema )}
547+ yield pa .RecordBatch .from_pydict ({name : [val ] for name , val in sums .items ()},
548+ schema = params .output_schema )
549+ return
550+ partial = SumAllColumnsState .deserialize_from_bytes (stored [0 ][1 ]).partial_sums
551+ sums = {name : partial .column (name )[0 ] for name in params .output_schema .names }
552+ yield pa .RecordBatch .from_pydict ({name : [val ] for name , val in sums .items ()},
553+ schema = params .output_schema )
496554
497555
498556@dataclass (kw_only = True )
@@ -505,14 +563,18 @@ class ExceptionProcessState(ArrowSerializableDataclass):
505563class ExceptionProcessFunction (
506564 SumAllColumnsFunction , TableInOutGenerator [SumAllColumnsFunctionArguments , ExceptionProcessState ]
507565):
508- """A function that raises an exception on the second batch."""
566+ """Buffered table function that raises an exception on the second batch."""
567+
568+ # Use our own state class, overriding SumAllColumnsFunction.state_class.
569+ state_class = ExceptionProcessState
509570
510571 class Meta (SumAllColumnsFunction .Meta ):
511572 """Metadata for ExceptionProcessFunction."""
512573
513574 name = "exception_process"
514575 description = "Test function that raises exception during process"
515576 categories = ["test" , "error" ]
577+ # buffered_table inherited from SumAllColumnsFunction.Meta
516578
517579 @classmethod
518580 def initial_state (cls , params : ProcessParams [SumAllColumnsFunctionArguments ]) -> ExceptionProcessState : # type: ignore[override]
@@ -531,23 +593,45 @@ def process( # type: ignore[override]
531593 state .batch_count += 1
532594 if state .batch_count % 2 == 0 :
533595 raise ValueError (f"Intentional exception on batch { state .batch_count } " )
534- out .emit (empty_batch (params .output_schema ))
596+ # Sink-only — no emit needed.
597+
598+ @classmethod
599+ def combine ( # type: ignore[override]
600+ cls , state_ids : list [int ], params : ProcessParams [SumAllColumnsFunctionArguments ]
601+ ) -> list [int ]:
602+ # Pass-through partitioning: no aggregation across states needed.
603+ return state_ids
604+
605+ @classmethod
606+ def finalize ( # type: ignore[override]
607+ cls , finalize_state_id : int , params : ProcessParams [SumAllColumnsFunctionArguments ]
608+ ) -> Iterator [pa .RecordBatch ]:
609+ # If we ever reach finalize, emit a zero-sum row (the only behavior
610+ # the existing test asserts is the *exception* path from process).
611+ sums = {name : pa .scalar (0 , type = field .type )
612+ for name , field in zip (params .output_schema .names , params .output_schema )}
613+ yield pa .RecordBatch .from_pydict ({name : [val ] for name , val in sums .items ()},
614+ schema = params .output_schema )
535615
536616
537617class ExceptionFinalizeFunction (SumAllColumnsFunction ):
538- """Test function that raises an exception during finalize()."""
618+ """Buffered table function that raises an exception during finalize()."""
539619
540620 class Meta (SumAllColumnsFunction .Meta ):
541621 """Metadata for ExceptionFinalizeFunction."""
542622
543623 name = "exception_finalize"
544624 description = "Test function that raises exception during finalize"
545625 categories = ["test" , "error" ]
626+ # buffered_table inherited from SumAllColumnsFunction.Meta
546627
547628 @classmethod
548- def finalize (cls , params : ProcessParams [SumAllColumnsFunctionArguments ]) -> list [pa .RecordBatch ]:
549- """Raise an intentional exception during finalize."""
629+ def finalize ( # type: ignore[override]
630+ cls , finalize_state_id : int , params : ProcessParams [SumAllColumnsFunctionArguments ]
631+ ) -> Iterator [pa .RecordBatch ]:
632+ """Raise an intentional exception when the C++ side pulls a batch."""
550633 raise ValueError ("Intentional exception during finalize()" )
634+ yield # type: ignore[unreachable] # make this a generator function
551635
552636
553637@dataclass (slots = True , kw_only = True )
0 commit comments