Skip to content

Commit ac1caf4

Browse files
rustyconoverclaude
andcommitted
streaming-partitioned aggregate fixture for integration tests
Add StreamingSumFunction to _test_fixtures/aggregate/streaming.py — a reference implementation of the streaming-partitioned protocol matching the windowed-aggregate fixture style (window.py). Cumulative running sum across (PARTITION BY key) partitions, in ORDER BY order; emits one running value per input row. The function implements both paths: * GROUP BY — initial_state / update / combine / finalize * Streaming — streaming_open / streaming_chunk / streaming_close so the same SQL function works in both shapes: SELECT k, vgi_streaming_sum(v) OVER (PARTITION BY k ORDER BY ts) FROM trades; -- streaming-partitioned SELECT k, vgi_streaming_sum(v) FROM trades GROUP BY k; -- group-by Wired into the fixture worker (vgi/_test_fixtures/worker.py) so the example catalog exposes vgi_streaming_sum. The companion sqllogictest in the vgi extension (test/sql/integration/aggregate/ streaming.test) covers correctness, parity with built-in sum() OVER, multi-partition interleaving, multi-window-expression queries, GROUP BY fallback, and streaming-on/off via the vgi_streaming_window setting. Also: MetaWorker (the dispatcher used by vgi-fixture-worker to route across multiple workers) gets aggregate_streaming_open / _chunk / _close forwarders alongside the existing aggregate_window_* forwarders. Without these, vgi_rpc's protocol validator rejects the MetaWorker for missing methods. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
1 parent 81f7236 commit ac1caf4

4 files changed

Lines changed: 214 additions & 0 deletions

File tree

‎vgi/_test_fixtures/aggregate/__init__.py‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
* :mod:`.dynamic` — dynamic_aggregate, dynamic_ml_aggregate
1414
(gated on VGI_WORKER_SUPPORTS_DYNAMIC_CODE)
1515
* :mod:`.window` — window_sum, window_median, window_listagg
16+
* :mod:`.streaming` — streaming_sum (streaming-partitioned protocol)
1617
"""
1718

1819
from vgi._test_fixtures.aggregate._common import ListAggState, SumState
@@ -29,6 +30,7 @@
2930
from vgi._test_fixtures.aggregate.generic import GenericSumFunction
3031
from vgi._test_fixtures.aggregate.listagg import ListAggFunction
3132
from vgi._test_fixtures.aggregate.percentile import PercentileFunction
33+
from vgi._test_fixtures.aggregate.streaming import StreamingSumFunction
3234
from vgi._test_fixtures.aggregate.varargs import SumAllFunction
3335
from vgi._test_fixtures.aggregate.window import (
3436
WindowListAggFunction,
@@ -46,6 +48,7 @@
4648
"ListAggFunction",
4749
"ListAggState",
4850
"PercentileFunction",
51+
"StreamingSumFunction",
4952
"SumAllFunction",
5053
"SumFunction",
5154
"SumState",
Lines changed: 197 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,197 @@
1+
"""Streaming-partitioned aggregate fixtures.
2+
3+
Exercise the ``streaming_partitioned`` opt-in: ``streaming_open`` /
4+
``streaming_chunk`` / ``streaming_close``. These are routed through the
5+
VGI DuckDB extension's custom streaming operator, which pipes input
6+
chunks straight to the worker without materialising the partition on
7+
the DuckDB side. State is bounded by partitions × per-partition state,
8+
not by row count — the structural answer to "running aggregate over
9+
unbounded ordered input."
10+
11+
These fixtures are reference implementations for the protocol. Real
12+
production aggregates (e.g. ``portfolio_agg``) follow the same shape
13+
but with domain-specific state and I/O optimisations (Decimal128 buffer
14+
tricks, etc.).
15+
16+
When the optimizer rule rejects a query (non-cumulative frame, EXCLUDE
17+
clause, DISTINCT/FILTER, etc.) DuckDB falls back to the standard
18+
windowed path — so all three of these classes also implement
19+
update/combine/finalize for plain GROUP BY usage and (optionally) the
20+
windowed callbacks. The streaming methods are additive.
21+
"""
22+
23+
from __future__ import annotations
24+
25+
from dataclasses import dataclass
26+
from typing import Annotated, Any
27+
28+
import pyarrow as pa
29+
from vgi_rpc import ArrowSerializableDataclass
30+
31+
from vgi._test_fixtures.aggregate._common import SumState
32+
from vgi.aggregate_function import AggregateFunction
33+
from vgi.arguments import Param, Returns
34+
from vgi.metadata import DistinctDependence, NullHandling, OrderDependence
35+
from vgi.table_function import ProcessParams
36+
37+
38+
class StreamingSumFunction(AggregateFunction[SumState]):
39+
"""Streaming-partitioned running sum.
40+
41+
Cumulative across each `(PARTITION BY key)` group, in `ORDER BY` order.
42+
For every input row, emits the running sum of the value column at that
43+
row's position in its partition.
44+
45+
Also wired for ``GROUP BY`` via ``update`` / ``combine`` / ``finalize``,
46+
so the same function works in both shapes::
47+
48+
-- streaming-partitioned (one running value per fill row):
49+
SELECT k, v, vgi_streaming_sum(v) OVER (PARTITION BY k ORDER BY ts)
50+
FROM trades;
51+
52+
-- group-by (one final value per partition):
53+
SELECT k, vgi_streaming_sum(v) FROM trades GROUP BY k;
54+
55+
State persistence: the per-partition dict lives in worker memory in an
56+
in-process LRU and is also persisted to ``FunctionStorage`` after each
57+
chunk so a follow-up chunk landing on a different worker pool entry
58+
can rehydrate. No special handling required from this class — the
59+
framework does it.
60+
"""
61+
62+
class Meta:
63+
name = "vgi_streaming_sum"
64+
description = (
65+
"Running sum across PARTITION BY keys via the streaming-partitioned "
66+
"protocol. Each input row emits the cumulative sum at its position."
67+
)
68+
null_handling = NullHandling.DEFAULT
69+
order_dependent = OrderDependence.NOT_ORDER_DEPENDENT
70+
distinct_dependent = DistinctDependence.NOT_DISTINCT_DEPENDENT
71+
supports_window = False
72+
# Opt into the streaming-partitioned operator. The optimizer rule
73+
# will route eligible OVER queries through it; ineligible shapes
74+
# (sliding frames, EXCLUDE, DISTINCT, FILTER) fall back to the
75+
# standard windowed path automatically.
76+
streaming_partitioned = True
77+
78+
# ------------------------------------------------------------------
79+
# GROUP BY path — required for plain aggregation queries.
80+
# ------------------------------------------------------------------
81+
82+
@classmethod
83+
def initial_state(cls, params: ProcessParams[None]) -> SumState:
84+
return SumState()
85+
86+
@classmethod
87+
def update(
88+
cls,
89+
states: dict[int, SumState],
90+
group_ids: pa.Int64Array,
91+
value: Annotated[pa.Int64Array, Param(doc="Column to sum")],
92+
) -> None:
93+
table = pa.table({"gid": group_ids, "value": value})
94+
grouped = table.group_by("gid").aggregate([("value", "sum")])
95+
for i in range(grouped.num_rows):
96+
gid: int = grouped.column("gid")[i].as_py()
97+
v = grouped.column("value_sum")[i].as_py()
98+
if v is not None:
99+
states[gid] = SumState(total=states[gid].total + v)
100+
101+
@classmethod
102+
def combine(
103+
cls, source: SumState, target: SumState, params: ProcessParams[None]
104+
) -> SumState:
105+
return SumState(total=source.total + target.total)
106+
107+
@classmethod
108+
def finalize(
109+
cls,
110+
group_ids: pa.Int64Array,
111+
states: dict[int, SumState],
112+
params: ProcessParams[None],
113+
) -> Annotated[pa.RecordBatch, Returns(pa.int64())]:
114+
results = [
115+
(s.total if (s := states.get(gid.as_py())) is not None else None)
116+
for gid in group_ids
117+
]
118+
return pa.record_batch({"result": pa.array(results, type=pa.int64())})
119+
120+
# ------------------------------------------------------------------
121+
# Streaming-partitioned path.
122+
# ------------------------------------------------------------------
123+
#
124+
# Three callbacks: open / chunk / close. The framework handles session
125+
# lifecycle (allocates execution_id, persists to FunctionStorage,
126+
# rehydrates across pool workers); user code only owns the in-memory
127+
# state object.
128+
129+
@classmethod
130+
def streaming_open(cls, params: ProcessParams[None]) -> dict[str, Any]:
131+
# Session state. Free shape — anything picklable. The framework
132+
# passes this object back to streaming_chunk and streaming_close
133+
# unchanged. For multi-partition aggregates, hold a per-partition
134+
# dict here; for single-partition, just hold the running scalar.
135+
return {
136+
# partition_key_tuple -> running int sum
137+
"partition_states": {},
138+
}
139+
140+
@classmethod
141+
def streaming_chunk(
142+
cls,
143+
chunk: pa.RecordBatch,
144+
streaming_state: dict[str, Any],
145+
partition_key_count: int,
146+
order_key_count: int,
147+
params: ProcessParams[None],
148+
) -> pa.Array:
149+
# Column layout from the operator:
150+
# [partition_key_cols..., order_key_cols..., value_cols...]
151+
# We don't actually need the order keys at runtime here — the
152+
# input arrives in (partition, order) order already, so cumulative
153+
# state is naturally correct.
154+
n = chunk.num_rows
155+
value_idx = partition_key_count + order_key_count
156+
157+
if partition_key_count > 0:
158+
pk_columns = [chunk.column(i).to_pylist() for i in range(partition_key_count)]
159+
else:
160+
pk_columns = []
161+
values = chunk.column(value_idx).to_pylist()
162+
163+
partition_states: dict[Any, int] = streaming_state["partition_states"]
164+
165+
# Returns one cumulative-sum int per input row. NULL value rows
166+
# leave state unchanged but still emit the current sum (matches
167+
# the GROUP BY path's NullHandling.DEFAULT semantics).
168+
out: list[int] = [0] * n
169+
for i in range(n):
170+
if partition_key_count == 0:
171+
key: Any = ()
172+
elif partition_key_count == 1:
173+
key = pk_columns[0][i]
174+
else:
175+
key = tuple(col[i] for col in pk_columns)
176+
177+
running = partition_states.get(key, 0)
178+
v = values[i]
179+
if v is not None:
180+
running += v
181+
partition_states[key] = running
182+
out[i] = running
183+
184+
return pa.array(out, type=pa.int64())
185+
186+
@classmethod
187+
def streaming_close(
188+
cls,
189+
streaming_state: dict[str, Any],
190+
params: ProcessParams[None],
191+
) -> None:
192+
# Cleanup hook. For this fixture there's nothing to release;
193+
# state is plain Python objects that GC collects when the
194+
# session is dropped from the framework's cache. Real
195+
# implementations might release file handles, close DB
196+
# connections, or flush logs here.
197+
return None

‎vgi/_test_fixtures/worker.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@
4242
GenericSumFunction,
4343
ListAggFunction,
4444
PercentileFunction,
45+
StreamingSumFunction,
4546
SumAllFunction,
4647
SumFunction,
4748
WeightedSumFunction,
@@ -357,6 +358,7 @@ def _build_enum_stats() -> dict[str, ColumnStatisticsInput]:
357358
ListAggFunction,
358359
NestTensorFunction,
359360
PercentileFunction,
361+
StreamingSumFunction,
360362
SumAllFunction,
361363
SumFunction,
362364
WeightedSumFunction,

‎vgi/meta_worker.py‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -363,6 +363,18 @@ def aggregate_window_batch(self, request: Any, ctx: CallContext) -> Any:
363363
"""Dispatch aggregate_window_batch to the right worker."""
364364
return self._dispatch_aggregate(request, "aggregate_window_batch", ctx)
365365

366+
def aggregate_streaming_open(self, request: Any, ctx: CallContext) -> Any:
367+
"""Dispatch aggregate_streaming_open to the right worker."""
368+
return self._dispatch_aggregate(request, "aggregate_streaming_open", ctx)
369+
370+
def aggregate_streaming_chunk(self, request: Any, ctx: CallContext) -> Any:
371+
"""Dispatch aggregate_streaming_chunk to the right worker."""
372+
return self._dispatch_aggregate(request, "aggregate_streaming_chunk", ctx)
373+
374+
def aggregate_streaming_close(self, request: Any, ctx: CallContext) -> Any:
375+
"""Dispatch aggregate_streaming_close to the right worker."""
376+
return self._dispatch_aggregate(request, "aggregate_streaming_close", ctx)
377+
366378
# ========== Serve entry point ==========
367379

368380
@classmethod

0 commit comments

Comments
 (0)