Algorithm Search⌘K

Techniqueadvanced

Pane-based window aggregation

Also called pane-based aggregation.

Split a sliding window of range R and slide S into panes of length gcd(R, S), aggregate each pane once, and compute each window from its R / gcd(R, S) pane partials.

Pane-based aggregation, of Li, Maier, Tufte, Papadimos and Tucker (2005), computes a sliding-window aggregate with range RR and slide SS by cutting the stream into panes of length g=gcd⁡(R,S)g = \gcd(R, S): each tuple is added once to the partial aggregate of its pane, and each window is the combination of its k=R/gk = R / g pane partials. It is a technique for one query with fixed RR and SS. Stream slicing generalizes it to slices of unequal length and to many queries and window types at once, and FlatFAT is a data structure that combines the partials of a window in O(log⁡n)O(\log n) operator calls instead of kk. The sliding window aggregation page states the general problem, and the two-stacks queue and the DABA queue solve it for windows that slide one item at a time.

In plain words

You must report, every 4 minutes, the total sales of the last 6 minutes. The plain way adds each sale to every report that covers it, and the reports overlap, so many sales are added twice. Panes avoid this. Cut time into blocks of 2 minutes, the largest length that fits both 6 and 4 an exact number of times. Keep one running total per block. Each sale goes into exactly one block. When a report is due, add up the last three block totals. Each sale is touched once, and each report costs three additions, however many sales there were.

When it applies

  • The windows are sliding windows in one time domain with a fixed range RR and a fixed slide SS, both integers in the unit of the timestamps: window jj is the interval [jS,jS+R)[jS, jS + R) for j=0,1,2,…j = 0, 1, 2, \ldots. These are the hopping windows of other pages, and with R=SR = S the tumbling windows.
  • The aggregate is bounded, which Li et al. define as distributive or algebraic in the sense of Gray et al.: it has a partial state of constant size with a lift, an associative combine and a final step. Sum, count, max, min and average (as a sum and a count) are bounded. Median, quantiles and mode are holistic and have no partial of constant size.
  • The stream gives each pane many tuples. The gain comes from doing one combine per tuple instead of R/SR / S of them, so it is largest when the windows overlap a lot and the tuples are dense.

The template

The page uses RR for the range and SS for the slide, both in time units, g=gcd⁡(R,S)g = \gcd(R, S) for the pane length and k=R/gk = R / g for the number of panes per window. Pane ii is [ig,(i+1)g)[ig, (i + 1)g). The aggregate has a lift, a combine ⊕\oplus with an identity, and a final step lower. A watermark ww says that no more tuples with a timestamp below ww are expected, and a pane closes when ww reaches its end.

  1. PANES(R, S) ▷ windows [jS, jS + R) for j = 0, 1, 2, ...
  2. 1g ← gcd(R, S); k ← R / g; next ← 0 ▷ next is the first pane that is not closed
  3. 2open ← an empty map from pane id to partial; last ← an empty queue of partials
  4. INSERT(t, v) ▷ the pane-level query
  5. 3i ← ⌊t / g⌋
  6. 4if i < next then count the tuple as late, drop it and return
  7. 5open[i] ← open[i] ⊕ lift(v) ▷ a missing entry is the identity
  8. ADVANCE(w) ▷ the watermark: no more tuples with a timestamp below w
  9. 6while (next + 1) · g ≤ w do
  10. 7append open[next] (the identity if missing) to last; remove it from open; if last holds k + 1 partials, drop the oldest
  11. 8e ← (next + 1) · g; next ← next + 1
  12. 9if e ≥ R and (e - R) mod S = 0 then ▷ a window ends at e
  13. 10emit the window [e - R, e) with lower(⊕ of the k partials in last) ▷ the window-level query

Li et al. state the technique as a rewrite of the query: the pane-level sub-query (PLQ) is a tumbling window aggregate with range and slide gg, and the window-level sub-query (WLQ) is an aggregate over the stream of pane results with range kk panes and slide S/gS / g panes. For count, the PLQ is count and the WLQ is sum; for max, both are max. Lines L3 to L5 are the PLQ and lines L9 and L10 are the WLQ.

Why it works. Three facts, each a theorem.

  1. Each window is exactly kk consecutive panes. Both ends jSjS and jS+RjS + R are multiples of gg, because gg divides SS and RR. So the window is the union of the panes from jS/gjS / g to jS/g+k−1jS / g + k - 1.
  2. No longer pane works for all windows. A pane length hh that puts every window boundary on a pane boundary must divide jSjS and jS+RjS + R for every jj, so it divides SS (take j=1j = 1 and j=0j = 0 for the starts) and RR (take the two ends of window 0), and so it divides gg.
  3. The output is the window aggregate. By fact 1 and line L7, when a window ends at ee the queue holds the partials of panes e/g−ke / g - k to e/g−1e / g - 1, which are its panes. Each partial is the ⊕\oplus of the lifted values of its tuples, so by associativity the ⊕\oplus of the kk partials is the ⊕\oplus over all tuples of the window. Tuples can arrive in any order inside a pane, so ⊕\oplus must also be commutative unless the input is in timestamp order.

Cost. Let nn be the number of tuples and mm the number of windows emitted.

  • Per tuple: one ⊕\oplus and one map lookup, O(1)O(1) worst case. A plain method that adds each tuple to every open window costs R/SR / S combines per tuple when SS divides RR, and ⌈R/S⌉\lceil R / S \rceil or ⌊R/S⌋\lfloor R / S \rfloor otherwise.
  • Per window: kk combines, worst case. In total, exactly n+mkn + mk calls of ⊕\oplus when each combine starts from the identity; the tests check this count.
  • Per pane: O(1)O(1) to close it, even if it is empty.
  • Memory: the last kk closed partials plus the open panes, independent of the number of tuples in a window. With in-order input there is one open pane, so at most k+1k + 1 partials. With a watermark that lags the largest timestamp by DD, about D/g+1D / g + 1 panes are open.

Late data. The technique needs to know when a pane is complete. The original paper assumes input in timestamp order, so a pane closes when the first tuple of a later pane arrives. With out-of-order input, a pane closes when the watermark passes its end, as above. A tuple that arrives after its pane has closed is late. The template drops it and counts it. The other choice is to reopen the pane, update its partial and emit a corrected result for each of the windows that contain it, which are at most ⌈R/S⌉\lceil R / S \rceil; this needs the pane partials of those windows to be kept until the corrections are no longer wanted. If the disorder is at most DD (each tuple arrives after only tuples whose timestamps are at most DD above its own) and the watermark is the largest timestamp seen minus DD, no tuple is late. Proof. The watermark before a tuple xx is at most tx+D−D=txt_x + D - D = t_x, and the pane of xx ends after txt_x, so it is still open. □\square

Classic examples

The example from the plain words. R=6R = 6, S=4S = 4, so g=2g = 2 and k=3k = 3. The tuples (time, value) are (0, 3), (1, 5), (3, 2), (4, 7), (5, 1), (7, 4), (8, 6), (9, 2), (11, 8), (12, 3) and (13, 5).

pane interval tuples sum max
0 [0, 2) 3, 5 8 5
1 [2, 4) 2 2 2
2 [4, 6) 7, 1 8 7
3 [6, 8) 4 4 4
4 [8, 10) 6, 2 8 6
5 [10, 12) 8 8 8
6 [12, 14) 3, 5 8 5
window panes sum max
[0, 6) 0, 1, 2 8 + 2 + 8 = 18 7
[4, 10) 2, 3, 4 8 + 4 + 8 = 20 7
[8, 14) 4, 5, 6 8 + 8 + 8 = 24 8
[12, 18) 6, 7, 8 8 5

Pane 2 is in two windows, and its partial is computed once. The three full windows hold 15 tuple occurrences, so the plain method adds 15 values; panes add the 11 tuples once and then combine 3 partials per window. Recomputed from scratch, the sums of the windows are 18, 20, 24 and 8, the same.

Count and average. For count, the PLQ counts the tuples of each pane and the WLQ adds the counts. For average, the partial is the pair (sum, count), the WLQ adds the pairs, and the final step divides. The implementation returns the pair, so that the tests compare exact integers.

A query that is not helped. With R=7R = 7 and S=3S = 3, g=1g = 1 and k=7k = 7: every time unit is a pane, and each window combines 7 partials. If a time unit holds about one tuple, this is no better than the plain method. Li et al. name this case, with very many groups and with slow streams, as the cases with no gain.

Variations

  • Differential aggregates. If ⊕\oplus has an inverse (sum, count, average), keep a running window value: at each window, add the new panes and subtract the panes that left. This costs S/gS / g additions and S/gS / g subtractions per window instead of kk combines. Li et al. call such aggregates differential. Max has no inverse.
  • A tree or a queue over the panes. For an aggregate that is associative but not invertible, such as max, keep the pane partials in a two-stacks queue, a DABA queue or a FlatFAT instead of combining kk partials each time. Each window then costs O(1)O(1) amortized, O(1)O(1) worst case, or O(log⁡k)O(\log k) operator calls.
  • Group-by. With a Group By clause, each group has its own panes. The memory is k+1k + 1 partials per group, and a pane must be closed for every group, which costs time in proportion to the number of groups even when a group has no tuples.
  • Holistic aggregates. For a holistic aggregate, the pane partial must be a summary that can be merged, for example the counts of each value for a heavy-hitter query, as in Section 3.3 of the paper. The partial then has no constant bound.
  • Paired windows and slicing. Krishnamurthy, Wu and Franklin (2006) cut each window of range RR and slide SS into two fragments of alternating lengths R mod SR \bmod S and S−(R mod S)S - (R \bmod S), so each slide has at most two partials instead of S/gS / g. With several queries, the fragments of all queries are cut at the union of their boundaries. This is the start of stream slicing.
  • Count-based windows. With [Rows N Slide L][\text{Rows } N \text{ Slide } L] the same scheme works on tuple positions, with panes of gcd⁡(N,L)\gcd(N, L) tuples, as long as the tuples arrive in order.

Pitfalls

  • Coprime range and slide. If gcd⁡(R,S)=1\gcd(R, S) = 1, panes have the length of one time unit and each window combines RR partials. Choose the time unit with care, or use paired windows or slicing.
  • Empty panes. The loop at line L6 closes every pane, also empty ones. On a sparse stream with a fine time unit this costs more than the tuples do. An implementation can jump over empty panes, but it must still emit the windows that end in the gap.
  • Late data. A heuristic watermark can be too fast. Then a tuple arrives after its pane has closed, and the results of the windows that contain it are wrong unless the system corrects them. State the policy: drop and count, or update and re-emit.
  • Holistic aggregates. Median and quantiles cannot be split into constant-size partials. A pane of sorted values or a mergeable summary works, but the cost bounds above no longer hold.
  • Windows that are not aligned. The template assumes that window jj starts at jSjS. If the windows start at an offset oo, cut the panes from oo as well. Session windows have no fixed boundaries, so panes do not apply to them; stream slicing handles them.
  • Commutativity. With out-of-order input, tuples enter a pane in arrival order. A combine that is associative but not commutative, such as the concatenation of strings, gives a wrong partial. Sort each pane by timestamp first, or use a commutative aggregate.

Code

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

panes_window_aggregation.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/panes-window-aggregation/. The authors are listed in prov/0B550K.jsonl.

"""Pane-based sliding-window aggregation (Li, Maier, Tufte, Papadimos and
Tucker 2005).

The windows are [j*S, j*S + R) for j = 0, 1, 2, ... in event time. The stream
is cut into panes of length g = gcd(R, S); each tuple is added to the partial
aggregate of its pane (the pane-level query), and each window is the
combination of its k = R / g pane partials (the window-level query).

Tuples may arrive out of order. The caller gives a watermark with advance(w):
no tuple with a timestamp below w is expected. A pane closes when the
watermark reaches its end. A tuple whose pane is closed is late; it is dropped
and counted.
"""

from collections import deque
from dataclasses import dataclass
from math import gcd
from typing import Any, Callable


@dataclass(frozen=True)
class Aggregate:
    """A bounded aggregate: lift a value, combine partials, lower the result."""

    name: str
    identity: Any
    lift: Callable[[Any], Any]
    combine: Callable[[Any, Any], Any]
    lower: Callable[[Any], Any]


def _max2(a, b):
    if a is None:
        return b
    if b is None:
        return a
    return a if a >= b else b


SUM = Aggregate("sum", 0, lambda v: v, lambda a, b: a + b, lambda a: a)
COUNT = Aggregate("count", 0, lambda v: 1, lambda a, b: a + b, lambda a: a)
MAX = Aggregate("max", None, lambda v: v, _max2, lambda a: a)
AVG = Aggregate(
    "avg",
    (0, 0),
    lambda v: (v, 1),
    lambda a, b: (a[0] + b[0], a[1] + b[1]),
    lambda a: None if a[1] == 0 else (a[0], a[1]),  # exact (sum, count)
)


class PanedAggregator:
    def __init__(self, R: int, S: int, agg: Aggregate):
        if R <= 0 or S <= 0:
            raise ValueError("R and S must be positive")
        self.R, self.S, self.agg = R, S, agg
        self.g = gcd(R, S)  # @line L1
        self.k = R // self.g
        self.next = 0  # the id of the first pane that is not closed
        self.open: dict[int, Any] = {}  # @line L2
        self.last: deque = deque()
        self.late = 0
        self.combines = 0  # calls of agg.combine, for the cost tests

    def _combine(self, a, b):
        self.combines += 1
        return self.agg.combine(a, b)

    def insert(self, t: int, v) -> bool:
        """Add one tuple. Return False if it is late and dropped."""
        i = t // self.g  # @line L3
        if i < self.next:  # @line L4
            self.late += 1
            return False
        self.open[i] = self._combine(self.open.get(i, self.agg.identity), self.agg.lift(v))  # @line L5
        return True

    def advance(self, w: int) -> list[tuple[int, int, Any]]:
        """Close the panes that end at or before w; return the finished windows."""
        out = []
        while (self.next + 1) * self.g <= w:  # @line L6
            self.last.append(self.open.pop(self.next, self.agg.identity))  # @line L7
            if len(self.last) > self.k:
                self.last.popleft()
            e = (self.next + 1) * self.g  # @line L8
            self.next += 1
            if e >= self.R and (e - self.R) % self.S == 0:  # @line L9
                acc = self.agg.identity
                for p in self.last:
                    acc = self._combine(acc, p)
                out.append((e - self.R, e, self.agg.lower(acc)))  # @line L10
        return out

    def state_size(self) -> int:
        """The number of partials held: open panes plus the last k closed ones."""
        return len(self.open) + len(self.last)


def run(arrivals, R: int, S: int, agg: Aggregate, delay: int = 0):
    """Feed (t, v) pairs in arrival order with the watermark max_t_seen - delay.

    At the end, flush every window whose start is at most the largest
    timestamp. Return (windows, the aggregator)."""
    pa = PanedAggregator(R, S, agg)
    out = []
    top = None
    for t, v in arrivals:
        pa.insert(t, v)
        top = t if top is None else max(top, t)
        out.extend(pa.advance(top - delay))
    if top is not None:
        out.extend(pa.advance((top // S) * S + R))
    return out, pa
test_panes_window_aggregation.py 144 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/panes-window-aggregation/. The authors are listed in prov/0B550K.jsonl.

import random

import pytest

from panes_window_aggregation import AVG, COUNT, MAX, SUM, PanedAggregator, run

EXAMPLE = [(0, 3), (1, 5), (3, 2), (4, 7), (5, 1), (7, 4), (8, 6), (9, 2), (11, 8), (12, 3), (13, 5)]


def scratch(tuples, R, S, name):
    """Recompute every window [j*S, j*S + R) from scratch, by definition."""
    if not tuples:
        return []
    top = max(t for t, _ in tuples)
    out = []
    for j in range(top // S + 1):
        vals = [v for t, v in tuples if j * S <= t < j * S + R]
        if name == "sum":
            r = sum(vals)
        elif name == "count":
            r = len(vals)
        elif name == "max":
            r = max(vals) if vals else None
        else:
            r = (sum(vals), len(vals)) if vals else None
        out.append((j * S, j * S + R, r))
    return out


def accepted_by_definition(arrivals, R, S, delay):
    """The tuples whose pane is still open when they arrive."""
    from math import gcd

    g = gcd(R, S)
    keep, top, closed_before = [], None, 0
    for t, v in arrivals:
        # panes [i*g, (i+1)*g) with (i+1)*g <= top - delay are closed
        if top is not None:
            closed_before = max(closed_before, (top - delay) // g)
        if t // g >= closed_before:
            keep.append((t, v))
        top = t if top is None else max(top, t)
    return keep


def random_stream(rng, n, span):
    ts = sorted(rng.randrange(span) for _ in range(n))
    return [(t, rng.randint(-5, 9)) for t in ts]


def shuffle_bounded(rng, tuples, D):
    keyed = [(t + rng.randint(0, D), i, (t, v)) for i, (t, v) in enumerate(tuples)]
    keyed.sort()
    return [x for _, _, x in keyed]


def test_hand_example():
    out, _ = run(EXAMPLE, 6, 4, SUM)
    assert out == [(0, 6, 18), (4, 10, 20), (8, 14, 24), (12, 18, 8)]
    out, _ = run(EXAMPLE, 6, 4, MAX)
    assert [r for _, _, r in out] == [7, 7, 8, 5]


def test_hand_example_costs():
    out, pa = run(EXAMPLE, 6, 4, SUM)
    assert pa.g == 2 and pa.k == 3
    # one combine per tuple (pane level) and k per window (window level)
    assert pa.combines == len(EXAMPLE) + len(out) * pa.k


@pytest.mark.parametrize("R,S", [(6, 4), (10, 4), (5, 5), (12, 8), (7, 3), (4, 6), (9, 1)])
def test_in_order_matches_scratch(R, S):
    rng = random.Random(1000 + 31 * R + S)
    for _ in range(25):
        tuples = random_stream(rng, rng.randint(0, 40), 50)
        for agg in (SUM, COUNT, MAX, AVG):
            out, pa = run(tuples, R, S, agg)
            assert out == scratch(tuples, R, S, agg.name)
            assert pa.late == 0
            assert pa.combines == len(tuples) + len(out) * pa.k


def test_state_bound_in_order():
    rng = random.Random(7)
    R, S = 12, 8
    tuples = random_stream(rng, 120, 200)
    pa = PanedAggregator(R, S, SUM)
    for t, v in tuples:
        pa.insert(t, v)
        pa.advance(t)
        # the last k closed panes and the one open pane
        assert pa.state_size() <= pa.k + 1


def test_bounded_disorder_has_no_late_tuples():
    rng = random.Random(11)
    for _ in range(40):
        R, S = rng.choice([(6, 4), (10, 4), (8, 8), (9, 6)])
        D = rng.randint(0, 6)
        tuples = random_stream(rng, rng.randint(1, 40), 60)
        arrivals = shuffle_bounded(rng, tuples, D)
        out, pa = run(arrivals, R, S, SUM, delay=D)
        assert pa.late == 0
        assert out == scratch(tuples, R, S, "sum")


def test_too_fast_watermark_drops_exactly_the_late_tuples():
    rng = random.Random(12)
    seen_late = 0
    for _ in range(60):
        R, S = rng.choice([(6, 4), (10, 4), (8, 8), (9, 6)])
        D = rng.randint(3, 8)
        tuples = random_stream(rng, rng.randint(1, 40), 60)
        arrivals = shuffle_bounded(rng, tuples, D)
        delay = rng.randint(0, D - 1)
        keep = accepted_by_definition(arrivals, R, S, delay)
        for agg in (SUM, MAX):
            out, pa = run(arrivals, R, S, agg, delay=delay)
            assert pa.late == len(arrivals) - len(keep)
            assert out == scratch(keep, R, S, agg.name)
        seen_late += len(arrivals) - len(keep)
    assert seen_late > 0


def test_each_window_is_k_consecutive_panes():
    for R in range(1, 13):
        for S in range(1, 13):
            pa = PanedAggregator(R, S, SUM)
            g = pa.g
            for j in range(5):
                assert (j * S) % g == 0 and (j * S + R) % g == 0
                assert (j * S + R - j * S) // g == pa.k
            # no larger pane length divides all window boundaries
            for h in range(g + 1, R + S + 1):
                assert not (R % h == 0 and S % h == 0)


def test_empty_and_errors():
    assert run([], 6, 4, SUM)[0] == []
    with pytest.raises(ValueError):
        PanedAggregator(0, 4, SUM)

Exercises

  1. For R=10R = 10 and S=4S = 4, give gg, kk and the panes of the windows [0,10)[0, 10), [4,14)[4, 14) and [8,18)[8, 18). How many partials does each window combine, and how many would paired windows need?
  2. Show that with a differential aggregate the cost per window is S/gS / g updates in each direction. Write the update of the running sum and say which pane leaves the window when the window that ends at ee is emitted.
  3. A stream has 3 tuples per time unit, R=60R = 60 and S=1S = 1. Compare the number of combines per window of the plain method, of panes, and of panes in a two-stacks queue.
  4. Prove that if the disorder of the stream is at most DD, a watermark of the largest timestamp seen minus DD makes no tuple late, and give a stream with disorder D+1D + 1 on which a tuple is late.

References

  1. Jin Li, David Maier, Kristin Tufte, Vassilis Papadimos and Peter A. Tucker, No pane, no gain, efficient evaluation of sliding-window aggregates over data streams, SIGMOD Record 34(1), 2005, pages 39 to 44, Section 3.1 (the pane-level sub-query PLQ and the window-level sub-query WLQ, with pane length gcd(RANGE, SLIDE)), Section 3.2 (distributive, algebraic and holistic aggregates, and differential aggregates) and Section 3.3 (when panes give no gain, and holistic aggregates such as heavy hitters)
  2. Semantics and evaluation techniques for window aggregates in data streams, the companion paper with window ids, which assigns tuples to windows without buffering them (general locator)
  3. Sailesh Krishnamurthy, Chung Wu and Michael J. Franklin, On-the-fly sharing for streamed aggregation, Proceedings of ACM SIGMOD 2006, pages 623 to 634, paired windows, which cut a window into two fragments of lengths S mod R and the rest, and need fewer partials than panes

Where this leads

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • three classic examples