Tumbling and Sliding Window Aggregation
Given (timestamp, value) events, compute per-window sums for tumbling windows of a given size and for sliding (hopping) windows of a given size and slide.
Tumbling: window start = floor(ts/size)*size, each event in exactly one window. Sliding: each event belongs to size/slide windows whose starts are multiples of slide in (ts-size, ts]; compute that range arithmetically instead of scanning windows. Use event time, not arrival order.
Try it first.
tests.py · 4 passing
events = [(1, 1), (2, 2), (5, 3), (11, 4)]
assert tumbling_sum(events, 5) == {0: 3, 5: 3, 10: 4}
assert sliding_sum(events, 10, 5) == {-5: 3, 0: 6, 5: 7, 10: 4}
assert sliding_sum(events, 5, 5) == tumbling_sum(events, 5) # slide == size is tumbling
assert tumbling_sum([(9, 1), (0, 1)], 10) == {0: 2} # out-of-order is fineIn a real stream when do you emit a window and drop its state? When the watermark (max event time minus allowed lateness) passes window end; late events after that go to a side output. For huge size/slide ratios, aggregate per slide 'pane' once and combine panes to avoid O(size/slide) updates per event.