|
| 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 |
0 commit comments