Algorithm Search⌘K

Techniqueresearch

Stream slicing

Also called window slicing, Cutty slicing.

Cut a stream into non-overlapping slices at the window boundaries of all queries, keep one partial aggregate per slice, and combine slices to answer each window, so that windows share work.

Stream slicing cuts a stream into non-overlapping slices at the boundaries of the windows of all queries, keeps one partial aggregate per slice, and computes each window by combining the slices that it covers, so that one tuple is aggregated once even when many windows of many queries contain it. Pane-based aggregation is the special case of one query with equal slices of length gcd⁡(R,S)\gcd(R, S); slicing allows slices of unequal length, cuts only where some window starts or ends, and also handles session windows and out-of-order data. Slicing decides which partials exist; a structure such as FlatFAT, a two-stacks queue or a DABA queue decides how fast the partials of one window are combined, and the sliding window aggregation page states that problem.

In plain words

Two reports read the same sales: one sums the last 6 minutes every 4 minutes, the other the last 5 minutes every 3 minutes. Mark on a time line every moment at which some report's window starts or ends. Between two marks, every sale belongs to exactly the same reports, so you can keep one running total for that stretch. Each report then adds up the totals of the stretches inside its window. A sale is added once, to its stretch, and the stretches are shared by both reports. If the input comes in time order, you need marks only where windows start: when a window ends in the middle of a stretch, the running total of that stretch so far is exactly the part you need.

When it applies

  • Several window aggregates read the same stream with the same aggregate (or aggregates that can share a partial, such as sum and average), but with different windows: tumbling, hopping or session windows, in time or in tuple counts.
  • The aggregate has an associative combine with an identity. If tuples come out of order, it should also be commutative, or the slices must keep their tuples.
  • The number of slices that one window covers is small compared with the number of tuples in it. Slicing gains when tuples are dense and windows overlap.

The template

A query qq has range RqR_q and slide SqS_q, and its windows are [jSq,jSq+Rq)[jS_q, jS_q + R_q) for j=0,1,2,…j = 0, 1, 2, \ldots. A cut is a time at which a slice ends and the next begins. There are two cutting rules.

  • Edges: cut at every window start jSqjS_q and every window end jSq+RqjS_q + R_q of every query. Each window is then a union of whole slices.
  • Starts: cut only at window starts. A window end then falls inside a slice. For input in timestamp order this is enough: when the stream reaches the end ee of a window, the open slice holds exactly the tuples from its start up to ee. This is the rule of Cutty (Carbone et al. 2016), which this page calls Cutty slicing.

For in-order input, with ⊕\oplus the combine and lift the map from a value to a partial:

  1. INSERT(t, v) ▷ timestamps do not decrease
  2. 1EMIT-UNTIL(t) ▷ finish every window that ends at or before t
  3. 2CLOSE-UNTIL(t)
  4. 3cur ← cur ⊕ lift(v) ▷ the partial of the open slice
  5. EMIT-UNTIL(t)
  6. 4for each window end e ≤ t, in time order, of a query with range R do
  7. 5CLOSE-UNTIL(e)
  8. 6acc ← the ⊕ of the closed slices that start at or after e - R, in time order; then acc ← acc ⊕ cur if the open slice starts before e
  9. 7emit the window [e - R, e) with acc; drop the closed slices that no open window can use
  10. CLOSE-UNTIL(t)
  11. 8while the next cut after the start of the open slice is at most t do
  12. 9move the open slice to the list of closed slices; open an empty slice at that cut

With the edges rule, line L5 always closes the slice that ends at ee, so the second part of line L6 never applies. With the starts rule, it applies whenever ee is not also a window start.

Why it works (theorem). Every window start is a cut under both rules, so each window [e−R,e)[e - R, e) begins at a slice boundary. Under the edges rule it also ends at one, and it is the union of the closed slices that start in [e−R,e)[e - R, e). Under the starts rule, the slices that start in [e−R,e)[e - R, e) cover [e−R,e)[e - R, e) exactly when the open slice is cut off at ee. Line L1 runs before any tuple with timestamp t≥et \ge e is added, so the open slice holds only tuples with timestamps below ee. In both cases line L6 combines, in time order, the partials of disjoint consecutive pieces whose union is the window, and associativity gives the aggregate of the window. Because the pieces are combined in time order, commutativity is not needed for in-order input. The tests check this with string concatenation, which is not commutative.

Cost. Let nn be the number of tuples, cc the number of slices that one window covers, and mm the number of windows emitted over all queries.

  • Per tuple: one ⊕\oplus, O(1)O(1) worst case. A plain method costs one ⊕\oplus for each window that contains the tuple, about ∑qRq/Sq\sum_q R_q / S_q.
  • Per window: cc calls of ⊕\oplus with a linear fold, as in the template. With the slice partials kept in FlatFAT, a window costs O(log⁡s)O(\log s) calls, where ss is the number of slices kept; with a two-stacks queue per query, O(1)O(1) amortized.
  • Total: exactly n+∑windowscn + \sum_{\text{windows}} c calls of ⊕\oplus for the template; the tests check this count.
  • Memory: the slices from the earliest open window start to now. For hopping windows this is the slices of the longest range, about max⁡qRq\max_q R_q divided by the mean slice length.
  • Number of slices: in a period of the least common multiple of the slides, the edges rule makes one slice per distinct start or end, the starts rule one per distinct start. A single query with SS dividing RR gets R/SR / S slices per window under both rules; panes would make R/gcd⁡(R,S)=R/SR / \gcd(R, S) = R / S too, but for SS not dividing RR the starts rule needs ⌈R/S⌉\lceil R / S \rceil slices per window and panes need R/gcd⁡(R,S)R / \gcd(R, S).

Late data. The template needs input in timestamp order. With out-of-order input and a watermark, Scotty (Traub et al. 2021) keeps the slices of the windows that are still open, adds a tuple that arrives behind the newest slice to the slice of its timestamp, and changes the slices when the tuple changes the windows: a late tuple can join two session windows, which merges their slices, or start a new session in a gap, which splits a slice. If the aggregate is commutative, the slice partial is updated in place; if not, or if a split falls inside a slice, the slice must keep its tuples, and Scotty keeps them only when the workload needs it. A tuple that arrives after the watermark has passed the end of all its windows is late and is dropped, or is used to send corrected results, by the same policies as in the Dataflow model. The starts rule does not work for such input: a window end inside a slice needs the partial up to that end, and a late tuple before the end can arrive after the partial has moved on.

Classic examples

Two queries on one stream. Q1Q_1 has R=6R = 6, S=4S = 4, and Q2Q_2 has R=5R = 5, S=3S = 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). In [0,24)[0, 24), the window starts are 0, 3, 4, 6, 8, 9, 12, 15, 16, 18, 20 and 21, and the window ends are 5, 6, 8, 10, 11, 14, 17, 18, 20, 22 and 23.

rule cuts in [0,24)[0, 24) slices
edges the 19 distinct starts and ends 19
starts (Cutty) the 12 starts 12
shared panes, gcd⁡(2,1)=1\gcd(2, 1) = 1 every time unit 24

The edges slices up to time 14 are [0, 3) with sum 8, [3, 4) with 2, [4, 5) with 7, [5, 6) with 1, [6, 8) with 4, [8, 9) with 6, [9, 10) with 2, [10, 11) with 0, [11, 12) with 8 and [12, 14) with 8. The window [4,10)[4, 10) of Q1Q_1 is the slices from 4 to 10: 7+1+4+6+2=207 + 1 + 4 + 6 + 2 = 20. The window [3,8)[3, 8) of Q2Q_2 is 2+7+1+4=142 + 7 + 1 + 4 = 14. Under the starts rule the slices are [0, 3), [3, 4), [4, 6), [6, 8), [8, 9), [9, 12) and [12, 15) up to 15, and the window [0,5)[0, 5) of Q2Q_2 is 8+28 + 2 plus the open slice [4, 6) at the moment the stream reaches 5, which holds only the 7, so 1717.

The nine windows that start before time 14 have the sums 18, 20, 24 and 8 for Q1Q_1 and 17, 14, 12, 18 and 8 for Q2Q_2, the same as a recomputation of each window from scratch. Their windows hold 34 tuple occurrences in all. The template makes 49 calls of ⊕\oplus with the edges rule and 38 with the starts rule: 11 for the tuples, and 38 or 27 for the slices of the windows. On this sparse example a plain method, with 34 additions, is cheaper, because each slice holds about one tuple. With 100 tuples per time unit, the plain method needs about 100 times as many additions, and the slice counts stay the same.

Panes as slices. For one query, the edges rule cuts at the multiples of SS and at the multiples of SS plus RR. All of these are multiples of gcd⁡(R,S)\gcd(R, S), so slicing never makes more slices than panes, and it makes fewer when not every multiple of the gcd is a boundary: for R=10R = 10 and S=4S = 4, the cuts in a period of 4 are at 0 and 2, so slicing gives slices of length 2, the same as panes, but for R=10R = 10 and S=6S = 6 the cuts in a period of 6 are at 0 and 4, which gives slices of lengths 4 and 2 where panes use three slices of length 2.

Session windows. A session window of gap gg ends when no tuple arrives for gg time units. A slicer cuts a new slice when a gap of gg is seen, and the slice is the session. With in-order input this is one partial per session. With out-of-order input, a late tuple that falls in a gap between two sessions and is closer than gg to both merges them, and Scotty merges their slices.

Variations

  • Paired windows (Krishnamurthy, Wu and Franklin 2006). For one query, cut each slide into two fragments, of lengths R mod SR \bmod S and S−(R mod S)S - (R \bmod S), so that each slide has at most two slices. For many queries, take the union of their cuts. These are the edges cuts of the query.
  • Cutty (Carbone et al. 2016). Windows are given by user functions that say when a window begins and ends, as long as the start of a window is known when its first tuple arrives. Slices begin only at window starts.
  • General stream slicing (Scotty, Traub et al. 2021). One slicer for all the windows of a stream: context-free windows (tumbling, hopping) and context-aware windows (sessions, and windows that end on a punctuation), measures in time and in tuple counts, in-order and out-of-order input. It chooses, from the aggregates and windows, whether slices must keep their tuples and whether they must support split and merge.
  • Combining slices fast. Keep the slice partials in FlatFAT, a two-stacks queue or a DABA queue, so that the cost per window does not grow with cc.
  • Shared selections. Krishnamurthy et al. also share work between queries whose filters differ, by cutting the data into fragments by the filters that each tuple passes. This is outside the time slicing of this page.

Pitfalls

  • Few tuples per slice. As the example shows, many queries with different slides can give slices that hold one tuple or none. The work per window then grows with the number of slices, and the plain method can be cheaper. Use a tree over the slices.
  • The starts rule needs order. Cutting only at starts uses the running partial of the open slice at the moment of a window end. Out-of-order input breaks this; use the edges rule, or keep the tuples of the open slice.
  • Late data. A heuristic watermark can be too fast, and a late tuple can change a window that has already been emitted. State the policy for each query. Session windows make this worse, because a late tuple can merge two sessions that were both emitted.
  • Count-based windows out of order. A window of the last NN tuples in timestamp order changes its contents when a late tuple arrives, because every later window moves by one tuple. The slice boundaries in counts shift, so slices must keep tuples to be split.
  • Holistic aggregates. Median and quantiles have no constant-size partial, so a slice holds a sorted run or a summary, and combining cc slices is not O(c)O(c).
  • Different aggregates. Queries can share slices only if their partials can be derived from one stored partial, for example a (sum, count) pair for sum, count and average. Max and sum need two partials per slice.

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.

stream_slicing.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/stream-slicing/. The authors are listed in prov/ZPAWWC.jsonl.

"""Stream slicing for several sliding-window queries that share one stream.

Each query q has a range R and a slide S; its windows are [j*S, j*S + R) for
j = 0, 1, 2, ... The stream is cut into slices, one partial aggregate per
slice, and each window result is combined from the slices it covers.

Two cutting rules are given:
- "edges": cut at every window start and every window end of every query
  (the general rule of Krishnamurthy et al. 2006 and Traub et al. 2021);
- "starts": cut only at window starts (the rule of Cutty, Carbone et al.
  2016). A window end then falls inside the open slice, and the result uses
  the running partial of that slice at the moment the end is reached.

The input must be in timestamp order (ties allowed). The aggregate needs only
an associative combine with an identity; it need not be commutative.
"""

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


@dataclass(frozen=True)
class Aggregate:
    name: str
    identity: Any
    lift: Callable[[Any], Any]
    combine: Callable[[Any, Any], Any]


SUM = Aggregate("sum", 0, lambda v: v, lambda a, b: a + b)
MAX = Aggregate("max", None, lambda v: v, lambda a, b: b if a is None else a if b is None else max(a, b))
CONCAT = Aggregate("concat", "", lambda v: str(v) + ",", lambda a, b: a + b)  # not commutative


def _next_multiple(x: int, S: int, offset: int = 0) -> int:
    """The smallest b > x with b = offset + j*S for an integer j >= 0."""
    if x < offset:
        return offset
    return offset + ((x - offset) // S + 1) * S


class Slicer:
    def __init__(self, queries: list[tuple[int, int]], agg: Aggregate, mode: str = "edges"):
        if mode not in ("edges", "starts"):
            raise ValueError("mode must be 'edges' or 'starts'")
        for R, S in queries:
            if R <= 0 or S <= 0:
                raise ValueError("R and S must be positive")
        self.queries, self.agg, self.mode = list(queries), agg, mode
        self.closed: deque = deque()  # (start, end, partial) of closed slices
        self.cur_start, self.cur = 0, agg.identity  # the open slice
        self.cur_end = self._next_boundary(0)
        self.next_end = [R for R, S in self.queries]  # the next window end of each query
        self.cuts = [0]  # the start of every slice made so far
        self.combines = 0

    def _next_boundary(self, x: int) -> int:
        """The first cut after time x."""
        best = None
        for R, S in self.queries:
            cands = [_next_multiple(x, S)]
            if self.mode == "edges":
                cands.append(_next_multiple(x, S, R))
            for b in cands:
                best = b if best is None else min(best, b)
        return best

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

    def _close_until(self, t: int) -> None:
        """Close the open slice while it ends at or before t."""
        while self.cur_end <= t:  # @line L8
            self.closed.append((self.cur_start, self.cur_end, self.cur))  # @line L9
            self.cur_start, self.cur = self.cur_end, self.agg.identity
            self.cur_end = self._next_boundary(self.cur_start)
            self.cuts.append(self.cur_start)

    def _emit_until(self, t: int, max_start=None) -> list[tuple[int, int, int, Any]]:
        """Emit, in time order, every window that ends at or before t.

        With max_start, a query stops at its first window that starts later."""
        out = []
        while True:
            q = min(range(len(self.queries)), key=lambda i: (self.next_end[i], i))
            e = self.next_end[q]
            if e > t:  # @line L4
                break
            R, S = self.queries[q]
            ws = e - R
            if max_start is not None and ws > max_start:
                self.next_end[q] = float("inf")
                continue
            self._close_until(e)  # @line L5
            acc = self.agg.identity
            for s0, s1, p in self.closed:  # @line L6
                if s0 >= ws:
                    acc = self._op(acc, p)
            if self.cur_start < e:  # only in mode "starts": the end is inside the open slice
                acc = self._op(acc, self.cur)
            out.append((q, ws, e, acc))  # @line L7
            self.next_end[q] = e + S
            # drop the slices that no window still open can use
            lo = min(ne - R2 for ne, (R2, _) in zip(self.next_end, self.queries))
            while self.closed and self.closed[0][1] <= lo:
                self.closed.popleft()
        return out

    def insert(self, t: int, v) -> list[tuple[int, int, int, Any]]:
        """Add a tuple with timestamp t (not below the previous one)."""
        out = self._emit_until(t)  # @line L1
        self._close_until(t)  # @line L2
        self.cur = self._op(self.cur, self.agg.lift(v))  # @line L3
        return out

    def flush(self, top: int) -> list[tuple[int, int, int, Any]]:
        """Emit every window that starts at or before top."""
        last = max((top // S) * S + R for R, S in self.queries)
        return self._emit_until(last, max_start=top)


def run(stream, queries, agg, mode="edges"):
    """Run the slicer on (t, v) pairs in timestamp order; return (windows, slicer)."""
    sl = Slicer(queries, agg, mode)
    out = []
    top = None
    for t, v in stream:
        if top is not None and t < top:
            raise ValueError("input must be in timestamp order")
        out.extend(sl.insert(t, v))
        top = t
    if top is not None:
        out.extend(sl.flush(top))
    return out, sl
test_stream_slicing.py 104 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/stream-slicing/. The authors are listed in prov/ZPAWWC.jsonl.

import random

import pytest

from stream_slicing import CONCAT, MAX, SUM, Slicer, run

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


def scratch(stream, queries, agg):
    """Recompute every window of every query from scratch, in arrival order."""
    if not stream:
        return []
    top = max(t for t, _ in stream)
    out = []
    for q, (R, S) in enumerate(queries):
        for j in range(top // S + 1):
            acc = agg.identity
            for t, v in stream:
                if j * S <= t < j * S + R:
                    acc = agg.combine(acc, agg.lift(v))
            out.append((q, j * S, j * S + R, acc))
    return sorted(out)


def boundaries(queries, horizon, mode):
    cuts = set()
    for R, S in queries:
        for j in range(horizon + 1):
            if j * S < horizon:
                cuts.add(j * S)
            if mode == "edges" and j * S + R < horizon:
                cuts.add(j * S + R)
    return sorted(cuts)


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]


@pytest.mark.parametrize("mode", ["edges", "starts"])
def test_hand_example(mode):
    out, _ = run(EXAMPLE, QUERIES, SUM, mode)
    got = {(q, s): r for q, s, e, r in out}
    assert [got[(0, s)] for s in (0, 4, 8, 12)] == [18, 20, 24, 8]
    assert [got[(1, s)] for s in (0, 3, 6, 9, 12)] == [17, 14, 12, 18, 8]
    assert sorted(out) == scratch(EXAMPLE, QUERIES, SUM)


@pytest.mark.parametrize("mode", ["edges", "starts"])
def test_cuts_match_the_rule(mode):
    stream = [(t, 1) for t in range(24)]
    _, sl = run(stream, QUERIES, SUM, mode)
    assert [c for c in sl.cuts if c < 24] == boundaries(QUERIES, 24, mode)
    expect = 19 if mode == "edges" else 12
    assert len(boundaries(QUERIES, 24, mode)) == expect


@pytest.mark.parametrize("mode", ["edges", "starts"])
def test_random_matches_scratch(mode):
    rng = random.Random(2024 if mode == "edges" else 2025)
    shapes = [(6, 4), (5, 3), (10, 4), (4, 4), (7, 2), (3, 5), (9, 6)]
    for _ in range(60):
        queries = rng.sample(shapes, rng.randint(1, 3))
        stream = random_stream(rng, rng.randint(0, 35), 40)
        for agg in (SUM, MAX, CONCAT):
            out, sl = run(stream, queries, agg, mode)
            assert sorted(out) == scratch(stream, queries, agg)


@pytest.mark.parametrize("mode", ["edges", "starts"])
def test_combine_count(mode):
    """One combine per tuple, and one per slice that a window covers."""
    rng = random.Random(77)
    for _ in range(30):
        queries = rng.sample([(6, 4), (5, 3), (10, 4), (8, 2)], 2)
        stream = random_stream(rng, rng.randint(1, 30), 40)
        out, sl = run(stream, queries, SUM, mode)
        per_window = sum(sum(1 for c in sl.cuts if s <= c < e) for _, s, e, _ in out)
        assert sl.combines == len(stream) + per_window


def test_starts_never_cut_more_than_edges():
    rng = random.Random(5)
    for _ in range(30):
        queries = rng.sample([(6, 4), (5, 3), (10, 4), (7, 2), (9, 6)], rng.randint(1, 3))
        a = boundaries(queries, 60, "starts")
        b = boundaries(queries, 60, "edges")
        assert set(a) <= set(b)


def test_errors():
    with pytest.raises(ValueError):
        Slicer([(0, 2)], SUM)
    with pytest.raises(ValueError):
        Slicer([(2, 2)], SUM, mode="pairs")
    with pytest.raises(ValueError):
        run([(3, 1), (2, 1)], [(2, 2)], SUM)
    assert run([], [(2, 2)], SUM)[0] == []

Exercises

  1. For the queries (R,S)=(10,4)(R, S) = (10, 4) and (9,6)(9, 6), list the cuts of the edges rule and of the starts rule in [0,24)[0, 24). How many slices does each window cover under each rule?
  2. Prove that for one query with SS dividing RR, the edges rule and the starts rule give the same cuts. Then give a query for which the starts rule makes fewer slices.
  3. Give an out-of-order stream, a watermark and a window for which the starts rule gives a wrong result while the edges rule gives the right one.
  4. A query has session windows with gap 3. The tuples arrive with timestamps 1, 2, 9, 10 and then, late, 5. Show the sessions and slices before and after the late tuple, and say which emitted results change.

References

  1. 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 and the sharing of slices among queries with different ranges and slides (general locator)
  2. Paris Carbone, Jonas Traub, Asterios Katsifodimos, Seif Haridi and Volker Markl, Cutty, aggregate sharing for user-defined windows, Proceedings of the 25th ACM International Conference on Information and Knowledge Management (CIKM), 2016, pages 1201 to 1210, slicing at window starts only, for windows defined by user functions (general locator)
  3. Jonas Traub, Philipp M. Grulich, Alejandro Rodriguez Cuellar, Sebastian Bress, Asterios Katsifodimos, Tilmann Rabl and Volker Markl, Scotty, general and efficient open-source window aggregation for stream processing systems, ACM Transactions on Database Systems 46(1), 2021, article 1, general stream slicing for in-order and out-of-order streams, for context-free and context-aware windows, and the split, merge and update of slices (general locator)
  4. 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 (panes of length gcd(RANGE, SLIDE), the special case of slicing for one query)

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