TExcelTAD
Home › Streaming, Sketching & Sublinear Algorithms › Stream Models: Insertion-Only, Cash Register and Turnstile

Stream Models: Insertion-Only, Cash Register and Turnstile

Before any algorithm, a streaming result has to say what the stream may contain. A bound proved for streams of insertions can fail completely once deletions are allowed, and a few lower bounds hold only when frequencies may become negative. This lesson fixes the models used in the rest of the course, introduces linear sketches, the tool that handles deletions for free, and works through the first sketch of the course: recovering a vector that has only one non-zero entry.

Updates and the frequency vector

The input is a sequence of updates (it,Δt)(i_t, \Delta_t) for t=1,…,mt = 1, \ldots, m, with it∈[n]i_t \in [n] and Δt∈Z\Delta_t \in \mathbb{Z}. The updates define the frequency vector

fi=∑t : it=iΔt,i∈[n],f_i = \sum_{t \,:\, i_t = i} \Delta_t , \qquad i \in [n] ,

and the algorithm must answer a question about ff (its largest entries, its norm, its number of non-zeros) at the end, or at any time. The models differ in which updates are allowed (the names follow Muthukrishnan, 2005):

Model Updates Typical source
insertion-only (unit cash register) Δt=1\Delta_t = 1: the stream is a list of items page views, packets, words of a text
cash register Δt>0\Delta_t > 0 bytes per flow, sales amounts
strict turnstile any Δt\Delta_t, but fi≥0f_i \ge 0 at all times a database table with inserts and deletes
general turnstile any Δt\Delta_t, ff may have negative entries the difference of two streams, f−gf - g

Each model contains the ones above it, so an algorithm for the general turnstile model works everywhere, and a lower bound for insertion-only streams holds everywhere. The difference between the last two rows matters: some guarantees (count-min's "never underestimates", for example) use f≥0f \ge 0 and are lost in the general model.

The time-series model, where ata_t is simply the value ftf_t, is the other classical model; it reduces to the cash register model by sending the update (t,at)(t, a_t).

The program generates one frequency vector in three ways and checks that the streams agree. Every model ends at the same ff; what differs is the path, and an algorithm sees only the path.

python · try it yourself
import random
from collections import Counter

rng = random.Random(1)
n = 8
target = [rng.randrange(0, 6) for _ in range(n)]

# insertion-only: each item listed f_i times, in random order
ins = [i for i in range(n) for _ in range(target[i])]
rng.shuffle(ins)

# cash register: positive increments that add up to f_i
cash = []
for i in range(n):
    left = target[i]
    while left:
        d = rng.randint(1, left)
        cash.append((i, d))
        left -= d
rng.shuffle(cash)

# strict turnstile: insert extra copies first, then delete them again (f never goes negative)
turn = [(i, +1) for i in ins] + [(i, +1) for i in range(n)] * 2
rng.shuffle(turn)
turn += [(i, -1) for i in range(n)] * 2

def freq(updates):
    f = [0] * n
    for i, d in updates:
        f[i] += d
    return f

print("target f      :", target)
print("insertion-only:", freq((i, 1) for i in ins), f"({len(ins)} updates)")
print("cash register :", freq(cash), f"({len(cash)} updates)")
print("turnstile     :", freq(turn), f"({len(turn)} updates)")
target f      : [1, 4, 0, 2, 0, 3, 3, 3]
insertion-only: [1, 4, 0, 2, 0, 3, 3, 3] (16 updates)
cash register : [1, 4, 0, 2, 0, 3, 3, 3] (10 updates)
turnstile     : [1, 4, 0, 2, 0, 3, 3, 3] (48 updates)

Resources and what "small" means

A streaming algorithm is judged by:

  • space, the number of bits (or words of O(log⁡n+log⁡m)O(\log n + \log m) bits) it keeps between updates. The goal is polylog⁡(n,m)\operatorname{polylog}(n, m), or O(ε−2polylog⁡)O(\varepsilon^{-2} \operatorname{polylog}) for an ε\varepsilon-approximation. Storing ff exactly takes nn words and is the trivial upper bound;
  • update time, the work per update, ideally O(1)O(1) or polylog⁡\operatorname{polylog};
  • query time, the work to produce an answer;
  • the number of passes. Almost everything in the course uses one pass; graph problems sometimes use a few.

Most interesting functions of ff cannot be computed exactly in sublinear space, even with randomization. The next lesson proves one such bound directly, and Space Lower Bounds from Communication Complexity gives the general method. So the algorithms of the course approximate, and almost all of them are randomized.

Linear sketches

A linear sketch stores S(f)=AfS(f) = A f for a matrix A∈Zk×nA \in \mathbb{Z}^{k \times n} (or over a field) with k≪nk \ll n, where AA is chosen at random from a family that can be described in small space, usually by a few hash functions. An update (i,Δ)(i, \Delta) changes the sketch by Δ\Delta times column ii of AA:

A(f+Δei)=Af+Δ Aei,A(f + \Delta e_i) = A f + \Delta \, A e_i ,

so the sketch can be maintained without storing ff, as long as column ii can be computed from the hash functions when it is needed. Linearity gives three properties at once:

  1. Deletions are free. The update rule does not care about the sign of Δ\Delta, so a linear sketch works in the general turnstile model.
  2. Merging. Two machines that saw streams with frequency vectors ff and gg, using the same AA, can add their sketches: Af+Ag=A(f+g)Af + Ag = A(f + g).
  3. Differences. Af−Ag=A(f−g)Af - Ag = A(f - g) summarizes how two streams differ, for example the traffic of a link measured at both ends.

Count-min, Count-Sketch and the AMS sketch are linear; Misra-Gries, Space-Saving and HyperLogLog are not (they use comparisons or maxima), which is why they need insertion-only streams. For the general turnstile model a converse holds under technical conditions: any algorithm can be turned into one that maintains a linear sketch with only a logarithmic loss in space (Li, Nguyen and Woodruff, 2014; the conditions, such as very long streams, exclude some practical settings).

A first sketch: recovering a 1-sparse vector

Suppose that at query time ff has at most one non-zero entry, but the stream before that may have touched many items: a router checking that all flows but one have balanced packet counts, or the classical puzzle of finding the one number missing from a shuffled list. Two counters suffice:

s0=∑ifi,s1=∑ii⋅fi.s_0 = \sum_i f_i , \qquad s_1 = \sum_i i \cdot f_i .

If f=c ejf = c \, e_j with c≠0c \ne 0, then s0=cs_0 = c and s1=jcs_1 = j c, so j=s1/s0j = s_1 / s_0. Both are linear in ff. They do not detect whether ff really is 1-sparse: f=e1+e3f = e_1 + e_3 gives s1/s0=2s_1 / s_0 = 2. A third, randomized counter fixes that. Pick a prime p>np > n and a random z∈Zpz \in \mathbb{Z}_p and keep

s2=∑ifi zi mod p.s_2 = \sum_i f_i \, z^i \bmod p .

If f=c ejf = c\, e_j then s2=czjs_2 = c z^j. Otherwise the polynomial ∑ifixi−c xj\sum_i f_i x^i - c\,x^j is a non-zero polynomial of degree at most nn (assuming the entries of ff are smaller than pp in absolute value), which vanishes at the random zz with probability at most n/pn/p by the Schwartz-Zippel lemma. So the test "is s0≠0s_0 \ne 0, is s1/s0s_1/s_0 an integer j∈[n]j \in [n], and is s2=s0zjs_2 = s_0 z^j?" accepts a vector that is not 1-sparse with probability at most n/pn/p. This 1-sparse recovery structure is the building block of ℓ0\ell_0-sampling (Sparse Recovery and l0-Sampling) and through it of the graph sketches of the course.

python · try it yourself
import random

P = (1 << 61) - 1
class OneSparse:
    def __init__(self, rng):
        self.z = rng.randrange(1, P)
        self.s0 = self.s1 = self.s2 = 0
    def update(self, i, d):                   # linear in f: works with deletions
        self.s0 += d
        self.s1 += d * i
        self.s2 = (self.s2 + d * pow(self.z, i, P)) % P
    def query(self):
        if self.s0 == 0:
            return "zero" if self.s1 == 0 and self.s2 == 0 else "not 1-sparse"
        j, r = divmod(self.s1, self.s0)
        if r == 0 and j >= 0 and self.s2 == self.s0 % P * pow(self.z, j, P) % P:
            return f"1-sparse: f[{j}] = {self.s0}"
        return "not 1-sparse"

rng = random.Random(7)
n = 100000
# all items inserted and deleted again in random order, except item 31337, inserted 3 times
ups = [(i, +1) for i in range(0, n, 7)] * 2 + [(31337, +1)] * 3
rng.shuffle(ups)
ups += [(i, -1) for i in range(0, n, 7)] * 2
s = OneSparse(rng)
for i, d in ups:
    s.update(i, d)
print(len(ups), "updates ->", s.query())

t = OneSparse(rng)                           # f = e_1 + e_3: the plain ratio would say "2"
for i, d in [(1, 1), (3, 1)]:
    t.update(i, d)
print("f = e1 + e3: s1/s0 =", t.s1 / t.s0, "->", t.query())
57147 updates -> 1-sparse: f[31337] = 3
f = e1 + e3: s1/s0 = 2.0 -> not 1-sparse

The structure keeps three numbers no matter how many updates arrive, and it found the one surviving item among about 57 000 updates. The second case shows why the fingerprint s2s_2 is needed.

In practice

  • Insertion-only is the right model for logs and counters, and the deterministic summaries of the next section (Misra-Gries, Space-Saving) are the usual choice there.
  • Turnstile arises with databases (inserts and deletes), with differences of streams and with graphs whose edges are added and removed. Linear sketches are then essentially the only option.
  • Sliding windows, where only the last WW items count, form a further model with its own techniques (exponential histograms, Datar, Gionis, Indyk and Motwani, 2002); the course does not treat it. The offline relative is the practice problem Sliding Window Maximum.

Test yourself

In which model may a frequency fif_i become negative?

  1. Insertion-only
  2. Cash register
  3. Strict turnstile
  4. General turnstile

Why does a linear sketch AfAf handle deletions?

  1. It stores the whole stream
  2. An update (i,Δ)(i, \Delta) adds Δ\Delta times column ii of AA, whatever the sign of Δ\Delta
  3. It ignores negative updates
  4. It recomputes AA after each deletion

The counters s0=∑ifis_0 = \sum_i f_i and s1=∑iifis_1 = \sum_i i f_i give s1/s0=2s_1/s_0 = 2. What can you conclude without the fingerprint s2s_2?

  1. f=c e2f = c\,e_2 for some cc
  2. Nothing certain: ff could also be, for example, e1+e3e_1 + e_3
  3. ff is zero
  4. ff has exactly two non-zero entries

Which of these summaries is a linear sketch?

  1. Misra-Gries
  2. HyperLogLog
  3. Count-min
  4. Space-Saving