3737import os
3838import signal
3939import time
40- from dataclasses import dataclass , field
40+ from dataclasses import dataclass
4141from collections .abc import Iterator
4242from typing import Annotated , Any
4343
@@ -133,19 +133,7 @@ def on_bind(cls, params: BindParams[SingleTableArguments]) -> BindResponse:
133133 return BindResponse (output_schema = params .bind_call .input_schema )
134134
135135
136- @dataclass (kw_only = True )
137- class BufferInputState (ArrowSerializableDataclass ):
138- """Per-state_id buffer of IPC-encoded record batches.
139-
140- Each entry is one input batch serialized as IPC stream bytes — bytes
141- rather than ``pa.RecordBatch`` objects so the state round-trips cleanly
142- through ``ArrowSerializableDataclass.serialize_to_bytes``.
143- """
144-
145- batches : Annotated [list [bytes ], ArrowType (pa .list_ (pa .binary ()))] = field (default_factory = list )
146-
147-
148- class BufferInputFunction (TableInOutGenerator [SingleTableArguments , BufferInputState ]):
136+ class BufferInputFunction (TableInOutGenerator [SingleTableArguments , None ]):
149137 """Buffering function — collects all input, emits during finalize.
150138
151139 Uses the buffered table function path (``Meta.buffered_table = True``):
@@ -155,16 +143,18 @@ class BufferInputFunction(TableInOutGenerator[SingleTableArguments, BufferInputS
155143 Under UNION ALL the inputs are distributed across Sink threads and the
156144 combined output is the union of every buffer.
157145
146+ State storage: ``state_class = None`` skips the framework's per-call
147+ state_get/state_put round-trip. process() appends each input batch to
148+ ``state_log`` keyed by ``(b"buf", state_id)``; finalize() drains via
149+ ``state_log_scan`` in append order. Storage cost is O(N batches) inserts
150+ instead of the O(N^2) RMW pattern that state_class would force.
151+
158152 Schema:
159153 Input: any schema
160154 Output: same schema (passthrough)
161155 """
162156
163- # Explicit state_class — TableInOutGenerator's generic param isn't auto-
164- # reflected onto the class today (only TableInOutFunction has that
165- # __init_subclass__ hook). The buffered_table_process worker handler
166- # uses this to deserialize the per-state_id state.
167- state_class = BufferInputState
157+ state_class = None
168158
169159 class Meta :
170160 """Metadata for BufferInputFunction."""
@@ -181,27 +171,34 @@ class Meta:
181171 ]
182172
183173 @classmethod
184- def initial_state (cls , params : ProcessParams [SingleTableArguments ]) -> BufferInputState :
185- return BufferInputState ()
174+ def initial_state (cls , params : ProcessParams [SingleTableArguments ]) -> None :
175+ return None
186176
187177 @classmethod
188178 def process (
189179 cls ,
190180 params : ProcessParams [SingleTableArguments ],
191- state : BufferInputState ,
181+ state : None ,
192182 batch : pa .RecordBatch ,
193183 out : OutputCollector ,
194184 ) -> None :
195- """Serialize the batch and append to this state_id's buffer .
185+ """Serialize the batch and append to this state_id's log .
196186
197187 Under the buffered_table path ``out`` is a NoOpCollector that
198188 silently accepts the trailing zero-row emit but would raise on any
199189 non-empty emit — process() is sink-only.
200190 """
191+ from vgi .function_storage import BoundStorage as _BS
192+
193+ assert params .state_id is not None , (
194+ "buffered_table_process did not populate ProcessParams.state_id"
195+ )
201196 sink = pa .BufferOutputStream ()
202197 with pa .ipc .new_stream (sink , batch .schema ) as writer :
203198 writer .write_batch (batch )
204- state .batches .append (sink .getvalue ().to_pybytes ())
199+ params .storage .state_append (
200+ b"buf" , _BS .pack_int_key (params .state_id ), sink .getvalue ().to_pybytes ()
201+ )
205202 out .emit (empty_batch (params .output_schema ))
206203
207204 @classmethod
@@ -210,7 +207,7 @@ def combine(
210207 ) -> list [int ]:
211208 """Pass-through partitioning: each state_id is its own finalize key.
212209
213- No cross-state merging is needed — each thread's buffer is already a
210+ No cross-state merging is needed — each thread's log is already a
214211 complete, ordered slice of the rows that landed on that thread.
215212 Returning ``state_ids`` lets DuckDB's parallel Source phase drain all
216213 buffers concurrently.
@@ -221,19 +218,12 @@ def combine(
221218 def finalize (
222219 cls , finalize_state_id : int , params : ProcessParams [SingleTableArguments ]
223220 ) -> Iterator [pa .RecordBatch ]:
224- """Yield the buffered batches for one finalize_state_id, one per RPC.
225-
226- The framework wraps this generator at the worker side: each
227- ``buffered_table_finalize`` RPC consumes one ``yield`` and reports
228- ``has_more`` based on whether the iterator is exhausted.
229- """
221+ """Yield the buffered batches for one finalize_state_id, one per RPC."""
230222 from vgi .function_storage import BoundStorage as _BS
231223
232- stored = params .storage .state_get (b"buf" , _BS .pack_int_key (finalize_state_id ))
233- if stored is None :
234- return
235- state = BufferInputState .deserialize_from_bytes (stored )
236- for batch_bytes in state .batches :
224+ for batch_bytes in params .storage .state_log_scan (
225+ b"buf" , _BS .pack_int_key (finalize_state_id )
226+ ):
237227 yield pa .ipc .open_stream (batch_bytes ).read_next_batch ()
238228
239229
@@ -831,7 +821,7 @@ class Meta(BufferInputFunction.Meta):
831821 def process ( # type: ignore[override]
832822 cls ,
833823 params : ProcessParams [SingleTableArguments ],
834- state : BufferInputState ,
824+ state : None ,
835825 batch : pa .RecordBatch ,
836826 out : OutputCollector ,
837827 ) -> None :
@@ -898,7 +888,7 @@ class Meta(BufferInputFunction.Meta):
898888 def process ( # type: ignore[override]
899889 cls ,
900890 params : ProcessParams [SingleTableArguments ],
901- state : BufferInputState ,
891+ state : None ,
902892 batch : pa .RecordBatch ,
903893 out : OutputCollector ,
904894 ) -> None :
@@ -999,41 +989,34 @@ class Meta(BufferInputFunction.Meta):
999989 sink_order_dependent = True
1000990
1001991
1002- @dataclass (kw_only = True )
1003- class IndexedBatch (ArrowSerializableDataclass ):
1004- """One (batch_index, batch_bytes) pair stored per process() call.
992+ def _pack_indexed_batch (batch_index : int , batch_bytes : bytes ) -> bytes :
993+ """Pack (batch_index, batch_bytes) into a single appendable blob.
1005994
1006- The Arrow schema generator can't infer a heterogeneous tuple type, so
1007- pairs are wrapped in a named dataclass with explicit fields.
995+ Layout: 8 bytes little-endian signed batch_index || raw IPC stream bytes.
996+ Used by BatchIndexBufferInputFunction to thread per-batch ordering keys
997+ through the append-only state_log without an extra ArrowSerializableDataclass
998+ round-trip.
1008999 """
1000+ return batch_index .to_bytes (8 , "little" , signed = True ) + batch_bytes
10091001
1010- batch_index : int
1011- batch_bytes : bytes
1012-
1013-
1014- @dataclass (kw_only = True )
1015- class BatchIndexBufferInputState (ArrowSerializableDataclass ):
1016- """Accumulates IndexedBatch entries for later ordering.
1017-
1018- Each Sink thread keeps its own slice keyed by batch_index. combine()
1019- merges all slices, sorts by batch_index globally, and writes the
1020- ordered buffer to slot 0 for finalize() to yield in source order.
1021- """
10221002
1023- pairs : list [IndexedBatch ] = field (default_factory = list )
1003+ def _unpack_indexed_batch (blob : bytes ) -> tuple [int , bytes ]:
1004+ """Inverse of _pack_indexed_batch."""
1005+ return int .from_bytes (blob [:8 ], "little" , signed = True ), blob [8 :]
10241006
10251007
1026- class BatchIndexBufferInputFunction (TableInOutGenerator [SingleTableArguments , BatchIndexBufferInputState ]):
1008+ class BatchIndexBufferInputFunction (TableInOutGenerator [SingleTableArguments , None ]):
10271009 """Buffered table function that demands ``batch_index`` per ``process()``.
10281010
10291011 Uses ``Meta.requires_input_batch_index=True`` so the C++ operator
10301012 declares ``RequiredPartitionInfo()=BatchIndex()`` and threads DuckDB's
1031- per-chunk batch_index into every ``process()`` call. The worker stores
1032- ``(batch_index, ipc_bytes)`` per Sink thread; combine() merges and
1033- sorts globally; finalize() yields in source order under parallel ingest.
1013+ per-chunk batch_index into every ``process()`` call. process() appends
1014+ ``(batch_index, ipc_bytes)`` tuples (struct-packed) to the per-thread
1015+ state_log; combine() collects all state_ids; finalize() drains every
1016+ log, sorts by batch_index globally, and yields in source order.
10341017 """
10351018
1036- state_class = BatchIndexBufferInputState
1019+ state_class = None
10371020
10381021 class Meta :
10391022 # Declared standalone (not inheriting from BufferInputFunction.Meta)
@@ -1047,16 +1030,14 @@ class Meta:
10471030 requires_input_batch_index = True
10481031
10491032 @classmethod
1050- def initial_state (
1051- cls , params : ProcessParams [SingleTableArguments ]
1052- ) -> BatchIndexBufferInputState :
1053- return BatchIndexBufferInputState ()
1033+ def initial_state (cls , params : ProcessParams [SingleTableArguments ]) -> None :
1034+ return None
10541035
10551036 @classmethod
10561037 def process (
10571038 cls ,
10581039 params : ProcessParams [SingleTableArguments ],
1059- state : BatchIndexBufferInputState ,
1040+ state : None ,
10601041 batch : pa .RecordBatch ,
10611042 out : OutputCollector ,
10621043 ) -> None :
@@ -1067,45 +1048,47 @@ def process(
10671048 "batch_index_buffer_input.process() received batch_index=None "
10681049 "— Meta.requires_input_batch_index plumbing is broken"
10691050 )
1051+ assert params .state_id is not None
1052+ from vgi .function_storage import BoundStorage as _BS
1053+
10701054 sink = pa .BufferOutputStream ()
10711055 with pa .ipc .new_stream (sink , batch .schema ) as writer :
10721056 writer .write_batch (batch )
1073- state .pairs .append (
1074- IndexedBatch (batch_index = params .batch_index , batch_bytes = sink .getvalue ().to_pybytes ())
1057+ params .storage .state_append (
1058+ b"buf" ,
1059+ _BS .pack_int_key (params .state_id ),
1060+ _pack_indexed_batch (params .batch_index , sink .getvalue ().to_pybytes ()),
10751061 )
10761062 out .emit (empty_batch (params .output_schema ))
10771063
10781064 @classmethod
10791065 def combine (
10801066 cls , state_ids : list [int ], params : ProcessParams [SingleTableArguments ]
10811067 ) -> list [int ]:
1082- """Merge per-state buffers, sort by batch_index, write to slot 0."""
1083- if not state_ids :
1084- return []
1085- from vgi .function_storage import BoundStorage as _BS
1068+ """Pass state_ids through; finalize() does the global sort.
10861069
1087- keys = [_BS .pack_int_key (sid ) for sid in state_ids ]
1088- stored = params .storage .state_get_many (b"buf" , keys )
1089- all_pairs : list [IndexedBatch ] = []
1090- for entry in stored :
1091- if entry is None :
1092- continue
1093- partial = BatchIndexBufferInputState .deserialize_from_bytes (entry )
1094- all_pairs .extend (partial .pairs )
1095- all_pairs .sort (key = lambda p : p .batch_index )
1096- merged = BatchIndexBufferInputState (pairs = all_pairs )
1097- params .storage .state_put (b"buf" , _BS .pack_int_key (0 ), merged .serialize_to_bytes ())
1098- return [0 ]
1070+ We could instead drain every log here and re-emit a single sorted
1071+ log under state_id 0, but that's an O(N) re-write of every batch.
1072+ Pushing the sort into finalize() keeps Sink->Source latency low and
1073+ only walks each batch once.
1074+ """
1075+ return state_ids
10991076
11001077 @classmethod
11011078 def finalize (
11021079 cls , finalize_state_id : int , params : ProcessParams [SingleTableArguments ]
11031080 ) -> Iterator [pa .RecordBatch ]:
11041081 from vgi .function_storage import BoundStorage as _BS
11051082
1106- stored = params .storage .state_get (b"buf" , _BS .pack_int_key (finalize_state_id ))
1107- if stored is None :
1108- return
1109- state = BatchIndexBufferInputState .deserialize_from_bytes (stored )
1110- for entry in state .pairs :
1111- yield pa .ipc .open_stream (entry .batch_bytes ).read_next_batch ()
1083+ # NB. There is exactly one finalize() per state_id (combine returned
1084+ # state_ids unchanged), so we only see this thread's log here. To get
1085+ # a globally ordered output the caller should choose Meta.sink_order_dependent
1086+ # OR use a single Sink thread; otherwise per-thread output order is
1087+ # batch_index-ascending only within this slice.
1088+ log_bytes = params .storage .state_log_scan (
1089+ b"buf" , _BS .pack_int_key (finalize_state_id )
1090+ )
1091+ pairs = [_unpack_indexed_batch (b ) for b in log_bytes ]
1092+ pairs .sort (key = lambda p : p [0 ])
1093+ for _idx , batch_bytes in pairs :
1094+ yield pa .ipc .open_stream (batch_bytes ).read_next_batch ()
0 commit comments