Algorithm Search⌘K

Data structureresearch

FlatFAT

Also called flat fixed-size aggregator tree.

A complete binary tree in an array that keeps partial aggregates of a window under any associative operator, with O(log n) operator calls per single update and amortized O(1) resizing.

Time
O(n) worst · buildO(log n) amortized · queryO(m + m log(n/m)) update
Space
O(W) extra
Where
W = the number of values in the window; m = the number of leaves written by one update; n = the number of leaves of the tree (a power of two)
Properties
deterministicexactnot externalnot in placeonlineiterative
Origin
Kanat Tangwongsan, Martin Hirzel, Scott Schneider, Kun Lung Wu, 2015

FlatFAT, short for flat fixed-size aggregator, is a complete binary tree stored in an array in which each internal node holds the combination of the values below it under an associative operator ⊕\oplus. Tangwongsan, Hirzel, Schneider and Wu (2015) use it to answer a sliding-window aggregation query: the window values are the leaves, used as a circular buffer, and a change to mm leaves costs O(m+mlog⁡(n/m))O(m + m \log(n/m)) calls of ⊕\oplus. The operator needs only associativity and an identity, so it can be non-commutative and non-invertible, such as concatenation, max or a product of matrices. It is a segment tree with a fixed layout, and the two-stacks queue and the DABA queue are faster alternatives for windows that are strictly first in, first out.

In plain words

You must always know the largest of the last few thousand readings, and readings come and go all the time. Put the readings in a row of boxes. Above each pair of boxes, write the larger of the two. Above each pair of those notes, write the larger again, and go on up to a single note at the top, which is the answer. When a reading changes, only the notes on its path to the top can change, and there are few of them, because each level halves the number of notes. The same scheme works for any way of combining two values that does not care how you group them. It does not need the values to be numbers, and it does not need a way to undo a combination.

The abstract type

The tree keeps an array a0,…,an−1a_0, \dots, a_{n-1} of values from a set with an associative operator ⊕\oplus and an identity ee, for a fixed capacity nn. The operations are:

  • new(vv): set the leaves to the values vv, padded with ee.
  • update(CC): for each pair (i,x)(i, x) in the set CC of changes, set ai←xa_i \leftarrow x.
  • aggregate(): return a0⊕a1⊕⋯⊕an−1a_0 \oplus a_1 \oplus \cdots \oplus a_{n-1}.
  • prefix(ii): return a0⊕⋯⊕aia_0 \oplus \cdots \oplus a_i.
  • suffix(jj): return aj⊕⋯⊕an−1a_j \oplus \cdots \oplus a_{n-1}.

A FIFO window on top of the tree adds insert(xx), which appends xx as the youngest value, evict(), which removes the oldest value, and query(), which returns v1⊕⋯⊕vcv_1 \oplus \cdots \oplus v_c for the cc window values v1,…,vcv_1, \dots, v_c, oldest first. Order matters: for concatenation, the query of the window "c", "d", "e" must be "cde" and not "ecd".

Representation

The capacity nn is a power of two, n=2Ln = 2^L. The array T[1..2n−1]T[1..2n-1] holds the tree: the root is T[1]T[1], the children of node hh are T[2h]T[2h] and T[2h+1]T[2h + 1], and leaf ii is T[n+i]T[n + i]. This page counts leaves from 0; the paper counts them from 1 and puts leaf ii at n+i−1n + i - 1. No pointers are stored, and the array is filled level by level, which is why the tree is called flat. Each internal node hh holds T[h]=T[2h]⊕T[2h+1]T[h] = T[2h] \oplus T[2h+1], which by associativity is the combination of the leaves below hh, in order from left to right. A leaf that holds no value holds ee.

The FIFO window uses the leaves as a circular buffer with a front FF (the slot of the oldest value), a back BB (the slot for the next value) and a count cc. When F<BF < B the values are in one block and the root is the answer. When the buffer wraps, the paper calls it inverted: the oldest values are at the right end of the array and the youngest at the left, and the root then holds them in the wrong order.

Operations

  1. FLATFAT(n, ⊕, e) ▷ n = 2^L leaves; leaf i is T[n + i]; the root is T[1]
  2. NEW(v)
  3. 1T[n .. 2n - 1] ← v, padded with e
  4. 2for h ← n - 1 down to 1 do
  5. 3T[h] ← T[2h] ⊕ T[2h + 1]
  6. UPDATE(C) ▷ C is a set of pairs (i, x) with distinct i
  7. 4for each (i, x) in C do T[n + i] ← x; add ⌊(n + i) / 2⌋ to the set D
  8. 5while D is not empty do ▷ D holds the changed nodes of one level
  9. 6for each h in D do T[h] ← T[2h] ⊕ T[2h + 1]
  10. 7D ← {⌊h / 2⌋ : h in D and h > 1}
  11. AGGREGATE()
  12. 8return T[1]
  13. PREFIX(i) ▷ a_0 ⊕ ... ⊕ a_i
  14. 9h ← n + i; a ← T[h]
  15. 10while h > 1 do
  16. 11if h is odd then a ← T[h - 1] ⊕ a ▷ the left sibling comes before i
  17. h ← ⌊h / 2⌋
  18. return a
  19. SUFFIX(j) ▷ a_j ⊕ ... ⊕ a_{n-1}
  20. 12h ← n + j; a ← T[h]; while h > 1 do
  21. 13if h is even then a ← a ⊕ T[h + 1]; h ← ⌊h / 2⌋
  22. return a
  23. INSERT(x) ▷ the FIFO window: front F, back B, count c
  24. 14if c = n then copy the c values, oldest first, into a new tree of 2n leaves; F ← 0; B ← c
  25. 15UPDATE({(B, x)}); B ← (B + 1) mod n; c ← c + 1
  26. EVICT()
  27. 16UPDATE({(F, e)}); F ← (F + 1) mod n; c ← c - 1
  28. 17if n > 1 and c < n / 4 then copy the c values into a new tree of n / 2 leaves; F ← 0; B ← c mod (n / 2)
  29. QUERY()
  30. 18if c = 0 then return e; if F < B or B = 0 then return AGGREGATE()
  31. 19return SUFFIX(F) ⊕ PREFIX(B - 1) ▷ inverted: the old part, then the young part

The update repairs one level at a time, from the leaves up. All leaves are at the same depth, so the set DD always holds nodes of a single level, and a node is repaired only after both its children are correct. When two changed leaves share an ancestor, the ancestor is in DD once and is repaired once, which is where the batch update saves work over mm single updates.

PREFIX climbs from leaf ii to the root. Each time the current node is a right child, its left sibling covers the leaves just before the part already collected, so the sibling goes on the left. SUFFIX is the mirror image.

Example

Take concatenation of strings, which is associative but not commutative, with n=8n = 8 and the leaves a, b, c, d, e, f, g, h. NEW makes 7 calls. The two children of the root hold "abcd" and "efgh", and the root holds "abcdefgh".

An update writes "C" into leaf 2 and "F" into leaf 5. The changed leaves are T[10]T[10] and T[13]T[13]. Line L6 repairs T[5]T[5] and T[6]T[6], then T[2]T[2] and T[3]T[3], then T[1]T[1]: 5 calls, and the root is "abCdeFgh". Two single updates would cost 3+3=63 + 3 = 6 calls, because they repair the root twice.

PREFIX(5) starts at T[13]T[13], which is a right child, so it computes T[12]⊕T[12] \oplus "F" = "eF". The next node, T[6]T[6], is a left child, so nothing is added. The node after that, T[3]T[3], is a right child, so the result is T[2]⊕T[2] \oplus "eF" = "abCdeF". That is 2 calls for 3 levels.

Now use a FIFO window that starts with one leaf. Insert a, b, c and d. The tree doubles from 1 to 2 leaves at b and from 2 to 4 at c, so the leaves are a, b, c, d with F=0F = 0 and B=0B = 0. Evict twice: the leaves become ee, ee, c, d with F=2F = 2. Insert "e": it goes into slot 0, and B=1B = 1. The leaves are now "e", ee, "c", "d", and the root holds "ecd", which is the wrong order. The buffer is inverted (F=2>B=1F = 2 > B = 1), so line L19 returns SUFFIX(2) ⊕\oplus PREFIX(0) = "cd" ⊕\oplus "e" = "cde" with 2 calls.

Correctness

The invariant is that every internal node holds the combination, in order, of the leaves below it. NEW sets it bottom-up, and UPDATE restores it on exactly the ancestors of the changed leaves, level by level, so that each node is set from two correct children. PREFIX keeps the combination of the leaves from the leftmost leaf below the current node to leaf ii, and it reaches the root with the leftmost leaf 0. For the window, the slots that hold no value hold ee, so the root is the answer when the values form one block. When the buffer wraps, the window is the suffix from FF followed by the prefix up to B−1B - 1, and associativity joins them. The full proofs are in the correctness proof; every statement there is a theorem.

Proof: FlatFAT keeps every node equal to the aggregate of its leaves, and its operations meet the stated boundsfull

We use the line numbers of the pseudocode. The operator ⊕\oplus is associative and has the identity ee; it need not be commutative or invertible. The tree has n=2Ln = 2^L leaves for an integer L≥0L \ge 0, stored in the array T[1..2n−1]T[1..2n-1]: the root is T[1]T[1], the children of node hh are 2h2h and 2h+12h + 1, and leaf ii (for 0≤i<n0 \le i < n) is T[n+i]T[n + i]. All leaves are at depth LL. For a node hh, let lo(h)\mathrm{lo}(h) and hi(h)\mathrm{hi}(h) be the positions of the leftmost and the rightmost leaf below hh, so the leaves below hh are the contiguous block alo(h),…,ahi(h)a_{\mathrm{lo}(h)}, \dots, a_{\mathrm{hi}(h)}, where aia_i is the value of leaf ii. For p≤qp \le q we write a[p..q]=ap⊕ap+1⊕⋯⊕aqa[p..q] = a_p \oplus a_{p+1} \oplus \cdots \oplus a_q; by associativity the bracketing does not matter, but the order does.

Invariant (I). For every internal node hh, T[h]=a[lo(h)..hi(h)]T[h] = a[\mathrm{lo}(h)..\mathrm{hi}(h)].

Lemma 1 (new). After lines L1 to L3, (I) holds, and the build makes exactly n−1n - 1 calls of ⊕\oplus.

Proof. Line L2 visits the internal nodes in the order n−1,n−2,…,1n - 1, n - 2, \dots, 1. The children 2h2h and 2h+12h + 1 of hh are larger than hh, so they are leaves or nodes that were already set. By induction on this order, T[2h]=a[lo(h)..m]T[2h] = a[\mathrm{lo}(h)..m] and T[2h+1]=a[m+1..hi(h)]T[2h+1] = a[m+1..\mathrm{hi}(h)] with m=hi(2h)m = \mathrm{hi}(2h), because the left block ends just before the right block starts. Line L3 sets T[h]T[h] to their combination, which is a[lo(h)..hi(h)]a[\mathrm{lo}(h)..\mathrm{hi}(h)] by associativity. There are n−1n - 1 internal nodes and one call each. □\square

Lemma 2 (update). Suppose (I) holds and an update writes m≥1m \ge 1 distinct leaves (lines L4 to L7). Then (I) holds after it, and the number of calls of ⊕\oplus is at most mr+m−1≤m(1+r)m r + m - 1 \le m(1 + r), where r=⌈log⁡2(n/m)⌉r = \lceil \log_2(n / m) \rceil.

Proof. Let AA be the set of the changed leaves. A node needs repair exactly when it is an ancestor of a leaf in AA; every other node has the same leaves below it as before, so (I) still holds for it. We show by induction on the iterations of line L5 that the kk-th iteration handles the set DkD_k of all ancestors of AA at depth L−kL - k, and that when it handles a node, both children are already correct. Line L4 puts into D1D_1 the parents of the changed leaves, which are all at depth L−1L - 1, because all leaves are at depth LL. The children of a node in D1D_1 are leaves, which hold their new values. Line L7 maps DkD_k to the set of the parents of its nodes, which is Dk+1D_{k+1}. A child of a node in Dk+1D_{k+1} is either in DkD_k, and so was repaired in iteration kk, or not an ancestor of AA, and so was already correct. Line L6 then sets each node of Dk+1D_{k+1} from its two correct children, as in Lemma 1. The loop stops after DL={1}D_L = \{1\}, so every ancestor is repaired once.

For the cost, iteration kk makes ∣Dk∣≤min⁡(m,2L−k)|D_k| \le \min(m, 2^{L-k}) calls, because each changed leaf has one ancestor at each depth and depth L−kL - k has 2L−k2^{L-k} nodes. Let c=⌈log⁡2m⌉c = \lceil \log_2 m \rceil. The depths with 2L−k≥m2^{L-k} \ge m are those with L−k≥cL - k \ge c; there are L−cL - c of them, and they give at most m(L−c)m(L - c) calls. The other depths give at most 2c−1+⋯+2+1=2c−12^{c-1} + \cdots + 2 + 1 = 2^c - 1 calls. If mm is a power of two, then 2c=m2^c = m and L−c=rL - c = r, so the total is at most mr+m−1m r + m - 1. Otherwise L−c=r−1L - c = r - 1 and 2c<2m2^c < 2m, so the total is less than m(r−1)+2m−1=mr+m−1m(r - 1) + 2m - 1 = m r + m - 1. □\square

For m=1m = 1 the bound is L=log⁡2nL = \log_2 n calls. The bound is exact when mm is a power of two and the changed leaves are 0,n/m,2n/m,…0, n/m, 2n/m, \dots, because then each depth below cc has mm distinct ancestors and the depths above it are full.

Lemma 3 (prefix and suffix). If (I) holds, PREFIX(ii) returns a[0..i]a[0..i] and SUFFIX(jj) returns a[j..n−1]a[j..n-1], each with at most LL calls of ⊕\oplus.

Proof. For PREFIX, we claim that at the test of line L10, aa holds a[lo(h)..i]a[\mathrm{lo}(h)..i]. At line L9, hh is the leaf ii and a=aia = a_i. If hh is odd, it is a right child, its sibling h−1h - 1 covers the block that ends just before lo(h)\mathrm{lo}(h), and lo(⌊h/2⌋)=lo(h−1)\mathrm{lo}(\lfloor h/2 \rfloor) = \mathrm{lo}(h - 1); line L11 puts T[h−1]T[h-1] on the left of aa, so the claim holds for the parent. If hh is even, it is a left child and lo(⌊h/2⌋)=lo(h)\mathrm{lo}(\lfloor h/2 \rfloor) = \mathrm{lo}(h), so the claim holds without a call. At the root, lo(1)=0\mathrm{lo}(1) = 0. The loop climbs LL levels and makes at most one call per level. SUFFIX is the mirror image: a left child hh adds its right sibling h+1h + 1 on the right of aa (line L13), and hi(1)=n−1\mathrm{hi}(1) = n - 1. □\square

The FIFO window

The window keeps FF, the slot of the oldest value, BB, the slot for the next value, and the count cc. The window holds the values in the slots F,F+1,…,F+c−1F, F + 1, \dots, F + c - 1, taken modulo nn, oldest first.

Invariant (W). The window values are in these cc slots in this order, every other leaf holds ee, and (I) holds.

Lemma 4. INSERT and EVICT keep (W), and a resize keeps (W) with F=0F = 0.

Proof. A resize (lines L14 and L17) reads the cc values oldest first, builds a new tree with them in the leaves 0,…,c−10, \dots, c - 1 and ee elsewhere (Lemma 1), and sets F=0F = 0 and B=c mod nB = c \bmod n. INSERT first makes room if c=nc = n; then slot BB is free and holds ee. Line L15 writes the new value there with an update (Lemma 2) and advances BB, so the new value is the youngest. EVICT (line L16) writes ee into slot FF, which is the oldest value, and advances FF. □\square

Theorem 1 (query). Under (W), QUERY returns v1⊕v2⊕⋯⊕vcv_1 \oplus v_2 \oplus \cdots \oplus v_c, where v1,…,vcv_1, \dots, v_c are the window values oldest first.

Proof. If c=0c = 0 the result is ee. If c>0c > 0 and F<BF < B, the values fill the slots F,…,B−1F, \dots, B - 1; if B=0B = 0, they fill the slots F,…,n−1F, \dots, n - 1. In both cases they are in order from left to right, and every other leaf holds ee. By (I) the root is the combination of all leaves in order, and the identities drop out, so line L18 is correct. Otherwise c>0c > 0, B>0B > 0 and F≥BF \ge B (with F=BF = B only when c=nc = n). Then the window wraps: its values are the leaves F,…,n−1F, \dots, n - 1 followed by the leaves 0,…,B−10, \dots, B - 1, and the leaves between hold ee. By Lemma 3 and associativity, line L19 returns a[F..n−1]⊕a[0..B−1]a[F..n-1] \oplus a[0..B-1], which is the window in order. ■\blacksquare

Costs

Theorem 2 (worst case). Without a resize, INSERT and EVICT make at most L=log⁡2nL = \log_2 n calls of ⊕\oplus, and QUERY at most 2L+12L + 1. A resize to n′n' leaves makes n′−1n' - 1 calls.

Proof. INSERT and EVICT are updates with m=1m = 1 (Lemma 2). QUERY makes no call on line L18 and two climbs and one combine on line L19 (Lemma 3). A resize is one build (Lemma 1). □\square

Theorem 3 (amortized resizing). Start from an empty window with n=1n = 1. Over any sequence of NN inserts and evicts, the resizes make at most 4N4N calls of ⊕\oplus in total, so O(1)O(1) amortized calls per operation.

Proof. Right after each resize the tree is at most half full: a doubling from nn to 2n2n happens at c=nc = n, and a halving from nn to n/2n/2 happens at c<n/4c < n/4, so c<(n/2)/2c < (n/2)/2. Charge each resize to the operations since the previous one. A doubling from nn to 2n2n costs 2n−12n - 1 calls, and it needs cc to grow from at most n/2n/2 to nn, so at least n/2n/2 inserts paid for it; this is at most 4 calls per operation. For a halving from nn to n/2n/2, consider the state right after the previous resize to nn. It was a doubling from n/2n/2, which left c=n/2c = n/2, or a halving from 2n2n, which left c=n/2−1c = n/2 - 1 (that halving happened at the first evict that took cc below 2n/42n/4, so cc went from n/2n/2 to n/2−1n/2 - 1). Now c≤n/4−1c \le n/4 - 1, so at least n/4n/4 evicts happened, and the halving costs n/2−1n/2 - 1 calls, at most 2 per operation. The first doubling, from n=1n = 1, costs one call and follows one insert. □\square

Space. The array has 2n2n entries. A halving from nn happens as soon as c<n/4c < n/4, so after every operation c≥⌊n/4⌋c \ge \lfloor n/4 \rfloor. This gives n≤4c+3n \le 4c + 3, and the extra space is O(W+1)O(W + 1) for a window of WW values.

Complexity

All costs count calls of ⊕\oplus in the word RAM, so a call is one step when ⊕\oplus takes constant time.

  • Theorem (Tangwongsan et al., Theorem 4.2). NEW makes n−1n - 1 calls. An update that writes mm leaves makes at most m(1+⌈log⁡2(n/m)⌉)m(1 + \lceil \log_2(n/m) \rceil) calls. PREFIX and SUFFIX make at most log⁡2n\log_2 n calls each, and AGGREGATE makes none. The proof on this page gives the slightly sharper bound mr+m−1m r + m - 1 with r=⌈log⁡2(n/m)⌉r = \lceil \log_2(n/m) \rceil, which is exact for mm evenly spaced leaves when mm is a power of two.
  • Theorem (worst case per tuple). In the FIFO window, insert and evict each make at most log⁡2n\log_2 n calls when no resize happens, and query makes at most 2log⁡2n+12 \log_2 n + 1. One resize to n′n' leaves makes n′−1n' - 1 calls, so the worst case of a single insert is O(n)O(n).
  • Theorem (amortized resizing). From one leaf, the doubling and halving rule spends at most 4 calls per insert or evict on resizes, amortized. So insert and evict cost O(log⁡n)O(\log n) amortized calls, and the window keeps n≤4W+3n \le 4W + 3 leaves, which is O(W)O(W) space.

The queries do not change the tree, so a window that is queried after every tuple pays O(log⁡n)O(\log n) for the update and O(log⁡n)O(\log n) for the query. The two-stacks queue and DABA do better for this case: O(1)O(1) amortized and O(1)O(1) worst case calls per operation.

Variants

  • The paper's resize rule. When the buffer is full, the paper compacts it in place if at most 3/4 of the slots hold values, and doubles it otherwise. After an eviction, it halves the buffer if fewer than 1/4 of the slots hold values. Resizing then costs amortized O(1)O(1). Compaction matters only for windows that are not FIFO (Section 5.2), where evictions leave holes in the middle; in a FIFO window there are no holes, and the code on this page uses plain doubling.
  • Windows that are not FIFO and late data. Because UPDATE can write any leaf, a value that arrives late but still has a slot in the buffer is written into that slot in O(log⁡n)O(\log n) calls, and an eviction in the middle writes ee. A value older than the front has no slot in the circular buffer of this page, so it must be dropped or counted as late, or the window must use a structure for out-of-order data such as the FiBA tree of Tangwongsan, Hirzel and Schneider (2019).
  • Batches. With slicing or panes, the leaves are partial aggregates of slices instead of single tuples, as in stream slicing and pane-based aggregation, and when the buffer does not wrap, SUFFIX(jj) gives the window of the youngest values from slot jj on, so one tree can answer several window sizes that end at the same time.
  • Invertible operators. When ⊕\oplus has an inverse, as for a sum, a single running total with subtract-on-evict costs O(1)O(1) and the tree is not needed. A Fenwick tree also needs an inverse to answer a range from two prefixes.

When to use it

Use FlatFAT when the operator is associative but has no inverse, when the window changes in batches or out of FIFO order, or when one structure must answer many sub-ranges of the window through PREFIX and SUFFIX. For a strictly FIFO window with one change at a time, the two-stacks queue or DABA is cheaper. For an invertible operator, a running total is cheapest.

Pitfalls

  • Order in the inverted buffer. When the buffer wraps, the root holds the values in the wrong order. This is harmless for max or sum and wrong for concatenation, list collection or matrix products. Test with a non-commutative operator.
  • The identity. Empty slots must hold the identity of ⊕\oplus, not 0 or None, unless the operator treats that value as the identity.
  • Repairing an ancestor twice. A batch update that applies mm single updates one after another is correct but costs mlog⁡2nm \log_2 n calls; the bound O(m+mlog⁡(n/m))O(m + m \log(n/m)) needs the level-by-level repair.
  • Resizing in the worst case. A doubling copies the whole window and rebuilds the tree, so one insert can cost O(n)O(n). Systems with a latency limit per tuple need a structure with a worst-case bound, such as DABA.
  • A power of two. The layout assumes that nn is a power of two. Other sizes must be rounded up and padded with the identity.

Implementations

The paper's Reactive Aggregator, built on FlatFAT, was implemented in IBM InfoSphere Streams and measured against the method of Arasu and Widom on a two-core Xeon machine; these results are measurements, and this page does not repeat their numbers. The Python code on this page has the tree, the batch update, PREFIX, SUFFIX and the FIFO window with doubling and halving, and it counts calls of ⊕\oplus. Its tests check every query against recomputation of the window from scratch, with concatenation, max and sum, and they check the call counts against the bounds above.

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.

flatfat.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/flatfat/. The authors are listed in prov/6M9DHR.jsonl.

"""FlatFAT, the flat fixed-size aggregator of Tangwongsan, Hirzel, Schneider
and Wu (PVLDB 2015), and a FIFO sliding window on top of it.

The tree is a complete binary tree with n leaves (n a power of two) stored in
an array: the root is at index 1, the children of node h are 2h and 2h + 1,
and leaf i (0-based) is at index n + i. Every internal node holds the
combination of its two children with an associative operator op, which need
not be commutative or invertible. Empty leaves hold the identity of op.

Positions are 0-based here: prefix(i) = a[0] op ... op a[i] and
suffix(j) = a[j] op ... op a[n-1].
"""

from typing import Any, Callable


class FlatFAT:
    def __init__(self, n: int, op: Callable[[Any, Any], Any], identity: Any):
        if n < 1 or n & (n - 1):
            raise ValueError("n must be a power of two")
        self.n, self._op, self.identity = n, op, identity
        self.calls = 0  # calls of op, for the tests of the cost bounds
        self.tree = [identity] * (2 * n)

    def op(self, a, b):
        self.calls += 1
        return self._op(a, b)

    def new(self, values) -> None:
        """Set the leaves to values (padded with the identity) and build."""
        values = list(values)
        if len(values) > self.n:
            raise ValueError("too many values")
        n = self.n
        self.tree[n:] = values + [self.identity] * (n - len(values))  # @line L1
        for h in range(n - 1, 0, -1):  # @line L2
            self.tree[h] = self.op(self.tree[2 * h], self.tree[2 * h + 1])  # @line L3

    def update(self, changes) -> None:
        """Write several leaves, then repair each changed ancestor once."""
        n = self.n
        level = set()
        for i, v in changes:
            if not 0 <= i < n:
                raise IndexError(i)
            self.tree[n + i] = v  # @line L4
            level.add((n + i) // 2)
        while level:  # @line L5
            for h in sorted(level):
                self.tree[h] = self.op(self.tree[2 * h], self.tree[2 * h + 1])  # @line L6
            level = {h // 2 for h in level if h > 1}  # @line L7

    def aggregate(self):
        return self.tree[1]  # @line L8

    def prefix(self, i: int):
        """a[0] op ... op a[i], with at most log2(n) calls of op."""
        h = self.n + i  # @line L9
        acc = self.tree[h]
        while h > 1:  # @line L10
            if h & 1:  # h is a right child: its left sibling is all before i
                acc = self.op(self.tree[h - 1], acc)  # @line L11
            h //= 2
        return acc

    def suffix(self, j: int):
        """a[j] op ... op a[n-1], with at most log2(n) calls of op."""
        h = self.n + j  # @line L12
        acc = self.tree[h]
        while h > 1:
            if not h & 1:  # h is a left child: its right sibling is all after j
                acc = self.op(acc, self.tree[h + 1])  # @line L13
            h //= 2
        return acc

    def leaves(self) -> list:
        return self.tree[self.n:]


class FifoWindow:
    """A FIFO sliding window on a FlatFAT used as a circular buffer.

    front is the slot of the oldest value and back the slot of the next value.
    The buffer doubles when it is full and halves when it is less than a
    quarter full, so it is at most half full right after each resize."""

    def __init__(self, op: Callable[[Any, Any], Any], identity: Any, capacity: int = 1):
        self._op, self.identity = op, identity
        self.fat = FlatFAT(capacity, op, identity)
        self.front, self.back, self.count = 0, 0, 0
        self.resizes = 0
        self.resize_calls = 0  # op calls spent to build the resized trees
        self.calls_retired = 0  # op calls of trees that a resize replaced

    @property
    def calls(self) -> int:
        return self.calls_retired + self.fat.calls

    def capacity(self) -> int:
        return self.fat.n

    def _values(self) -> list:
        n = self.fat.n
        return [self.fat.tree[n + (self.front + k) % n] for k in range(self.count)]

    def _resize(self, n: int) -> None:
        vals = self._values()
        self.calls_retired += self.fat.calls
        self.fat = FlatFAT(n, self._op, self.identity)
        self.fat.new(vals)
        self.resize_calls += self.fat.calls
        self.front, self.back = 0, len(vals) % n
        self.resizes += 1

    def insert(self, v) -> None:
        if self.count == self.fat.n:  # @line L14
            self._resize(2 * self.fat.n)
        self.fat.update([(self.back, v)])  # @line L15
        self.back = (self.back + 1) % self.fat.n
        self.count += 1

    def evict(self):
        """Remove and return the oldest value."""
        if self.count == 0:
            raise IndexError("evict from an empty window")
        old = self.fat.tree[self.fat.n + self.front]
        self.fat.update([(self.front, self.identity)])  # @line L16
        self.front = (self.front + 1) % self.fat.n
        self.count -= 1
        if self.fat.n > 1 and self.count < self.fat.n // 4:  # @line L17
            self._resize(self.fat.n // 2)
        return old

    def query(self):
        """The op of all values in the window, oldest first."""
        if self.count == 0:
            return self.identity
        if self.front < self.back or self.back == 0:  # @line L18
            return self.fat.aggregate()  # the other leaves hold the identity
        # inverted: the oldest values are at the end of the array
        return self.fat.op(self.fat.suffix(self.front), self.fat.prefix(self.back - 1))  # @line L19
test_flatfat.py 146 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/flatfat/. The authors are listed in prov/6M9DHR.jsonl.

import random
from collections import deque
from functools import reduce

import pytest

from flatfat import FifoWindow, FlatFAT

CONCAT = (lambda a, b: a + b, "")  # associative, not commutative
MAX = (lambda a, b: a if b is None else b if a is None else max(a, b), None)
SUM = (lambda a, b: a + b, 0)


def scratch(op, identity, values):
    return reduce(op, values, identity)


def ceil_log2(x: float) -> int:
    k = 0
    while 2**k < x:
        k += 1
    return k


def test_page_example():
    fat = FlatFAT(8, *CONCAT)
    fat.new("abcdefgh")
    assert fat.calls == 7
    assert fat.aggregate() == "abcdefgh"
    assert fat.tree[2:4] == ["abcd", "efgh"]
    fat.calls = 0
    fat.update([(2, "C"), (5, "F")])
    assert fat.aggregate() == "abCdeFgh"
    assert fat.calls == 5  # 2 (level 1) + 2 (level 2) + 1 (root)
    fat.calls = 0
    assert fat.prefix(5) == "abCdeF" and fat.calls == 2
    fat.calls = 0
    assert fat.suffix(2) == "CdeFgh" and fat.calls == 2
    fat.calls = 0
    assert fat.prefix(4) == "abCde" and fat.calls == 1


@pytest.mark.parametrize("op", [CONCAT, MAX, SUM])
def test_prefix_suffix_and_bounds(op):
    rng = random.Random(11)
    for n in (1, 2, 4, 8, 16, 64):
        L = n.bit_length() - 1
        values = [rng.choice("xyz") if op is CONCAT else rng.randint(-9, 9) for _ in range(n)]
        fat = FlatFAT(n, *op)
        fat.new(values)
        assert fat.calls == n - 1
        for i in range(n):
            fat.calls = 0
            assert fat.prefix(i) == scratch(op[0], op[1], values[: i + 1])
            assert fat.calls <= L
            fat.calls = 0
            assert fat.suffix(i) == scratch(op[0], op[1], values[i:])
            assert fat.calls <= L
        assert fat.aggregate() == scratch(op[0], op[1], values)


def test_update_bound():
    """m distinct writes cost at most m*r + m - 1 <= m(1 + r) calls, r = ceil(log2(n/m))."""
    rng = random.Random(7)
    for n in (2, 8, 32, 128):
        fat = FlatFAT(n, *CONCAT)
        values = [rng.choice("pq") for _ in range(n)]
        fat.new(values)
        for _ in range(40):
            m = rng.randint(1, n)
            pos = rng.sample(range(n), m)
            changes = [(i, rng.choice("pqr")) for i in pos]
            for i, v in changes:
                values[i] = v
            fat.calls = 0
            fat.update(changes)
            r = ceil_log2(n / m)
            assert fat.calls <= m * r + m - 1 <= m * (1 + r)
            assert fat.aggregate() == "".join(values)
            assert fat.leaves() == values


def test_update_bound_is_tight():
    for n in (4, 16, 64):
        m = 1
        while m <= n:
            fat = FlatFAT(n, *SUM)
            fat.new([0] * n)
            fat.calls = 0
            fat.update([(k * (n // m), 1) for k in range(m)])
            assert fat.calls == m * ceil_log2(n / m) + m - 1
            m *= 2


@pytest.mark.parametrize("op", [CONCAT, MAX, SUM])
def test_fifo_window_matches_scratch(op):
    rng = random.Random(2015)
    for _ in range(15):
        w = FifoWindow(*op)
        window = deque()
        ops = 0
        top = 1
        for _ in range(300):
            if window and rng.random() < 0.48:
                assert w.evict() == window.popleft()
            else:
                v = rng.choice("abcde") if op is CONCAT else rng.randint(-20, 20)
                w.insert(v)
                window.append(v)
            ops += 1
            top = max(top, w.capacity())
            assert w.count == len(window)
            assert w.capacity() == 1 or len(window) >= w.capacity() // 4
            before = w.calls
            assert w.query() == scratch(op[0], op[1], window)
            assert w.calls - before <= 2 * (w.capacity().bit_length() - 1) + 1
        # every resize to capacity c costs c - 1 calls and is paid for by
        # at least c/4 operations since the previous resize
        assert w.resize_calls <= 4 * ops


def test_sliding_window_of_fixed_size():
    """The classic use: a count-based window of the last 5 values."""
    rng = random.Random(3)
    w = FifoWindow(*MAX)
    values = [rng.randint(0, 99) for _ in range(200)]
    for k, v in enumerate(values):
        w.insert(v)
        if w.count > 5:
            w.evict()
        assert w.query() == max(values[max(0, k - 4): k + 1])


def test_errors():
    with pytest.raises(ValueError):
        FlatFAT(6, *SUM)
    with pytest.raises(ValueError):
        FlatFAT(2, *SUM).new([1, 2, 3])
    with pytest.raises(IndexError):
        FlatFAT(2, *SUM).update([(2, 1)])
    with pytest.raises(IndexError):
        FifoWindow(*SUM).evict()
    assert FifoWindow(*SUM).query() == 0

History

Arasu and Widom (2004) kept precomputed partial aggregates over intervals of the window to share work between sliding-window aggregates with different ranges. Tangwongsan, Hirzel, Schneider and Wu (2015) gave FlatFAT as a general structure for any associative operator, stored it in a flat array, gave exact operator counts, and added the circular buffer with resizing for windows whose size changes over time. The same group later gave DABA (2017) for FIFO windows with worst-case O(1)O(1) calls, and FiBA (2019) for out-of-order windows.

References

  1. Kanat Tangwongsan, Martin Hirzel, Scott Schneider and Kun-Lung Wu, General incremental sliding-window aggregation, PVLDB 8(7), 2015, pages 702 to 713, Section 4 (the FlatFAT layout, Theorem 4.1 with O(m + m log(n/m)) time and O(n) space, and Theorem 4.2 with the exact operator counts of new, update, prefix, suffix and aggregate), Section 5.1 (the circular buffer, the query suffix(F) and prefix(B) of an inverted buffer, and the resizing rule), Section 5.2 (windows that are not FIFO), Section 6 (the experiments)
  2. Kanat Tangwongsan, Martin Hirzel and Scott Schneider, Optimal and general out-of-order sliding-window aggregation, PVLDB 12(10), 2019, pages 1167 to 1180, the FiBA tree for out-of-order insertions and evictions, which the same authors give as the successor for windows that are not in order (general locator)
  3. Resource sharing in continuous sliding-window aggregates, the earlier tree of partial aggregates that FlatFAT is compared with (general locator; the page numbers are not confirmed here)

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.query
  • a full proof of time.update
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)
WritingW4 complete
  • a review of the text: no review record reviews/6M9DHR/text.yaml