Skip to content

Commit a6e87d3

Browse files
committed
window batch experiements
1 parent 60cf0b3 commit a6e87d3

7 files changed

Lines changed: 334 additions & 14 deletions

File tree

‎tests/test_aggregate_function.py‎

Lines changed: 144 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -724,3 +724,147 @@ def _make_dummy_params(output_type: pa.DataType) -> ProcessParams[None]:
724724
secrets={},
725725
storage=BoundStorage(storage, b"dummy"),
726726
)
727+
728+
729+
# =========================================================================
730+
# Test Group 5: window_batch hook
731+
# =========================================================================
732+
733+
734+
def _make_window_partition(values: list[int | None]) -> Any:
735+
"""Build a single-column int64 WindowPartition for batch-window tests."""
736+
from vgi.aggregate_function import WindowPartition
737+
738+
arr = pa.array(values, type=pa.int64())
739+
batch = pa.record_batch({"value": arr})
740+
return WindowPartition(
741+
inputs=batch,
742+
row_count=len(values),
743+
filter_mask=None,
744+
frame_stats=((0, 0), (0, 0)),
745+
all_valid=[True],
746+
)
747+
748+
749+
class TestWindowBatchDefault:
750+
"""Default ``window_batch`` should call ``window`` once per row."""
751+
752+
def test_dispatches_to_window_per_row(self) -> None:
753+
from vgi._test_fixtures.aggregate import WindowSumFunction
754+
755+
partition = _make_window_partition([1, 2, 3, 4, 5])
756+
result = WindowSumFunction.window_batch(
757+
row_ids=[0, 1, 2, 3, 4],
758+
subframes=[
759+
[(0, 1)], [(0, 2)], [(0, 3)], [(0, 4)], [(0, 5)],
760+
],
761+
partition=partition,
762+
window_state=None,
763+
params=_make_dummy_params(pa.int64()),
764+
)
765+
# Default returns list[Any] — same shape as calling window() per row.
766+
assert isinstance(result, list)
767+
assert result == [1, 3, 6, 10, 15]
768+
769+
def test_default_matches_window_per_row(self) -> None:
770+
"""Per-row window() and default window_batch() return the same values."""
771+
from vgi._test_fixtures.aggregate import WindowSumFunction
772+
773+
partition = _make_window_partition([10, 20, 30])
774+
params = _make_dummy_params(pa.int64())
775+
776+
per_row = [
777+
WindowSumFunction.window(rid, [(0, rid + 1)], partition, None, params)
778+
for rid in range(3)
779+
]
780+
batched = WindowSumFunction.window_batch(
781+
row_ids=[0, 1, 2],
782+
subframes=[[(0, 1)], [(0, 2)], [(0, 3)]],
783+
partition=partition,
784+
window_state=None,
785+
params=params,
786+
)
787+
assert per_row == batched
788+
789+
790+
class TestWindowBatchOverride:
791+
"""Overridden ``window_batch`` may return a pa.Array directly."""
792+
793+
def test_returns_pa_array_when_overridden(self) -> None:
794+
from vgi._test_fixtures.aggregate import WindowSumBatchFunction
795+
796+
partition = _make_window_partition([1, 2, 3, 4, 5])
797+
result = WindowSumBatchFunction.window_batch(
798+
row_ids=[0, 1, 2, 3, 4],
799+
subframes=[
800+
[(0, 1)], [(0, 2)], [(0, 3)], [(0, 4)], [(0, 5)],
801+
],
802+
partition=partition,
803+
window_state=None,
804+
params=_make_dummy_params(pa.int64()),
805+
)
806+
assert isinstance(result, pa.Array)
807+
assert result.type == pa.int64()
808+
assert result.to_pylist() == [1, 3, 6, 10, 15]
809+
810+
def test_override_matches_default(self) -> None:
811+
"""The overriding fixture computes the same answers as the default path."""
812+
from vgi._test_fixtures.aggregate import (
813+
WindowSumBatchFunction,
814+
WindowSumFunction,
815+
)
816+
817+
partition = _make_window_partition([1, 2, 3, 4, 5])
818+
params = _make_dummy_params(pa.int64())
819+
subframes = [[(0, i + 1)] for i in range(5)]
820+
821+
default_path = WindowSumFunction.window_batch(
822+
row_ids=[0, 1, 2, 3, 4],
823+
subframes=subframes,
824+
partition=partition,
825+
window_state=None,
826+
params=params,
827+
)
828+
override_path = WindowSumBatchFunction.window_batch(
829+
row_ids=[0, 1, 2, 3, 4],
830+
subframes=subframes,
831+
partition=partition,
832+
window_state=None,
833+
params=params,
834+
)
835+
assert default_path == override_path.to_pylist()
836+
837+
838+
class TestBuildBatchResult:
839+
"""``_build_batch_result`` accepts both list and pa.Array, validates shape."""
840+
841+
def test_list_input_packs_via_pa_array(self) -> None:
842+
from vgi.worker import _build_batch_result
843+
844+
schema = pa.schema([("result", pa.int64())])
845+
batch = _build_batch_result([1, 2, 3], schema, expected_count=3)
846+
assert batch.column("result").to_pylist() == [1, 2, 3]
847+
848+
def test_pa_array_input_shipped_directly(self) -> None:
849+
from vgi.worker import _build_batch_result
850+
851+
schema = pa.schema([("result", pa.int64())])
852+
arr = pa.array([10, 20, 30], type=pa.int64())
853+
batch = _build_batch_result(arr, schema, expected_count=3)
854+
# The returned column is the same Arrow array we passed in.
855+
assert batch.column("result").to_pylist() == [10, 20, 30]
856+
857+
def test_pa_array_wrong_type_raises(self) -> None:
858+
from vgi.worker import _build_batch_result
859+
860+
schema = pa.schema([("result", pa.int64())])
861+
arr = pa.array([1.0, 2.0, 3.0], type=pa.float64())
862+
with pytest.raises(TypeError, match="expected int64"):
863+
_build_batch_result(arr, schema, expected_count=3)
864+
865+
def test_count_mismatch_raises(self) -> None:
866+
from vgi.worker import _build_batch_result
867+
868+
schema = pa.schema([("result", pa.int64())])
869+
with pytest.raises(ValueError, match="expected 5"):
870+
_build_batch_result([1, 2, 3], schema, expected_count=5)

‎uv.lock‎

Lines changed: 2 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎vgi/_test_fixtures/aggregate/__init__.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@
3333
from vgi._test_fixtures.aggregate.window import (
3434
WindowListAggFunction,
3535
WindowMedianFunction,
36+
WindowSumBatchFunction,
3637
WindowSumFunction,
3738
)
3839

@@ -51,5 +52,6 @@
5152
"WeightedSumFunction",
5253
"WindowListAggFunction",
5354
"WindowMedianFunction",
55+
"WindowSumBatchFunction",
5456
"WindowSumFunction",
5557
]

‎vgi/_test_fixtures/aggregate/window.py‎

Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -270,3 +270,107 @@ def window(
270270
if v is not None:
271271
parts.append(v)
272272
return ",".join(parts) if parts else None
273+
274+
275+
class WindowSumBatchFunction(AggregateFunction[SumState]):
276+
"""Windowed running-sum that overrides ``window_batch`` to return a
277+
pre-built ``pa.Array`` rather than a Python list.
278+
279+
Functionally equivalent to :class:`WindowSumFunction`. The point of this
280+
fixture is to exercise the framework's polymorphic batch return: when
281+
user code returns a ``pa.Array``, the worker should ship it directly
282+
without round-tripping through ``pa.array(list, type=...)``.
283+
284+
Used by the unit tests for ``window_batch`` to confirm the dispatcher
285+
accepts both a list and a pa.Array, and that the pa.Array path
286+
produces identical answers.
287+
"""
288+
289+
class Meta:
290+
name = "vgi_window_sum_batch"
291+
description = "Windowed sum demonstrating window_batch returning pa.Array"
292+
null_handling = NullHandling.DEFAULT
293+
order_dependent = OrderDependence.NOT_ORDER_DEPENDENT
294+
distinct_dependent = DistinctDependence.NOT_DISTINCT_DEPENDENT
295+
supports_window = True
296+
297+
@classmethod
298+
def initial_state(cls, params: ProcessParams[None]) -> SumState:
299+
return SumState()
300+
301+
@classmethod
302+
def update(
303+
cls,
304+
states: dict[int, SumState],
305+
group_ids: pa.Int64Array,
306+
value: Annotated[pa.Int64Array, Param(doc="Column to sum")],
307+
) -> None:
308+
table = pa.table({"gid": group_ids, "value": value})
309+
grouped = table.group_by("gid").aggregate([("value", "sum")])
310+
for i in range(grouped.num_rows):
311+
gid: int = grouped.column("gid")[i].as_py()
312+
val = grouped.column("value_sum")[i].as_py()
313+
if val is not None:
314+
states[gid] = SumState(total=states[gid].total + val)
315+
316+
@classmethod
317+
def combine(cls, source: SumState, target: SumState, params: ProcessParams[None]) -> SumState:
318+
return SumState(total=source.total + target.total)
319+
320+
@classmethod
321+
def finalize(
322+
cls,
323+
group_ids: pa.Int64Array,
324+
states: dict[int, SumState],
325+
params: ProcessParams[None],
326+
) -> Annotated[pa.RecordBatch, Returns(pa.int64())]:
327+
results = [s.total if (s := states[gid.as_py()]) is not None else None for gid in group_ids]
328+
return pa.record_batch({"result": pa.array(results, type=pa.int64())})
329+
330+
@classmethod
331+
def window(
332+
cls,
333+
rid: int,
334+
subframes: list[tuple[int, int]],
335+
partition: WindowPartition,
336+
window_state: Any,
337+
params: ProcessParams[None],
338+
) -> int | None:
339+
# Single-row fallback (still required so plain window() invocations
340+
# work in unit tests). Production callers go through window_batch.
341+
return cls._sum_one(subframes, partition)
342+
343+
@classmethod
344+
def window_batch(
345+
cls,
346+
row_ids: list[int],
347+
subframes: list[list[tuple[int, int]]],
348+
partition: WindowPartition,
349+
window_state: Any,
350+
params: ProcessParams[None],
351+
) -> pa.Array:
352+
out = [cls._sum_one(frames, partition) for frames in subframes]
353+
return pa.array(out, type=pa.int64())
354+
355+
@staticmethod
356+
def _sum_one(
357+
subframes: list[tuple[int, int]],
358+
partition: WindowPartition,
359+
) -> int | None:
360+
import pyarrow.compute as pc
361+
362+
value_col = partition.inputs.column(0)
363+
total = 0
364+
any_valid = False
365+
for begin, end in subframes:
366+
if end <= begin:
367+
continue
368+
slice_ = value_col.slice(begin, end - begin)
369+
if partition.filter_mask is not None:
370+
mask = partition.filter_mask.slice(begin, end - begin)
371+
slice_ = slice_.filter(mask)
372+
s = pc.sum(slice_)
373+
if s.is_valid:
374+
total += s.as_py()
375+
any_valid = True
376+
return total if any_valid else None

‎vgi/_test_fixtures/worker.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@
4747
WeightedSumFunction,
4848
WindowListAggFunction,
4949
WindowMedianFunction,
50+
WindowSumBatchFunction,
5051
WindowSumFunction,
5152
)
5253
from vgi._test_fixtures.cancellable import SlowCancellableFunction, SlowCancellableInOutFunction
@@ -361,6 +362,7 @@ def _build_enum_stats() -> dict[str, ColumnStatisticsInput]:
361362
WeightedSumFunction,
362363
WindowListAggFunction,
363364
WindowMedianFunction,
365+
WindowSumBatchFunction,
364366
WindowSumFunction,
365367
],
366368
views=[

‎vgi/aggregate_function.py‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -475,3 +475,43 @@ def window(
475475
476476
"""
477477
raise NotImplementedError(f"{cls.__name__}: Meta.supports_window=True requires overriding window()")
478+
479+
@classmethod
480+
def window_batch(
481+
cls,
482+
row_ids: list[int],
483+
subframes: list[list[tuple[int, int]]],
484+
partition: WindowPartition,
485+
window_state: Any,
486+
params: ProcessParams[Any],
487+
) -> "pa.Array | list[Any]":
488+
"""Compute the aggregate value for ``count`` consecutive output rows.
489+
490+
Default implementation calls :meth:`window` once per row. Override
491+
when per-row Python object construction dominates the call cost
492+
and you want to build the output as an Arrow array directly,
493+
bypassing the framework's default ``pa.array(results, ...)``
494+
conversion.
495+
496+
Args:
497+
row_ids: Partition-local row indices being filled. Length is
498+
the batch size.
499+
subframes: ``subframes[i]`` is the frame ranges for output
500+
row ``row_ids[i]``. Same shape as :meth:`window`'s
501+
``subframes`` argument, one per row.
502+
partition: The cached partition data.
503+
window_state: As :meth:`window`.
504+
params: As :meth:`window`.
505+
506+
Returns:
507+
Either a :class:`pa.Array` of length ``len(row_ids)`` matching
508+
the function's output type — shipped directly as the response
509+
with no further conversion — or a ``list[Any]`` of the same
510+
length, fed through ``pa.array(results, type=output_type)``
511+
(equivalent to the default per-row path).
512+
513+
"""
514+
return [
515+
cls.window(rid, frames, partition, window_state, params)
516+
for rid, frames in zip(row_ids, subframes, strict=True)
517+
]

0 commit comments

Comments
 (0)