Algorithm Search⌘K

Algorithmadvanced

Chain scheduling

Also called chain operator scheduling.

Schedule stream operators by the slopes of the lower envelopes of their progress charts, so that tuples shrink as fast as possible and the queues between operators use little memory.

Time
O(log k) worstO(k) build
Space
O(n + k) extra
Where
k = the total number of operators of all queries; n = the number of waiting tuples
Properties
deterministicexactnot externalnot in placeonlineiterative
Origin
Brian Babcock, Shivnath Babu, Mayur Datar, Rajeev Motwani, 2003

Chain is a rule of Babcock, Babu, Datar and Motwani (2003) for deciding which operator a data stream system runs next when tuples wait in queues between operators. Each query is a chain of operators, and each operator changes the size of a tuple, for example a filter that drops most tuples or a projection that removes columns. Chain draws the size of a tuple against the processing time it has had, takes the lower convex envelope of this progress chart, and always runs the waiting tuple that sits on the steepest segment of its envelope. The goal is little memory in the queues during bursts of input, and the paper claims that Chain is near-optimal for single-stream queries with selections, projections and foreign-key joins with stored relations.

In plain words

Tuples arrive in bursts, faster than the system can process them, and they wait in queues. Each step of work makes a tuple smaller or removes it, but some steps help a lot and some help almost nothing. To keep the queues small, you should spend your time on the work that frees the most memory per unit of time. The catch is that a step that frees nothing can be the gate to a step that frees a lot. Chain looks ahead along each query: it groups such a step with the later steps that make it worth while, and it gives the whole group the average rate of the group. Then it always works on the best group, the oldest tuple first.

The problem

A query is a chain of operators o1,…,oko_1, \dots, o_k that every tuple of the query passes through in order. A tuple enters with size s0s_0, and after ojo_j its size is sjs_j; a filter with selectivity pp turns size ss into the expected size psp s, and a projection makes a tuple smaller. The output leaves the system after oko_k, so sk=0s_k = 0. Operator ojo_j takes the time tjt_j per tuple. One processor runs one operator on one tuple at a time, and tuples arrive at times that the system does not control. The memory at a time is the total size of the tuples that wait in the system. The scheduling problem is to choose, at each step, the next operator to run so that the memory stays low at all times, and in particular at the peak of a burst.

The progress chart of a query is the polyline through the points Pj=(Tj,sj)P_j = (T_j, s_j) with T0=0T_0 = 0 and Tj=t1+⋯+tjT_j = t_1 + \cdots + t_j. Its lower envelope is its lower convex hull. The slope of a segment, with the sign changed, is the size that a tuple loses per unit of processing time on that segment.

The algorithm

  1. ENVELOPE(s_0, ..., s_k; t_1, ..., t_k) ▷ the chart of one query; T_0 = 0 and T_j = t_1 + ... + t_j
  2. 1i ← 0
  3. 2while i < k do
  4. 3j* ← the j > i with the largest (s_i - s_j) / (T_j - T_i); the largest such j on a tie
  5. 4the priority of o_{i+1}, ..., o_{j*} ← (s_i - s_{j*}) / (T_{j*} - T_i)
  6. 5i ← j*
  7. CHAIN(arrivals) ▷ one operator step per time unit
  8. for each time unit do
  9. 6add the tuples that arrive now to the set of waiting tuples
  10. 7if some tuple waits then
  11. 8x ← the waiting tuple whose next operator has the highest priority; the oldest tuple on a tie
  12. 9run the next operator o_j on x; the memory falls by s_{j-1} - s_j
  13. 10if o_j is the last operator of its query then x leaves the system

The envelope depends only on the chart, so it is computed once per query, when the query is registered or when the statistics change. Lines L1 to L5 find each segment as the steepest descent from the current vertex, which is O(k2)O(k^2) for a chain of kk operators; a monotone hull scan, as in the Graham scan, finds the same envelope in O(k)O(k), because the points are already sorted by time.

In a system, the tuples that wait before an operator form a queue in arrival order, so the oldest tuple of an operator is the head of its queue. Line L8 then needs only the queue heads: keep the non-empty operator queues in a heap keyed by the priority and the arrival time of the head.

Example

Two queries have unit-time operators. Query A has the chart 1,1,1/5,01, 1, 1/5, 0: a first operator that keeps every tuple, such as a costly test that passes all of them, then a filter that keeps a fifth of the size, then the output. Query B has the chart 1,2/5,01, 2/5, 0.

The envelope of A goes from (0,1)(0, 1) to (2,1/5)(2, 1/5) with slope 2/52/5, because that is steeper than the slope 0 to (1,1)(1, 1) and the slope 1/31/3 to (3,0)(3, 0). Then it goes on to (3,0)(3, 0) with slope 1/51/5. So the priorities of A are 2/5,2/5,1/52/5, 2/5, 1/5: the first operator frees nothing, but it shares the priority of the filter after it. The chart of B is convex, and its priorities are its drops, 3/53/5 and 2/52/5.

A tuple of A and a tuple of B arrive at time 0, a second tuple of B at time 1, and a second tuple of A at time 2. The table gives the memory after each step, in units of 1/51/5.

step 0 1 2 3 4 5 6 7 8 9
Chain 7 9 14 10 8 6 6 2 1 0
FIFO 10 11 15 12 10 7 5 5 1 0
best for this step 7 9 12 10 8 6 4 2 1 0

At step 0, Chain runs the first tuple of B (priority 3/53/5) and FIFO runs the first operator of A, which frees nothing. At step 2, all four candidates have priority 2/52/5, and Chain takes the oldest, the first tuple of A, whose next step frees nothing; the step after it frees 4/54/5. The last row is the least memory over all schedules for each step on its own, found by search. Chain has the lower peak (14 against 15) and the lower total (63 against 76) than FIFO here, but it is not optimal at steps 2 and 6, because the chart of A is not convex. These numbers are the output of the code on this page, so they are measurements on one input.

Correctness

Chain is a rule, so the question is how good its schedules are. The proofs are in the correctness proof, for the model of the code: one processor and operators of unit time.

  • Theorem. Lines L1 to L5 compute the lower convex hull of the chart. Each operator gets the rate at which the hull falls over it, and the priorities do not increase along the chain.
  • Theorem. If the chart of every query is convex, so that the drops do not increase along each chain, then Chain gives the least possible memory at every step at once, over all schedules. The proof writes the memory as the arrived size minus the total drop of the steps run so far. It relaxes the problem by dropping the order of the operators inside a chain, and shows by an exchange argument that the greedy rule "the heaviest released job first" is optimal for unit jobs with release times. With convex charts, this greedy rule runs the steps in chain order, so it is Chain.
  • A counterexample for charts that are not convex: with the charts 1,1,01, 1, 0 and 1,2/5,01, 2/5, 0 and one tuple of each at time 0, Chain has memory 7/57/5 after two steps, and running query A first gives 1.

For charts that are not convex, the envelope is a heuristic in this model: it replaces a chain by the convex chart that it could follow if it ran each segment without a break. Babcock et al. prove a near-optimality result for this case in their own model. This page does not state the form of that bound, because it could not confirm it.

Proof: The envelope gives convex priorities, and Chain minimizes memory at every instant when every chart is convexfull

We use the line numbers of the pseudocode. This proof covers the model of the code on the page, which is narrower than the model of Babcock, Babu, Datar and Motwani: one processor, operators of unit time, and one operator step per time unit. A query qq is a chain of operators o1,…,oko_1, \dots, o_k with sizes s0≥s1≥⋯≥sk=0s_0 \ge s_1 \ge \cdots \ge s_k = 0 and s0>0s_0 > 0: a tuple of qq enters with size s0s_0, has size sjs_j after ojo_j, and leaves the system after oko_k. The drop of ojo_j is dj=sj−1−sj≥0d_j = s_{j-1} - s_j \ge 0. Tuples arrive at given times. The memory M(τ)M(\tau) after step τ\tau is the total size of the tuples that have arrived and not yet left.

Part 1: the envelope

Let T0=0T_0 = 0 and Tj=t1+⋯+tjT_j = t_1 + \cdots + t_j for positive times tjt_j, and let Pj=(Tj,sj)P_j = (T_j, s_j). The lower envelope is the lower convex hull of P0,…,PkP_0, \dots, P_k, seen as a function hh on [0,Tk][0, T_k].

Lemma 1. Lines L1 to L5 give each operator ojo_j the priority (h(Tj−1)−h(Tj))/tj(h(T_{j-1}) - h(T_j)) / t_j, and the priorities do not increase along the chain.

Proof. We use one fact about the hull. If all points lie on or above a line ℓ\ell, and ℓ\ell passes through PaP_a and PbP_b with a<ba < b, then h=ℓh = \ell on [Ta,Tb][T_a, T_b]. Indeed, h(x)h(x) is the least value at xx of a convex combination of the points, every such combination is on or above ℓ\ell because ℓ\ell is linear, and the combinations of PaP_a and PbP_b reach ℓ\ell.

Let i0=0,i1,i2,…i_0 = 0, i_1, i_2, \dots be the values of ii that the loop reaches, and let σm\sigma_m be the slope that line L3 finds at imi_m, so σm=(sim−sim+1)/(Tim+1−Tim)\sigma_m = (s_{i_m} - s_{i_{m+1}}) / (T_{i_{m+1}} - T_{i_m}) is the largest descent from PimP_{i_m} to a later point. Let ℓm\ell_m be the line through PimP_{i_m} with slope −σm-\sigma_m. We show by induction on mm that every point PjP_j lies on or above ℓm\ell_m, and that σm≤σm−1\sigma_m \le \sigma_{m-1} for m≥1m \ge 1.

Points after imi_m are on or above ℓm\ell_m by the choice of σm\sigma_m. For m=0m = 0 there are no earlier points. For m≥1m \ge 1, the point Pim+1P_{i_{m+1}} is on or above ℓm−1\ell_{m-1} by the induction hypothesis, and ℓm−1\ell_{m-1} passes through PimP_{i_m}, so sim+1≥sim−σm−1(Tim+1−Tim)s_{i_{m+1}} \ge s_{i_m} - \sigma_{m-1}(T_{i_{m+1}} - T_{i_m}), which gives σm≤σm−1\sigma_m \le \sigma_{m-1}. To the left of TimT_{i_m}, the line ℓm\ell_m is then on or below ℓm−1\ell_{m-1}, because both pass through PimP_{i_m} and ℓm\ell_m is less steep. The points before imi_m are on or above ℓm−1\ell_{m-1}, so they are on or above ℓm\ell_m.

By the fact above, h=ℓmh = \ell_m on [Tim,Tim+1][T_{i_m}, T_{i_{m+1}}], so hh falls at the rate σm\sigma_m there. Line L4 gives each operator oim+1,…,oim+1o_{i_m + 1}, \dots, o_{i_{m+1}} the priority σm\sigma_m, which is (h(Tj−1)−h(Tj))/tj(h(T_{j-1}) - h(T_j)) / t_j on this piece, and line L5 moves on to im+1i_{m+1}. The order σ0≥σ1≥⋯\sigma_0 \ge \sigma_1 \ge \cdots is the second claim. □\square

The test of the code compares the priorities with a brute-force hull over all pairs of points.

The chart is convex when d1/t1≥d2/t2≥⋯≥dk/tkd_1 / t_1 \ge d_2 / t_2 \ge \cdots \ge d_k / t_k. Then the chart is its own envelope, and the priority of ojo_j is dj/tjd_j / t_j; with unit times, it is djd_j.

Part 2: optimality for convex charts

Write A(τ)A(\tau) for the total entry size s0s_0 of the tuples that arrive at or before step τ\tau, and D(τ)D(\tau) for the total drop of the operator steps run in steps 0,…,τ0, \dots, \tau. Then

M(τ)=A(τ)−D(τ),M(\tau) = A(\tau) - D(\tau),

because a tuple that has run o1,…,ojo_1, \dots, o_j has size s0−d1−⋯−djs_0 - d_1 - \cdots - d_j. A(τ)A(\tau) does not depend on the schedule, so a schedule minimizes M(τ)M(\tau) if and only if it maximizes D(τ)D(\tau).

The relaxation. Make one job (x,j)(x, j) for each tuple xx and each operator ojo_j of its query, with weight djd_j and release time the arrival time of xx. A relaxed schedule runs at most one released job per step, in any order, without the rule that (x,j)(x, j) must wait for (x,j−1)(x, j - 1). Every real schedule is a relaxed schedule, so the best relaxed value of D(τ)D(\tau) is an upper bound for every real schedule.

Lemma 2. Let GG be the relaxed schedule that, at each step, runs a released job of the largest weight that is not done yet. For every τ\tau, GG maximizes the total weight of the jobs done in steps 0,…,τ0, \dots, \tau over all relaxed schedules.

Proof. Fix τ\tau, and among the relaxed schedules with the largest weight by τ\tau take one, OO, that agrees with GG on the most initial steps, say on steps 0,…,u−10, \dots, u - 1 with u≤τu \le \tau as large as possible. Suppose u≤τu \le \tau and let gg be the job of GG at step uu; then gg is released by step uu and not done before it. If OO runs gg at a later step u′≤τu' \le \tau, exchange the jobs of OO at steps uu and u′u'. The job oo that OO ran at step uu is released by u≤u′u \le u', so the result is a valid relaxed schedule with the same weight by τ\tau that agrees with GG on step uu too. If OO does not run gg by τ\tau, replace the job of OO at step uu (or an idle step) by gg. The weight by τ\tau changes by d(g)−d(o)≥0d(g) - d(o) \ge 0, because oo was also released and not done at step uu, and GG picked the heaviest such job. In both cases we get an optimal schedule that agrees with GG on more steps, which is a contradiction. So OO agrees with GG up to τ\tau, and GG is optimal. □\square

Lemma 3. If every chart is convex and times are unit, then GG with the tie rule "the largest weight, then the oldest tuple, then the smallest jj" runs exactly the same steps as Chain (lines L6 to L10) with the tie rule "the highest priority, then the oldest tuple".

Proof. By induction on the steps: suppose both have done the same jobs before step uu, so for each tuple, the done jobs of GG are a prefix (x,1),…,(x,px)(x, 1), \dots, (x, p_x) of its chain, as for Chain. Let ww be the largest weight of a released job that is not done. Each such job (x,j)(x, j) has j>pxj > p_x, and since the chart is convex, the next job (x,px+1)(x, p_x + 1) has weight dpx+1≥djd_{p_x + 1} \ge d_j. So ww is also the largest weight of a next job, which is the largest Chain priority among the waiting tuples, by Lemma 1. The tuples that own a job of weight ww are exactly the tuples whose next job has weight ww. Both rules take the oldest of these tuples, and GG takes its smallest job of weight ww, which is its next job. So both run the same job, and GG keeps the prefix form. □\square

Theorem. If every query has a convex chart and all operators take unit time, then for every step τ\tau, Chain gives the least memory M(τ)M(\tau) over all schedules.

Proof. By Lemma 3, Chain's schedule is GG, which is a real schedule. By Lemma 2, GG has the largest D(τ)D(\tau) over all relaxed schedules, and so over all real schedules. Since M(τ)=A(τ)−D(τ)M(\tau) = A(\tau) - D(\tau), it has the least memory. ■\blacksquare

The theorem is false without convexity. With the charts 1,1,01, 1, 0 and 1,2/5,01, 2/5, 0 and one tuple of each at time 0, Chain gives the priorities 1/2,1/21/2, 1/2 and 3/5,2/53/5, 2/5, so it runs the second query first and has memory 7/57/5 after two steps, while running both operators of the first query first gives memory 1. The tests check this case, and they check the theorem against a search over all schedules on random small inputs.

Complexity

  • Per scheduling step. With a heap of the non-empty operator queues, line L8 costs O(log⁡k)O(\log k) in the worst case per step, and line L9 and the queue update cost O(1)O(1), so the scheduler adds O(log⁡k)O(\log k) per operator step and O(klog⁡k)O(k \log k) per tuple of a query with kk operators. These are worst-case bounds. The code on this page scans all waiting tuples, which is O(n)O(n) per step and is meant for tests only.
  • The envelope. O(k)O(k) per query with a hull scan, O(k2)O(k^2) with lines L1 to L5, once per change of the statistics.
  • Memory. The scheduler stores the priorities, O(k)O(k), and the queues hold the nn waiting tuples. Chain does not change the size of a tuple; it changes how many tuples wait at each size.

Properties

  • Deterministic with the tie rule, and online: it decides each step from the tuples that have arrived.
  • Starvation. A query with low priorities waits as long as tuples of a query with higher priorities keep arriving, so its latency can grow without bound during a long burst. This follows from the rule, and it is the reason for the latency variant below.
  • Late data. Chain orders work by priority and arrival time, not by event time. A late tuple is ordinary work for it; the windows and the watermarks of the operators decide what a late tuple means. A long delay in a queue can make a tuple late for a downstream window, so a system that uses Chain must set its allowed lateness with the queueing delay in mind.

Variants and improvements

  • Chain-Flush. The journal version (2004) adds Chain-Flush, a variant that aims at low output latency. This page does not give its rule, because it could not confirm the details.
  • Operator times. With different times tjt_j, the priority is the drop per unit of time, and the envelope uses the times on its horizontal axis. The function on this page accepts such times, but the theorem above is only for unit times.
  • Queries over several streams. The paper's claim is for single-stream queries with selections, projections and foreign-key joins with stored relations. Joins of two streams, where one input tuple can make many output tuples, do not fit the model of a chart whose size only falls, and this page does not cover them.
  • Other schedulers. FIFO, round robin and a greedy rule that looks only at the next operator are simpler. In the example above the greedy rule gives the memory 7, 9, 12, 10, 10, 6, 5, 5, 1, 0: a lower peak than Chain (12 against 14), because it does not run the step that frees nothing early, but a higher total (65 against 63). Neither rule is better on all inputs.

When to use it

Use Chain when memory is the limit during bursts, the queries are chains of operators that make tuples smaller, and the system has good estimates of selectivities and costs. When the output latency matters more than memory, use Chain-Flush, FIFO, or a scheduler with deadlines. When the arrival rate stays above the processing rate, no scheduler helps, and the system needs backpressure or load shedding.

Pitfalls

  • Bad statistics. The priorities come from estimated selectivities and costs. If the estimates are wrong, the schedule is wrong too, and the statistics must be watched and the envelopes recomputed.
  • Reading the slope as a greedy drop. The priority of an operator is the slope of its envelope segment, not its own drop. An operator that frees nothing can have a high priority because of the operators after it, as in the example.
  • Breaking a segment. The envelope assumes that the tuple goes on along its segment. If other tuples with the same priority interleave, as at step 2 of the example, the memory can rise before it falls.
  • Starvation. Without a bound on waiting time, tuples of low-priority queries can wait for a long time.

Implementations

This page did not confirm the details of the implementation in the papers. The Python code on this page computes the envelope with exact fractions, simulates Chain, FIFO and the greedy rule with unit operator times, and finds the least memory at each step by a search over all schedules. Its tests compare the envelope with a brute-force hull, check the theorem for convex charts against the search on random inputs, and check the counterexample.

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.

chain_scheduling.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/chain-scheduling/. The authors are listed in prov/XJAPP3.jsonl.

"""Chain operator scheduling (Babcock, Babu, Datar and Motwani, SIGMOD 2003).

A query is a chain of operators o_1, ..., o_k. A tuple enters with size s_0
and has size s_j after o_j; the last size s_k is 0 because the output leaves
the system. Operator o_j takes time t_j per tuple. The progress chart of the
query is the polyline through the points (T_j, s_j) with T_j = t_1 + ... + t_j.
Chain gives each operator the slope (the size lost per unit of time) of the
segment of the lower envelope of the chart that covers it, and at each step
runs the waiting tuple whose next operator has the highest priority, the
oldest tuple first on a tie.

The simulator uses unit times (t_j = 1), one operator step per time unit and
one processor. lower_envelope accepts any positive times.
"""

from fractions import Fraction
from typing import Sequence


def check_chart(sizes: Sequence) -> list:
    sizes = [Fraction(s) for s in sizes]
    if len(sizes) < 2 or sizes[-1] != 0:
        raise ValueError("a chart needs at least one operator and must end at size 0")
    if any(b > a for a, b in zip(sizes, sizes[1:])) or sizes[0] <= 0:
        raise ValueError("sizes must be positive at the start and must not grow")
    return sizes


def lower_envelope(sizes: Sequence, times: Sequence | None = None) -> list:
    """The Chain priority of each operator o_1..o_k: the slope of its envelope segment."""
    sizes = check_chart(sizes)
    k = len(sizes) - 1
    times = [1] * k if times is None else list(times)
    if len(times) != k or any(t <= 0 for t in times):
        raise ValueError("one positive time per operator")
    T = [0]
    for t in times:
        T.append(T[-1] + t)
    prio = [None] * k
    i = 0  # @line L1
    while i < k:  # @line L2
        # the point after i with the steepest descent from point i; the farthest on a tie
        best, best_slope = None, None
        for j in range(i + 1, k + 1):  # @line L3
            slope = Fraction(sizes[i] - sizes[j]) / (T[j] - T[i])
            if best is None or slope >= best_slope:
                best, best_slope = j, slope
        for j in range(i, best):  # @line L4
            prio[j] = best_slope
        i = best  # @line L5
    return prio


class Tuple_:
    __slots__ = ("query", "arrival", "seq", "pos")

    def __init__(self, query: int, arrival: int, seq: int):
        self.query, self.arrival, self.seq, self.pos = query, arrival, seq, 0


def simulate(charts: Sequence[Sequence], arrivals: Sequence[tuple[int, int]], horizon: int, policy: str = "chain"):
    """Run one operator step per time unit for horizon units.

    charts[q] are the sizes s_0..s_k of query q, with unit operator times.
    arrivals are (time, q) pairs: a tuple of query q enters before step time.
    Returns the memory (the total size of the waiting tuples) after each step.
    """
    charts = [check_chart(c) for c in charts]
    prios = [lower_envelope(c) for c in charts]
    by_time: dict[int, list[int]] = {}
    for t, q in arrivals:
        by_time.setdefault(t, []).append(q)
    waiting: list[Tuple_] = []
    memory = Fraction(0)
    trace = []
    seq = 0
    for now in range(horizon):
        for q in by_time.get(now, []):  # @line L6
            waiting.append(Tuple_(q, now, seq))
            seq += 1
            memory += charts[q][0]
        if waiting:  # @line L7
            if policy == "chain":
                key = lambda x: (-prios[x.query][x.pos], x.arrival, x.seq)
            elif policy == "fifo":
                key = lambda x: (x.arrival, x.seq)
            elif policy == "greedy":  # the largest drop of the next step only
                key = lambda x: (charts[x.query][x.pos + 1] - charts[x.query][x.pos], x.arrival, x.seq)
            else:
                raise ValueError("unknown policy")
            x = min(waiting, key=key)  # @line L8
            c = charts[x.query]
            memory -= c[x.pos] - c[x.pos + 1]  # @line L9
            x.pos += 1
            if x.pos == len(c) - 1:  # @line L10
                waiting.remove(x)  # the output leaves the system
        trace.append(memory)
    return trace


def best_memory(charts: Sequence[Sequence], arrivals: Sequence[tuple[int, int]], horizon: int):
    """The least memory after each step over all schedules, by search over states.

    A state is the position of every tuple in its chain. Idling never helps,
    because sizes do not grow, so every step runs some waiting tuple."""
    charts = [check_chart(c) for c in charts]
    tuples = sorted((t, q) for t, q in arrivals)
    n = len(tuples)
    states = {tuple([0] * n)}
    out = []
    for now in range(horizon):
        here = [i for i, (t, _) in enumerate(tuples) if t <= now]
        nxt = set()
        for st in states:
            moves = [i for i in here if st[i] < len(charts[tuples[i][1]]) - 1]
            if not moves:
                nxt.add(st)
            for i in moves:
                s2 = list(st)
                s2[i] += 1
                nxt.add(tuple(s2))
        states = nxt
        out.append(min(sum(charts[tuples[i][1]][st[i]] for i in here) for st in states))
    return out
test_chain_scheduling.py 129 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/chain-scheduling/. The authors are listed in prov/XJAPP3.jsonl.

import random
from fractions import Fraction as Fr

import pytest

from chain_scheduling import best_memory, lower_envelope, simulate


def hull_value(T, s, x):
    """The lower convex hull of the chart at x, by brute force over all pairs of points."""
    best = None
    for a in range(len(T)):
        for b in range(a, len(T)):
            if T[a] <= x <= T[b]:
                if T[a] == T[b]:
                    v = min(s[a], s[b])
                else:
                    v = s[a] + (s[b] - s[a]) * Fr(x - T[a], T[b] - T[a])
                best = v if best is None else min(best, v)
    return best


def random_chart(rng, k, convex=False):
    if convex:
        drops = sorted((Fr(rng.randint(0, 6), 6) for _ in range(k)), reverse=True)
        total = sum(drops)
        if total == 0:
            drops[0], total = Fr(1), Fr(1)
        drops = [d / total for d in drops]  # start at size 1, end at size 0
    else:
        cuts = sorted(Fr(rng.randint(0, 12), 12) for _ in range(k - 1))
        pts = [Fr(1)] + [1 - c for c in cuts] + [Fr(0)]
        drops = [a - b for a, b in zip(pts, pts[1:])]
    sizes = [Fr(1)]
    for d in drops:
        sizes.append(sizes[-1] - d)
    return sizes


def random_arrivals(rng, nq, n, span):
    return [(rng.randrange(span), rng.randrange(nq)) for _ in range(n)]


def test_page_example():
    # query A: o1 keeps every tuple, o2 drops it; query B: o1 halves it twice
    A = [1, 1, 0]
    B = [1, Fr(1, 2), 0]
    assert lower_envelope(A) == [Fr(1, 2), Fr(1, 2)]
    assert lower_envelope(B) == [Fr(1, 2), Fr(1, 2)]
    C = [1, Fr(1, 4), 0]
    assert lower_envelope(C) == [Fr(3, 4), Fr(1, 4)]
    charts = [[1, 1, Fr(1, 5), 0], [1, Fr(2, 5), 0]]
    assert lower_envelope(charts[0]) == [Fr(2, 5), Fr(2, 5), Fr(1, 5)]
    assert lower_envelope(charts[1]) == [Fr(3, 5), Fr(2, 5)]
    arrivals = [(0, 0), (0, 1), (1, 1), (2, 0)]
    chain = simulate(charts, arrivals, 10, "chain")
    fifo = simulate(charts, arrivals, 10, "fifo")
    greedy = simulate(charts, arrivals, 10, "greedy")
    best = best_memory(charts, arrivals, 10)
    assert chain == [Fr(x, 5) for x in (7, 9, 14, 10, 8, 6, 6, 2, 1, 0)]
    assert fifo == [Fr(x, 5) for x in (10, 11, 15, 12, 10, 7, 5, 5, 1, 0)]
    assert greedy == [Fr(x, 5) for x in (7, 9, 12, 10, 10, 6, 5, 5, 1, 0)]
    assert best == [Fr(x, 5) for x in (7, 9, 12, 10, 8, 6, 4, 2, 1, 0)]
    assert max(chain) < max(fifo) and sum(chain) < sum(fifo)


def test_envelope_matches_brute_force_hull():
    rng = random.Random(41)
    for _ in range(300):
        k = rng.randint(1, 6)
        sizes = random_chart(rng, k)
        times = [rng.randint(1, 3) for _ in range(k)]
        prio = lower_envelope(sizes, times)
        T = [0]
        for t in times:
            T.append(T[-1] + t)
        for j in range(k):
            h0, h1 = hull_value(T, sizes, T[j]), hull_value(T, sizes, T[j + 1])
            assert prio[j] == (h0 - h1) / times[j]
        assert all(a >= b for a, b in zip(prio, prio[1:]))  # the envelope is convex


def test_convex_charts_are_optimal_at_every_instant():
    rng = random.Random(2003)
    for _ in range(60):
        nq = rng.randint(1, 3)
        charts = [random_chart(rng, rng.randint(1, 3), convex=True) for _ in range(nq)]
        arrivals = random_arrivals(rng, nq, rng.randint(1, 5), 4)
        horizon = 20
        assert simulate(charts, arrivals, horizon, "chain") == best_memory(charts, arrivals, horizon)


def test_non_convex_chart_is_not_always_optimal():
    charts = [[1, 1, 0], [1, Fr(2, 5), 0]]
    arrivals = [(0, 0), (0, 1)]
    chain = simulate(charts, arrivals, 4, "chain")
    best = best_memory(charts, arrivals, 4)
    assert chain == [Fr(7, 5), Fr(7, 5), Fr(2, 5), 0]
    assert best == [Fr(7, 5), 1, Fr(2, 5), 0]
    assert chain[1] > best[1]


def test_never_below_the_optimum():
    rng = random.Random(9)
    for _ in range(40):
        nq = rng.randint(1, 3)
        charts = [random_chart(rng, rng.randint(1, 3)) for _ in range(nq)]
        arrivals = random_arrivals(rng, nq, rng.randint(1, 5), 5)
        best = best_memory(charts, arrivals, 20)
        for policy in ("chain", "fifo", "greedy"):
            got = simulate(charts, arrivals, 20, policy)
            assert all(g >= b for g, b in zip(got, best))
            # every policy is work conserving, so all work is done by the end
            assert got[-1] == 0


def test_errors():
    with pytest.raises(ValueError):
        lower_envelope([1, Fr(1, 2)])  # does not end at 0
    with pytest.raises(ValueError):
        lower_envelope([1, 2, 0])  # grows
    with pytest.raises(ValueError):
        lower_envelope([1, 0], [0])
    with pytest.raises(ValueError):
        simulate([[1, 0]], [(0, 0)], 2, "lifo")
    assert simulate([[1, 0]], [], 3) == [0, 0, 0]

History

Babcock, Babu, Datar and Motwani introduced the progress chart and Chain at SIGMOD 2003, as part of the work on adaptive query processing over data streams in the STREAM project. The journal version of 2004, with Dilys Thomas, added Chain-Flush.

References

  1. Brian Babcock, Shivnath Babu, Mayur Datar and Rajeev Motwani, Chain: operator scheduling for memory minimization in data stream systems, Proceedings of ACM SIGMOD 2003, pages 253 to 264, the progress chart of an operator chain, its lower envelope, the Chain rule with the earliest arrival on a tie, and the claim of the abstract that Chain is near-optimal for single-stream queries with selections, projections and foreign-key joins with stored relations (the exact form of the bound is not repeated here)
  2. Brian Babcock, Shivnath Babu, Mayur Datar, Rajeev Motwani and Dilys Thomas, Operator scheduling in data stream systems, The VLDB Journal 13(4), 2004, pages 333 to 353, the journal version, which adds Chain-Flush for latency (general locator)

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 proofH1 sketch
  • a full proof of time.build
  • a full proof of time.worst
  • a full proof of space.extra
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
  • at least three sources
  • a scene preset for the example