diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 831138e..14b7b61 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -34,7 +34,7 @@ cargo install mdbook && mdbook serve --open Live-reloads at `http://localhost:3000`. Chapters live in `src/`, diagrams in `src/images/`, and the sidebar is generated from `src/SUMMARY.md`, so a new chapter needs an entry there or it won't appear. -Diagrams are inline SVG using `currentColor` for strokes and text so they work in both light and dark themes. They're pulled in with `{{#include ../images/name.svg}}` inside a `
`. Two constraints: no blank lines inside an SVG file (a blank line ends the raw-HTML block in Markdown), and don't hard-code black or white. +Diagrams are inline SVG using `currentColor` for strokes and text so they work in both light and dark themes. They're pulled in with `{{#include ../images/name.svg}}` inside a `
`. Three constraints: no blank lines inside an SVG file (a blank line ends the raw-HTML block in Markdown); don't hard-code black or white; and prefix every CSS class and element id with the file's name (`.btree-split-node`, not `.node`), because inline `", content, re.S) + for cls in set(re.findall(r"\.([A-Za-z_][\w-]*)", style.group(1) if style else "")): + if cls in seen_cls and seen_cls[cls] != f: + fail("%s: figures %s and %s both define CSS class .%s (prefix classes with the file name)" % (page, seen_cls[cls], f, cls)) + seen_cls.setdefault(cls, f) + for i in set(re.findall(r'\bid="([^"]+)"', content)): + if i in seen_id and seen_id[i] != f: + fail("%s: figures %s and %s both use id=%s" % (page, seen_id[i], f, i)) + seen_id.setdefault(i, f) print(" svgs checked") diff --git a/src/appendices/appendix-a-complexity-cheat-sheet.md b/src/appendices/appendix-a-complexity-cheat-sheet.md index 40fe9a6..d0ea965 100644 --- a/src/appendices/appendix-a-complexity-cheat-sheet.md +++ b/src/appendices/appendix-a-complexity-cheat-sheet.md @@ -19,6 +19,8 @@ Two conventions for reading these tables: | Deque | O(1) | O(n) | O(1)★ at either end | O(1)★ at either end | O(n) | | Circular buffer (fixed capacity) | O(1) | O(n) | O(1) at the rear | O(1) at the front | O(capacity) | | Bit array | O(1) | O(n/w) | O(1) set a bit | O(1) clear a bit | n bits | +| Persistent vector (32-way trie) | O(log₃₂ n) | O(n) | O(log₃₂ n) append, path copied | O(log₃₂ n) update | O(n), shared between versions | +| Finger tree | O(log n) by index; O(1)★ at the ends | O(n) | O(1)★ at either end | O(1)★ at either end | O(n) | | Gap buffer (text) | O(1) | O(n) | O(1) at the cursor, O(distance) to move it | O(1) at the cursor | O(n) | | Rope (text) | O(log n) | O(n) | O(log n) anywhere | O(log n) anywhere | O(n) | | Piece table (text, list of k pieces) | O(k) | O(n) | O(k), text itself never moves | O(k) | O(n + k) | @@ -35,6 +37,7 @@ The linked-list rows come with the caveat that makes them much less useful than | AVL tree | O(log n) | O(log n) | O(log n) | O(log n) | O(n) | | Red-black tree | O(log n) | O(log n) | O(log n) | O(log n) | O(n) | | Splay tree | O(log n)★ | O(n) single op | O(log n)★ | O(log n)★ | O(n) | +| Left-leaning red-black tree | O(log n) | O(log n) | O(log n) | O(log n) | O(n) | | Treap | O(log n) expected | O(n) | O(log n) expected | O(log n) expected | O(n) | | Skip list | O(log n) expected | O(n) | O(log n) expected | O(log n) expected | **O(n) expected** | | B-tree / B+ tree | O(log_B n) I/Os | O(log_B n) I/Os | O(log_B n) | O(log_B n) | O(n) | @@ -48,6 +51,8 @@ Where **L** = key length, **N** = total characters stored across all keys, **A** On a BST of height h, successor, predecessor, floor and ceiling are O(h), and reporting every key in a range is O(h + k) for k results. A B-tree with minimum degree t has height at most log_t((n+1)/2); with t = 500, a billion keys fit in 4 levels. ([Chapter 7](../volume-1/ch07-binary-search-trees.md), [Chapter 10](../volume-1/ch10-multiway-search-trees-and-b-trees.md)) +AVL insertion needs at most one single or double rotation, but AVL deletion may rotate at every level on the way up, O(log n) rotations. Red-black trees need at most 2 rotations per insert and 3 per delete, plus O(log n) recolourings ([Chapter 8](../volume-1/ch08-self-balancing-trees.md)). + Two rows worth reading carefully. **Skip list space is O(n) expected**, not O(n log n): with promotion probability p = ½, the expected total number of nodes across all levels is 2n. The O(log n) is the expected *height*, which is a different quantity. And **splay trees** have no per-operation guarantee at all: a single access can cost O(n), and only a sequence of m operations is bounded, at O(m log n). That makes them unsuitable for latency-sensitive work regardless of their excellent amortized behavior. ## A.3 Hash-Based Structures @@ -209,7 +214,32 @@ Where **μ** = distance to the cycle and **λ** = cycle length. See [Chapter 29](../volume-5/ch29-system-design-as-data-structure-composition.md) for the simulations behind both tables. -## A.10 Complexity Growth Reference +## A.10 Allocators, Clocks and Routing + +| Memory allocator | malloc | free | Fragmentation | +|------------------|--------|------|---------------| +| Implicit free list, first fit | O(blocks) | O(1) with boundary tags | External; depends on placement policy | +| Segregated free lists (size classes) | O(1) typical | O(1) | Internal, bounded by class spacing (about 20% in jemalloc) | +| Buddy system | O(log M) splits | O(log M) merges | Internal, up to about 50% from rounding to a power of two | +| Slab (fixed-size objects) | O(1) | O(1) | Little, for objects of one size | +| Arena / bump | O(1) | Only all at once | None until reset | + +Where **M** = the size of the managed region in units of the smallest block ([Chapter 2](../volume-1/ch02-primitive-types-and-memory-organization.md)). + +| Logical clock | Timestamp size | Detects concurrency? | Close to wall-clock time? | +|---------------|----------------|----------------------|---------------------------| +| Lamport clock | O(1) | No | No | +| Vector clock | O(n) for n processes | Yes | No | +| Hybrid logical clock | O(1) | No | Yes, within the clock skew | + +| Routing lookup (W-bit addresses, N prefixes) | Memory reads per lookup | Memory | +|---------------------------------------------|------------------------|--------| +| Binary trie | Up to W | Up to 1 + N·W nodes | +| Multibit trie, stride k | ⌈W/k⌉ | Grows with 2^k per node (controlled prefix expansion) | +| DIR-24-8 (IPv4) | 1 for prefixes up to /24, else 2 | 32 MB first-level table plus second-level blocks | +| Maglev table (ECMP / load balancing) | 1 hash and 1 table read | O(M) for a prime table size M | + +## A.11 Complexity Growth Reference How the classes actually behave, for intuition about when each becomes infeasible: diff --git a/src/appendices/appendix-c-glossary.md b/src/appendices/appendix-c-glossary.md index 68ce10a..1994960 100644 --- a/src/appendices/appendix-c-glossary.md +++ b/src/appendices/appendix-c-glossary.md @@ -22,6 +22,8 @@ ## Structural Terms +**2-3-4 Tree**: A balanced search tree whose nodes hold one, two or three keys. A red-black tree is a binary encoding of one: each black node together with its red children is one 2-3-4 node. + **Augmented Tree**: A tree whose nodes store extra summary data about their subtrees (sizes, sums, maximums) that is kept correct through inserts, deletes and rotations. Order-statistic trees and interval trees are examples. **Balanced Tree**: A tree whose subtree heights differ by at most a constant factor, guaranteeing O(log n) height. @@ -34,6 +36,8 @@ **Degenerate Tree**: A tree that has degraded to essentially a linked list, the worst case for an unbalanced BST. +**Double Black**: The bookkeeping state in red-black tree deletion when removing a black node leaves one path short of a black node. The four repair cases correspond to borrowing from or merging with a sibling in the 2-3-4 view. + **Fan-out**: The number of children a node can have. High fan-out is what makes B-trees shallow. **Fill Factor**: How full a B-tree's nodes are allowed or chosen to be. Sorted inserts leave nodes about half full; bulk loading can pack them completely. @@ -44,6 +48,8 @@ **Leaf**: A node with no children. +**Left-Leaning Red-Black Tree**: A red-black variant (Sedgewick, 2008) in which red links may only lean left, corresponding to 2-3 trees and shortening insertion code considerably. + **Minimum Degree (t)**: The B-tree parameter that bounds node size: every node except the root holds between t − 1 and 2t − 1 keys. **Order Statistic**: The k-th smallest element of a set. A BST augmented with subtree sizes answers select (k-th smallest) and rank (position of a key) in O(height). @@ -86,14 +92,22 @@ ## Memory and Storage +**Arena (Bump Allocator)**: An allocator that hands out memory by advancing a pointer through a large block and frees everything at once. O(1) allocation, no per-object free; used by compilers and per-request memory pools. + **Bit-Packing**: Storing a block of small integers in exactly as many bits each as the largest needs. With delta encoding, the basis of posting-list compression in search engines. +**Boundary Tag**: A size-and-status field stored at both ends of a heap block, so the allocator can find and merge a free neighbour in O(1) when a block is freed. + +**Buddy Allocator**: An allocator that splits memory into power-of-two blocks and merges a freed block with its "buddy", found by flipping one address bit. The Linux page allocator uses it. + **Cache Line**: The unit of transfer between memory and cache, typically 64 bytes. Reading one byte costs the same as reading its whole line. **Cache-Oblivious**: Achieving optimal I/O performance without knowing the block size. By being well-organized at every scale simultaneously. **External Memory Model**: A cost model counting block transfers rather than operations. Predicts real disk performance where the RAM model does not. +**Fragmentation**: Memory that is free but unusable. *Internal* fragmentation is wasted space inside allocated blocks (rounding up); *external* fragmentation is free space split into pieces too small to satisfy a request. + **Gap Buffer**: A text buffer that keeps one contiguous gap at the cursor, so typing is O(1) but moving the cursor far away costs a large copy. Used by Emacs. **Locality**: The tendency of an access pattern to touch nearby addresses. Sequential access has good locality; pointer chasing has none. @@ -106,6 +120,10 @@ **Segment (search index)**: An immutable chunk of an inverted index. New documents create new segments, deletions are marked in a bitset, and background merges combine segments, much like LSM-tree compaction. +**Size Class**: One of a fixed set of block sizes an allocator rounds requests up to, each with its own free list. The basis of jemalloc, tcmalloc and glibc's bins. + +**Slab Allocator**: An allocator that keeps caches of same-sized, pre-initialized objects carved from pages. Introduced by Bonwick in 1994; Linux's SLUB is a descendant. + **Varint (Variable-Byte Encoding)**: Encoding an integer in 7-bit groups, one per byte, with the high bit marking that more bytes follow. Small numbers take one byte. **Write Amplification**: The ratio of bytes actually written to storage versus bytes logically written by the application. @@ -114,10 +132,16 @@ **ABA Problem**: A compare-and-swap succeeds because a pointer's value is unchanged, even though the state it refers to has changed and changed back. Defended against with tagged pointers or hazard pointers. +**Banker's Queue**: Okasaki's persistent queue, which keeps amortized O(1) operations even when old versions are reused by scheduling the expensive list reversal lazily and memoizing it. + **CAS (Compare-and-Swap)**: An atomic hardware instruction that sets a memory location to a new value only if it currently holds an expected one. The universal primitive for lock-free programming. **Copy-on-Write**: Sharing data until a write occurs, at which point the written portion is duplicated. +**Fat Node**: A persistence technique that stores every historical value of a field, stamped with its version, inside the node itself. Updates cost O(1) space; reads pay a search over the stamps. + +**Finger Tree**: A persistent sequence with amortized O(1) access at both ends and O(log n) split and concatenation. Annotating it with a monoid yields indexed sequences, priority queues and interval trees from one structure. + **Linearizability**: Every operation appears to take effect instantaneously at some moment between its call and return, consistent with real time. The standard correctness condition for concurrent objects, and notable for composing. **Lock-Free**: Guaranteeing that *some* thread always makes progress. Weaker than **wait-free**, which guarantees *every* thread finishes in bounded steps. @@ -128,6 +152,8 @@ **Persistent**: Preserving previous versions after modification. *Partial* persistence allows querying old versions; *full* allows updating them; *confluent* allows merging them. Unrelated to durable storage. +**Persistent Vector**: A persistent array stored as a wide trie (typically 32-way) indexed by groups of bits of the position. Updates copy one root-to-leaf path, O(log₃₂ n). Used by Clojure and Scala. + **Structural Sharing**: Reusing unchanged subtrees between versions of an immutable structure. What makes persistence affordable. ## Distributed Systems @@ -142,8 +168,18 @@ **DHT (Distributed Hash Table)**: A hash table partitioned across many machines, with a routing protocol for locating the responsible node. +**ECMP (Equal-Cost Multipath)**: Spreading traffic across several equally good next hops by hashing each flow's header fields, so that packets of one flow stay on one path and are not reordered. + **Eventual Consistency**: A guarantee that replicas converge given no further updates, with no bound on when. +**Happens-Before**: The causal order of events in a distributed system: a precedes b if they are on the same process in that order, or a message chain connects them. Events not ordered either way are concurrent. + +**Hybrid Logical Clock (HLC)**: A timestamp that stays close to physical time but, like a Lamport clock, never violates causality. Used by CockroachDB. + +**Lamport Clock**: A per-process counter incremented on each event and advanced past any timestamp received in a message. If a happens before b then L(a) < L(b), but not conversely. + +**Maglev Hashing**: Google's consistent hashing scheme for load balancers: each backend fills a prime-sized lookup table in its own permutation order, giving near-perfect balance and little remapping when a backend changes. + **Merkle Tree**: A tree of hashes where each node hashes its children, allowing two large datasets to be compared (and their differences located) in logarithmic work. **Power of Two Choices**: Sending each request to the less loaded of two randomly chosen servers. Cuts the maximum load from Θ(log n / log log n) to Θ(log log n) and avoids the herding that "least loaded" suffers with stale data. @@ -152,6 +188,8 @@ **Scan Resistance**: A cache policy's ability to survive a one-off sequential scan without evicting its genuinely popular items. LRU has none; LFU, ARC and W-TinyLFU do. +**Sequence CRDT**: A replicated list or text that gives every element a unique, ordered identifier so concurrent inserts and deletes converge. RGA, used in Automerge, is one example. + **Vector Clock**: A per-replica counter vector that distinguishes causally-ordered updates from genuinely concurrent ones. ## Probabilistic and Compressed @@ -172,10 +210,14 @@ **Border**: A string that is both a proper prefix and a suffix of another. The prefix function (KMP's failure function) records the longest border of each prefix of a pattern. +**Controlled Prefix Expansion**: Rewriting routing prefixes whose length is not a multiple of a trie's stride into several longer prefixes that are, so a multibit trie can consume several address bits per memory access. + **Inverted Index**: A map from each term to its posting list, the sorted list of documents containing it. The core structure of full-text search. **LCP Array**: Longest Common Prefix between each pair of adjacent suffixes in a suffix array. Together they encode a suffix tree implicitly. +**Longest-Prefix Match**: The IP routing lookup: among all table prefixes matching an address, choose the longest, because it is the most specific route. + **MBR (Minimum Bounding Rectangle)**: The smallest axis-aligned rectangle enclosing a set of objects. The key type in an R-tree, and overlap between sibling MBRs is what degrades R-tree queries. **Posting List**: The sorted list of document IDs (plus frequencies or positions) for one term in an inverted index. Stored as compressed gaps between consecutive IDs. diff --git a/src/images/avl-rotation.svg b/src/images/avl-rotation.svg index 6971c2e..8e82199 100644 --- a/src/images/avl-rotation.svg +++ b/src/images/avl-rotation.svg @@ -1,46 +1,46 @@ - Before: left-heavy at z - balance(z) = +2 - - - - - z - y - x - - T3 - - T4 + Before: left-heavy at z + balance(z) = +2 + + + + + z + y + x + + T3 + + T4 - - - rotate right + + + rotate right - After: balanced - balance(y) = 0 - - - - y - x - z - - T3 - - T4 - T3 changes parent from y to z, the only pointer rewrite besides the two rotated nodes. - In-order sequence is identical before and after: x, T3, y, T4, z → the BST property is preserved. + After: balanced + balance(y) = 0 + + + + y + x + z + + T3 + + T4 + T3 changes parent from y to z, the only pointer rewrite besides the two rotated nodes. + In-order sequence is identical before and after: x, T3, y, T4, z → the BST property is preserved. diff --git a/src/images/big-o-growth.svg b/src/images/big-o-growth.svg index 6649095..cfdaad6 100644 --- a/src/images/big-o-growth.svg +++ b/src/images/big-o-growth.svg @@ -1,35 +1,35 @@ - + - - - input size n → - operations → + + + input size n → + operations → - - - - - + + + + + - O(1) - O(log n) - O(n) - O(n log n) - O(n²) - Feasible at n = 10⁶: O(1), O(log n), O(n), O(n log n). Not feasible: O(n²) and worse. + O(1) + O(log n) + O(n) + O(n log n) + O(n²) + Feasible at n = 10⁶: O(1), O(log n), O(n), O(n log n). Not feasible: O(n²) and worse. diff --git a/src/images/bloom-filter.svg b/src/images/bloom-filter.svg index 13b3b73..097679f 100644 --- a/src/images/bloom-filter.svg +++ b/src/images/bloom-filter.svg @@ -1,53 +1,53 @@ - Inserting two elements with k = 3 hash functions + Inserting two elements with k = 3 hash functions - "cat" - "dog" + "cat" + "dog" - - - + + + - - - + + + - 0 - 1 - 0 - 1 - 0 - 1 - 0 - 1 - 0 - 0 - 1 - 0 - 1 - 0 + 0 + 1 + 0 + 1 + 0 + 1 + 0 + 1 + 0 + 0 + 1 + 0 + 1 + 0 - "emu" - (never inserted) - - - - All three bits are already 1, set by "cat" and "dog". - The filter reports "possibly present". This is a false positive. - No false negatives are possible: an inserted element's bits are never unset, so "definitely not present" is always trustworthy. - Deletion is impossible for the same reason: clearing a bit could erase another element's evidence. That is what counting Bloom filters fix. + "emu" + (never inserted) + + + + All three bits are already 1, set by "cat" and "dog". + The filter reports "possibly present". This is a false positive. + No false negatives are possible: an inserted element's bits are never unset, so "definitely not present" is always trustworthy. + Deletion is impossible for the same reason: clearing a bit could erase another element's evidence. That is what counting Bloom filters fix. diff --git a/src/images/bst-successor.svg b/src/images/bst-successor.svg index 60590ec..03fd910 100644 --- a/src/images/bst-successor.svg +++ b/src/images/bst-successor.svg @@ -1,59 +1,59 @@ - Case 1: right subtree exists - - - - - - - - - 8 - 3 - 10 - 1 - 6 - 14 - 4 - 7 - 13 - succ(3): step right to 6, then left - as far as possible. Answer: 4. - Case 2: no right subtree, walk up - - - - - - - - - 8 - 3 - 10 - 1 - 6 - 14 - 4 - 7 - 13 - succ(7): climb while arriving from a right - child (7→6→3); 3 is a left child, so stop at 8. - Dashed: the node whose successor we want. Filled: the successor. Predecessor is the mirror image. + Case 1: right subtree exists + + + + + + + + + 8 + 3 + 10 + 1 + 6 + 14 + 4 + 7 + 13 + succ(3): step right to 6, then left + as far as possible. Answer: 4. + Case 2: no right subtree, walk up + + + + + + + + + 8 + 3 + 10 + 1 + 6 + 14 + 4 + 7 + 13 + succ(7): climb while arriving from a right + child (7→6→3); 3 is a left child, so stop at 8. + Dashed: the node whose successor we want. Filled: the successor. Predecessor is the mirror image. diff --git a/src/images/btree-borrow-merge.svg b/src/images/btree-borrow-merge.svg index 1d25225..7570739 100644 --- a/src/images/btree-borrow-merge.svg +++ b/src/images/btree-borrow-merge.svg @@ -1,72 +1,72 @@ - Borrow (rotation): delete 30. The child [30] has only t − 1 = 1 key. + Borrow (rotation): delete 30. The child [30] has only t − 1 = 1 key. - 20 - 40 + 20 + 40 - - - - 10 - 30 + + + + 10 + 30 - 50 - 60 + 50 + 60 - Right sibling [50 60] can spare a key. - - + Right sibling [50 60] can spare a key. + + - 20 - 50 + 20 + 50 - - - - 10 + + + + 10 - 30 - 40 + 30 + 40 - 60 - 40 rotates down, 50 rotates up. Then delete 30 - from the leaf, which now has a key to spare. + 60 + 40 rotates down, 50 rotates up. Then delete 30 + from the leaf, which now has a key to spare. - Merge: then delete 10. The child [10] and its only sibling [40] are minimal. + Merge: then delete 10. The child [10] and its only sibling [40] are minimal. - 20 - 50 + 20 + 50 - - - - 10 - 40 - 60 - No sibling can spare a key. - - - 50 - - + + + + 10 + 40 + 60 + No sibling can spare a key. + + + 50 + + - 10 - 20 - 40 + 10 + 20 + 40 - 60 - The separator 20 comes down between them: - (t − 1) + 1 + (t − 1) = 2t − 1 keys, a full node. + 60 + The separator 20 comes down between them: + (t − 1) + 1 + (t − 1) = 2t − 1 keys, a full node. diff --git a/src/images/btree-split.svg b/src/images/btree-split.svg index 3630dd9..1996492 100644 --- a/src/images/btree-split.svg +++ b/src/images/btree-split.svg @@ -1,62 +1,62 @@ - Before: inserting 26 overflows a node of order 5 (max 4 keys) + Before: inserting 26 overflows a node of order 5 (max 4 keys) - 40 + 40 - - + + - 10 - 18 - 26 - 31 - 35 + 10 + 18 + 26 + 31 + 35 - 5 keys, one too many. The median (26) is promoted. + 5 keys, one too many. The median (26) is promoted. - 55 - 70 + 55 + 70 - - - split + + + split - After: median rises, node becomes two half-full nodes + After: median rises, node becomes two half-full nodes - 26 - 40 + 26 + 40 - - - + + + - 10 - 18 + 10 + 18 - 31 - 35 + 31 + 35 - 55 - 70 + 55 + 70 - Splits propagate upward. The - tree grows in height only when - the root itself splits, which is - why every leaf stays at the - same depth. + Splits propagate upward. The + tree grows in height only when + the root itself splits, which is + why every leaf stays at the + same depth. diff --git a/src/images/buddy-allocator.svg b/src/images/buddy-allocator.svg new file mode 100644 index 0000000..68bac14 --- /dev/null +++ b/src/images/buddy-allocator.svg @@ -0,0 +1,59 @@ + + + order 6 + order 5 + order 4 + order 3 + order 2 + + [0, 64) split + + [0, 32) split + + free [32, 64) + + [0, 16) split + + + B 12/16 + + + A 5/8 + + [8, 16) + + + C 3/4 + + free + + + 0 + + 8 + + 12 + + 16 + + 32 + + 64 + Buddy of a block = its address XOR its size. C: 8 XOR 4 = 12. [8, 16): 8 XOR 8 = 0. [0, 16): 0 XOR 16 = 16. + Free A, then C: C merges with 12 into [8, 16), that merges with A into [0, 16), and B at 16 stops it. + requested + rounding waste (internal fragmentation) + free + split + diff --git a/src/images/consistent-hashing.svg b/src/images/consistent-hashing.svg index 48dbfc9..ad85da7 100644 --- a/src/images/consistent-hashing.svg +++ b/src/images/consistent-hashing.svg @@ -1,54 +1,54 @@ - Three nodes on the ring - + Three nodes on the ring + - - - - A - B - C - - - - - - - A key is owned by the first node - clockwise from its hash. + + + + A + B + C + + + + + + + A key is owned by the first node + clockwise from its hash. - Node B fails - - - - + Node B fails + + + + - - A - B - C - - - - - - - Only B's keys move, to C. - A and C keep everything else. - With ordinary modulo hashing, removing one of n servers remaps roughly (n−1)/n of all keys, a cache stampede. Consistent - hashing remaps only the departing node's share, about 1/n. - In production each node is placed at 100–200 points on the ring (virtual nodes), so load stays even and a departing node's keys spread across all survivors rather than one. + + A + B + C + + + + + + + Only B's keys move, to C. + A and C keep everything else. + With ordinary modulo hashing, removing one of n servers remaps roughly (n−1)/n of all keys, a cache stampede. Consistent + hashing remaps only the departing node's share, about 1/n. + In production each node is placed at 100–200 points on the ring (virtual nodes), so load stays even and a departing node's keys spread across all survivors rather than one. diff --git a/src/images/dijkstra-trace.svg b/src/images/dijkstra-trace.svg index 20474cb..bcd0281 100644 --- a/src/images/dijkstra-trace.svg +++ b/src/images/dijkstra-trace.svg @@ -1,40 +1,40 @@ - - 4 - - 1 - - 2 - - 1 - - 5 - - 3 - S - dist 0 - A - dist 3 - B - dist 1 - C - dist 4 - D - dist 7 - shortest-path tree (parent pointers) - relaxed, but not on a shortest path + + 4 + + 1 + + 2 + + 1 + + 5 + + 3 + S + dist 0 + A + dist 3 + B + dist 1 + C + dist 4 + D + dist 7 + shortest-path tree (parent pointers) + relaxed, but not on a shortest path diff --git a/src/images/floyd-cycle.svg b/src/images/floyd-cycle.svg index b1f59e2..95900eb 100644 --- a/src/images/floyd-cycle.svg +++ b/src/images/floyd-cycle.svg @@ -1,52 +1,52 @@ - Floyd cycle detection: tail μ = 3, cycle λ = 5 - head - - - - - - - - - 1 - 2 - 3 - 4 - 5 - 6 - 7 - 8 - - tail: μ = 3 steps from head to the cycle - cycle start - meeting point - cycle - λ = 5 - - k − μ = 2 steps into the cycle - - μ = 3 more steps reach the start - Phase 1: slow moves 1, fast moves 2. They meet at node 6 after k = 5 steps; k is a multiple of λ. - Phase 2: restart one pointer at the head. Both move 1 step; after μ = 3 steps both are at node 4. + Floyd cycle detection: tail μ = 3, cycle λ = 5 + head + + + + + + + + + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + + tail: μ = 3 steps from head to the cycle + cycle start + meeting point + cycle + λ = 5 + + k − μ = 2 steps into the cycle + + μ = 3 more steps reach the start + Phase 1: slow moves 1, fast moves 2. They meet at node 6 after k = 5 steps; k is a multiple of λ. + Phase 2: restart one pointer at the head. Both move 1 step; after μ = 3 steps both are at node 4. diff --git a/src/images/hash-collision.svg b/src/images/hash-collision.svg index 7340548..60cbbeb 100644 --- a/src/images/hash-collision.svg +++ b/src/images/hash-collision.svg @@ -1,68 +1,68 @@ - Separate chaining - Collisions extend a list. Load factor may exceed 1. + Separate chaining + Collisions extend a list. Load factor may exceed 1. - 0 - - - - + 0 + + + + - 0 - 1 - 2 - 3 - 4 + 0 + 1 + 2 + 3 + 4 - - cat - - dog - - emu + + cat + + dog + + emu - - ant - Lookup cost = 1 + chain length. - Extra pointer per entry; poor cache locality. - Java HashMap converts a chain to a red-black - tree past 8 entries, capping the worst case at O(log n). + + ant + Lookup cost = 1 + chain length. + Extra pointer per entry; poor cache locality. + Java HashMap converts a chain to a red-black + tree past 8 entries, capping the worst case at O(log n). - Open addressing (linear probing) - Collisions probe forward. Load factor must stay below 1. + Open addressing (linear probing) + Collisions probe forward. Load factor must stay below 1. - - cat - dog - emu - + + cat + dog + emu + - 0 - 1 - 2 - 3 - 4 + 0 + 1 + 2 + 3 + 4 - - - h+1 - h+2 - All entries live in the table: one cache line per probe. - No pointers, better locality, less memory. - Deletion needs tombstones. Performance collapses - as load factor approaches 1. Resize by ~0.75. + + + h+1 + h+2 + All entries live in the table: one cache line per probe. + No pointers, better locality, less memory. + Deletion needs tombstones. Performance collapses + as load factor approaches 1. Resize by ~0.75. diff --git a/src/images/heap-array-mapping.svg b/src/images/heap-array-mapping.svg index 34586f0..540a839 100644 --- a/src/images/heap-array-mapping.svg +++ b/src/images/heap-array-mapping.svg @@ -1,59 +1,59 @@ - The array is the tree read level by level, left to right + The array is the tree read level by level, left to right - - - - - - - - + + + + + + + + - 90i=0 - 80i=1 - 70i=2 - 50i=3 - 40i=4 - 60i=5 - 30i=6 - 10i=7 - 20i=8 + 90i=0 + 80i=1 + 70i=2 + 50i=3 + 40i=4 + 60i=5 + 30i=6 + 10i=7 + 20i=8 - For i = 1 (value 80): - parent (1 − 1) / 2 = 0 - children 2·1 + 1 = 3 and 2·1 + 2 = 4 + For i = 1 (value 80): + parent (1 − 1) / 2 = 0 + children 2·1 + 1 = 3 and 2·1 + 2 = 4 - 90 - 80 - 70 - 50 - 40 - 60 - 30 - 10 - 20 - 012 - 345 - 678 - array + 90 + 80 + 70 + 50 + 40 + 60 + 30 + 10 + 20 + 012 + 345 + 678 + array - level 0 - level 1 - level 2 - level 3 + level 0 + level 1 + level 2 + level 3 diff --git a/src/images/lsm-vs-btree.svg b/src/images/lsm-vs-btree.svg index 13e4c06..91f3f49 100644 --- a/src/images/lsm-vs-btree.svg +++ b/src/images/lsm-vs-btree.svg @@ -1,54 +1,54 @@ - B-tree: update in place - write - - find the right page - + B-tree: update in place + write + + find the right page + - page - - page - - page - + page + + page + + page + - Each write seeks to a different page. Random I/O. - Reads are fast: one path, O(log_B n) transfers. + Each write seeks to a different page. Random I/O. + Reads are fast: one path, O(log_B n) transfers. - LSM tree: buffer, then flush sequentially - write - - - memtable(sorted, in RAM) - - flush when full + LSM tree: buffer, then flush sequentially + write + + + memtable(sorted, in RAM) + + flush when full - SST L0 - SST L0 + SST L0 + SST L0 - - background compaction - SST L1 (merged, larger) - Every disk write is sequential. - Write throughput ~10× a B-tree. - Reads may check several SSTs, - a Bloom filter per SST skips most. - B-tree: fast reads, random writes. - LSM: fast writes, more read work - and space amplification. + + background compaction + SST L1 (merged, larger) + Every disk write is sequential. + Write throughput ~10× a B-tree. + Reads may check several SSTs, + a Bloom filter per SST skips most. + B-tree: fast reads, random writes. + LSM: fast writes, more read work + and space amplification. diff --git a/src/images/memory-hierarchy.svg b/src/images/memory-hierarchy.svg index b4cea55..2c3d70d 100644 --- a/src/images/memory-hierarchy.svg +++ b/src/images/memory-hierarchy.svg @@ -1,56 +1,56 @@ - capacity - latency - ≈ human scale + capacity + latency + ≈ human scale - - L1 cache - ~1 ns - 1 second - 32 KB - - L2 cache - ~4 ns - 4 seconds - 256 KB - - L3 cache - ~15 ns - 15 seconds - 8 MB - - Main memory (DRAM) - ~100 ns - 1.5 minutes - 64 GB - - NVMe SSD - ~10 μs - 3 hours - 1 TB - - Hard disk (seek) - ~10 ms - 4 months - 10 TB + + L1 cache + ~1 ns + 1 second + 32 KB + + L2 cache + ~4 ns + 4 seconds + 256 KB + + L3 cache + ~15 ns + 15 seconds + 8 MB + + Main memory (DRAM) + ~100 ns + 1.5 minutes + 64 GB + + NVMe SSD + ~10 μs + 3 hours + 1 TB + + Hard disk (seek) + ~10 ms + 4 months + 10 TB - - - slower, larger, cheaper → - The right-hand column is the point. - If an L1 hit took one second, a disk seek would take four months. The RAM model of Chapter 1 treats those - two accesses as identical, which is why it mispredicts real performance by orders of magnitude. - Memory moves in blocks: 64-byte cache lines, 4 KB pages. Reading one byte costs the same as reading its - whole block, so a structure whose data sits together gets the rest of the block for free. + + + slower, larger, cheaper → + The right-hand column is the point. + If an L1 hit took one second, a disk seek would take four months. The RAM model of Chapter 1 treats those + two accesses as identical, which is why it mispredicts real performance by orders of magnitude. + Memory moves in blocks: 64-byte cache lines, 4 KB pages. Reading one byte costs the same as reading its + whole block, so a structure whose data sits together gets the rest of the block for free. diff --git a/src/images/multibit-trie.svg b/src/images/multibit-trie.svg new file mode 100644 index 0000000..c51f1ec --- /dev/null +++ b/src/images/multibit-trie.svg @@ -0,0 +1,93 @@ + + + Binary trie: 1 bit per level + Stride-2 trie: 2 bits per level + Routes: P1 = 0*, P2 = 1*, P3 = 00*, P4 = 101*, P5 = 111*, P6 = 1000* + + + + + + + + + + + 0 + 1 + 0 + 0 + 1 + 0 + 1 + 1 + 0 + + + + P1 + P2 + + P3 + + + + + P4 + + P5 + P6 + 10 nodes, 4 levels. Lookup 1011 (blue) reads + a node per bit and stops at 101 with P4. + + 00 + 01 + 10 + 11 + P3 + P1 + P2 + P2 + + + + + + + 00 + 01 + 10 + 11 + P6 + · + P4 + P4 + + + 00 + 01 + 10 + 11 + · + · + P5 + P5 + P2 = 1* is expanded into slots 10 and 11. + P3 = 00* overrides P1 = 0* in slot 00: longer wins. + P4 = 101* fills two slots, 1010 and 1011. + An empty slot (·) falls back to the best match + remembered from the level above. + 3 nodes, 2 levels. Lookup 1011 reads + 2 slots: P2, then P4. + diff --git a/src/images/path-copying.svg b/src/images/path-copying.svg index a8ce402..251da00 100644 --- a/src/images/path-copying.svg +++ b/src/images/path-copying.svg @@ -1,53 +1,53 @@ - Inserting 35 into a persistent BST. Version 1 stays valid + Inserting 35 into a persistent BST. Version 1 stays valid - v1 root - v2 root + v1 root + v2 root - - - + + + - - - - + + + + - + - 50 - 50′ - 30 - 30′ - 70 - 10 - 35 + 50 + 50′ + 30 + 30′ + 70 + 10 + 35 - + - - Copied: a child pointer changed (2 nodes) - - New node + + Copied: a child pointer changed (2 nodes) + + New node - - Shared with v1: nothing about it changed + + Shared with v1: nothing about it changed - Cost per update: O(log n) copied nodes, not O(n). - Node 30 must be copied. Its right pointer now points to 35. + Cost per update: O(log n) copied nodes, not O(n). + Node 30 must be copied. Its right pointer now points to 35. diff --git a/src/images/piece-table.svg b/src/images/piece-table.svg index adb363b..e11a4bd 100644 --- a/src/images/piece-table.svg +++ b/src/images/piece-table.svg @@ -1,95 +1,95 @@ - Original buffer (read-only: the file as loaded) - t0 - h1 - e2 - ␣3 - f4 - o5 - x6 - ␣7 - j8 - u9 - m10 - p11 - e12 - d13 - - - - "ed" was deleted, but the - bytes stay: no piece points here - Pieces, in text order: - (buffer, start, length) - (orig, 0, 4) - (add, 0, 12) - (orig, 4, 8) - (add, 12, 1) - Add buffer (append-only: everything ever typed) - q0 - u1 - i2 - c3 - k4 - ␣5 - b6 - r7 - o8 - w9 - n10 - ␣11 - s12 - - - - - - - - - - - Text: - - t - h - e - ␣ - - q - u - i - c - k - ␣ - b - r - o - w - n - ␣ - - f - o - x - ␣ - j - u - m - p - - s + Original buffer (read-only: the file as loaded) + t0 + h1 + e2 + ␣3 + f4 + o5 + x6 + ␣7 + j8 + u9 + m10 + p11 + e12 + d13 + + + + "ed" was deleted, but the + bytes stay: no piece points here + Pieces, in text order: + (buffer, start, length) + (orig, 0, 4) + (add, 0, 12) + (orig, 4, 8) + (add, 12, 1) + Add buffer (append-only: everything ever typed) + q0 + u1 + i2 + c3 + k4 + ␣5 + b6 + r7 + o8 + w9 + n10 + ␣11 + s12 + + + + + + + + + + + Text: + + t + h + e + ␣ + + q + u + i + c + k + ␣ + b + r + o + w + n + ␣ + + f + o + x + ␣ + j + u + m + p + + s diff --git a/src/images/posting-list-compression.svg b/src/images/posting-list-compression.svg index 808e13e..10fbc4a 100644 --- a/src/images/posting-list-compression.svg +++ b/src/images/posting-list-compression.svg @@ -1,74 +1,74 @@ - One posting list, from doc IDs to bytes + One posting list, from doc IDs to bytes - term - "data" - the term dictionary points to the term's posting list - + term + "data" + the term dictionary points to the term's posting list + - doc IDs - 70000 - 70003 - 70010 - 70130 - 90000 - as int32: - 20 bytes + doc IDs + 70000 + 70003 + 70010 + 70130 + 90000 + as int32: + 20 bytes - - subtract the previous ID + + subtract the previous ID - d-gaps - 70000 - 3 - 7 - 120 - 19870 - mostly - small + d-gaps + 70000 + 3 + 7 + 120 + 19870 + mostly + small - - 7 data bits per byte, low-order group first + + 7 data bits per byte, low-order group first - varint bytes - F0 - A2 - 04 - 03 - 07 - 78 - 9E - 9B - 01 - 9 bytes - high bit 1: more bytes follow - high bit 0: last byte of this number + varint bytes + F0 + A2 + 04 + 03 + 07 + 78 + 9E + 9B + 01 + 9 bytes + high bit 1: more bytes follow + high bit 0: last byte of this number - Zoom: the gap 70000 is 100 0100010 1110000 in binary - 7-bit groups - 0000100 - 0100010 - 1110000 - - - - bytes out - 11110000 F0 - 10100010 A2 - 00000100 04 - The lowest group - goes out first. - Each byte gets a - continuation flag. + Zoom: the gap 70000 is 100 0100010 1110000 in binary + 7-bit groups + 0000100 + 0100010 + 1110000 + + + + bytes out + 11110000 F0 + 10100010 A2 + 00000100 04 + The lowest group + goes out first. + Each byte gets a + continuation flag. diff --git a/src/images/rb-234.svg b/src/images/rb-234.svg new file mode 100644 index 0000000..d12185f --- /dev/null +++ b/src/images/rb-234.svg @@ -0,0 +1,87 @@ + + + Red-black tree + The 2-3-4 tree it encodes + + + + + + + + + + + + 40 + 20 + 60 + 10 + 30 + 50 + 70 + + 20 + 40 + 10 + 30 + 50 + 60 + 70 + + + + 2-node = black node alone · 3-node = black + one red child + 4-node = black + two red children + + + insert 80 below red 70: recolor 50, 60, 70 (no rotation) = split the 4-node, 60 moves up + + + + + + + + + + + + + 40 + 20 + 60 + 10 + 30 + 50 + 70 + 80 + 20 + 40 + 60 + 10 + 30 + 50 + 70 + 80 + + + + + Every root-to-NIL path crosses 2 black nodes, + so every 2-3-4 leaf is at depth 2. + diff --git a/src/images/selection-flowchart.svg b/src/images/selection-flowchart.svg new file mode 100644 index 0000000..d4bd3d1 --- /dev/null +++ b/src/images/selection-flowchart.svg @@ -0,0 +1,70 @@ + + + + + + Storing keys and looking them up + + no + + yes + + no + + yes + + yes + + no + + yes + + no + + yes + + no + + yes + + no + + Does any query need order? + range, next key, minimum, top k + + Must answers be exact? + + Is the data static? + + Bloom or cuckoo filter, + HyperLogLog, Count-Min + + Small, dense integer keys? + + Array or bitset + + Hash table + + Sorted array + + binary search + + Only the min or max? + + Binary heap + + Fits in memory? + + Balanced BST + or skip list + + B+ tree or LSM tree + diff --git a/src/images/skip-list.svg b/src/images/skip-list.svg index 8fccbb2..ed1d0c7 100644 --- a/src/images/skip-list.svg +++ b/src/images/skip-list.svg @@ -1,74 +1,74 @@ - Searching for 47 + Searching for 47 - L3 - L2 - L1 - L0 + L3 + L2 + L1 + L0 - - + + - - - - + + + + - - - - - + + + + + - - - - - - - + + + + + + + - - - - - head + + + + + head - 9 + 9 - 17 - 17 - 17 + 17 + 17 + 17 - 25 + 25 - 31 - 31 - 31 - 31 + 31 + 31 + 31 + 31 - 47 - 47 + 47 + 47 - 59 - 59 - 59 + 59 + 59 + 59 - - - - - - Each node's height comes from a coin flip: ~½ the nodes reach L1, ~¼ reach L2, ~⅛ reach L3. Expected height is O(log n) and - expected total space is O(n), about 2n nodes, not n log n. Search drops a level whenever the next key overshoots. + + + + + + Each node's height comes from a coin flip: ~½ the nodes reach L1, ~¼ reach L2, ~⅛ reach L3. Expected height is O(log n) and + expected total space is O(n), about 2n nodes, not n log n. Search drops a level whenever the next key overshoots. diff --git a/src/images/veb-tree.svg b/src/images/veb-tree.svg index d18055f..528f913 100644 --- a/src/images/veb-tree.svg +++ b/src/images/veb-tree.svg @@ -1,95 +1,95 @@ - - V (u = 16) - min = 2, max = 15 - 2 is stored only here, - not in cluster 0 - - - - - + + V (u = 16) + min = 2, max = 15 + 2 is stored only here, + not in cluster 0 + + + + + - - summary - - - - - 0123 - nonempty clusters + + summary + + + + + 0123 + nonempty clusters - - cluster 0 - min 3, max 3 - holds low 3 - - cluster 1 - empty: no entry - in the hash table - - cluster 2 - min 1, max 1 - holds low 1 - - cluster 3 - min 1, max 3 - holds lows 1, 2, 3 + + cluster 0 + min 3, max 3 + holds low 3 + + cluster 1 + empty: no entry + in the hash table + + cluster 2 + min 1, max 1 + holds low 1 + + cluster 3 + min 1, max 3 + holds lows 1, 2, 3 - 1 - 2 - 3 + 1 + 2 + 3 - - - - + + + + - keys 0 to 15, - grouped by high(x) - 0 - 1 - 2 - 3 - 4 - 5 - 6 - 7 - 8 - 9 - 10 - 11 - 12 - 13 - 14 - 15 - low 0123 - high 0high 1high 2high 3 + keys 0 to 15, + grouped by high(x) + 0 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 + 12 + 13 + 14 + 15 + low 0123 + high 0high 1high 2high 3 - x = 9 = 10 01 in binary: high(9) = 2 picks the cluster, low(9) = 1 is the position inside it. - successor(9): - 1 - cluster 2 has max 1 = low(9): nothing larger in this cluster. - 2 - summary.successor(2) = 3: the next nonempty cluster (one recursive call, on u = 4). - 3 - cluster 3's min is 1, read in O(1): the answer is 3 · 4 + 1 = 13. + x = 9 = 10 01 in binary: high(9) = 2 picks the cluster, low(9) = 1 is the position inside it. + successor(9): + 1 + cluster 2 has max 1 = low(9): nothing larger in this cluster. + 2 + summary.successor(2) = 3: the next nonempty cluster (one recursive call, on u = 4). + 3 + cluster 3's min is 1, read in O(1): the answer is 3 · 4 + 1 = 13. diff --git a/src/images/vector-clocks.svg b/src/images/vector-clocks.svg new file mode 100644 index 0000000..c97de33 --- /dev/null +++ b/src/images/vector-clocks.svg @@ -0,0 +1,62 @@ + + + Each event labelled name, Lamport time L, and vector clock [A,B,C] + + A + + B + + C + time → + + + m1 + + + m2 + + + m3 + + a1 · L=1 + [1,0,0] + + a2 · L=2 + [2,0,0] + + a3 · L=7 + [3,3,3] + + b1 · L=1 + [0,1,0] + + b2 · L=3 + [2,2,0] + + b3 · L=4 + [2,3,0] + + c1 · L=1 + [0,0,1] + + c2 · L=5 + [2,3,2] + + c3 · L=6 + [2,3,3] + c1 and b3 are concurrent although L(c1) = 1 < L(b3) = 4: their vectors [0,0,1] and [2,3,0] are incomparable. + a1 → c2 holds (a1 → a2 → b2 → b3 → c2), and [1,0,0] ≤ [2,3,2] entry by entry. + diff --git a/src/index.md b/src/index.md index b3c16e4..e652ece 100644 --- a/src/index.md +++ b/src/index.md @@ -2,7 +2,7 @@ **A complete course on data structures: from asymptotic analysis to the storage engines behind Spanner and Kafka.** -Five volumes · 31 chapters · 4 appendices · ~185,000 words · 241 exercises with worked solutions · Python, C, C++, Java, and Go +Five volumes · 31 chapters · 4 appendices · ~220,000 words · 258 exercises with worked solutions · Python, C, C++, Java, and Go By **Ngoc Anh Khoa Doan**, with the editorial help of Claude. diff --git a/src/volume-1/ch02-primitive-types-and-memory-organization.md b/src/volume-1/ch02-primitive-types-and-memory-organization.md index 6f0f168..09991c2 100644 --- a/src/volume-1/ch02-primitive-types-and-memory-organization.md +++ b/src/volume-1/ch02-primitive-types-and-memory-organization.md @@ -52,7 +52,7 @@ IEEE 754 standardizes floating-point representation: - 8 bits: exponent (biased) - 23 bits: mantissa (fraction) -This gives the familiar scientific notation: (-1)^sign × 1.mantissa × 2^exponent +This gives the familiar scientific notation: (-1)^sign × 1.mantissa × 2^(exponent − 127) for normal numbers. A 64-bit double has the same layout with an 11-bit exponent (bias 1023) and a 52-bit fraction. Key considerations for data structures: - Floating-point equality is problematic (0.1 + 0.2 ≠ 0.3) @@ -60,6 +60,24 @@ Key considerations for data structures: - Infinity arithmetic has special rules - Denormalized numbers provide gradual underflow +**Why 0.1 + 0.2 ≠ 0.3.** A double holds a 53-bit binary significand, and 1/10 has no finite binary expansion (0.0001100110011... in binary, repeating forever), so the literal `0.1` is rounded to the nearest double. `float.hex` and `decimal.Decimal` show exactly what is stored: + +```python +from decimal import Decimal + +for x in (0.1, 0.2, 0.3, 0.1 + 0.2): + print(x.hex(), Decimal(x)) +``` + +``` +0x1.999999999999ap-4 0.1000000000000000055511151231257827021181583404541015625 +0x1.999999999999ap-3 0.200000000000000011102230246251565404236316680908203125 +0x1.3333333333333p-2 0.299999999999999988897769753748434595763683319091796875 +0x1.3333333333334p-2 0.3000000000000000444089209850062616169452667236328125 +``` + +The repeating hex digit 9 ends in a rounded-up `a`, so `0.1` and `0.2` are both stored slightly too large, while `0.3` is stored slightly too small. The exact sum of the two stored values is 0.3000000000000000166533453693773481063544750213623046875. Doubles between 0.25 and 0.5 are 2^−54 ≈ 5.55 × 10^−17 apart, and this sum lies exactly halfway between the double for `0.3` (significand ending in hex 3) and the next one up (ending in hex 4). IEEE 754's default rounding breaks ties toward the even significand, the one ending in 4, so `0.1 + 0.2` is one unit in the last place above `0.3`. Every step was correctly rounded; the inputs were never the decimal numbers they were written as. Compare with a tolerance (`math.isclose`), or compute in integers (cents, not dollars) or `decimal` when exact decimal results matter. Exercise 2.5 shows what the difference does to a hash table. + ### Character Types Characters represent text elements: @@ -126,7 +144,7 @@ Two primary memory regions exist for dynamic data: **Heap:** - Manual management (malloc/free, new/delete) -- Slower allocation (search for free block) +- Slower allocation (search for a free block, Section 2.5) - Manual or garbage-collected deallocation - Large size (limited by physical + virtual memory) - Good for large or long-lived objects @@ -238,7 +256,313 @@ Bit fields pack multiple boolean or small-integer fields into single bytes. Howe - Layout is implementation-defined - May be slower to access than full bytes -## 2.5 Type Systems and Generic Programming +## 2.5 How malloc Works: Allocators as Data Structures + +Section 2.2 described heap allocation as "search for a free block". That search is a data-structure problem in its own right. The allocator keeps a set of free address ranges and must answer two operations quickly: `malloc(n)`, "give me a range of at least n bytes", and `free(p)`, "the range starting at p is free again". Every linked structure in this book calls `malloc` once per node, so the allocator's costs show up inside all of them. + +### The Problem + +Three facts make this harder than it looks. + +- **Sizes vary and frees arrive in any order.** A C or C++ allocator cannot move a live block, because the program holds raw pointers to it and the allocator cannot find them all to fix them up. (A compacting garbage collector can, which is why it doesn't have this problem.) So the free space breaks into holes between live blocks. +- **`free(p)` gets only a pointer.** The allocator must recover the block's size and find its neighbours from the address alone. Programs call `free` about as often as `malloc`, so this has to be O(1), not a search. +- **Memory is lost two ways.** *Internal fragmentation* is space inside an allocated block that the program didn't ask for: headers, alignment padding, rounding up to a size class. *External fragmentation* is free memory split into holes too small to use. Fill a 1 MiB heap with 1,024 blocks of 1 KiB and free every other one: 512 KiB is free, yet a 2 KiB request fails because no two free blocks are adjacent. + +No placement policy avoids external fragmentation on every input. J. M. Robson showed in 1971 that for any allocator that never moves blocks, some sequence of requests forces the heap to exceed the live data by a factor that grows with the logarithm of the ratio between the largest and smallest block sizes. Allocators are therefore judged on real programs, not worst cases. + +### Implicit Free Lists and Boundary Tags + +The simplest design puts the bookkeeping in the heap itself. Each block starts with a one-word *header* holding the block's size. Sizes are multiples of the alignment (8 or 16 bytes on real systems), so the low bits of the size are always zero, and one of them stores an "allocated" flag. Starting from the first block and adding sizes walks every block in address order: the list is *implicit*, because the links are the sizes. + +- `malloc(n)` walks the blocks until it finds a free one that is big enough. If the block is much bigger, it *splits* it: the front becomes the allocated block and the rest a new free block. It returns the address just past the header. +- `free(p)` reads the header one word before `p` to get the size. The next block's header is at the header plus the size, so checking whether the next block is free and merging with it (*coalescing*) is O(1). + +The previous block is the hard part. Nothing in our header says where the previous block starts. Knuth's *boundary tag* fixes this: copy the tag into a *footer*, the last word of every block. The word just before our header is then the previous block's footer, which gives its size and state in O(1). With immediate coalescing on every `free`, the heap keeps one invariant: **no two free blocks are adjacent**. + +The simulation below models the heap as a Python list of words. Sizes are in words and always even, so bit 0 of a tag is free to hold the allocated flag. + +```python +class FreeListHeap: + """Implicit free list with boundary tags, first fit and immediate coalescing. + + mem is the heap, one list entry per word. Every block is laid out as + [header, payload..., footer], and header and footer both hold the tag + size | used, where size counts the whole block in words and is always even. + """ + MIN_BLOCK = 4 # header + 2 payload words + footer + + def __init__(self, words): + assert words % 2 == 0 and words >= self.MIN_BLOCK + self.mem = [0] * words + self._tag(0, words, 0) # one free block covers the heap + + def _tag(self, addr, size, used): + self.mem[addr] = self.mem[addr + size - 1] = size | used + + def _size(self, i): # i is a header or footer word + return self.mem[i] & ~1 + + def _used(self, i): + return self.mem[i] & 1 + + def blocks(self): + addr = 0 + while addr < len(self.mem): + yield addr, self._size(addr), self._used(addr) + addr += self._size(addr) + + def malloc(self, n): + need = max(self.MIN_BLOCK, (n + 3) & ~1) # n + header + footer, rounded up to even + for addr, size, used in self.blocks(): # first fit: lowest address that fits + if not used and size >= need: + if size - need >= self.MIN_BLOCK: # split; the tail stays free + self._tag(addr + need, size - need, 0) + size = need + self._tag(addr, size, 1) + return addr + 1 # the pointer is the first payload word + return None # no free block is big enough + + def free(self, p): + addr = p - 1 + size = self._size(addr) + nxt = addr + size + if nxt < len(self.mem) and not self._used(nxt): # next block's header + size += self._size(nxt) + if addr > 0 and not self._used(addr - 1): # previous block's footer + addr -= self._size(addr - 1) + size += self._size(addr) + self._tag(addr, size, 0) +``` + +A trace on a 24-word heap, writing blocks as `start:size` with U for used and F for free: + +| Operation | Returns | Blocks afterwards | What happened | +|-----------|---------|-------------------|---------------| +| start | | 0:24 F | one free block | +| `p = malloc(3)` | 1 | 0:6 U, 6:18 F | 3 + 2 tags = 5, rounded up to 6; split | +| `q = malloc(5)` | 7 | 0:6 U, 6:8 U, 14:10 F | 5 + 2 = 7, rounded up to 8 | +| `r = malloc(2)` | 15 | 0:6 U, 6:8 U, 14:4 U, 18:6 F | exactly the minimum block | +| `free(p)` | | 0:6 F, 6:8 U, 14:4 U, 18:6 F | both neighbours used (there is no left one) | +| `free(r)` | | 0:6 F, 6:8 U, 14:10 F | header at 18 says free: merge right | +| `free(q)` | | 0:24 F | header at 14 and footer at 5 both say free: merge both ways | + +After the three `malloc` calls the list `mem` begins `[7, 0, 0, 0, 0, 7, 9, ...]`: tag 7 is size 6 with the used bit set, and the same tag sits in word 0 (header) and word 5 (footer). Each block carries one word of internal fragmentation from rounding plus two words of tags. + +**Cost.** `free` is O(1) worst case. `malloc` is O(B) worst case, where B is the number of blocks, allocated *and* free, because the walk steps over every allocated block too. The footer costs a word per block. Real allocators such as dlmalloc save it on allocated blocks: a free block keeps its footer, and each header carries a "previous block in use" bit, so the footer is only read when that bit says the previous block is free. + +### Explicit Free Lists and Placement Policies + +Walking allocated blocks is wasted work. An *explicit* free list threads a doubly linked list (Chapter 4) through the free blocks only, storing the `prev` and `next` pointers in the free block's payload, which nobody else is using. `malloc` now costs O(F) for F free blocks. `free` stays O(1): coalescing unlinks the free neighbours, which a doubly linked list does in O(1) given the node, and pushes the merged block. The price is a larger minimum block, header plus two pointers plus footer: 32 bytes on a 64-bit machine, so `malloc(1)` costs 32 bytes. Pushing freed blocks at the head (LIFO order) is O(1); keeping the list sorted by address costs O(F) per `free` but fragments less. + +Which free block to choose is the *placement policy*: + +- **First fit** takes the first block in the list that is big enough. With an address-ordered list, small leftover splinters collect at the low addresses and every search has to step over them. +- **Next fit** resumes the search where the previous one stopped. Searches are shorter, but allocations get scattered across the whole heap. +- **Best fit** takes the smallest block that is big enough, leaving the smallest leftover. On a plain list it scans all F blocks; with free blocks kept in a balanced tree or a trie keyed by size it costs O(log F). + +Intuition says best fit should create many useless tiny leftovers. Measurements say otherwise: Johnstone and Wilson ("The Memory Fragmentation Problem: Solved?", 1998) replayed the allocation traces of real programs and found that best fit and address-ordered first fit both waste very little memory, while next fit does noticeably worse. Neither policy dominates on every input (Exercise 2.8 builds a case for each), and Knuth's *fifty-percent rule* says the search cost doesn't go away: in steady state under first fit there are about half as many free blocks as allocated ones. + +### Segregated Free Lists and Size Classes + +Every production allocator replaces the single list with an array of lists, one per *size class*. `malloc(n)` rounds n up to its class and pops the head of that list in O(1), falling back to a larger class or fresh memory only when the list is empty. Most programs allocate a small number of distinct sizes over and over, so the fast path hits almost every time. + +The extreme form, *simple segregated storage*, gives each class its own pages carved into equal slots and never splits or coalesces. Objects then need no header at all: the allocator finds the size class from the page the address falls in. What it gives up is flexibility: memory parked in the free list of one class cannot serve a request for another. + +- **dlmalloc** (Doug Lea, first released in 1987) is "in most ways a best-fit allocator", in its own documentation's words. Chunks under 256 bytes live in *small bins*, exact-size doubly linked lists 8 bytes apart, and larger free chunks live in bins covering ranges of sizes, kept as bitwise tries so the best fit is found quickly. Chunks carry Knuth's boundary tags. glibc's `malloc` (ptmalloc) is derived from it and added a per-thread cache, *tcache*, in glibc 2.26 (2017). +- **jemalloc** (Jason Evans, written for FreeBSD's libc) spaces its small size classes at four per doubling of size after the smallest ones: 16, 32, 48, ..., 128, then 160, 192, 224, 256, then 320, 384, 448, 512, and so on. Its manual states that this limits internal fragmentation to about 20% for all but the smallest classes: a 129-byte request gets a 160-byte slot and wastes 31 bytes, 19%. It runs several independent *arenas* (by default four per CPU) to cut lock contention, and gives each thread a cache of free objects so most requests need no synchronization at all. +- **tcmalloc** (Google, "thread-caching malloc") maps small requests to one of 60 to 80 size classes. Its front end is a cache per thread (the original design) or, in newer versions, per CPU. Behind it, each size class has a *transfer cache* and a *central free list* that carves objects out of *spans* of pages; requests above the largest class go straight to the page heap. + +The thread or CPU cache matters as much as the size classes. A single free list behind one lock serializes every allocation in a multithreaded program. A thread-local list needs no lock and no atomic instruction; the cost is memory sitting idle in one thread's cache while another thread asks the operating system for more. + +### The Buddy System + +The buddy system trades internal fragmentation for very cheap coalescing. The managed space has 2^m units. Every block has a size 2^k (its *order* is k) and starts at a multiple of 2^k. There is one free list per order. + +- **Allocate n units:** round up to the smallest order k with 2^k ≥ n. Take a free block of the smallest order j ≥ k that has one. While j > k, split it into two halves of order j − 1, keep the low half and put the high half on the free list. The two halves of a split are each other's *buddies*. +- **Free a block of order k at address a:** its buddy is at **a XOR 2^k**. Because a is a multiple of 2^k, bit k is the only bit that differs between the low and high halves of their parent, so flipping it gives the other half. If the buddy is free and still of order k, merge the two into the parent (which starts at `a` with bit k cleared) and repeat one order up. + +No footers and no searching for neighbours: the address alone identifies the only block it can merge with. + +```python +class BuddyAllocator: + """Binary buddy system over addresses 0 .. 2**max_order - 1 (units, e.g. pages).""" + + def __init__(self, max_order): + self.max_order = max_order + self.free_lists = [set() for _ in range(max_order + 1)] # order k -> free addresses + self.free_lists[max_order].add(0) + self.order_of = {} # allocated address -> order + + def alloc(self, n): + k = max(0, (n - 1).bit_length()) # smallest k with 2**k >= n + j = k + while j <= self.max_order and not self.free_lists[j]: + j += 1 # smallest non-empty order that is big enough + if j > self.max_order: + return None + addr = self.free_lists[j].pop() + while j > k: # split, keep the low half, free the high half + j -= 1 + self.free_lists[j].add(addr + (1 << j)) + self.order_of[addr] = k + return addr + + def free(self, addr): + k = self.order_of.pop(addr) + while k < self.max_order: + buddy = addr ^ (1 << k) # flip bit k of the address + if buddy not in self.free_lists[k]: + break # buddy is allocated or split: stop merging + self.free_lists[k].remove(buddy) + addr &= ~(1 << k) # the merged block starts at the lower buddy + k += 1 + self.free_lists[k].add(addr) +``` + +The free lists are sets here so that "is my buddy free?" and "remove my buddy" are O(1). The Linux kernel gets the same effect with doubly linked lists plus a flag and the order stored in each page's descriptor. + +Trace on 64 units (`BuddyAllocator(6)`): + +1. `A = alloc(5)` needs order 3 (8 units). Only order 6 is free, so 64 splits into 32 + 32, the low 32 into 16 + 16, the low 16 into 8 + 8. A = 0. Free: 8 at order 3, 16 at order 4, 32 at order 5. +2. `B = alloc(12)` needs order 4 and takes the free 16. B = 16. +3. `C = alloc(3)` needs order 2. Order 2 is empty, so the order-3 block at 8 splits into 4 + 4. C = 8, and 12 is free at order 2. +4. `free(A)`: the buddy of 0 at order 3 is 0 XOR 8 = 8. Block 8 is split (C lives in it), so there is no merge, and 0 goes on the order-3 list. +5. `free(C)`: buddy 8 XOR 4 = 12 is free, so merge into 8 at order 3. Buddy 8 XOR 8 = 0 is free at order 3, so merge into 0 at order 4. Buddy 0 XOR 16 = 16 is B, allocated, so stop. Free: 0 at order 4 and 32 at order 5. + +
+{{#include ../images/buddy-allocator.svg}} +
The space after step 3, each block drawn above the addresses it covers: every split creates a pair of buddies, and the shaded part of each allocated block is what was asked for.
+
+ +**Cost.** Allocation and free are both O(m) worst case, one step per order, where m is log2 of the space size in units. The price is internal fragmentation: the three requests above total 20 units but occupy 28, 29% waste. Rounding up to a power of two wastes just under half the block in the worst case (a request of 2^k + 1 gets 2^(k+1)) and a quarter on average if request sizes are spread uniformly between consecutive powers of two. There is also external fragmentation the buddy rule cannot fix: two adjacent free blocks that are not buddies, such as free blocks at 12 and 16 in a 64-unit space, can never merge. + +Kenneth Knowlton described the binary buddy system in "A Fast Storage Allocator" (CACM, 1965). The Linux kernel's page allocator is a buddy allocator over physical page frames: it keeps free lists per order in each memory zone (`/proc/buddyinfo` prints how many free blocks of each order there are), finds a buddy by XORing the page frame number with `1 << order`, and by default goes up to order 10, blocks of 1,024 pages, which is 4 MiB with 4 KiB pages. + +### Slab Allocation + +Jeff Bonwick's slab allocator ("The Slab Allocator: An Object-Caching Kernel Memory Allocator", USENIX 1994, written for the SunOS 5.4 kernel) starts from an observation about kernels: they allocate a few kinds of fixed-size objects (inodes, process descriptors, network buffers) over and over, and initializing an object often costs more than allocating it. + +- There is a **cache** per object type. A cache owns **slabs**: one or more contiguous pages, obtained from the page allocator, cut into equal-size objects, with a free list of the objects in each slab. +- Allocation pops an object from a partially full slab, and free pushes it back. Both are O(1). Objects have no headers, and there is no external fragmentation inside a slab: the only waste is the leftover tail of the slab that is too small for another object. +- Freed objects keep their *constructed* state (initialized locks, list heads), so the constructor runs once when the slab is created, not on every allocation. When memory runs short, completely free slabs go back to the page allocator. +- *Slab colouring* starts the objects in different slabs at slightly different offsets, so the same field of different objects doesn't always land in the same CPU cache sets. + +This is segregated storage with one class per type, layered on top of the buddy allocator. Linux had three implementations: SLAB (following Bonwick's design), SLOB (for very small systems) and SLUB (Christoph Lameter, merged in 2007), which is simpler and keeps its per-slab metadata in the page descriptor. SLOB was removed in Linux 6.4 and SLAB in 6.8 (2024), so SLUB is now the only one. `kmalloc` serves general requests from caches named by size (`kmalloc-32`, `kmalloc-64`, `kmalloc-96`, ...), which you can see in `/proc/slabinfo`. Memcached's slab classes (Chapter 29) apply the same idea in user space. + +### Arenas and Bump Allocation + +When many objects die at the same time, the allocator doesn't need to track them individually at all. An *arena* (or *region*) is a large chunk with a pointer `top` to its first unused byte. Allocation rounds `top` up to the required alignment (Section 2.2), returns it, and advances it. There is no per-object free. Instead, `reset` frees everything at once by setting `top` back to the start. + +```python +class Arena: + """Bump allocator over one chunk of `size` bytes; offsets stand in for addresses.""" + + def __init__(self, size): + self.size, self.top = size, 0 + + def alloc(self, n, align=8): # align must be a power of two + start = (self.top + align - 1) & -align # round up to a multiple of align + if start + n > self.size: + return None # a real arena would chain a new chunk + self.top = start + n + return start + + def reset(self): + self.top = 0 # frees every object at once +``` + +Both operations are O(1) worst case and take a handful of instructions; a real arena that chains chunks frees them all on reset. Objects allocated together sit next to each other, which helps the cache. The stack of Section 2.2 is a bump allocator whose frees must come in LIFO order. + +Arenas fit any workload with phases. Compilers put the syntax tree and intermediate code for a compilation unit in arenas (LLVM's `BumpPtrAllocator`, GCC's obstacks). Servers give each request a pool that is discarded when the response is sent (Apache's APR pools, PostgreSQL's memory contexts, which are reset at the end of a query). Game engines allocate per-frame scratch data from an arena that is reset every frame. The cost is that memory is not reused until reset, and one long-lived object in an arena keeps the whole arena alive; a pointer kept past a reset points into memory that the next phase will overwrite. + +### Testing the Simulations + +An allocator bug usually shows up far from its cause, as one object silently overwriting another. The simulations above can be checked directly: after every operation of a long random sequence, assert that the blocks tile the space exactly, that no two live allocations overlap, that the allocator agrees with the test about which blocks are live, and that no two free blocks could still be merged. For the free list, a brute-force first fit also predicts every `malloc` result. + +```python +import random + + +def assert_disjoint(intervals): + intervals = sorted(intervals) + for (s1, e1), (s2, e2) in zip(intervals, intervals[1:]): + assert e1 <= s2, "two live allocations overlap" + + +def check_free_list(h, live): + """live maps each pointer the test holds to the number of words it asked for.""" + end, prev_free, found = 0, False, {} + for addr, size, used in h.blocks(): + assert h.mem[addr] == h.mem[addr + size - 1], "header and footer disagree" + if used: + found[addr + 1] = size - 2 # payload capacity + else: + assert not prev_free, "two adjacent free blocks" + prev_free = not used + end = addr + size + assert end == len(h.mem), "blocks do not tile the heap" + assert found.keys() == live.keys() + assert all(found[p] >= n for p, n in live.items()) + assert_disjoint((p, p + n) for p, n in live.items()) + + +def first_fit_reference(h, n): + need = max(h.MIN_BLOCK, (n + 3) & ~1) + return next((a + 1 for a, s, u in h.blocks() if not u and s >= need), None) + + +def check_buddy(b, live): + blocks = sorted([(a, k) for k, s in enumerate(b.free_lists) for a in s] + + list(b.order_of.items())) + pos = 0 + for addr, k in blocks: + assert addr == pos and addr % (1 << k) == 0, "blocks do not tile the space" + pos += 1 << k + assert pos == 1 << b.max_order + for k, s in enumerate(b.free_lists[:-1]): + assert all(a ^ (1 << k) not in s for a in s), "free buddies not merged" + assert b.order_of.keys() == live.keys() + assert all(1 << b.order_of[a] >= n for a, n in live.items()) + assert_disjoint((a, a + n) for a, n in live.items()) + + +random.seed(1) +for trial in range(200): + h, b = FreeListHeap(256), BuddyAllocator(8) + live_h, live_b = {}, {} + for step in range(300): + if live_h and random.random() < 0.45: + p = random.choice(list(live_h)) + h.free(p) + del live_h[p] + else: + n = random.randint(1, 40) + expect = first_fit_reference(h, n) + p = h.malloc(n) + assert p == expect + if p is not None: + live_h[p] = n + if live_b and random.random() < 0.45: + a = random.choice(list(live_b)) + b.free(a) + del live_b[a] + else: + n = random.randint(1, 70) + a = b.alloc(n) + if a is not None: + live_b[a] = n + check_free_list(h, live_h) + check_buddy(b, live_b) + for p in list(live_h): + h.free(p) + for a in list(live_b): + b.free(a) + assert list(h.blocks()) == [(0, 256, 0)] # everything coalesced back + assert b.free_lists[8] == {0} +print("all invariants held") +``` + +## 2.6 Type Systems and Generic Programming Modern languages provide mechanisms for writing data structures that work with arbitrary types. @@ -523,9 +847,85 @@ assert unpack(records[3]) == (1, 0, 42) +**2.7 ★★ Buddy allocation by hand.** A buddy allocator manages 64 units, all free. It receives `P = alloc(7)`, `Q = alloc(20)`, `R = alloc(2)`, `S = alloc(9)`, in that order, and splits as in Section 2.5 (keep the low half, free the high half). + +(a) Give the address and block size of P, Q, R and S, and list the free blocks afterwards. + +(b) How many units are lost to internal fragmentation? + +(c) Now `free(R)`. Compute each buddy address the allocator checks, say which merges happen, and give the free blocks afterwards. + +
+Solution + +**(a)** P needs order 3 (8 units). The only free block is 0..63, which splits into 32 + 32, then 16 + 16, then 8 + 8: **P = 0** (size 8), leaving free blocks 8 (order 3), 16 (order 4) and 32 (order 5). Q needs order 5 and takes **Q = 32** (size 32). R needs order 1 (2 units); orders 1 and 2 are empty, so the order-3 block at 8 splits into 4 + 4 and the low 4 into 2 + 2: **R = 8** (size 2), leaving 10 free at order 1 and 12 free at order 2. S needs order 4 and takes **S = 16** (size 16). Free afterwards: **10 (2 units) and 12 (4 units)**. + +**(b)** The requests total 7 + 20 + 2 + 9 = 38 units and the blocks total 8 + 32 + 2 + 16 = 58, so **20 units** (34% of the allocated space) are internal fragmentation. + +**(c)** R is at 8 with order 1. Buddy 8 XOR 2 = **10** is free at order 1: merge into 8 at order 2. Buddy 8 XOR 4 = **12** is free at order 2: merge into 8 at order 3. Buddy 8 XOR 8 = **0** is P, which is allocated: stop. Free afterwards: **one block of 8 units at 8**. Running the `BuddyAllocator` of Section 2.5 on the same calls gives the same addresses. + +
+ +**2.8 ★★ No policy wins everywhere.** A heap has two free blocks: 20 words at address 0 and 15 words at address 100. Ignore headers and minimum sizes, so a request of n words takes exactly n words from the front of the chosen block. + +(a) The requests are 15, then 20. Show that first fit fails and best fit succeeds. + +(b) The requests are 10, 10, then 15. Show that best fit fails and first fit succeeds. + +(c) What does this mean for choosing a policy? + +
+Solution + +**(a)** First fit gives the 15 to the first block that fits, the 20-word block at 0, leaving free blocks of 5 and 15. The request for 20 then fails. Best fit gives the 15 to the 15-word block, an exact fit, so the 20-word block is still whole and the second request succeeds. + +**(b)** First fit: 10 from the 20-word block (free: 10 and 15), 10 more from it (free: 0 and 15), then 15 from the 15-word block. All succeed. Best fit: the first 10 goes to the smaller block that fits, the 15 (free: 20 and 5), the second 10 goes to the 20 (free: 10 and 5), and the 15 fails although 15 words are free in total. + +**(c)** Each policy has inputs on which it fails while the other succeeds, so neither dominates, consistent with Robson's lower bound that some sequence defeats every non-moving allocator. Policies are compared on traces of real programs, where best fit and address-ordered first fit both do well. + +
+ +**2.9 ★★ Arena alignment and reset.** Use the `Arena` class from Section 2.5 with a 64-byte chunk. + +(a) Allocate, in order, (size, alignment) = (1, 1), (8, 8), (2, 2), (4, 4), (16, 16), (1, 1). Give each offset, the final `top`, and the bytes lost to padding. + +(b) Find an order for the same six requests that wastes no padding. + +(c) A request handler keeps the offset of the 16-byte object in a global variable, the arena is reset, and the next request allocates (16, 16) and writes to it. What does the stale offset now refer to? + +
+Hint + +`(top + align - 1) & -align` rounds `top` up to the next multiple of `align`. This is the same rule as struct padding in Exercise 2.3. + +
+ +
+Solution + +**(a)** + +| Request | `top` before | Offset | Padding | +|---------|--------------|--------|---------| +| (1, 1) | 0 | 0 | 0 | +| (8, 8) | 1 | 8 | 7 | +| (2, 2) | 16 | 16 | 0 | +| (4, 4) | 18 | 20 | 2 | +| (16, 16) | 24 | 32 | 8 | +| (1, 1) | 48 | 48 | 0 | + +Final `top` is **49**. The objects total 32 bytes and **17 bytes** are padding. + +**(b)** Decreasing alignment: (16, 16), (8, 8), (4, 4), (2, 2), (1, 1), (1, 1) land at offsets 0, 16, 24, 28, 30, 31 and `top` ends at **32**, no padding. Each object ends on a multiple of the next object's alignment, the same reason sorting struct fields by decreasing alignment works. + +**(c)** After `reset`, `top` is 0 and the next request lays out its objects from offset 0 again, so its (16, 16) object lands at offset 0. Offset 32 now belongs to whatever object of the new request covers byte 32, or to unallocated space if the request uses less. Reads through the stale offset see another request's data and writes corrupt it, and nothing detects it. This is the arena form of use-after-free, and the reason an arena-allocated object must not outlive the phase its arena belongs to. + +
+ --- ## Where this connects - [Chapter 3: Arrays—The Foundation of Contiguous Storage](ch03-arrays-the-foundation-of-contiguous-storage.md). The first structure built directly on this memory model - [Chapter 16: External Memory and Cache-Oblivious Structures](../volume-3/ch16-external-memory-and-cache-oblivious-structures.md). What the memory hierarchy does to these assumptions +- [Chapter 29: System Design as Data Structure Composition](../volume-5/ch29-system-design-as-data-structure-composition.md). Memcached's slab classes, the size-class idea of Section 2.5 applied to a cache diff --git a/src/volume-1/ch08-self-balancing-trees.md b/src/volume-1/ch08-self-balancing-trees.md index b20b6ed..7514254 100644 --- a/src/volume-1/ch08-self-balancing-trees.md +++ b/src/volume-1/ch08-self-balancing-trees.md @@ -169,6 +169,171 @@ Node* insert_avl(Node *node, int key) { } ``` +Why is one rotation (single or double) enough for an insertion? Let z be the lowest unbalanced ancestor of the new node. Before the insertion z's subtree had some height H. The insertion pushed it to H + 1, and that extra level is what unbalanced z. The rotation at z removes exactly that level, so z's subtree is back to height H, the height it had before the insertion. Every ancestor above z sees the same subtree height as before, so nothing above z can be unbalanced. + +### AVL Deletion + +Deletion starts as BST deletion (Section 7.2): a node with two children takes its successor's key, and the successor, which has at most one child, is unlinked instead. Then, as with insertion, walk back up the search path, updating heights and rotating wherever a balance factor reaches ±2. Two things are different. + +**The case is chosen from the child's balance factor, not the key.** The insertion code compares the new key with the child's key to tell Left-Left from Left-Right. A deletion removes a key from the *shorter* side, so the key says nothing about the shape of the taller side. Look at the taller child y instead. If y leans the same way as z, or not at all (balance factor 0), do a single rotation; if y leans the other way, do a double rotation. The balance-0 case never arises after an insertion (the child that just grew always leans one way), but it does after a deletion, and there a double rotation would leave a node unbalanced (Exercise 8.8). + +**One rotation may not finish the job.** Say z is left-heavy and lost a level on the right. Before the deletion z had height H, with a left subtree of height H − 1 and a right subtree of height H − 2. After it the right subtree has height H − 3. A single rotation when y leans left, or a double rotation when y leans right, leaves the subtree with height H − 1: one *less* than before the deletion. So z's parent now sees a shorter child and may itself be unbalanced, and so may every ancestor above it. Only when y has balance 0 does the single rotation keep height H, and then the walk can stop. + +Here is the AVL code in Python, with the four cases folded into one `rebalance` that insertion and deletion share. Heights follow the C code: an empty tree has height 0 and a leaf has height 1. + +```python +class Node: + def __init__(self, key): + self.key = key + self.left = self.right = None + self.height = 1 + + +def height(node): + return node.height if node else 0 + + +def get_balance(node): + return height(node.left) - height(node.right) + + +def update(node): + node.height = 1 + max(height(node.left), height(node.right)) + + +def rotate_right(z): + y = z.left + z.left, y.right = y.right, z + update(z) + update(y) + return y + + +def rotate_left(z): + y = z.right + z.right, y.left = y.left, z + update(z) + update(y) + return y + + +def rebalance(node): + update(node) + balance = get_balance(node) + if balance > 1: # left-heavy + if get_balance(node.left) < 0: # Left-Right: straighten first + node.left = rotate_left(node.left) + return rotate_right(node) # Left-Left, or child balance 0 + if balance < -1: # right-heavy, the mirror image + if get_balance(node.right) > 0: # Right-Left + node.right = rotate_right(node.right) + return rotate_left(node) # Right-Right, or child balance 0 + return node + + +def insert_avl(node, key): + if node is None: + return Node(key) + if key < node.key: + node.left = insert_avl(node.left, key) + elif key > node.key: + node.right = insert_avl(node.right, key) + else: + return node # duplicate + return rebalance(node) + + +def delete_avl(node, key): + if node is None: + return None # key not present + if key < node.key: + node.left = delete_avl(node.left, key) + elif key > node.key: + node.right = delete_avl(node.right, key) + else: + if node.left is None: + return node.right + if node.right is None: + return node.left + successor = min_value(node.right) # Section 7.2 + node.key = successor.key + node.right = delete_avl(node.right, successor.key) + return rebalance(node) +``` + +`delete_avl` calls `rebalance` at every node on the way back up, so it handles the cascade without any special code. For simplicity it keeps rebalancing after the height stops changing; those extra calls find nothing to do. + +**Worked example: a deletion that rotates twice.** The tree below is a *Fibonacci tree*, the thinnest AVL tree of its height (Exercise 8.4; heights here count nodes, as in the code, so they are one more than in that exercise). Every internal node is left-heavy, with balance factor +1. Delete 12. + +``` +Before (height 5): After deleting 12 (height 4): + + 8 5 + / \ / \ + 5 11 3 8 + / \ / \ / \ / \ + 3 7 10 12 2 4 7 10 + / \ / / / / / \ + 2 4 6 9 1 6 9 11 + / + 1 +``` + +``` +delete_avl(12) 12 is a leaf: return None, so 11.right = None +rebalance(11) heights: left (10) = 2, right = 0, balance +2 + child 10 has balance +1: Left-Left, rotate_right(11) + the subtree is now 10 with children 9 and 11, height 2 (was 3) +rebalance(8) heights: left (5) = 4, right (10) = 2, balance +2 + child 5 has balance +1: Left-Left, rotate_right(8) + 5 is the new root; tree height 4 (was 5) +``` + +Both ancestors of the deleted leaf needed a rotation, because each rotation made its subtree one shorter, which unbalanced the next node up. In bigger Fibonacci trees the cascade keeps going: deleting the right leaf of the 232-node Fibonacci tree of height 11 causes 5 rotations, about one for every two levels. An insertion into any AVL tree never needs more than 2. + +**Cost.** Each level of the path does O(1) work: update a height and do at most one single or double rotation. Deletion is therefore O(log n) worst case, with O(log n) rotations in the worst case, against O(1) rotations for insertion. + +**Testing it.** A balanced tree can return the right answers while silently breaking its invariant, so check the invariant, not just the answers. After every operation, compare the tree's in-order keys with a sorted Python list that receives the same operations, and verify every node's stored height and balance factor: + +```python +import bisect +import random + + +def min_value(node): # Section 7.2 + while node.left: + node = node.left + return node + + +def check_avl(node, lo=None, hi=None): + """Return the keys in order; fail if order, a height or a balance is wrong.""" + if node is None: + return [] + assert (lo is None or lo < node.key) and (hi is None or node.key < hi) + keys = check_avl(node.left, lo, node.key) + [node.key] \ + + check_avl(node.right, node.key, hi) + assert node.height == 1 + max(height(node.left), height(node.right)) + assert abs(get_balance(node)) <= 1 + return keys + + +root, reference = None, [] +for _ in range(5000): + key = random.randrange(300) + if random.random() < 0.5: + root = insert_avl(root, key) + if key not in reference: + bisect.insort(reference, key) + else: + root = delete_avl(root, key) + if key in reference: + reference.remove(key) + assert check_avl(root) == reference +``` + +The children are checked before the parent, so each stored height is compared against children whose heights have already been verified. + ### AVL Properties - Height ≤ 1.44 log₂(n+1) (tight bound) @@ -267,6 +432,53 @@ void fix_violation(Node **root, Node *z) { } ``` +### Deletion and the Double Black + +Deletion is where red-black trees earn their reputation. Start with BST deletion (Section 7.2): if the node has two children, copy in its successor's key and remove the successor instead. Either way, the node y that is physically unlinked has at most one child, x (possibly a NIL leaf), which takes y's place. + +- **y was red.** No path lost a black node, and y's neighbours were black, so no red-red appears. Done. +- **y was black and x is red.** Color x black. The paths through x get their black node back. Done. +- **y was black and x is black** (usually x is NIL). Every path through x now has one black node too few, breaking property 5. Pretend x carries an *extra black*: it is **double black** and counts twice. The counts are now correct, and the rest of the algorithm moves the extra black around until it can be dropped. + +Let x be a left child, p its parent and w its sibling (the cases for a right child are mirror images). w cannot be NIL: before the deletion, every path down x's side passed through the removed black node y, so every path down w's side contains a black node too, besides its final NIL. + +| Case | Situation | Action | Then | +|------|-----------|--------|------| +| 1 | w is red | Rotate left at p; swap the colors of p and w | x has a black sibling: go to case 2, 3 or 4 | +| 2 | w is black, both its children black | Color w red; move the extra black up to p | p red: color it black, done. p black: p is double black, repeat one level up | +| 3 | w is black, near child (w.left) red, far child black | Rotate right at w; swap the colors of w and its old near child | Now the far child is red: case 4 | +| 4 | w is black, far child (w.right) red | Rotate left at p; w takes p's color; p and the far child become black | Done | + +In case 2, coloring w red removes one black from every path on w's side, matching the shortage on x's side; the whole subtree at p is now one short, which is what moving the extra black up to p records. In case 4 the rotation puts p, now black, above x, giving x's paths the black node they were missing, while w (in p's old position and color) and the far child (now black) keep the counts on the other side. If the extra black reaches the root, drop it: every path loses one black node at once, which property 5 allows. + +**Cost.** Case 2 can repeat up the tree, but it only recolors. A case 1 rotation is followed by case 2 with a red parent (which stops) or by case 3 or 4 (which stop), so a deletion makes **at most 3 rotations** (cases 1, 3, 4) and O(log n) recolorings: O(log n) worst case. AVL deletion may need a rotation on many levels; this bounded number of structural changes is one reason libraries prefer red-black trees for update-heavy maps. + +**Worked example.** Insert 10, 20, ..., 100 in order, then delete 10: + +``` +Before: After deleting 10: + B40 B60 + / \ / \ + B20 B60 B40 B80 + / \ / \ / \ / \ + B10 B30 B50 R80 B20 B50 B70 B90 + / \ \ \ + B70 B90 R30 R100 + \ + R100 +``` + +``` +remove 10 10 is a black leaf: its NIL is double black (x), p = 20, w = 30 +case 2 at 20 w = 30 is black with black (NIL) children: color 30 red, + the extra black moves to 20, which is black, so continue +case 4 at 40 x = 20, p = 40, w = 60 is black, far child 80 is red: + rotate left at 40; 60 takes 40's color (black); + 40 and 80 become black. Done +``` + +Every root-to-NIL path still has 3 black nodes before the NIL, and no red node has a red child. The recoloring and rotation look arbitrary here; Section 8.4 shows that they are a B-tree merge followed by a B-tree borrow. + ### AVL vs Red-Black Comparison | Aspect | AVL | Red-Black | @@ -279,7 +491,267 @@ void fix_violation(Node **root, Node *z) { | Memory overhead | Height field | Color bit | | Use case | Read-heavy | Write-heavy | -## 8.4 Splay Trees +## 8.4 Red-Black Trees Are 2-3-4 Trees + +The five red-black properties and the case analyses above look like a list of tricks. They are a B-tree in disguise. A **2-3-4 tree** is a B-tree of order 4 ([Chapter 10](ch10-multiway-search-trees-and-b-trees.md)): every node holds 1, 2 or 3 keys and has 2, 3 or 4 children, and all leaves are at the same depth. Take any red-black tree and merge every red node into its parent. Each black node, together with its red children, becomes one 2-3-4 node: + +| 2-3-4 node | Red-black encoding | +|------------|--------------------| +| 2-node `[b]` | a black node with no red children | +| 3-node `[a b]` | a black node with one red child (b black with red left child a, or a black with red right child b) | +| 4-node `[a b c]` | the middle key b, black, with red children a and c | + +Run the merge backwards and any 2-3-4 tree becomes a red-black tree. The correspondence is not one-to-one, because a 3-node can lean either way. + +
+{{#include ../images/rb-234.svg}} +
Each shaded group is one 2-3-4 node: a black node plus its red children. Inserting 80 recolors three nodes, and in the 2-3-4 tree that is a 4-node split that pushes 60 up into its parent.
+
+ +### What the Rules Mean + +With the 2-3-4 tree in view, each red-black property states a B-tree fact: + +- **No red node has a red child** keeps every group to one black node and at most two red children, so a node never holds more than 3 keys. +- **Every path has the same number of black nodes**: each 2-3-4 node contains exactly one black node, so a path's black count is the number of 2-3-4 levels it crosses. Equal black counts means all 2-3-4 leaves are at the same depth, which is the B-tree invariant and the whole source of the balance. +- **The root is black** because the top of every group is black. +- **The height bound** follows in one line. A 2-3-4 tree of n keys has at most log₂(n + 1) levels, since every node has at least 2 children, and each level becomes at most two red-black levels (a black node and a red child). So the red-black height is at most 2 log₂(n + 1), the bound of Section 8.3. + +### Insertion Is Splitting + +A new red-black node is red, which means a new key joins an existing 2-3-4 leaf. That matches B-tree insertion, which always adds to a leaf. + +- **Parent is black.** The leaf was a 2-node or a 3-node, and the key fits: a 2-node becomes a 3-node, and a 3-node becomes a 4-node already in the standard shape (black middle, two red children). Done. +- **Case 1, red uncle.** The parent and the uncle are both red children of the grandparent, so the grandparent's group is a 4-node, and the new key would be its fourth. The B-tree answer is to split: the middle key moves up into the parent node and the two halves become separate nodes. Recoloring does exactly that. The grandparent turns red, which moves it up into its own parent's group; the parent and uncle turn black, so they become the tops of two separate nodes. If the grandparent's parent is also red, the node above has overflowed in turn: continue from there, as a B-tree split propagates upward. When the split reaches the root, recoloring the root black creates a new top level, the only way either tree grows taller. +- **Cases 2 and 3, black uncle.** The grandparent's group is a 3-node (the black uncle belongs to a different node), so there is room for the new key, and the result is a 4-node. But its three keys form a chain of two red links instead of a black middle key with two red children. The rotations reshape the chain into that standard form. The 2-3-4 tree does not change; only its encoding does. + +The figure shows Case 1. Inserting 80 under red 70 meets the 4-node `[50 60 70]`. Coloring 50 and 70 black and 60 red splits it: 60 joins the root, which becomes the 4-node `[20 40 60]`, and 80 joins 70 to form the 3-node `[70 80]`. The parent of 60 is black, so the process stops there with no rotation at all. + +### Deletion Is Borrowing and Merging + +Deletion maps onto Chapter 10's B-tree deletion in the same way. Removing a red node, or a black node with a red child, takes a key out of a 3-node or 4-node, which still has a key left. A double black is an **underflow**: a 2-node has lost its only key. The four cases are the B-tree repairs: + +- **Case 2 (black sibling, both children black)**: the sibling is a 2-node, so there is nothing to borrow. **Merge**: the parent key comes down and joins the sibling, and coloring w red puts the two in one group. If p was red, the parent node had keys to spare; coloring p black finishes the merge. If p was black, the parent was itself a 2-node and is now empty: the underflow moves up a level, just as a B-tree merge can propagate to the root. When it reaches the root, the tree loses a level. +- **Cases 3 and 4 (black sibling with a red child)**: the sibling is a 3-node or 4-node. **Borrow** through the parent: the parent key comes down into the empty node and a sibling key goes up to replace it (from a 4-node sibling, the key nearest x comes across as well). Case 4's rotation does this in one step; case 3 only reshapes the sibling so that case 4's rotation applies. +- **Case 1 (red sibling)**: w is red, so it is in the same group as p. The parent's 2-3-4 node is a 3-node encoded with the wrong lean, and x's red-black sibling is not its 2-3-4 sibling. The rotation flips the lean, and nothing in the 2-3-4 tree changes. After it, x's sibling is a real 2-3-4 sibling, and case 2, 3 or 4 applies. + +Here is the worked deletion of Section 8.3 again, as a 2-3-4 tree: + +``` +Before: [40] + / \ + [20] [60 80] + / \ / | \ + [10] [30] [50] [70] [90 100] + +Delete 10: [10] is empty. Its sibling [30] is a 2-node, so merge: +20 comes down and joins 30, giving [20 30]. Now [20]'s old node is empty +(case 2 with a black parent). Its sibling [60 80] is a 3-node, so borrow: +40 comes down, 60 goes up (case 4). + +After: [60] + / \ + [40] [80] + / \ / \ + [20 30] [50] [70] [90 100] +``` + +Read the "after" tree of Section 8.3 back through the table above and you get exactly this. + +This view explains why the classic algorithm has so many cases. A 2-3-4 tree has one operation for each situation (add a key, split, merge, borrow), but the binary encoding has several shapes for each 3-node and 4-node in transit, and each shape has its own case and its own mirror image. Rudolf Bayer introduced the structure in 1972 as the *symmetric binary B-tree*, a binary representation of B-trees with "horizontal" links where red links are now; the red and black colors came later. The next section shows what happens when the encoding is restricted to one shape per node. + +## 8.5 Left-Leaning Red-Black Trees + +Robert Sedgewick's **left-leaning red-black tree** (LLRB, 2008) removes the choice. It adds one rule: a red node must be a left child. Thinking of a red node as a red *link* from its parent, the invariant is: + +1. Red links lean left. +2. No node has two red links touching it. +3. Every path from the root to a NIL link has the same number of black links. + +Rule 2 forbids a red node with a red child and also a black node with two red children, so there are no 4-nodes. An LLRB tree is a 2-3 tree in which each 3-node is drawn one way, black on top with a red left child. Each 2-3 tree has exactly one LLRB encoding, so the mirror-image cases disappear. + +### Insertion + +A new key is attached with a red link, as before. Then, on the way back up the recursion, three local fixes repair whatever the insertion broke, in this order: + +```python +RED, BLACK = True, False + + +class LLRBNode: + def __init__(self, key): + self.key = key + self.left = self.right = None + self.color = RED # a new key joins an existing node + + +def is_red(h): + return h is not None and h.color == RED + + +def rotate_left(h): # a red right link now leans left + x = h.right + h.right, x.left = x.left, h + x.color, h.color = h.color, RED + return x + + +def rotate_right(h): # a red left link now leans right + x = h.left + h.left, x.right = x.right, h + x.color, h.color = h.color, RED + return x + + +def flip_colors(h): # split a temporary 4-node + h.color = not h.color + h.left.color = not h.left.color + h.right.color = not h.right.color + + +def fix_up(h): + if is_red(h.right) and not is_red(h.left): + h = rotate_left(h) # right-leaning 3-node + if is_red(h.left) and is_red(h.left.left): + h = rotate_right(h) # 4-node as a chain of two reds + if is_red(h.left) and is_red(h.right): + flip_colors(h) # balanced 4-node: split it + return h + + +def llrb_insert(root, key): + root = _insert(root, key) + root.color = BLACK + return root + + +def _insert(h, key): + if h is None: + return LLRBNode(key) + if key < h.key: + h.left = _insert(h.left, key) + elif key > h.key: + h.right = _insert(h.right, key) + return fix_up(h) +``` + +(These `rotate_left` and `rotate_right` belong with `LLRBNode`, not with the AVL code of Section 8.2: they move colors, not heights.) + +Each line of `fix_up` is one 2-3 tree situation. A red right link with a black left link is a 3-node leaning the wrong way: rotate it left. Two red links in a row on the left are a 4-node drawn as a chain: rotate right to balance it. Two red children are a balanced 4-node: flip the colors, which splits it and passes the middle key up as a red link to the parent, where the next `fix_up` call deals with it. The three classic insertion cases and their mirror images all reduce to these three lines, applied at every node on the search path. + +Insertion is O(log n) worst case. Sedgewick's paper also gives a variant that calls `flip_colors` on the way *down*, before the recursive calls; it splits 4-nodes top-down and keeps them, so it is the 2-3-4 version. The code above, with the flip last, is the 2-3 version used in Sedgewick and Wayne's *Algorithms* (4th edition). + +### Deletion + +Deletion uses the same plan as Chapter 10's single-pass B-tree deletion: never step down into a node that has only one key, so that the key to be removed is never the only key in its leaf. `move_red_left` makes sure the left child is not a 2-node before the descent goes left. It first flips colors, merging the parent key and both children into a temporary 4-node; if the right sibling was a 3-node, it then borrows from it instead, with two rotations and a flip back. On the way back up, `fix_up` cleans up the temporary 4-nodes and right-leaning links left behind. + +```python +def move_red_left(h): + # h is red and h.left is a 2-node: give h.left a red link + flip_colors(h) # merge h.left, h, h.right + if is_red(h.right.left): # sibling is a 3-node: borrow + h.right = rotate_right(h.right) + h = rotate_left(h) + flip_colors(h) + return h + + +def move_red_right(h): + flip_colors(h) + if is_red(h.left.left): + h = rotate_right(h) + flip_colors(h) + return h + + +def delete_min(h): + if h.left is None: + return None + if not is_red(h.left) and not is_red(h.left.left): + h = move_red_left(h) + h.left = delete_min(h.left) + return fix_up(h) + + +def llrb_delete(root, key): # key must be in the tree + if not is_red(root.left) and not is_red(root.right): + root.color = RED + root = _delete(root, key) + if root is not None: + root.color = BLACK + return root + + +def _delete(h, key): + if key < h.key: + if not is_red(h.left) and not is_red(h.left.left): + h = move_red_left(h) + h.left = _delete(h.left, key) + else: + if is_red(h.left): + h = rotate_right(h) # lean right so a red link goes down + if key == h.key and h.right is None: + return None # h is a red leaf: drop it + if not is_red(h.right) and not is_red(h.right.left): + h = move_red_right(h) + if key == h.key: + successor = h.right + while successor.left: + successor = successor.left + h.key = successor.key + h.right = delete_min(h.right) + else: + h.right = _delete(h.right, key) + return fix_up(h) +``` + +The precondition matters: with an absent key, the descent can reach `h.left.left` on a missing child. Check membership first (an O(log n) search) when the caller cannot guarantee it. Both operations are O(log n) worst case. + +The same kind of test as for the AVL tree checks every LLRB rule after every operation: + +```python +import bisect +import random + + +def check_llrb(h, lo=None, hi=None): + """Return (black height, keys in order); fail if any LLRB rule is broken.""" + if h is None: + return 0, [] + assert (lo is None or lo < h.key) and (hi is None or h.key < hi) + assert not is_red(h.right) # red links lean left + assert not (is_red(h) and is_red(h.left)) # never two reds in a row + black_left, left = check_llrb(h.left, lo, h.key) + black_right, right = check_llrb(h.right, h.key, hi) + assert black_left == black_right # perfect black balance + return black_left + (not is_red(h)), left + [h.key] + right + + +root, reference = None, [] +for _ in range(5000): + key = random.randrange(300) + if random.random() < 0.5: + root = llrb_insert(root, key) + if key not in reference: + bisect.insort(reference, key) + elif key in reference: + root = llrb_delete(root, key) + reference.remove(key) + assert not is_red(root) + assert check_llrb(root)[1] == reference +``` + +### Trade-offs + +The LLRB insertion is short enough to write from memory, and that is its real contribution: it makes the 2-3 correspondence visible in code. But it is not a better red-black tree in every respect. + +- **Deletion is still fiddly.** The deletion code is more than twice the length of the insertion code, and it is harder to check by eye, because it deliberately creates temporary right-leaning links and 4-nodes and relies on `fix_up` to remove them later. +- **More rotations.** A classic insertion makes at most 2 rotations. The LLRB insertion keeps rotating on the way up to restore the left lean, sometimes at many levels. Inserting 100,000 random keys with the code above averaged about 1.19 rotations per insertion, with up to 13 in a single insertion; the classic algorithm averaged about 0.58 on the same keys. +- **Recursion without parent pointers.** That makes the code short, but production trees usually keep parent pointers anyway, for iterators and for deleting a node the caller already holds, and then the classic bottom-up fix-up is just as natural. Java's `TreeMap` (adapted from Cormen, Leiserson and Rivest), libstdc++'s `std::map` and the Linux kernel's `rbtree` all use the classic algorithm. + +Arne Andersson's AA tree (1993, Chapter 7) made the mirror-image choice earlier, requiring red links to lean right; its two fix-up steps, *skew* and *split*, play the role of `fix_up`'s three lines. + +## 8.6 Splay Trees Splay trees (Sleator and Tarjan, 1985) use a different strategy: instead of maintaining invariants, they "splay" accessed nodes to the root. @@ -325,7 +797,7 @@ Key property: Recently accessed elements are near the root (temporal locality). - No guaranteed worst-case (unlike AVL, Red-Black) - Can be made partially persistent -## 8.5 Scapegoat Trees +## 8.7 Scapegoat Trees Scapegoat trees maintain balance by rebuilding subtrees when they become too unbalanced. @@ -352,7 +824,7 @@ The scapegoat is not necessarily the deepest unbalanced node; any node on the pa - Simple to implement - Good for systems where rotations are expensive -## 8.6 Treaps +## 8.8 Treaps Treaps combine BST with random heap priorities. @@ -389,7 +861,7 @@ def treap_insert(root, node): return root ``` -## 8.7 Performance Comparison +## 8.9 Performance Comparison
{{#include ../images/skip-list.svg}} @@ -407,7 +879,7 @@ def treap_insert(root, node): *Amortized or expected -## 8.8 Real-World Usage +## 8.10 Real-World Usage | Tree Type | Real-World Uses | |-----------|----------------| @@ -416,6 +888,14 @@ def treap_insert(root, node): | Splay | Network routing (LRU caches), memory allocators | | Treap | Skip list alternative in some databases | +## 8.11 Historical Context + +Georgy Adelson-Velsky and Evgenii Landis described the AVL tree in 1962 ("An algorithm for the organization of information", *Doklady Akademii Nauk SSSR*), the first binary search tree with a worst-case O(log n) height guarantee. + +Rudolf Bayer, co-inventor of the B-tree (Chapter 10), introduced *symmetric binary B-trees* in 1972 (*Acta Informatica*): B-trees of order 4 stored as binary nodes, the structure of Section 8.4. Leonidas Guibas and Robert Sedgewick recast them in 1978 with the red and black coloring ("A dichromatic framework for balanced trees", FOCS), and used the coloring as a common framework for many balanced-tree schemes. The double-black formulation of deletion in Section 8.3 follows Cormen, Leiserson and Rivest's *Introduction to Algorithms* (1990). Sedgewick returned to the structure thirty years later with the left-leaning variant of Section 8.5 (2008). + +Daniel Sleator and Robert Tarjan introduced splay trees in "Self-adjusting binary search trees" (*Journal of the ACM*, 1985). Scapegoat trees are named in Igal Galperin and Ronald Rivest's 1993 paper (SODA); Arne Andersson had described essentially the same partial-rebuilding scheme in 1989. Treaps come from Cecilia Aragon and Raimund Seidel's "Randomized search trees" (FOCS 1989; journal version by Seidel and Aragon in *Algorithmica*, 1996). The shape they rely on, a tree that is a BST on keys and a heap on a second value, is Jean Vuillemin's *Cartesian tree* (1980). + ## Exercises Difficulty: ★ check your understanding · ★★ apply it · ★★★ stretch. @@ -542,7 +1022,7 @@ so h + 1 ≤ log_φ(n + 1) = log₂(n + 1) / log₂ φ ≈ 1.44 log₂(n + 1), a -**8.5 ★★ Splay a chain.** Insert 5, 4, 3, 2, 1 into a plain BST, giving a left-leaning chain with 5 at the root. (a) Splay node 1 to the root using the zig, zig-zig and zig-zag steps of Section 8.4, working from the bottom up. Draw the tree after each step and give the final height. (b) Then splay node 3 and draw the result. +**8.5 ★★ Splay a chain.** Insert 5, 4, 3, 2, 1 into a plain BST, giving a left-leaning chain with 5 at the root. (a) Splay node 1 to the root using the zig, zig-zig and zig-zag steps of Section 8.6, working from the bottom up. Draw the tree after each step and give the final height. (b) Then splay node 3 and draw the result.
Hint @@ -673,9 +1153,135 @@ Check: every root-to-NIL path has 2 black nodes before the NIL (10 and 5, 10 and
+**8.8 ★★ Why deletion looks at the child's balance factor.** The AVL tree below is what `insert_avl` builds from 20, 10, 60, 5, 40, 80, 30, 70. (a) Delete 5 with `delete_avl`. Which node becomes unbalanced, which rotation is done, and does the walk up need to continue? (b) The C `insert_avl` picks the case by comparing the key with the child's key. Since 5 < 60, that test would choose Right-Left. Do that double rotation instead and show that the result is not an AVL tree. + +``` + 20 + / \ + 10 60 + / / \ + 5 40 80 + / / + 30 70 +``` + +
+Hint + +Compute the balance factor of 60 before deciding anything. It is the case that never happens after an insertion. + +
+ +
+Solution + +(a) Removing the leaf 5 leaves 10 as a leaf (height 1). At 20 the left height is 1 and the right height (60) is 3, so the balance factor is −2. The taller child 60 has balance 0: its subtrees 40 and 80 both have height 2. `rebalance` sees `get_balance(node.right) > 0` is false and does a single `rotate_left(20)`: + +``` + 60 + / \ + 20 80 + / \ / + 10 40 70 + / + 30 +``` + +20 has balance 1 − 2 = −1 and 60 has balance 3 − 2 = +1, so the tree is valid. Its height is 4, the same as before the deletion, so no ancestor could be affected and the walk could stop here. (This is the one case where a deletion's rotation does not shorten the subtree.) + +(b) The double rotation first does `rotate_right(60)`, lifting 40, then `rotate_left(20)`: + +``` + 40 + / \ + 20 60 + / \ \ + 10 30 80 + / + 70 +``` + +Node 60 has an empty left subtree and a right subtree of height 2: balance −2. The double rotation is right only when the inner grandchild (40) is the taller part of 60's subtree. When 60 is balanced, moving 40 up leaves 80's whole subtree hanging under 60 with nothing on the other side. Insertion never meets this case because the child that just grew always leans one way, which is why the C code can get away with comparing keys. + +
+ +**8.9 ★★ Red-black deletion, two views.** Start again from the red-black tree that inserting 10, 20, ..., 100 produces (the "before" tree of the worked deletion in Section 8.3) and delete 40, the root. (a) Trace the deletion: which node is physically removed, and which cases of the double-black table fire? Draw the result. (b) Redo it on the corresponding 2-3-4 tree (Section 8.4) and check that the two results correspond. + +
+Hint + +40 has two children, so its successor is removed instead. Look at the color of the double black's sibling first. + +
+ +
+Solution + +(a) The successor of 40 is 50, the minimum of the right subtree. 50's key is copied into the root, and the node that held 50, a black leaf, is unlinked. Its NIL is double black, with parent p = 60 and sibling w = 80. + +- **Case 1**: w = 80 is red. Rotate left at 60 and swap the colors of 60 and 80: 80 is now black, with red left child 60. x's new sibling is 70, black. +- **Case 2**: 70 is black with two black (NIL) children. Color 70 red and move the extra black to p = 60. 60 is red, so color it black. Done. + +``` + B50 + / \ + B20 B80 + / \ / \ + B10 B30 B60 B90 + \ \ + R70 R100 +``` + +Every root-to-NIL path still has 3 black nodes, and no red node has a red child. The repair took one rotation and four color changes. + +(b) The 2-3-4 tree is `[40]` at the root, with children `[20]` (over `[10]` and `[30]`) and `[60 80]` (over `[50]`, `[70]` and `[90 100]`). Deleting 40 from an internal node replaces it with its successor 50 from a leaf, which leaves the leaf `[50]` empty. Its 2-3-4 sibling is `[70]`, a 2-node, so **merge**: the separating key 60 comes down and joins 70, giving `[60 70]`, and the parent `[60 80]` shrinks to `[80]`. The parent still has a key, so the repair stops. + +``` + [50] + / \ + [20] [80] + / \ / \ + [10] [30] [60 70] [90 100] +``` + +Reading the red-black result as groups gives exactly this. Case 1 did not change the 2-3-4 tree: the 3-node `[60 80]` was encoded with 60 on top, which made 80 the red-black sibling of the empty node even though its real 2-3-4 sibling was `[70]`. The rotation re-encoded the same 3-node with 80 on top. Case 2 with a red parent is a merge that the parent can absorb. + +
+ +**8.10 ★★ LLRB insertion by hand.** Insert 1, 2, 3, 4, 5, 6, 7 in that order into an empty LLRB tree with `llrb_insert` (Section 8.5). After each insertion, say which of the three lines of `fix_up` fire (and at which node), draw the tree, and give the 2-3 tree it encodes. + +
+Solution + +Red nodes are marked R; everything else is black. + +| Insert | `fix_up` actions | LLRB tree | 2-3 tree | +|--------|------------------|-----------|----------| +| 1 | none | 1 | `[1]` | +| 2 | rotate left at 1 (red right link) | 2 with left child R1 | `[1 2]` | +| 3 | flip at 2 (two red children); the root is then reset to black | 2 with children 1 and 3 | `[2]` over `[1]`, `[3]` | +| 4 | rotate left at 3 | 2 with children 1 and 4; 4 has left child R3 | `[2]` over `[1]`, `[3 4]` | +| 5 | flip at 4, which makes 4 red, a red right link of 2; then rotate left at 2 | 4 with children R2 and 5; 2 has children 1 and 3 | `[2 4]` over `[1]`, `[3]`, `[5]` | +| 6 | rotate left at 5 | as before, but 6 replaces 5, with left child R5 | `[2 4]` over `[1]`, `[3]`, `[5 6]` | +| 7 | flip at 6, then flip at 4 (2 and 6 are both red); the root is reset to black | perfect tree: 4; 2, 6; 1, 3, 5, 7; all black | `[4]` over `[2]`, `[6]`, over `[1]`, `[3]`, `[5]`, `[7]` | + +``` +After 5: After 7: + B4 B4 + / \ / \ + R2 B5 B2 B6 + / \ / \ / \ +B1 B3 B1 B3 B5 B7 +``` + +Insertion 5 shows a split propagating: the flip at 4 splits the temporary 4-node `[3 4 5]` and sends 4 up as a red right link, and the rotation at 2 makes `[2 4]` a left-leaning 3-node. Insertion 7 splits two 4-nodes in a row, `[5 6 7]` and then `[2 4 6]`, and the second split happens at the root, so the tree gains a level. Sorted input, the worst case for a plain BST, gives a perfectly balanced tree here, and that continues: inserting 1 to 2^k − 1 in order gives a perfect all-black tree (checked with the code above for every k up to 12). + +
+ --- ## Where this connects - [Chapter 7: Binary Search Trees](ch07-binary-search-trees.md). The unbalanced baseline these structures fix +- [Chapter 10: Multiway Search Trees and B-Trees](ch10-multiway-search-trees-and-b-trees.md). The 2-3-4 trees and B-tree splits, borrows and merges that red-black trees encode (Section 8.4) - [Chapter 21: Algorithm Design Using Data Structures](../volume-3/ch21-algorithm-design-using-data-structures.md). Why skip lists trade rotations for randomness diff --git a/src/volume-1/index.md b/src/volume-1/index.md index 2f86ea6..b3a5597 100644 --- a/src/volume-1/index.md +++ b/src/volume-1/index.md @@ -11,7 +11,7 @@ The volume moves from the language of cost (Chapter 1) and how memory really wor | Chapter | After it you can | |---------|------------------| | [1: The Philosophy and Mathematics of Data Structures](ch01-the-philosophy-and-mathematics-of-data-structures.md) | Read and reason with O, Ω and Θ; tell worst-case, average and amortized cost apart; explain why a dynamic array's append is O(1) amortized | -| [2: Primitive Types and Memory Organization](ch02-primitive-types-and-memory-organization.md) | Explain what a pointer is, why integers overflow, how structs are padded, and why memory layout affects speed | +| [2: Primitive Types and Memory Organization](ch02-primitive-types-and-memory-organization.md) | Explain what a pointer is, why integers overflow, how structs are padded, how malloc manages the heap (free lists, buddy and slab allocators), and why memory layout affects speed | ## Part 2: Fundamental Linear Structures @@ -27,7 +27,7 @@ The volume moves from the language of cost (Chapter 1) and how memory really wor |---------|------------------| | [6: Tree Fundamentals and Binary Trees](ch06-tree-fundamentals-and-binary-trees.md) | Use tree vocabulary precisely, traverse a tree four ways (recursively and with an explicit stack), and write recursive tree functions | | [7: Binary Search Trees](ch07-binary-search-trees.md) | Search, insert and delete in a BST, answer successor, range and rank queries, and explain why insertion order can ruin it | -| [8: Self-Balancing Trees](ch08-self-balancing-trees.md) | Perform rotations, state the AVL and red-black invariants, and choose between AVL, red-black, splay trees and treaps | +| [8: Self-Balancing Trees](ch08-self-balancing-trees.md) | Perform rotations, insert into and delete from AVL and red-black trees, see a red-black tree as a 2-3-4 tree, and choose between AVL, red-black, splay trees and treaps | | [9: Heaps and Priority Queues](ch09-heaps-and-priority-queues.md) | Implement a binary heap, build one in O(n), support decrease-key, and solve top-k and running-median problems | | [10: Multiway Search Trees and B-Trees](ch10-multiway-search-trees-and-b-trees.md) | Insert into and delete from a B-tree, explain why databases use B+ trees, and estimate how many disk reads a lookup costs | diff --git a/src/volume-3/ch17-persistent-data-structures.md b/src/volume-3/ch17-persistent-data-structures.md index ffc0d40..2edc3fc 100644 --- a/src/volume-3/ch17-persistent-data-structures.md +++ b/src/volume-3/ch17-persistent-data-structures.md @@ -81,9 +81,104 @@ There is no mutation anywhere in that function (it only ever constructs new node Balance matters more here than in the ephemeral case, because an unbalanced tree costs you both time *and* permanent space on every update. Red-black trees and AVL trees both path-copy cleanly; the rotations simply produce a few more copied nodes. -**Fat nodes** are the alternative technique: instead of copying a node, store a list of (version, value) pairs inside it and binary search for the right one at query time. This gives O(1) space per update rather than O(log n), at the cost of an O(log m) slowdown on every access for m versions. **Node copying** (Driscoll, Sarnak, Sleator, and Tarjan, 1986) combines both: give each node a small fixed number of extra modification slots, and only copy when they fill. Achieving O(1) amortized space with no query slowdown. That paper is where the general theory of making any pointer structure persistent comes from. +Path copying is not the only technique. Section 17.3 covers the two alternatives, fat nodes and node copying, which avoid copying the path at all. -## 17.3 Persistent Arrays and HAMTs +## 17.3 Fat Nodes and Node Copying + +Path copying pays for the whole root-to-leaf path because of a cascade: a changed pointer forces a copy of the node holding it, which changes a pointer in *its* parent, and so on up to the root. Driscoll, Sarnak, Sleator and Tarjan ("Making Data Structures Persistent", STOC 1986; journal version 1989) asked the general question. Take any ephemeral pointer structure, where an update is a sequence of **update steps** (each writes one field of one node) and a query is a sequence of **access steps** (each reads one field). How cheaply can it be made persistent? They gave two answers, both of which stop the cascade at the first node. + +### Fat nodes + +Never overwrite a field. Each field keeps its whole history as a list of (version, value) pairs. A write in version v appends (v, value); a read in version v takes the latest entry stamped ≤ v. Under partial persistence versions are numbered 1, 2, 3, ... and writes only go to the newest version, so each history is sorted by construction and a read is a binary search. + +```python +from bisect import bisect_right + +class FatNode: + """A BST node whose child fields keep their whole history.""" + def __init__(self, key): + self.key = key # never changes + self.left = ([0], [None]) # (version stamps, values), stamps ascending + self.right = ([0], [None]) + +def read(field, v): + stamps, values = field + return values[bisect_right(stamps, v) - 1] # last write stamped <= v: O(log m) + +def write(field, v, value): + stamps, values = field + stamps.append(v) # v is the newest version, so order holds + values.append(value) + +class FatBST: + """Partially persistent BST: query any version, insert into the newest.""" + def __init__(self): + self.roots = [None] # roots[v] is the root of version v + + def insert(self, key): + v = len(self.roots) # the version this insert creates + root = self.roots[-1] + self.roots.append(root if root is not None else FatNode(key)) + node = root + while node is not None and node.key != key: + field = node.left if key < node.key else node.right + child = read(field, v) + if child is None: + write(field, v, FatNode(key)) # the only change: one field entry + node = child + return v + + def contains(self, key, v): + node = self.roots[v] + while node is not None and node.key != key: + node = read(node.left if key < node.key else node.right, v) + return node is not None + +t = FatBST() +for k in [50, 30, 70, 10, 35]: + t.insert(k) # versions 1 to 5 +assert t.contains(35, 5) and not t.contains(35, 4) +assert t.contains(10, 4) and not t.contains(10, 3) +``` + +Trace the same keys as Section 17.2. Each insert allocates one node and appends one entry to one field: version 4 writes B(30)'s `left`, version 5 writes B(30)'s `right`. After version 5, B's `right` field holds stamps `[0, 5]` and values `[None, E(35)]`. The query `contains(35, 4)` reaches B and reads `right` at version 4: `bisect_right([0, 5], 4) - 1 = 0`, so it sees `None` and reports 35 absent. At version 5 the index is 1 and it finds E. Nothing was copied; A, B, C and D are the same objects in every version. + +The bounds: **O(1) worst-case space per update step** (one appended pair), and an **O(log m) slowdown per access step**, where m is the number of writes to that field. A search of depth d in an old version costs O(d log m) rather than O(d). For full persistence the versions form a tree, so "latest version ≤ v" needs an order on that tree. DSST keep the versions in an order-maintenance list (a linear order consistent with the version tree, comparable in O(1)) and store each field's history in a search tree under that order. The space stays O(1) per update step and the slowdown O(log m). + +### Node copying + +Node copying keeps the O(1) space and removes the log factor, for partial persistence of structures with **bounded in-degree**: no node is pointed to by more than p nodes, for a constant p. A binary tree with parent pointers qualifies with p = 3 (a parent and two children point at each node). + +Each node keeps the field values it was created with, plus a fixed number of **modification slots**, 2p of them, each holding (version, field, value). It also keeps up to p **back pointers** to the nodes that point at it in the newest version; those are only ever needed for the newest version, so they are overwritten in place. + +- **Read** field f in version v: take the creation value, overridden by the latest slot for f stamped ≤ v. There are at most 2p slots, so this is O(1) worst case. +- **Write** field f in the newest version v: if the node has a free slot, fill it. If all 2p are full, make a **copy** holding the newest value of every field (with this write applied) and no slots in use. Each of the at most p nodes that point at the old node, found through its back pointers, must now point at the copy in version v, and the copy's children get their back pointers redirected to it. Redirecting a predecessor is a write to *its* field, done by this same procedure, so it may fill a slot or cascade into another copy. If the copied node was the root, the copy becomes version v's root. + +The cascade can run far, but it cannot run often. Let c be the cost of copying a node (a constant, since nodes have bounded size) and let the potential be Φ = c × (number of filled slots in nodes of the newest version). Claim: every write has amortized cost at most 2c. + +- **Free slot:** actual cost at most c, and Φ rises by c. Amortized: at most 2c. +- **Full node:** the copy costs c. The old node leaves the newest version and takes its 2p filled slots with it, so Φ falls by 2pc; the copy starts with none. Then come at most p recursive writes, each amortized at most 2c by induction. Amortized: at most c − 2pc + p · 2c = c. + +So each update step costs **O(1) amortized time and space** (copies are the only space beyond the slots), and each access step costs **O(1) worst case**: no slowdown at all. This is the headline DSST result: any pointer structure with bounded in-degree can be made partially persistent with O(1) amortized overhead per update step and O(1) per access step. Their **node splitting** method extends it to full persistence with the same amortized bounds. + +A red-black tree insertion performs O(1) amortized update steps (at most two rotations and O(1) amortized recolorings), so a node-copying persistent red-black tree costs O(1) amortized space per insertion, against O(log n) for path copying. Sarnak and Tarjan used exactly this for **planar point location**. Sweep a vertical line across a planar subdivision with n edges, keeping the edges that cross the line in a persistent search tree; each vertex the sweep passes creates a new version. That is O(n) space in total, and a query takes O(log n): binary-search the x-coordinate to pick the version, then search that version's tree by y. + +### Comparing the three + +| | Path copying | Fat nodes | Node copying | +|---|---|---|---| +| Space per update | Length of the path: O(log n) in a balanced tree | O(1) worst case per update step | O(1) amortized per update step | +| Time per access step | O(1) | O(log m) | O(1) | +| Old versions' nodes | Never touched | Histories grow in place | Slots filled in place | +| Purely functional | Yes | No | No | +| Level | Full | Partial; full with an ordered version list | Partial; full by node splitting | +| Restriction | No parent or back pointers | None | Bounded in-degree | + +The restriction on path copying is real: if children point back at their parent, copying a node forces a copy of each child (its parent pointer must now lead to the copy), then of their children, and the copying spreads to the whole structure. That is why persistent trees in functional languages have no parent pointers. + +Path copying still wins in practice, for reasons the asymptotics do not show. It never writes to memory an old version can see, so readers of old versions need no synchronization (the property Section 17.7 builds on) and it works in languages with no mutation at all. A version nobody references can be reclaimed by the garbage collector, while fat nodes and node copying embed every version's history inside nodes that stay live. And it is a few lines of code. Fat nodes and node copying are the theory's answer, and the right tool when space per update is what matters, as in the point-location sweep. Chapter 24 (Section 24.9) sketches a fat-node modification log at the research level. + +## 17.4 Persistent Arrays and HAMTs Trees path-copy naturally because they are already logarithmic-depth pointer structures. Arrays do not. A persistent array cannot copy 1,000,000 elements per write. @@ -103,11 +198,358 @@ The standard solution is to stop using a flat array and use a **wide, shallow tr Update one element: copy 4 nodes (~128 pointers), share everything else. ``` +### Inside the persistent vector + +Three design decisions make this work in Clojure's `PersistentVector`, and Scala's immutable `Vector` uses the same 32-way radix layout. + +**Bit-partitioned indexing.** Nodes have 2^b children (b = 5 gives 32), and every leaf except the last is full, so an index *is* a path. Read it b bits at a time from the top: in a three-level trie, index 13,399 = `01101 00010 10111` in binary goes to slot 13 of the root, slot 2 of the next node, and slot 23 of the leaf. Each level is a shift and a mask, `(i >> level) & 31`, with no comparisons and no keys stored. + +**Path copying.** `set(i, x)` rebuilds the one node per level on that path and shares every other child pointer. + +**The tail.** The last partial leaf (up to 32 elements) is kept outside the trie, in a separate `tail` array. An append that fits copies only the tail. Only every 32nd append pushes the full tail into the trie as a new leaf, path-copying O(log₃₂ n) nodes, and when the trie is completely full the root grows a level. The last elements, which stack-like code reads most, are found without entering the trie at all. + +Here is a small version with the branching factor as a parameter. Nodes are tuples, so nothing is modified in place: + +```python +class PVector: + """Bit-partitioned persistent vector (Clojure's design) with 2**bits-way nodes. + The last, possibly partial, leaf lives in `tail`, outside the trie.""" + + def __init__(self, bits=5, count=0, shift=None, root=(), tail=()): + self.bits, self.width, self.mask = bits, 1 << bits, (1 << bits) - 1 + self.count, self.root, self.tail = count, root, tail + self.shift = bits if shift is None else shift # index bits above the leaf level + + def _new(self, count, shift, root, tail): + return PVector(self.bits, count, shift, root, tail) + + def _tail_offset(self): # index of tail[0] + if self.count < self.width: + return 0 + return ((self.count - 1) >> self.bits) << self.bits + + def __len__(self): + return self.count + + def __getitem__(self, i): + if not 0 <= i < self.count: + raise IndexError(i) + if i >= self._tail_offset(): + return self.tail[i - self._tail_offset()] + node = self.root + for level in range(self.shift, 0, -self.bits): # one chunk of bits per level + node = node[(i >> level) & self.mask] + return node[i & self.mask] + + def set(self, i, x): + if not 0 <= i < self.count: + raise IndexError(i) + off = self._tail_offset() + if i >= off: + t = self.tail + return self._new(self.count, self.shift, self.root, + t[:i - off] + (x,) + t[i - off + 1:]) + def assoc(node, level): # path copying: one new node per level + j = (i >> level) & self.mask + child = x if level == 0 else assoc(node[j], level - self.bits) + return node[:j] + (child,) + node[j + 1:] + return self._new(self.count, self.shift, assoc(self.root, self.shift), self.tail) + + def append(self, x): + if len(self.tail) < self.width: # common case: copy only the tail + return self._new(self.count + 1, self.shift, self.root, self.tail + (x,)) + # The tail is full: it becomes a leaf of the trie, and x starts a new tail. + if (self.count >> self.bits) > (1 << self.shift): # no room: grow a level + root = (self.root, self._path(self.shift, self.tail)) + return self._new(self.count + 1, self.shift + self.bits, root, (x,)) + return self._new(self.count + 1, self.shift, + self._push_tail(self.shift, self.root), (x,)) + + def _path(self, level, leaf): # fresh chain of one-child nodes + return leaf if level == 0 else (self._path(level - self.bits, leaf),) + + def _push_tail(self, level, node): + j = ((self.count - 1) >> level) & self.mask # slot on the path to the new leaf + if level == self.bits: + child = self.tail + elif j < len(node): + child = self._push_tail(level - self.bits, node[j]) + else: + child = self._path(level - self.bits, self.tail) + return node[:j] + (child,) + node[j + 1:] +``` + +The overflow test reads: after this push the trie holds `count >> bits` full leaves, and a trie whose root sits `shift` bits above the leaves has room for 2^shift of them. + +With 4-way nodes (`bits=2`) the trie gets deep quickly, which makes the structure easy to see. Appending 0, 10, ..., 200 gives 21 elements: + +``` +shift = 4, tail = (200,), tail offset 20 +root ─┬─ [0] ─┬─ (0, 10, 20, 30) indices 0..3 + │ ├─ (40, 50, 60, 70) 4..7 + │ ├─ (80, 90, 100, 110) 8..11 + │ └─ (120, 130, 140, 150) 12..15 + └─ [1] ─── (160, 170, 180, 190) 16..19 +``` + +The 21st append is the one that grew the root. Its tail (160 to 190) was full, the trie already held 4 leaves (= 2^2, full for `shift = 2`), so 20 >> 2 = 5 > 4: the old root became child 0 of a new root and a one-child path to the new leaf became child 1. Looking up index 13 = `00 11 01` takes slot 0, then slot 3, then slot 1: the value 130. `set(13, -1)` copies the root, node [0] and leaf 3, three tuples, and shares the other three leaves, node [1] and the tail: + +```python +v = PVector(bits=2) # 4-way nodes, so the trie gets deep fast +for i in range(21): + v = v.append(i * 10) +assert (v.shift, v.tail, len(v)) == (4, (200,), 21) +assert v[13] == 130 # 13 = 0b00_11_01: slots 0, 3, 1 +w = v.set(13, -1) +assert v[13] == 130 and w[13] == -1 # v is untouched +assert w.root[1] is v.root[1] and w.root[0][0] is v.root[0][0] # shared, not copied +``` + +**What "effectively constant" means.** Lookup and update cost Θ(log₃₂ n) = Θ(log₂ n / 5). That is a constant factor of 5 fewer levels than a binary tree, not a different growth rate. The claim of "effectively O(1)" rests on the fact that n is bounded in practice: with 32-bit indices there are at most 7 levels (32 bits in 5-bit chunks), and by the same logic a balanced binary tree is "effectively at most 32 levels". The concrete costs are what matter. A lookup is up to 7 dependent pointer loads where an array needs one (the top levels usually sit in cache, the lower ones often do not). An update allocates up to 7 nodes of 32 slots, a couple of hundred words, where an array writes one. Clojure and Scala offer **transient** vectors and builders for bulk construction, which mutate nodes that no other version can see yet and then freeze the result. + +The design has one hard limit: the index arithmetic requires every leaf except the last to be full, so concatenating two vectors means re-appending one of them element by element, O(n), and a real slice from the middle has to be rebuilt the same way. (Clojure's `subvec` is O(1) only because it returns a view that keeps the whole original alive.) **RRB trees** (relaxed radix balanced trees) allow some nodes to be less than full and store a small table of subtree sizes in those nodes, which gives O(log n) concatenation and splitting while keeping radix lookup on the full parts. + The **Hash Array Mapped Trie (HAMT)** applies the same structure to maps. Hash the key, then use 5 bits of the hash per level to index into a 32-wide node. The refinement that makes it space-efficient is a bitmap in each node marking which of the 32 slots are occupied, so a node with 3 children stores 3 pointers and a 32-bit mask rather than 32 mostly-null pointers. Population count on the bitmap converts a logical index to a physical one in one instruction. HAMTs are the backbone of persistent maps in Clojure, Scala, and Haskell, and the same idea appears in Erlang and in immutable-collections libraries for JavaScript. -## 17.4 Functional Data Structures +## 17.5 Persistent Queues: Amortization Meets Persistence + +The functional queue is the two-stack queue of Exercise 5.5 ([Chapter 5](../volume-1/ch05-stacks-and-queues-ordered-access-patterns.md)) built from immutable lists: a front list F, a rear list R holding the newest element first, enqueue conses onto R, dequeue takes from F, and when F runs out R is reversed to become the new F. Every element is reversed once, so n operations cost O(n): amortized O(1). Exercise 17.6 runs the experiment that breaks it. Take a version whose F is empty and whose R holds n elements, and call dequeue on that same version n times. Every call reverses all n elements and returns the result inside a new version that the caller throws away: n² work for n operations. + +The analysis failed because it is a **credit** argument. Each cheap enqueue puts a coin in the bank, and the expensive reversal spends the coins. Under persistence a version has many futures, and every future spends the same coins. No credit argument survives that, because the same savings can be withdrawn any number of times. + +### Debits instead of credits + +Okasaki's repair turns the accounting around and changes the code to match. It has two ingredients. + +1. **Lazy evaluation with memoization.** The rotation is not performed. It is stored in the new version as a **suspension**, a thunk that runs the first time anyone needs its result and caches the answer. Every version derived from that one shares the same suspension object, so the work runs at most once, however many futures reach it. +2. **Schedule the expensive work early.** Rotate as soon as R would become longer than F, building `F ++ reverse(R)` lazily. The invariant |R| ≤ |F| puts the reversed part behind |F| elements, so on any path through the version tree, |F| dequeues must happen before anything can force it. + +The accounting uses **debits**. When a suspension is created, its cost is recorded as a debt against it, and the rule is that it may only be forced after earlier operations have paid that debt off. If two futures each do their |F| dequeues, the debt is paid twice, which is harmless overpayment; memoization guarantees the real cost is incurred only once. Credits can be double-spent; debits can only be double-paid. That asymmetry is the whole idea. + +For this **banker's queue** the bookkeeping is concrete. Number the cells of F from 0 and let D(i) be the total debt on cells 0 through i. The invariant is + +> D(i) ≤ min(2i, |F| − |R|) + +- Cell 0 always carries zero debt, so the dequeue that forces it is allowed. +- An enqueue that does not rotate lowers |F| − |R| by one, so it pays off 1 debit. +- A dequeue moves every cell one place forward (lowering 2i by 2) and lowers |F| − |R| by one, so it pays off 2 debits. +- A rotation happens when |R| reaches |F| + 1, with |F| = m. Just before that enqueue, |F| = |R| = m, so the invariant forced every D(i) to 0: the old front was fully paid for. The rotation puts 1 debit on each of the first m cells (each step of the lazy append is a small suspension) and m + 1 on cell m (the reversal), so D(i) = i + 1 for i < m and D(m) = 2m + 1. The enqueue pays the debit on cell 0, leaving D(i) = i ≤ 2i and D(m) = 2m ≤ min(2m, 2m + 1). The invariant holds again. + +Every operation does O(1) unshared work and pays at most 2 debits, so the banker's queue is **O(1) amortized per operation, under any pattern of persistent use**. + +Python is strict, so laziness has to be simulated. A `Susp` holds a thunk and memoizes it, and a stream is a `Susp` whose value is `None` or a `(head, stream)` pair: + +```python +class Susp: + """A memoized thunk: the computation runs at most once, ever.""" + def __init__(self, thunk): + self.thunk, self.value = thunk, None + + def force(self): + if self.thunk is not None: + self.value, self.thunk = self.thunk(), None + return self.value + +def ready(cell): + """A stream cell that is already evaluated.""" + s = Susp(None) + s.value = cell + return s + +EMPTY = ready(None) # a stream is a Susp whose value is None or (head, stream) +steps = 0 # counts reversal work, for the experiments below + +def append(s, t): + """Lazy s ++ t: each cell costs O(1), paid only when that cell is forced.""" + def cell(): + c = s.force() + return t.force() if c is None else (c[0], append(c[1], t)) + return Susp(cell) + +def reverse(lst): + """Lazy but monolithic: the first force reverses the whole cons list.""" + def run(): + global steps + out, rest = EMPTY, lst + while rest is not None: + steps += 1 + out, rest = ready((rest[0], out)), rest[1] + return out.force() + return Susp(run) + +# A banker's queue is (len_f, front stream, len_r, rear cons list), len_r <= len_f. +EMPTY_Q = (0, EMPTY, 0, None) + +def check(lf, f, lr, r): + if lr <= lf: + return (lf, f, lr, r) + return (lf + lr, append(f, reverse(r)), 0, None) # rotate early, lazily + +def enqueue(q, x): + lf, f, lr, r = q + return check(lf, f, lr + 1, (x, r)) + +def dequeue(q): + lf, f, lr, r = q + x, rest = f.force() + return x, check(lf - 1, rest, lr, r) +``` + +Now attack it the way Exercise 17.6 attacks the naive queue. Enqueue 0 to 1022, which rotates at |R| = 1, 2, 4, ..., 512 and leaves |F| = 1023, |R| = 0. Dequeue down to the version p whose next dequeue must force the 512-element reversal, and replay that dequeue from p a thousand times: + +```python +q = EMPTY_Q +for i in range(1023): + q = enqueue(q, i) # rotations at |R| = 1, 2, 4, ..., 512 +assert steps == 0 # nothing has been reversed yet: all lazy +p = q +for i in range(511): + x, p = dequeue(p) # p: the 512-element reversal is next in line +assert steps == 511 # the smaller reversals, 1 + 2 + ... + 256 +for _ in range(1000): + x, _ = dequeue(p) # replay the expensive dequeue 1000 times + assert x == 511 +assert steps == 1023 # the big reversal ran once, not 1000 times +``` + +Every element was reversed exactly once in total. Change `force` to rerun the thunk on every call instead of caching it, and the replay loop alone does 512,000 reversal steps, 512 per call: the failure of the naive queue again. Memoization alone is not enough either: Exercise 17.8 keeps it but rotates only when F is empty, and a replay attack comes back. The two ingredients only work together. + +### Real-time queues + +A worst-case bound needs no accounting at all, and no usage pattern can break it: if no operation ever costs more than c, replaying one costs at most c too. Hood and Melville (1981) made the functional queue O(1) worst case by doing the reversal a few steps at a time. Okasaki (1995) found a much simpler construction from the same lazy pieces: + +- **Make the rotation incremental.** `rotate(f, r, acc)` computes `f ++ reverse(r) ++ acc` one O(1) cell at a time, moving one element of r onto the accumulator for each cell of f. It needs |r| = |f| + 1 so that the reversal finishes exactly when f does, and that is exactly when the banker's queue rotates. +- **Keep a schedule.** A pointer s to the first unevaluated cell of the front, with |s| = |F| − |R|. Every operation forces exactly one cell of s and advances it. When s runs out, |R| = |F| + 1 and the next rotation starts. + +The schedule forces each cell of the front before any dequeue reaches it, so no operation does more than one O(1) step of rotation: **O(1) worst case** per operation, persistent or not. + +```python +def rotate(f, r, acc): + """Lazy f ++ reverse(r) ++ acc, one O(1) step per cell. Needs |r| == |f| + 1.""" + def cell(): + global steps + steps += 1 + c = f.force() + y, r_rest = r + if c is None: # r has exactly one element left + return (y, acc) + return (c[0], rotate(c[1], r_rest, ready((y, acc)))) + return Susp(cell) + +# A real-time queue is (front stream, rear cons list, schedule), |schedule| == |f| - |r|. +RT_EMPTY = (EMPTY, None, EMPTY) + +def exec1(f, r, s): + c = s.force() # force exactly one cell of the front + if c is not None: + return (f, r, c[1]) + f = rotate(f, r, EMPTY) # schedule used up: |r| == |f| + 1 + return (f, None, f) + +def rt_enqueue(q, x): + f, r, s = q + return exec1(f, (x, r), s) + +def rt_dequeue(q): + f, r, s = q + x, rest = f.force() + return x, exec1(rest, r, s) +``` + +A test that operates on randomly chosen old versions, checks every answer against a plain list, and measures the most rotation work any single call does: + +```python +import random + +versions = [(RT_EMPTY, [])] # (queue, the list it should hold) +worst = 0 +for _ in range(20000): + q, ref = random.choice(versions) # operate on ANY old version + before = steps + if ref and random.random() < 0.45: + x, q2 = rt_dequeue(q) + assert x == ref[0] + versions.append((q2, ref[1:])) + else: + versions.append((rt_enqueue(q, len(versions)), ref + [len(versions)])) + worst = max(worst, steps - before) +assert worst == 1 # never more than one rotate step per call +``` + +In practice the banker's queue is usually faster, because it does less bookkeeping per operation; the real-time queue is for code where a latency bound matters more than throughput. Both are why a lazy functional language can offer an O(1) persistent queue without any mutation. + +## 17.6 Finger Trees + +A deque, an indexable sequence, a priority queue, an ordered set and an interval tree are usually five structures. Hinze and Paterson's **2-3 finger tree** (2006) is one persistent structure that provides all five, by changing one parameter. + +**Shape.** A finger tree is empty, a single element, or a `Deep` node holding a **prefix** and a **suffix** of 1 to 4 elements each (the "fingers"), plus a **middle** finger tree whose elements are 2-3 nodes (`Node2` or `Node3`) of the outer element type. The middle's middle holds nodes of nodes, so level k of the spine holds complete 2-3 trees of depth k. The ends of the sequence sit at the top of the structure, which is the point: the elements touched most are the cheapest to reach. + +To push x onto the back, add it to the suffix if the suffix has fewer than 4 elements. If the suffix is full, `[a, b, c, d]`, it becomes `[d, x]` and `Node3(a, b, c)` is pushed onto the back of the middle tree, by the same rule one level down. Pushing 1 to 10 in order: + +``` +after 5: Deep [1] Empty [2, 3, 4, 5] +after 6: Deep [1] (Single N3(2,3,4)) [5, 6] +after 9: Deep [1] (Deep [N3(2,3,4)] Empty [N3(5,6,7)]) [8, 9] +after 10: Deep [1] (Deep [N3(2,3,4)] Empty [N3(5,6,7)]) [8, 9, 10] +``` + +**Costs.** A push reaches the middle only when a digit is full, and it leaves that digit with two elements, so that level overflows again only after three more pushes; deeper levels are reached geometrically less often, like the carries of a counter. Pushes and pops at either end are **amortized O(1)**. Hinze and Paterson keep the middle tree lazy and use the debit argument of Section 17.5, so these bounds hold under persistent use. **Concatenation** is O(log(min(n₁, n₂))) and **splitting** at position i is O(log(min(i, n − i))); both work down the spine, regrouping the loose digit elements into 2-3 nodes at each level. + +**Measures.** Each node caches a **measure** of its subtree, taken from a **monoid**: an associative operation ⊕ with an identity element. The measure of a node is the ⊕ of its children's measures, left to right, so it is maintained in O(1) whenever a node is built. A `split` with a predicate that is false and then true as elements are added left to right walks down the tree, skipping every digit and subtree whose cached measure does not flip the predicate. + +With the size measure (each element measures 1, ⊕ is +), finding index 6 (0-based, the element 7) in the tree above goes: the outer prefix [1] measures 1, which is ≤ 6, so skip it and look for index 5 in the middle; the middle's prefix N3(2,3,4) measures 3, which is ≤ 5, so skip it and look for index 2; the middle's middle is empty; the middle's suffix starts with N3(5,6,7), and index 2 inside it is 7. Three cached measures were consulted and no element was scanned one by one. + +Changing the monoid changes the structure: + +| Element measure, ⊕, identity | Split predicate | Result | +|---|---|---| +| 1, +, 0 | running size > i | Indexable sequence: index, split and concatenate in O(log n). This is Haskell's `Data.Sequence`. | +| priority, max, −∞ | running max ≥ max of the whole tree | Max-priority queue: the root's measure is the maximum, and split finds and removes it in O(log n). | +| key, "rightmost key", no key | running key ≥ k | Ordered sequence (elements kept sorted): insert, delete and search by key in O(log n), and merge. | +| (low, high), componentwise max, (−∞, −∞) | running max high ≥ q | Interval tree (intervals sorted by low endpoint): the first interval reaching q contains q if its low endpoint is ≤ q, and otherwise no interval does. | + +The table is the real contribution. The tree code is written once against an abstract monoid, and each structure is a few lines of instance declaration. Here is what `split` computes, written as a linear scan so the semantics are easy to check; the finger tree computes exactly this in O(log n) by skipping subtrees whose measures cannot flip the predicate: + +```python +from collections import namedtuple + +Monoid = namedtuple("Monoid", "identity op measure") + +def split(m, pred, xs): + """What a finger tree split computes: the first x at which pred becomes true + on the running measure. The tree does it in O(log n) by skipping subtrees + whose cached measure cannot flip pred; this reference version scans.""" + acc = m.identity + for i, x in enumerate(xs): + acc = m.op(acc, m.measure(x)) + if pred(acc): + return xs[:i], x, xs[i + 1:] + return xs, None, [] + +size = Monoid(0, lambda a, b: a + b, lambda x: 1) +priority = Monoid(float("-inf"), max, lambda job: job[1]) +interval = Monoid((float("-inf"), float("-inf")), # (largest low, largest high) + lambda a, b: (max(a[0], b[0]), max(a[1], b[1])), + lambda iv: iv) + +assert split(size, lambda n: n > 3, list("finger")) == (list("fin"), "g", list("er")) + +jobs = [("a", 3), ("b", 9), ("c", 4), ("d", 9)] +top = max(p for _, p in jobs) # in the tree: the root's cached measure, O(1) +assert split(priority, lambda p: p >= top, jobs)[1] == ("b", 9) + +ivs = [(1, 4), (2, 3), (5, 9), (6, 7)] # kept sorted by low endpoint +_, hit, _ = split(interval, lambda m: m[1] >= 6, ivs) +assert hit == (5, 9) and hit[0] <= 6 # first interval reaching 6; it contains 6 +``` + +The low-endpoint half of the interval measure is not used by this query. It is the ordered-sequence key, used to split by low endpoint when inserting a new interval in its sorted place. + +**In practice.** Haskell's `Data.Sequence` (in the `containers` library) is a finger tree specialised to the size measure, with O(1) length, O(log(min(i, n − i))) indexing and O(log(min(n₁, n₂))) concatenation, and the `fingertree` package exposes the general measured version. The price is constant factors: each `Deep` node, its digits and their cached measures are several allocations per element, so for plain stack or queue use, a list or the banker's queue is faster. The finger tree is for when one sequence needs several of these operations at once. + +## 17.7 Functional Data Structures Functional languages favor immutable structures: - Thread-safe by default @@ -129,21 +571,31 @@ Each of those bullets deserves unpacking, because they are the practical reasons **Where persistence earns its cost:** -- **Version control.** Git is a persistent data structure. Every commit is a new root over a Merkle tree of directory nodes, sharing every unchanged subtree, which is exactly why committing a one-line change to the Linux kernel does not copy the kernel. -- **Databases.** MVCC (multi-version concurrency control) in PostgreSQL is partial persistence: readers see a consistent snapshot at their transaction's start while writers proceed, without either blocking the other. CouchDB and Datomic go further and keep every version permanently. +- **Version control.** Git is a persistent data structure, which is exactly why committing a one-line change to the Linux kernel does not copy the kernel (details below). +- **Databases.** MVCC (multi-version concurrency control) in PostgreSQL is partial persistence: readers see a consistent snapshot at their transaction's start while writers proceed, without either blocking the other (details below). CouchDB and Datomic go further and keep every version permanently. - **Filesystems.** ZFS and Btrfs are copy-on-write; a snapshot is just a retained old root, which is why it is instant and initially free. - **UI frameworks.** React's rendering model assumes immutable props, so change detection is a reference comparison rather than a deep traversal. - **Debugging.** Time-travel debuggers replay old versions directly, because they still exist. **The cost side**, stated plainly: 2–4× slower on write-heavy single-threaded workloads, higher memory use and allocation churn, and worse cache locality than a flat array. The wide-trie designs mitigate that last one but do not eliminate it. Persistence is the right default in concurrent and versioned settings, and the wrong one in a tight numerical loop. -## 17.5 Historical Context +### Persistence in the wild: Git and MVCC + +**Git's object store** is built from four object types, each named by the hash of its content (SHA-1, or SHA-256 in repositories created with that option). A *blob* is a file's bytes, a *tree* is a directory listing of (mode, name, hash) entries, a *commit* names one root tree and its parent commits, and a *tag* names another object. Edit `src/lib/util.c` and commit, and Git writes a new blob, new trees for `src/lib`, `src` and the root, and a new commit. That is path copying, with the directory path as the path; every other blob and tree is shared, by hash, with the parent commit. + +Naming objects by content adds two things path copying alone does not give. Sharing is global rather than only along history: identical files anywhere, in any commit, are one blob, and reverting a file reuses its old blob. And equal hashes mean equal subtrees, which makes the store a **Merkle DAG** (the structure Dynamo uses to compare replicas in [Chapter 31](../volume-5/ch31-real-world-case-studies.md)): `git diff` skips any pair of subtrees whose hashes match without opening them, and `git fetch` transfers only the objects the other side lacks. Merge commits have two parents, so the history is confluent (Exercise 17.1). A branch is a mutable name for an immutable root, the same atomic root pointer as above, and `git gc` is a garbage collector: it deletes objects that no branch, tag or reflog entry can reach. (Packfiles also delta-compress objects on disk; that is storage compression, separate from the structural sharing.) + +**MVCC** keeps old versions of rows so that readers can work from a snapshot. PostgreSQL never overwrites a row in an UPDATE: it writes a new row version, and each version records the transaction that created it (`xmin`) and the one that superseded or deleted it (`xmax`). A reader compares those stamps against its snapshot to decide which version it sees. That is the fat node method of Section 17.3 applied per row, version-stamped values with a lookup for the newest one visible at the reader's version, and like fat nodes the history accumulates in place, so PostgreSQL needs `VACUUM` to reclaim versions no snapshot can still see. InnoDB and Oracle instead update rows in place and keep old versions in undo logs, rebuilding an older row by applying undo records backwards. LMDB takes the path-copying route: its B+ tree is copy-on-write, a write transaction copies the root-to-leaf paths it touches and publishes a new root, and a reader keeps using the root it started with. Spanner's timestamped row versions and Delta Lake's versioned table log are covered in [Chapter 31](../volume-5/ch31-real-world-case-studies.md) (Sections 31.1 and 31.4). -Driscoll, Sarnak, Sleator, and Tarjan's 1986 paper "Making Data Structures Persistent" is the foundational work: it established the partial/full/confluent taxonomy and proved that any pointer-based structure with bounded in-degree can be made partially persistent with O(1) amortized space overhead per update. A much stronger and more general result than the path-copying technique most implementations actually use. +## 17.8 Historical Context -Chris Okasaki's *Purely Functional Data Structures* (1998), which grew out of his 1996 CMU thesis, addressed the complementary question: which structures can be implemented efficiently *without any mutation at all*? His treatment of amortization under persistence is the subtle part. The usual banker's argument breaks when an expensive operation can be re-executed by replaying an old version, and Okasaki's solution using lazy evaluation and memoization is why the book remains standard reading. +Driscoll, Sarnak, Sleator, and Tarjan's 1986 paper "Making Data Structures Persistent" (journal version 1989) is the foundational work. It defined partial and full persistence and introduced fat nodes, node copying and node splitting, proving that any pointer-based structure with bounded in-degree can be made partially or fully persistent with O(1) amortized time and space per update step and no slowdown on access. That is a much stronger and more general result than the path-copying technique most implementations actually use. Sarnak and Tarjan applied it the same year to planar point location with persistent search trees. Confluent persistence was named later, by Driscoll, Sleator and Tarjan in their work on catenable lists (1994), and Brodal (1996) made the update cost of bounded-degree partial persistence O(1) in the worst case. -Phil Bagwell introduced the Hash Array Mapped Trie in 2001. Rich Hickey built Clojure's collections on it in 2007, which more than anything else moved persistent structures from a functional-programming specialty into general practice. +Chris Okasaki's *Purely Functional Data Structures* (1998), which grew out of his 1996 CMU thesis, addressed the complementary question: which structures can be implemented efficiently *without any mutation at all*? His treatment of amortization under persistence is the subtle part. The usual credit argument breaks when an expensive operation can be re-executed by replaying an old version, and Okasaki's solution using lazy evaluation and memoization (Section 17.5) is why the book remains standard reading. Hood and Melville had made functional queues O(1) worst case in 1981 by spreading the reversal over many operations; Okasaki's 1995 real-time queue reached the same bound much more simply with lazy evaluation and a schedule. + +Finger search trees, which keep a "finger" at a position of interest so that nearby searches are fast, go back to Guibas, McCreight, Plass and Roberts (1977). Ralf Hinze and Ross Paterson's 2-3 finger trees (2006) brought the idea into purely functional programming, with a monoid annotation that made one structure serve as sequence, priority queue and search tree; Haskell's `Data.Sequence` is built on it. + +Phil Bagwell introduced the Hash Array Mapped Trie in 2001. Rich Hickey built Clojure's collections on it and on the 32-way bit-partitioned vector in 2007, which more than anything else moved persistent structures from a functional-programming specialty into general practice. Bagwell and Tiark Rompf's RRB trees (2011) added efficient concatenation to those vectors. Git, written by Linus Torvalds in 2005, put a content-addressed persistent structure in front of most working programmers. ## Exercises @@ -151,7 +603,7 @@ Difficulty: ★ check your understanding · ★★ apply it · ★★★ stretch **17.1 ★ Which level of persistence?** Classify each system as partial, full, or confluent persistence, and name the shape of its version history (line, tree, or DAG). -1. PostgreSQL MVCC, as described in 17.4: a transaction reads the snapshot that existed when it started, and writers only ever modify the current state. +1. PostgreSQL MVCC, as described in 17.7: a transaction reads the snapshot that existed when it started, and writers only ever modify the current state. 2. An editor with an undo *tree* (Vim and Emacs both have one): you can undo back to any earlier state, make a new edit there, and the abandoned branch stays reachable. 3. Git, including merge commits. 4. A ZFS filesystem with read-only snapshots. @@ -335,7 +787,7 @@ def dequeue(q): return x, (front, back) ``` -Ephemerally, this queue is O(1) amortized: each element is moved by `reverse` once. Enqueue 0 through n−1 into `(None, None)` to get version `q`. Then (a) dequeue all n elements in a chain, always using the latest version, and (b) call `dequeue(q)` n times on the *same* version `q`. How many `reverse` steps does each pattern take? Explain what went wrong with the amortized argument, and how Okasaki's approach from 17.5 repairs it. +Ephemerally, this queue is O(1) amortized: each element is moved by `reverse` once. Enqueue 0 through n−1 into `(None, None)` to get version `q`. Then (a) dequeue all n elements in a chain, always using the latest version, and (b) call `dequeue(q)` n times on the *same* version `q`. How many `reverse` steps does each pattern take? Explain what went wrong with the amortized argument, and how Okasaki's approach from Section 17.5 repairs it.
Hint @@ -356,7 +808,97 @@ Measured with n = 1000: 1,000 steps for (a), 1,000,000 for (b). The amortized argument charges the expensive reversal to the n cheap enqueues that preceded it, which works only if that "credit" is spent once. Persistence lets you return to version `q` as often as you like, and each return spends the same credit again. Any amortized bound that relies on an expensive operation happening rarely is vulnerable in the same way. -Okasaki's fix is to make the expensive work *shared* rather than repeated. The reversal is created as a lazy suspension stored inside the version itself and memoized when it is first forced, and the queue creates it early (as soon as the back list grows longer than the front) so that enough cheap operations have already paid for it. Every version that descends from `q` holds the *same* suspension object, so whichever one forces it first pays, and the rest reuse the memoized result. The debt is paid once per version, not once per use, and O(1) amortized holds even under persistence. This is the "lazy evaluation and memoization" from 17.5. +Okasaki's fix is to make the expensive work *shared* rather than repeated. The reversal is created as a lazy suspension stored inside the version itself and memoized when it is first forced, and the queue creates it early (as soon as the back list grows longer than the front) so that enough cheap operations have already paid for it. Every version that descends from `q` holds the *same* suspension object, so whichever one forces it first pays, and the rest reuse the memoized result. The debt is paid once per version, not once per use, and O(1) amortized holds even under persistence. Section 17.5 builds this queue (the banker's queue) and proves the bound. + +
+ +**17.7 ★★ Index arithmetic in a 32-way vector.** A `PVector` from Section 17.4 with the default `bits=5` holds n = 1,000,000 elements, built by appending 0, 1, 2, ... in order. + +1. Where does the tail start, how many elements does it hold, what is `shift`, and how many children does the root have? +2. Which slot does `v[777_777]` take at each level? +3. How many nodes does `v.set(777_777, x)` copy, and how many slots do the copies hold in total? +4. Of the 1,000,000 appends, how many pushed a tail into the trie, and how many grew a new root level? + +
+Solution + +1. The tail offset is ((1,000,000 − 1) >> 5) << 5 = 31,249 × 32 = 999,968, so the tail holds the 32 elements 999,968 to 999,999. The trie holds the other 999,968 elements in 31,249 full leaves. Since 32² = 1,024 < 31,249 ≤ 32³ = 32,768, three levels of internal nodes sit above the leaves: `shift = 15`. Each root child covers 1,024 leaves, so the root has ⌈31,249 / 1,024⌉ = 31 children. +2. 777,777 is below the tail offset, so it is in the trie. In binary it is `10111 10111 10001 10001`: slot 23 of the root, slot 23 of the next node, slot 17 of the next, and slot 17 of the leaf. Check: 23 × 32,768 + 23 × 1,024 + 17 × 32 + 17 = 777,777. +3. One node per level: the root (31 slots), two internal nodes (32 each) and the leaf (32), so 4 nodes and 127 slots. A mutable array writes 1 slot; copying the whole vector would write 1,000,000. +4. An append pushes the tail exactly when the tail is full, which happens when the current count is a positive multiple of 32: counts 32, 64, ..., 999,968, so 31,249 pushes, one per leaf. The root grows when the number of leaves passes 2^shift: from 32 to 33 leaves (shift 5 to 10) and from 1,024 to 1,025 (shift 10 to 15), so twice. The other 968,751 appends copied only the tail. + +
+ +**17.8 ★★★ Memoization is not enough.** Keep `Susp`, `append`, `reverse`, `enqueue` and `dequeue` from Section 17.5, but change `check` to rotate only when the front is empty, the way the naive queue does. Used single-threaded, this is still O(1) amortized. Find a persistent usage pattern that makes it cost Θ(n) per operation, measure it for n = 1000, and explain why the banker's `check`, which rotates as soon as |R| > |F|, is immune to the same pattern. + +
+Hint + +Memoization only saves work when two futures force the *same* suspension. Which call creates the rotation suspension, and how soon after can it be forced? + +
+ +
+Solution + +Enqueue 0 to n − 1. The first enqueue sees an empty front and rotates [0] into it; the rest go to the rear, leaving |F| = 1, |R| = n − 1. Now, from that same version q, dequeue twice, over and over. The first dequeue empties the front, so its `check` builds a rotation suspension inside the version it returns. That is a *new* object on every call, shared with no other future, so memoization never gets a chance. The second dequeue forces it at once: n − 1 reversal steps per round. + +```python +def check(lf, f, lr, r): # replaces the check of Section 17.5 + if lf > 0: + return (lf, f, lr, r) + return (lr, append(f, reverse(r)), 0, None) # rotate only when F is empty + +n = 1000 +q = EMPTY_Q +for i in range(n): + q = enqueue(q, i) +assert (q[0], q[2]) == (1, n - 1) # 0 was rotated into the front at once +steps = 0 +for _ in range(n): + _, q1 = dequeue(q) # empties the front: builds a NEW rotation + dequeue(q1) # ...and forces it immediately +assert steps == 999_001 # 999 per round, plus 1 for the first rotation +``` + +The banker's `check` defeats this because of where it puts the work. A rotation created by any operation sits behind all |F| elements of the front, so a future must perform |F| more dequeues before it can force that rotation, and those dequeues pay its debits. A pattern that keeps going back to q and creating fresh rotations never gets far enough to force them. Running the same loop with the banker's `check` (where q has |F| = 511 and |R| = 489) does 3 reversal steps in total. Laziness makes repeated work shareable; early scheduling guarantees that unshared work has been paid for before it runs. + +
+ +**17.9 ★★ Pick the measure.** A music player keeps a playlist as a finger tree of `(title, seconds)` songs, and needs both (a) "which song is playing t seconds into the playlist, and how far into it?" and (b) "what is the i-th song?" in O(log n), from one tree. Give the monoid and the two split predicates, and check them with the reference `split` from Section 17.6 on `[("Intro", 95), ("Blue", 240), ("Static", 185), ("Coda", 60)]`. + +
+Hint + +A pair of monoids, combined componentwise, is again a monoid. + +
+ +
+Solution + +Measure each song as the pair (1, seconds), combine pairs by adding componentwise, with identity (0, 0). Associativity and the identity law hold in each component, so they hold for the pair. Every song adds at least 1 to the count and a non-negative duration, so the running totals never decrease and each predicate below flips from false to true exactly once, which is what `split` needs. + +- (a) Split where the running seconds exceed t. The song found is playing, and it started at the total seconds of the left part, which the tree has as the measure of that part. +- (b) Split where the running count exceeds i. + +```python +songs = [("Intro", 95), ("Blue", 240), ("Static", 185), ("Coda", 60)] # (title, seconds) +both = Monoid((0, 0), lambda a, b: (a[0] + b[0], a[1] + b[1]), + lambda song: (1, song[1])) # (count, total seconds) + +def playing_at(t): # (a): the song playing t seconds in + left, song, _ = split(both, lambda m: m[1] > t, songs) + played = sum(s for _, s in left) # in the tree: the measure of `left` + return song[0], t - played # title, and how far into it we are + +assert playing_at(0) == ("Intro", 0) +assert playing_at(95) == ("Blue", 0) +assert playing_at(400) == ("Static", 65) +assert split(both, lambda m: m[0] > 2, songs)[1][0] == "Static" # (b): song index 2 +``` + +At t = 400 the running seconds are 95, 335, 520: the first to exceed 400 is "Static", which started at 335, so it is 65 seconds in. The same tree also supports moving a song (split it out, concatenate it elsewhere) in O(log n) while keeping both answers correct, because every node's cached pair is rebuilt as the tree is reassembled.
@@ -366,3 +908,5 @@ Okasaki's fix is to make the expensive work *shared* rather than repeated. The r - [Chapter 18: Concurrent Data Structures](ch18-concurrent-data-structures.md). The concurrency hazards immutability removes outright - [Chapter 7: Binary Search Trees](../volume-1/ch07-binary-search-trees.md). The BST being made persistent here +- [Chapter 5: Stacks and Queues](../volume-1/ch05-stacks-and-queues-ordered-access-patterns.md). The two-stack queue whose amortized bound Section 17.5 rebuilds to survive persistence +- [Chapter 31: Real-World Case Studies](../volume-5/ch31-real-world-case-studies.md). MVCC in Spanner and the versioned table log of Delta Lake diff --git a/src/volume-3/index.md b/src/volume-3/index.md index 6f071db..96175e0 100644 --- a/src/volume-3/index.md +++ b/src/volume-3/index.md @@ -7,7 +7,7 @@ The structures in Volumes I and II assume a single machine, a single thread, exa | Answers must be exact | [14: Probabilistic Data Structures](ch14-probabilistic-data-structures.md) | Bloom filters, cuckoo filters, HyperLogLog and Count-Min trade a controlled error rate for huge savings in memory | | Keys are one-dimensional | [15: Spatial and Geometric Data Structures](ch15-spatial-and-geometric-data-structures.md) | KD-trees, quadtrees, R-trees and geohashes answer "what is near this point?" | | Memory access is uniform | [16: External Memory and Cache-Oblivious Structures](ch16-external-memory-and-cache-oblivious-structures.md) | Count block transfers instead of operations, and design layouts that are fast at every level of the memory hierarchy | -| Updates destroy the old version | [17: Persistent Data Structures](ch17-persistent-data-structures.md) | Path copying and structural sharing keep every version alive cheaply, the basis of functional languages and MVCC | +| Updates destroy the old version | [17: Persistent Data Structures](ch17-persistent-data-structures.md) | Path copying, fat nodes and structural sharing keep every version alive cheaply; persistent vectors, queues and finger trees; the basis of functional languages, Git and MVCC | | One thread at a time | [18: Concurrent Data Structures](ch18-concurrent-data-structures.md) | Locks, compare-and-swap, the ABA problem, and when lock-free is worth its complexity | | The textbook is the state of the art | [19: Emerging and Specialized Structures](ch19-emerging-and-specialized-structures.md) | Succinct structures, learned indexes, vector search, and why some theoretical winners lose in practice | diff --git a/src/volume-4/ch25-complete-selection-guide-and-complexity-reference.md b/src/volume-4/ch25-complete-selection-guide-and-complexity-reference.md index 362d1fb..44d582f 100644 --- a/src/volume-4/ch25-complete-selection-guide-and-complexity-reference.md +++ b/src/volume-4/ch25-complete-selection-guide-and-complexity-reference.md @@ -1,20 +1,33 @@ # Chapter 25: Complete Selection Guide and Complexity Reference +This chapter is for the moment you have a problem and need a structure. Section 25.1 maps common needs to choices, split by whether the data is static or changing. Sections 25.2 and 25.3 are the reference tables. Section 25.4 gives a short decision procedure for when no row of the matrix fits exactly, Section 25.5 works through six realistic selection problems end to end, and Section 25.6 lists the mistakes that come up again and again in code review. + ## 25.1 Data Structure Selection Matrix -| Need | Primary Choice | CP Alternative | Research Alternative | -|------|---------------|-----------------|----------------------| -| Range sum/query | Fenwick Tree | Segment Tree | Succinct Range Sum | -| Range min/max | Segment Tree | Sparse Table | Range Min Query | -| K-th order stat | Wavelet Tree | Merge Sort Tree | Wavelet Matrix | -| Path queries (tree) | HLD + SegTree | Link-Cut Tree | Euler Tour Tree | -| String search | Trie | Suffix Automaton | FM-Index | -| Palindromes | Palindromic Tree | Hash + binary | LCS-based | -| Dynamic connectivity | DSU (offline) | HDT (Holm–de Lichtenberg–Thorup) | Euler Tour Trees | -| Priority queue | Binary Heap | Fibonacci Heap | Buffered Heap | -| Ordered statistics | Order Statistic Tree | Treap | van Emde Boas | -| Approx membership | Bloom Filter | Cuckoo Filter | Quotient Filter | -| Approx counting | HyperLogLog | Count-Min Sketch | Count Sketch | +Most selection questions turn on one distinction first: is the data **static** (built once, queried many times) or does it **change** between queries? Static data admits simpler, faster, smaller structures, and that column is often the right answer even when it looks too simple. + +| Need | Static data | With updates | Notes | +|------|-------------|--------------|-------| +| Lookup by exact key | Sorted array + binary search; perfect hashing for a fixed key set | Hash table (Robin Hood or Swiss table, [Chapter 12](../volume-2/ch12-hash-tables.md)) | A hash table gives up ordering; if you will ever need "next key" or a range, see the next row | +| Ordered map: successor, range scans | Sorted array | Red-black tree or skip list in memory; B+ tree on disk | Sorted arrays win for read-heavy data even with occasional bulk rebuilds | +| Integer keys below u: predecessor | Sorted array | B-tree or radix tree in practice; vEB or y-fast trie in theory ([Chapter 24](ch24-research-grade-data-structures.md)) | The O(log log u) structures rarely beat a cache-friendly B-tree below about 10⁷ keys | +| Repeated minimum or maximum | Sorted array | Binary heap (4-ary is often faster); indexed heap if you need decrease-key; radix heap for monotone integer keys | A balanced BST also works and supports deletion of arbitrary keys | +| Range sum | Prefix sums, O(1) query | Fenwick tree (point updates); segment tree with lazy propagation (range updates) | | +| Range minimum or maximum | Sparse table, O(1) query; Fischer-Heun RMQ in 2n + o(n) bits | Segment tree | Idempotence (min(x, x) = x) is what lets a sparse table use overlapping windows | +| k-th smallest overall, rank of a key | Sorted array | Order-statistic tree; Fenwick tree over compressed values | Redis sorted sets use a skip list with span counts | +| k-th smallest in a subarray a[l..r] | Wavelet tree or wavelet matrix | Offline techniques, or a Fenwick tree of order-statistic trees in O(log² n) | | +| Path or subtree queries on a tree | Heavy-light decomposition + segment tree | Link-cut tree when edges are linked and cut | Euler tour + segment tree handles subtree aggregates | +| Connectivity | Union-find, when edges are only added | Offline with deletions: rollback DSU over a segment tree of time; online: HDT (research) | | +| Find one pattern in a text | KMP, Z-algorithm, or the language's built-in search | | Rabin-Karp when many windows must be compared | +| Find many patterns in one pass | Aho-Corasick | | | +| Many queries against one fixed text | Suffix array + LCP; FM-index when it must be compressed | Suffix automaton supports appending | | +| Palindromes | Manacher's algorithm (all maximal palindromes in O(n)) | Palindromic tree (distinct palindromes, append-only) | | +| Approximate membership | Bloom filter; xor filter for a fixed set | Cuckoo filter (supports deletion); quotient filter | | +| Count of distinct items | HyperLogLog | HyperLogLog | Mergeable across machines | +| Item frequencies, heavy hitters | Count-Min sketch; Space-Saving for top-k | Same | | +| Quantiles over a stream | t-digest, KLL | Same | | +| Cache | | LRU (hash map + doubly linked list); W-TinyLFU for skewed workloads | [Chapter 29](../volume-5/ch29-system-design-as-data-structure-composition.md) | +| Text being edited | | Piece table or rope; gap buffer for a single cursor | [Chapter 13](../volume-2/ch13-string-data-structures.md) | ## 25.2 Complete Complexity Reference @@ -65,6 +78,132 @@ Each paradigm is defined by a bookkeeping question it must answer repeatedly, an The recurring trap: greedy is only correct when the problem has the matroid property or an equivalent exchange argument. Without it, greedy produces plausible wrong answers, which is worse than obviously wrong ones, because they pass casual testing. +## 25.4 A Decision Procedure + +When no row of the matrix fits exactly, five questions, asked in order, usually narrow the choice to one or two candidates. + +1. **What are the operations, and in what proportion?** Write them down with rough frequencies: "10⁶ lookups per second, 10³ inserts per second, a range scan per minute". Most bad choices come from optimising an operation that is rare. A structure that makes the common operation O(1) and the rare one O(n) is often right. +2. **Is the data static, append-only, or fully dynamic?** Static data allows sorted arrays, sparse tables, perfect hashing and succinct structures, all of which are smaller and faster than their dynamic counterparts. Append-only data allows logs, LSM trees and suffix automata. +3. **Does order matter?** If any query mentions "next", "range", "smallest", "top" or "before", you need an ordered structure (sorted array, balanced tree, B-tree, skip list, heap). If every query is "is this key present, and what is its value", a hash table is almost always the answer. +4. **Does it fit in memory, and on one machine?** If not, the cost model changes from operations to block transfers ([Chapter 16](../volume-3/ch16-external-memory-and-cache-oblivious-structures.md)): B+ trees and LSM trees on one machine, partitioned structures across several ([Chapter 27](../volume-5/ch27-distributed-data-structures.md)). +5. **Can the answer be approximate?** If a small, bounded error is acceptable, a probabilistic structure ([Chapter 14](../volume-3/ch14-probabilistic-data-structures.md)) can be thousands of times smaller. If it must be exact and the exact structure fits in memory, use the exact one. + +
+{{#include ../images/selection-flowchart.svg}} +
Questions 2 to 5 as a flowchart, for the common case of storing keys and looking them up. It is a starting point, not a verdict; Section 25.5 shows how workload details change the answer.
+
+ +After choosing, check the answer against three practical constraints the asymptotics ignore: memory per element (a Python dict entry costs around 100 bytes once you include the key and value objects, so 50 million entries need about 5 GB), worst-case latency (amortized and expected bounds allow occasional slow operations), and whether a well-tested library already provides it ([Chapter 22](../volume-3/ch22-practical-considerations.md)). + +## 25.5 Worked Selection Problems + +Each problem states the workload, the choice, the cost, and why the obvious alternatives lose. + +### Autocomplete over a fixed vocabulary + +**Workload.** Ten million product names, each with a popularity score, rebuilt nightly. Each keystroke asks for the 10 most popular names starting with the typed prefix, at thousands of queries per second. + +**Choice.** The data is static, so sort the names. All names with a given prefix form one contiguous block of the sorted array, found with two binary searches. Inside the block, the top 10 by popularity come from a sparse table of "index of the maximum score" (Section 23.11) and a heap: take the maximum of the block, split the block around it, push the maximum of each half, and repeat 10 times. + +```python +import heapq +from bisect import bisect_left + + +class Autocomplete: + """Top-k most popular completions of a prefix, over a fixed vocabulary.""" + + def __init__(self, words_with_scores): + pairs = sorted(words_with_scores) # sort by word + self.words = [w for w, _ in pairs] + self.score = [s for _, s in pairs] + n = len(pairs) + # Sparse table of argmax over the scores (Chapter 23.11). + self.table = [list(range(n))] + j = 1 + while (1 << j) <= n: + prev, half = self.table[-1], 1 << (j - 1) + row = [] + for i in range(n - (1 << j) + 1): + a, b = prev[i], prev[i + half] + row.append(a if self.score[a] >= self.score[b] else b) + self.table.append(row) + j += 1 + + def _argmax(self, lo, hi): # best index in [lo, hi) + j = (hi - lo).bit_length() - 1 + a, b = self.table[j][lo], self.table[j][hi - (1 << j)] + return a if self.score[a] >= self.score[b] else b + + def complete(self, prefix, k): + lo = bisect_left(self.words, prefix) + hi = bisect_left(self.words, prefix + '￿') # end of the prefix block + heap, out = [], [] + if lo < hi: + i = self._argmax(lo, hi) + heap.append((-self.score[i], i, lo, hi)) + while heap and len(out) < k: + _, i, a, b = heapq.heappop(heap) + out.append(self.words[i]) + for x, y in ((a, i), (i + 1, b)): # split around the winner + if x < y: + m = self._argmax(x, y) + heapq.heappush(heap, (-self.score[m], m, x, y)) + return out +``` + +**Cost.** O(n log n) to build, once a night. Each query is O(log n) for the binary searches plus O(k log k) for the heap, independent of how many names match the prefix. With "car" typed, the block might hold 50,000 names; the query still touches only about 2k of them. + +**Why not the alternatives?** A trie answers the prefix part in O(prefix length) but then must explore every completion to find the most popular, unless each trie node stores its own top 10, which multiplies memory by the average depth. Scanning the block and sorting by popularity costs O(block size) per keystroke, which is fine for long prefixes and fatal for "a". + +### A live leaderboard + +**Workload.** 50 million players, each with an integer score between 0 and 10⁶. Scores change constantly. Queries: a player's rank, and the top 100. + +**Choice.** Two options are both good, and the score range decides. A general **order-statistic structure** (a skip list with span counts, as in Redis sorted sets, or a size-augmented balanced tree, [Chapter 7](../volume-1/ch07-binary-search-trees.md)) gives O(log n) update and rank for any score type. Because scores here are bounded integers, a **Fenwick tree indexed by score** that counts players per score value is smaller and faster: an update is two point updates (remove the old score, add the new one), and a rank is one prefix sum, each O(log 10⁶), about 20 steps, in a 4 MB array. Ties are broken separately (for example by time reached). + +**Why not the alternatives?** Sorting on every query is O(n log n), seconds per query at 50 million. A hash map from player to score answers "what is my score" but not "what is my rank". + +### Has the crawler seen this URL? + +**Workload.** A web crawler has seen 5 billion URLs and checks each newly discovered link before fetching it. The full URL set lives in an on-disk key-value store. + +**Choice.** A **Bloom filter** in memory in front of the on-disk store. At a 1% false-positive rate it needs about 9.6 bits per URL, which is about 6 GB for 5 billion URLs, with 7 hash functions. A "not present" answer is always correct, so new URLs (the common case for a crawler at the frontier) never touch the disk. A "present" answer is checked against the store, which catches the 1% of false positives. + +**Why not the alternatives?** An exact in-memory hash set of 5 billion URLs at an average of 70 bytes each needs well over 350 GB. Checking the disk store for every link costs a random read per link. The Bloom filter is the classic case of question 5 in Section 25.4: approximate is acceptable because an exact check backs it up. + +### A rate limiter for an API + +**Workload.** A million API keys, each allowed 100 requests per minute, checked on every request. + +**Choice.** A **hash map from API key to a token bucket** (two numbers: tokens remaining and last refill time, [Chapter 29](../volume-5/ch29-system-design-as-data-structure-composition.md)). Each check is O(1) expected and the whole table is tens of megabytes. + +**When it changes.** If the keys are unbounded (rate limiting by client IP during an attack, say), the map can be made to grow without limit. Then a **Count-Min sketch** per time window bounds memory regardless of the number of distinct clients. It never undercounts, so it never lets an abuser through; at worst it rate-limits a few legitimate clients early. + +### Meeting rooms and overlapping intervals + +**Workload.** A calendar service stores bookings as [start, end) intervals per room and must reject any new booking that overlaps an existing one. + +**Choice.** Bookings in one room never overlap one another, so a **balanced ordered map keyed by start time** is enough: a new interval [s, e) conflicts only with the booking whose start is the floor of s (does it end after s?) or the ceiling of s (does it start before e?). Two O(log n) lookups ([Chapter 7](../volume-1/ch07-binary-search-trees.md), floor and ceiling). An **interval tree** is needed only when stored intervals may overlap one another, for example when the query is "which of all these events are happening at 3 pm?" + +### Latency percentiles across a fleet + +**Workload.** A thousand servers each record request latencies; a dashboard shows the fleet-wide p50, p99 and p99.9 every minute. + +**Choice.** A **t-digest** (or a KLL sketch) per server per minute, a few kilobytes each, merged centrally ([Chapter 14](../volume-3/ch14-probabilistic-data-structures.md)). Mergeability is the deciding property: you cannot average per-server p99s to get the fleet p99, but you can merge the sketches and query the merged one. + +**Why not the alternatives?** Shipping every raw latency costs gigabytes per minute. Fixed histogram buckets work if you know the range in advance, and HdrHistogram is a good choice when you do; t-digest needs no such tuning and is most accurate at the extreme percentiles you care about. + +## 25.6 Common Selection Mistakes + +- **A hash map when the queries need order.** The code then sorts the keys on every request. If any query mentions a range or "the next one", choose an ordered structure up front. +- **A linked list for "fast insertion".** Insertion is O(1) only once you hold the node, and finding it is O(n) with a cache miss per step. A dynamic array usually wins even for insertions in the middle ([Chapter 22](../volume-3/ch22-practical-considerations.md) has the measurements). +- **Linear operations hidden in a library call.** `x in some_list`, `list.pop(0)` and `list.insert(0, x)` in Python are all O(n). Inside a loop they quietly make an algorithm quadratic. +- **Choosing by asymptotic bounds alone.** Fibonacci heaps, van Emde Boas trees and many other theoretical winners lose to simpler structures at realistic sizes because of constant factors and cache behaviour. +- **Approximate structures where exact ones fit.** A Bloom filter for 10,000 keys saves a few hundred kilobytes and adds false positives to debug. Use probabilistic structures when the exact one does not fit, or when mergeability or a fixed memory budget matters. +- **Ignoring worst-case latency.** Amortized O(1) includes the occasional O(n) resize, and expected O(1) includes the occasional long probe sequence. For a latency-sensitive path, preallocate, or choose structures with worst-case bounds. +- **Distributing too early.** A structure that fits on one machine is far simpler and faster than any distributed one. Check the memory arithmetic before reaching for a cluster. + ## Exercises Difficulty: ★ check your understanding · ★★ apply it · ★★★ stretch. @@ -153,7 +292,7 @@ x starts in a set of size 1, and no set exceeds n, so x's set can double at most -**25.6 ★★★ Offline dynamic connectivity.** The matrix lists "DSU (offline)" for dynamic connectivity. You are given the whole sequence of operations in advance: `('add', u, v)`, `('remove', u, v)` and `('query', u, v)` ("are u and v connected right now?"). A plain DSU cannot delete edges. Using the rollback `DSU` of Section 23.14 and a segment tree over time, write `offline_connectivity(n, ops)` that returns the query answers in order, and state its running time. +**25.6 ★★★ Offline dynamic connectivity.** Section 25.1 lists an offline approach for connectivity when edges can also be removed. You are given the whole sequence of operations in advance: `('add', u, v)`, `('remove', u, v)` and `('query', u, v)` ("are u and v connected right now?"). A plain DSU cannot delete edges. Using the rollback `DSU` of Section 23.14 and a segment tree over time, write `offline_connectivity(n, ops)` that returns the query answers in order, and state its running time.
Hint @@ -225,6 +364,121 @@ Cost: each edge lands in O(log T) segment tree nodes, and each of those causes o
+**25.7 ★★ The leaderboard, by hand and in code.** Section 25.5 suggests a Fenwick tree indexed by score for a leaderboard with bounded integer scores. (a) Five players have scores 3, 5, 5, 1 and 7, with scores between 0 and 7. A player's rank is 1 plus the number of players with a strictly higher score. Give the rank of a player with each score 7, 5, 3 and 1, and say which prefix sum computes each. (b) The player with score 1 improves to 6. What changes in the tree, and what are the new ranks? (c) Implement it. + +
+Hint + +The number of players with a strictly higher score than s is the total minus the number with score at most s, and "at most s" is a prefix sum over the count array. + +
+ +
+Solution + +(a) Counts per score: 1 player at 1, 1 at 3, 2 at 5, 1 at 7, total 5. Rank(s) = 1 + 5 − (players with score ≤ s): + +| Score | Players ≤ score (prefix sum) | Rank | +|-------|------------------------------|------| +| 7 | 5 | 1 | +| 5 | 4 | 2 | +| 3 | 2 | 4 | +| 1 | 1 | 5 | + +Both players with score 5 share rank 2, and the next rank is 4: standard competition ranking. + +(b) Two point updates: subtract 1 at score 1, add 1 at score 6, each O(log 8). Scores are now 3, 5, 5, 6, 7, and the ranks of 7, 6, 5, 3 are 1, 2, 3, 5. + +(c) + +```python +class ScoreLeaderboard: + """Rank queries for integer scores in [0, max_score], via a Fenwick tree.""" + + def __init__(self, max_score): + self.n = max_score + 1 + self.tree = [0] * (self.n + 1) # 1-indexed Fenwick tree + self.total = 0 + + def _add(self, score, delta): + i = score + 1 + while i <= self.n: + self.tree[i] += delta + i += i & -i + + def _count_at_most(self, score): # players with score <= s + i, s = score + 1, 0 + while i > 0: + s += self.tree[i] + i -= i & -i + return s + + def add_player(self, score): + self._add(score, 1) + self.total += 1 + + def change(self, old, new): + self._add(old, -1) + self._add(new, 1) + + def rank(self, score): + """1 + number of players with a strictly higher score.""" + return 1 + self.total - self._count_at_most(score) +``` + +Every operation is O(log S) for S possible scores, regardless of the number of players, and the memory is S + 1 integers. For scores up to 10⁶ that is about 20 steps per operation in a 4 MB array. + +
+ +**25.8 ★★ Room bookings without an interval tree.** Section 25.5 claims that for one room, where stored bookings never overlap, an ordered map keyed by start time is enough to reject overlapping bookings. (a) Explain why a new booking [s, e) can only conflict with the stored booking that starts at or just after s, or the one just before it. (b) Implement `can_book` with two sorted lists and `bisect`, and trace the bookings [9, 10), [13, 15), [10, 13), [9, 11), [14, 16), [8, 9) in that order. (c) When does this stop being enough? + +
+Solution + +(a) Stored bookings are disjoint, so sorted by start they are also sorted by end. Every booking after the first one starting at or after s starts even later, so if that first one starts at or after e, all later ones do too. Every booking before the one just before s ends no later than that one does, so if it ends at or before s, all earlier ones do too. Checking those two neighbours is enough. + +(b) + +```python +from bisect import bisect_left + + +def can_book(starts, ends, s, e): + """starts is sorted; bookings [starts[i], ends[i]) never overlap.""" + i = bisect_left(starts, s) # first booking starting at or after s + if i < len(starts) and starts[i] < e: # it starts before we end + return False + if i > 0 and ends[i - 1] > s: # the one before ends after we start + return False + return True + + +def book(starts, ends, s, e): + if not can_book(starts, ends, s, e): + return False + i = bisect_left(starts, s) + starts.insert(i, s) + ends.insert(i, e) + return True +``` + +Trace, with half-open intervals so that touching is allowed: + +| Request | Result | Why | +|---------|--------|-----| +| [9, 10) | booked | empty | +| [13, 15) | booked | no neighbour overlaps | +| [10, 13) | booked | touches [9, 10) and [13, 15) but overlaps neither | +| [9, 11) | rejected | the booking starting at 9 starts before 11 | +| [14, 16) | rejected | [13, 15) ends after 14 | +| [8, 9) | booked | touches [9, 10) | + +`can_book` is O(log n). With Python lists, `book` is O(n) because of `insert`; a balanced tree or `sortedcontainers.SortedList` makes it O(log n). + +(c) It relies on stored intervals never overlapping. If they can overlap (several rooms in one structure, or "show every event at 3 pm" over arbitrary events), sorting by start no longer sorts by end, and an interval tree or a segment tree over time is needed. + +
+ --- ## Where this connects diff --git a/src/volume-5/ch27-distributed-data-structures.md b/src/volume-5/ch27-distributed-data-structures.md index d7ceb6b..05fb125 100644 --- a/src/volume-5/ch27-distributed-data-structures.md +++ b/src/volume-5/ch27-distributed-data-structures.md @@ -167,6 +167,8 @@ class LWWRegister: self.timestamp = other.timestamp ``` +Timestamps must be unique for this register to converge: if two replicas write different values with the same timestamp, each keeps its own, since neither is strictly greater. Use (time, replica_id) pairs, compared lexicographically. Where the time comes from matters too; §27.8 shows why raw wall-clock time can let an older write beat a newer one. + ### State-based Sets (Convergent CRDTs) Operations are applied locally and entire state is merged using join operations: @@ -267,6 +269,353 @@ class VersionVector: ) ``` +### Anti-entropy with Merkle trees + +A version vector tells two replicas how their copies of *one* key relate. It does not tell a replica which of its million keys differ from another replica's. Read repair fixes keys that happen to be read, and hinted handoff replays writes that a node missed during a short outage, but a key that is never read and whose hint was lost stays divergent forever. **Anti-entropy** closes that gap. Each replica builds a Merkle tree over a key range: each leaf hashes a bucket of keys, and each internal node hashes its children's hashes. Two replicas exchange root hashes; if they match (the common case), the ranges are identical and nothing more is sent. If not, they exchange the children of every node that differs and recurse. Each round trip descends one level, so a binary tree over n leaves locates the differing leaves in about log₂ n round trips, and with k differing leaves about 2k·log₂(n/k) hashes cross the network. [§31.2](ch31-real-world-case-studies.md) shows how Dynamo uses this, and Exercise 31.4 does the arithmetic. + +Cassandra's `nodetool repair` is the best-documented production case. Each replica reads its copy of the range and builds a Merkle tree (a *validation compaction*, which is why repair is I/O-heavy), the trees are compared, and the token ranges under mismatched leaves are streamed between replicas. The tree has a fixed resolution (DataStax documents a depth of 15, about 32,000 leaves), so when a leaf covers many partitions, one damaged partition causes all of its leaf's partitions to be streamed. Operators reduce this *overstreaming* by repairing in smaller subranges, which gives each tree a finer resolution. + +## 27.8 Logical Clocks + +Several structures in this chapter quietly depend on a notion of time: the LWW-Register compares timestamps, version vectors compare histories, Raft orders leaders by term, and the Chandy-Lamport snapshot must not record a receive without its send. Physical clocks cannot supply that order reliably. Clocks synchronized by NTP typically disagree by milliseconds, and by far more after a bad sync or a VM pause, so a wall-clock timestamp can place an effect before its cause. What these structures actually need is the order of **causality**, and that can be tracked exactly without reading any clock. + +### Happens-before + +Lamport (1978) defined the **happens-before** relation → on the events of a distributed system (local steps, sends and receives): + +1. If a and b are on the same process and a comes first, then a → b. +2. If a is the send of a message and b is its receipt, then a → b. +3. If a → b and b → c, then a → c. + +If neither a → b nor b → a, the events are **concurrent**, written a ∥ b. Concurrent does not mean simultaneous: it means no chain of messages connects them, so neither could have influenced the other. Happens-before is a partial order, and a logical clock is a way of attaching timestamps to events that respects it. + +### Lamport clocks + +Each process keeps one integer L. Before every local event or send it increments L; a message carries the sender's L; on receiving a message stamped t, the receiver sets L = max(L, t) + 1. + +```python +class LamportClock: + def __init__(self): + self.time = 0 + + def local(self): # a local event, or a send + self.time += 1 + return self.time + + send = local + + def receive(self, msg_time): + self.time = max(self.time, msg_time) + 1 + return self.time +``` + +This guarantees the **clock condition**: a → b implies L(a) < L(b). Each of the three rules makes the timestamp strictly increase along one step of a causal chain, so it increases along the whole chain. + +The converse is false: **L(a) < L(b) does not imply a → b**. Lamport time squashes a partial order into a chain of integers, and in doing so it forgets which pairs were concurrent. In the example below, L(b1) = 1 < L(a2) = 2, but no message reaches A from B before a2, so b1 ∥ a2. What Lamport timestamps do give is a cheap **total order consistent with causality**: compare (L, process_id) pairs lexicographically. That is how Lamport's mutual exclusion algorithm orders requests, how the RGA in §27.9 names characters, and the right way to break ties in the LWW-Register of §27.5. Each timestamp is one integer, and each event costs O(1), worst-case. + +### Vector clocks + +To detect concurrency rather than just respect causality, each process keeps one counter per process: a **vector clock** (Fidge and Mattern, independently, 1988). This is the same structure as the `VersionVector` of §27.7, with the same `merge` and the same comparison. The difference is what ticks it. A version vector belongs to a replicated *object* and increments when a replica updates that object. A vector clock belongs to a *process* and increments on every event, including sends and receives, and merges on every receive. So we build it on `VersionVector` rather than writing a second version: + +```python +class VectorClock(VersionVector): + """The VersionVector of §27.7, ticked on every event of one process.""" + + def __init__(self, node_id): + super().__init__() + self.node_id = node_id + + def stamp(self): # an immutable copy to attach to an event + snapshot = VersionVector() + snapshot.versions = dict(self.versions) + return snapshot + + def local(self): # a local event, or a send + self.increment(self.node_id) + return self.stamp() + + send = local + + def receive(self, msg_stamp): + self.merge(msg_stamp) # entry-wise max with the sender's vector + self.increment(self.node_id) + return self.stamp() + + +def concurrent(x, y): + return (x.versions != y.versions + and not x.happens_before(y) + and not y.happens_before(x)) +``` + +Entry j of V(e) counts the events of process j in e's causal past (including e itself, when e is on process j). That gives the **strong clock condition**: a → b if and only if V(a) < V(b), where < means ≤ in every entry and strictly less in at least one, which is exactly `happens_before`. If a → b, everything a has seen, b has seen too, plus b itself. Conversely, if a is the k-th event of process i and V(b)[i] ≥ k, then b's causal past contains a. So two events are concurrent exactly when their vectors are incomparable. + +**Worked example.** Three processes exchange three messages: A sends m1 to B, B sends m2 to C, C sends m3 to A. Vectors are written [A, B, C]. + +
+{{#include ../images/vector-clocks.svg}} +
Lamport time orders c1 before b3, but only the vector clocks reveal that no message path connects them.
+
+ +| event | what happens | Lamport L | vector V | +|---|---|---|---| +| a1 | A, local | 1 | [1,0,0] | +| a2 | A sends m1 | 2 | [2,0,0] | +| b1 | B, local | 1 | [0,1,0] | +| b2 | B receives m1 | max(1, 2) + 1 = 3 | max([0,1,0], [2,0,0]) = [2,1,0], tick: [2,2,0] | +| b3 | B sends m2 | 4 | [2,3,0] | +| c1 | C, local | 1 | [0,0,1] | +| c2 | C receives m2 | max(1, 4) + 1 = 5 | [2,3,1], tick: [2,3,2] | +| c3 | C sends m3 | 6 | [2,3,3] | +| a3 | A receives m3 | max(2, 6) + 1 = 7 | [2,3,3], tick: [3,3,3] | + +```python +lamport = {p: LamportClock() for p in "ABC"} +vector = {p: VectorClock(p) for p in "ABC"} +L, V = {}, {} + +def local(name, p): + L[name], V[name] = lamport[p].local(), vector[p].local() + +def send(name, p): + local(name, p) # a send is a local event whose stamp travels + return L[name], V[name] + +def receive(name, p, msg): + L[name], V[name] = lamport[p].receive(msg[0]), vector[p].receive(msg[1]) + +local("a1", "A"); m1 = send("a2", "A") +local("b1", "B"); receive("b2", "B", m1); m2 = send("b3", "B") +local("c1", "C"); receive("c2", "C", m2); m3 = send("c3", "C") +receive("a3", "A", m3) + +assert L["b1"] < L["a2"] and concurrent(V["b1"], V["a2"]) +assert L["c1"] < L["b3"] and concurrent(V["c1"], V["b3"]) +assert V["a1"].happens_before(V["c2"]) # a1 → a2 → b2 → b3 → c2 +assert [V["a3"].versions[p] for p in "ABC"] == [3, 3, 3] +``` + +c1 has Lamport time 1, tied for the smallest in the run, yet it is concurrent with every event on A and B before a3: nothing C did reached anyone until m3. + +**Cost.** A vector timestamp takes O(n) space for n processes, and comparing or merging two takes O(n), worst-case. This is not a weakness of the encoding: Charron-Bost (1991) proved that characterizing causality with vectors compared entry by entry needs n entries in the worst case. That is why vector clocks are attached to replicated objects with a few writers (Dynamo keeps one per key and truncates it past a size threshold by dropping the oldest entry) and not to every event in a large cluster. + +### Hybrid logical clocks + +A database that assigns a timestamp to every write would like three things at once: + +1. **Causality**: if a → b then ts(a) < ts(b), so a write that follows a read of another write sorts after it. +2. **Constant size**: a timestamp on every MVCC version cannot grow with the cluster. +3. **Closeness to wall-clock time**: "read the database as of 10:00:00", TTLs and log correlation all need timestamps that mean something in seconds. + +Physical clocks give 2 and 3 but break 1 under skew. Lamport clocks give 1 and 2 but drift arbitrarily far from real time, since a busy node drives everyone's counter up and the counter has no units. Vector clocks give 1 but not 2 or 3. **Hybrid logical clocks** (HLC; Kulkarni, Demirbas, Madappa, Avva and Leone, 2014) give all three. A timestamp is a pair (l, c): l is the largest physical time the node has heard of, from its own clock or from any message, and c is a counter that orders events sharing the same l. Pairs compare lexicographically. + +```python +class HybridLogicalClock: + def __init__(self, physical_clock): + self.pt = physical_clock # function returning this node's wall clock + self.l = 0 # largest physical time seen so far + self.c = 0 # orders events that share the same l + + def local(self): # a local event, or a send + old = self.l + self.l = max(old, self.pt()) + self.c = self.c + 1 if self.l == old else 0 + return (self.l, self.c) + + send = local + + def receive(self, msg): + lm, cm = msg + old = self.l + self.l = max(old, lm, self.pt()) + if self.l == old == lm: + self.c = max(self.c, cm) + 1 + elif self.l == old: + self.c += 1 + elif self.l == lm: + self.c = cm + 1 + else: # the local clock is ahead of everything + self.c = 0 + return (self.l, self.c) +``` + +Three properties follow. **Causality**: each rule makes (l, c) strictly increase over the previous local value and, on a receive, over the message's value, so a → b implies hlc(a) < hlc(b). **Bounded drift**: l is always at least the local physical time, and it is a physical reading taken somewhere in the event's causal past, so it can be ahead of the local clock by at most ε, the maximum skew between any two clocks. **Small counter**: c resets to 0 whenever the local physical clock moves past l, so it only grows while a node is behind the largest time it has heard of (the paper proves a bound). Like a Lamport clock, an HLC cannot detect concurrency: hlc(a) < hlc(b) does not imply a → b. + +**Worked example.** A's clock reads 10 and B's reads 7: B is 3 units behind. A writes key k and sends the write to B. B reads it and overwrites k. + +| event | local wall clock | physical timestamp | HLC | +|---|---|---|---| +| A writes k = 1, sends it | 10 | 10 | (10, 0) | +| B receives the write | 7 | 7 | max(0, 10, 7) = 10 from the message: (10, 0 + 1) = (10, 1) | +| B writes k = 2 | 7 | 7 | l unchanged at 10: (10, 2) | +| B, later, local event | 11 | 11 | clock passed l: (11, 0) | + +With physical timestamps, B's write (7) sorts before A's (10), so every replica running last-writer-wins keeps k = 1 and silently discards the write that causally came second. With HLC, (10, 2) > (10, 0) and B's write wins. Once B's clock passes 10, its timestamps are plain wall time again with c = 0. + +```python +wall = {"A": 10, "B": 7} # B's clock is 3 units behind A's +hlc_a = HybridLogicalClock(lambda: wall["A"]) +hlc_b = HybridLogicalClock(lambda: wall["B"]) + +m = hlc_a.send() # A writes k = 1 +assert m == (10, 0) +assert hlc_b.receive(m) == (10, 1) +w = hlc_b.local() # B overwrites k = 2 +assert w == (10, 2) and w > m # physical time would say 7 < 10 +wall["B"] = 11 +assert hlc_b.local() == (11, 0) # back to tracking the wall clock +``` + +CockroachDB and YugabyteDB both timestamp transactions and MVCC versions with HLCs. CockroachDB's default maximum clock offset is 500 ms; a node whose clock drifts too far from the rest of the cluster shuts itself down, because the bound on ε is what keeps HLC timestamps meaningful. Compare Spanner's TrueTime ([§31.1](ch31-real-world-case-studies.md)), which buys a small ε with GPS and atomic clocks and then waits it out on every commit. HLC accepts ordinary NTP-grade skew and pays for it elsewhere, for example by restarting a read that finds a value whose timestamp falls within its uncertainty window. + +| clock | timestamp size | cost per event | a → b ⇒ ts(a) < ts(b) | detects concurrency | close to wall time | +|---|---|---|---|---|---| +| physical | O(1) | O(1) | no | no | yes | +| Lamport | O(1) | O(1) | yes | no | no | +| vector | O(n) | O(n) | yes, and the converse | yes | no | +| hybrid logical | O(1) | O(1) | yes | no | yes, within ε | + +All costs are worst-case per event, for n processes. + +## 27.9 Sequence CRDTs for Collaborative Editing + +The CRDTs of §27.5 are counters, registers and sets, which have no order. Text does, and users edit it by position. Operations addressed by integer index do not commute. Two replicas hold "cat". A types "s" at index 3, giving "cats"; concurrently, B types "h" at index 1, giving "chat". A then applies B's insert(1, "h") and gets "chats". B applies A's insert(3, "s") and gets "chast". The index 3 meant "after the t" on A, but B's earlier insert shifted the t. Operational transformation (OT) repairs this by rewriting each incoming index against the concurrent operations it missed, which is manageable with a central server ordering everything. A **sequence CRDT** removes the problem instead: every character gets a **unique identifier that never changes**, and the document order is defined on identifiers, not indices. + +That needs three things. Identifiers must be **unique** without coordination: a (counter, replica_id) pair does it. They must be **ordered between neighbours**: a character inserted between x and y must land between x and y on every replica, and concurrent inserts at the same spot need a deterministic tie-break. And **deletes must leave tombstones**: a concurrent insert may name the deleted character as its neighbour, so the identifier has to stay resolvable after the character disappears from view. + +### Fractional positions and the interleaving anomaly + +The direct approach gives every character a position in a dense ordered space and sorts by (position, replica_id). Logoot (Weiss, Urso and Molli, 2009) uses sequences of digits as positions, so there is always room between two of them; floats make a simpler (if finite) stand-in. Suppose A types "dog" and B types "cat" concurrently into an empty document, each character placed halfway between the previous one and the end: + +```python +def fractional_typing(word, replica, lo=0.0, hi=1.0): + out = [] + for ch in word: + lo = (lo + hi) / 2 # halfway between the last char and the end + out.append(((lo, replica), ch)) + return out + +doc = sorted(fractional_typing("dog", "A") + fractional_typing("cat", "B")) +assert "".join(ch for _, ch in doc) == "dcoagt" +``` + +Both replicas converge, on garbage. Both users chose positions 0.5, 0.75 and 0.875, and the tie-break on replica ID alternates them. This is the **interleaving anomaly**: concurrently typed runs at the same place merge character by character. Kleppmann, Gomes, Mulligan and Beresford (2019) found it in Logoot and LSEQ. Convergence is a necessary property of a collaborative editor, not a sufficient one. + +### RGA: the Replicated Growable Array + +RGA (Roh, Jeon, Kim and Lee, 2011) anchors each insert to a character instead of a number. An element is identified by a Lamport timestamp (counter, replica_id) from §27.8; the original paper used a custom timestamp type, and later presentations use Lamport timestamps. An insert operation is (id, ref, char), where ref is the id of the character immediately to the left at the moment of insertion (`None` for the start). A delete operation marks its target as a tombstone and keeps it in the list. + +To apply an insert, find ref, then **skip right past every element whose id is greater than the new id**, and insert there: + +```python +class RGA: + def __init__(self, replica_id): + self.replica_id = replica_id + self.clock = 0 # Lamport counter: ids are (counter, replica_id) + self.elems = [] # [id, char, deleted], in document order + + def _visible(self): + return [e for e in self.elems if not e[2]] + + def _find(self, elem_id): + for i, e in enumerate(self.elems): + if e[0] == elem_id: + return i + raise KeyError(elem_id) + + def text(self): + return "".join(e[1] for e in self._visible()) + + # Local edits, by visible position; each returns the op to broadcast. + def insert(self, pos, char): + ref = self._visible()[pos - 1][0] if pos > 0 else None + op = ("ins", (self.clock + 1, self.replica_id), ref, char) + self.apply(op) + return op + + def delete(self, pos): + op = ("del", self._visible()[pos][0]) + self.apply(op) + return op + + # Remote and local ops both go through apply. + def apply(self, op): + if op[0] == "del": + self.elems[self._find(op[1])][2] = True # tombstone + return + _, elem_id, ref, char = op + if any(e[0] == elem_id for e in self.elems): + return # duplicate delivery + self.clock = max(self.clock, elem_id[0]) + i = 0 if ref is None else self._find(ref) + 1 + while i < len(self.elems) and self.elems[i][0] > elem_id: + i += 1 # skip newer inserts + self.elems.insert(i, [elem_id, char, False]) +``` + +**Why the skip rule converges.** Picture the elements as a tree: each element's parent is its ref, siblings are ordered by descending id, and the document is the pre-order traversal. Because an insert's Lamport timestamp exceeds that of its ref, every element's id is larger than all of its ancestors'. Starting just after ref, the list holds ref's child subtrees in descending order. A child with a larger id than the new element is skipped along with its whole subtree, whose ids are larger still. The first element with a smaller id is either a smaller sibling or lies beyond ref's subtree (the element there is a later sibling of ref or of one of its ancestors, so its id is smaller than that node's, which is no larger than ref's, which is smaller than the new element's). The new element goes exactly there, which is its place in the pre-order traversal. The tree depends only on the *set* of operations, not on the order they arrived in, so any two replicas that have applied the same operations hold the same list. The only delivery requirement is that an insert arrives after the insert of its ref and a delete after the insert of its target, which causal delivery provides. + +**Worked trace.** A types "ab", giving ids (1,A) for a and (2,A) for b, and B receives both. Concurrently, A inserts "x" after a, with id (3,A), while B inserts "y" after a, with id (3,B), and then deletes b. + +- On A, which holds `a x b`: y's ref is a, at index 0, so start at 1. x's id (3,A) is less than (3,B): stop. Result `a y x b`. +- On B, which holds `a y b†` (b† is the tombstone): x's ref is a, start at 1. y's id (3,B) is greater than (3,A): skip. b's id (2,A) is less than (3,A): stop. Result `a y x b†`. After applying B's delete, A matches. + +Both read "ayx". The tombstone mattered: had B's delete arrived first and physically removed b, an insert after b from a third replica would have had nothing to anchor to. + +The test below gives three replicas the same starting text, lets them make 30 edits with no syncing at all (every edit is concurrent with the other replicas' edits), and then applies the full set of operations in 100 different random causal orders to fresh replicas, as well as in log order to the three originals. Every one ends with the same text. + +```python +import random + +def dependency(op): + return op[2] if op[0] == "ins" else op[1] + +def random_causal_order(ops, rng): + """A delivery order in which every op's ref or target arrives first.""" + pending, present, order = list(ops), {None}, [] + while pending: + op = rng.choice([o for o in pending if dependency(o) in present]) + pending.remove(op) + order.append(op) + if op[0] == "ins": + present.add(op[1]) + return order + +rng = random.Random(27) +replicas = [RGA(r) for r in "ABC"] +ops = [replicas[0].insert(i, ch) for i, ch in enumerate("cat")] +for r in replicas[1:]: + for op in ops: + r.apply(op) + +for _ in range(30): # concurrent edits, no syncing + r = rng.choice(replicas) + if r.text() and rng.random() < 0.3: + ops.append(r.delete(rng.randrange(len(r.text())))) + else: + ops.append(r.insert(rng.randint(0, len(r.text())), rng.choice("xyz"))) + +results = set() +for _ in range(100): + fresh = RGA("D") + for op in random_causal_order(ops, rng): + fresh.apply(op) + results.add(fresh.text()) +for r in replicas: # own ops are skipped as duplicates + for op in ops: + r.apply(op) + results.add(r.text()) +assert len(results) == 1 +``` + +**Interleaving in RGA.** Text typed left to right stays together: every character after the first is anchored to its predecessor in the same run, so a concurrent run from another user can only go before or after the whole run. In the "dog" and "cat" scenario, RGA produces "catdog" on every replica. But a run typed by repeatedly inserting at the same position (moving the cursor back after each keystroke) anchors every character to the same ref, and those siblings are ordered only by timestamp: A inserting g, o, d at position 0 while B inserts t, a, c at position 0 merges to "cdaotg". Kleppmann et al. (2019) called this the lesser interleaving anomaly; Fugue (Weidner and Kleppmann, 2023) is a later list CRDT designed specifically to minimize interleaving. + +**Cost.** In this list version every operation is O(n), worst-case, where n counts tombstones too: finding ref, converting a visible position to an element, and the list insert are all linear scans. The skip loop itself only passes over concurrent inserts at the same spot. Production implementations keep elements in a balanced tree whose nodes store the number of *visible* characters below them (the same weight trick as the rope in [§13.7](../volume-2/ch13-string-data-structures.md)), plus a hash map from id to element, for O(log n) position lookups. They also compress runs: Yjs stores consecutive characters typed by one client as a single item. Space is the real cost. Tombstones are never removed by the algorithm itself, so a document's metadata grows with every character ever typed. A tombstone can only be discarded once every replica has seen the delete and no operation still in flight can refer to it, which requires knowing who all the replicas are. Yjs, for example, discards a deleted item's content but keeps a small placeholder recording its length. + +**In practice.** Yjs implements an adaptation of YATA (Nicolaescu et al., 2016), which anchors each insert to both its left and its right neighbour (each item records an origin and a right origin). Automerge documents its list type as an RGA sequence. Both use (client, counter) identifiers and tombstones as above. + +**Local versus replicated buffers.** The gap buffer, rope and piece table of [Chapter 13](../volume-2/ch13-string-data-structures.md) address text by integer offset, which works because a single writer's offsets only change through that writer's own edits. A replicated buffer cannot, as "chast" shows; it must address by identifier. An editor built on a sequence CRDT usually keeps both: an ordinary local buffer for rendering and cursor movement, and the CRDT for merging. Local edits are translated from offset to identifier on the way out, and remote operations from identifier to offset on the way in, which is why the position lookup above has to be fast. + ## Exercises Difficulty: ★ check your understanding · ★★ apply it · ★★★ stretch. @@ -497,9 +846,68 @@ Convergence: each of P and N is a G-Counter, whose merge (entry-wise max) is com +**27.8 ★★ Lamport and vector timestamps by hand.** Three processes run these events, each process in the order listed. A: a1 sends m1 to C, a2 is local, a3 receives m2. B: b1 is local, b2 sends m2 to A, b3 receives m3. C: c1 receives m1, c2 sends m3 to B. (a) Give every event's Lamport time and vector clock [A, B, C] using the rules of §27.8. (b) Decide whether a1 → b3, whether a2 → b3, and whether b1 → c2. (c) Find every pair of events x, y with L(x) < L(y) that are nevertheless concurrent. + +
+Solution + +(a) + +| event | L | V | +|---|---|---| +| a1 (send m1) | 1 | [1,0,0] | +| a2 | 2 | [2,0,0] | +| b1 | 1 | [0,1,0] | +| b2 (send m2) | 2 | [0,2,0] | +| c1 (receive m1) | max(0, 1) + 1 = 2 | [1,0,1] | +| c2 (send m3) | 3 | [1,0,2] | +| b3 (receive m3) | max(2, 3) + 1 = 4 | max([0,2,0], [1,0,2]) = [1,2,2], tick: [1,3,2] | +| a3 (receive m2) | max(2, 2) + 1 = 3 | max([2,0,0], [0,2,0]) = [2,2,0], tick: [3,2,0] | + +(b) a1 → b3: yes, [1,0,0] ≤ [1,3,2] in every entry, through a1 → c1 → c2 → b3. a2 → b3: no. [2,0,0] has A = 2 > 1, and [1,3,2] has larger B and C entries, so they are concurrent: m1 left A before a2, so a2 never reached C or B. b1 → c2: no, [0,1,0] and [1,0,2] are incomparable; B's events only reach A. + +(c) Comparing the vectors of all pairs, the concurrent pairs with unequal Lamport times are (a1, b2), (b1, a2), (b1, c1), (b1, c2), (a2, c2), (a2, b3), (b2, c2), (c1, a3) and (a3, b3), each listed with the smaller Lamport time first. For example L(a2) = 2 < L(b3) = 4 although a2 ∥ b3, and L(c1) = 2 < L(a3) = 3 although c1 ∥ a3. Lamport order agrees with causality where causality exists and is arbitrary everywhere else. + +
+ +**27.9 ★★ A hybrid clock with a fast neighbour.** A's wall clock reads 100, B's reads 41 and C's reads 47. A sends a message to B; B receives it, then sends a message (at wall time 42) to C, which receives it. (a) Give the HLC timestamp of each of the four events. (b) Later B's wall clock reaches 101 and B performs a local event. What is its timestamp? (c) The bounded-drift property says l is never more than the maximum clock skew ahead of the local clock. Check it here, and explain what goes wrong if A's clock is not 59 units fast but a full day fast because of a bad sync. + +
+Hint + +On each receive, l becomes the largest of the old l, the message's l, and the local physical time. Which of the three wins on B and on C? + +
+ +
+Solution + +(a) A's send: l = max(0, 100) = 100, a new l, so (100, 0). B's receive: l = max(0, 100, 41) = 100, equal to the message's l only, so c = 0 + 1: (100, 1). B's send at wall time 42: l stays 100, so c increments: (100, 2). C's receive at 47: l = max(0, 100, 47) = 100 from the message, c = 2 + 1: (100, 3). Every timestamp increases along the causal chain even though B's and C's clocks are far behind A's. + +(b) At wall time 101, l = max(100, 101) = 101, a new value, so c resets: (101, 0). + +(c) The largest skew is 100 − 41 = 59 (between A and B). B's l − pt is 100 − 41 = 59 and then 100 − 42 = 58; C's is 100 − 47 = 53. All are within 59. If A's clock were a day fast, every node that heard from A, directly or indirectly, would carry an l a day in the future, and its timestamps would stay pinned at that l with a growing counter until its own clock caught up a day later. Causality would still hold, but "as of time t" reads, TTLs and anything comparing timestamps to real time would be wrong for a day, and nothing would bring l back down. This is why production systems refuse to run with an unbounded ε: CockroachDB shuts down a node whose clock is too far from the rest of the cluster rather than let its timestamps spread. + +
+ +**27.10 ★★ Why RGA keeps tombstones.** Replicas A and B both hold "abc", with ids (1,A), (2,A), (3,A). Concurrently, A deletes b and B inserts "x" right after b. (a) Give B's insert operation and the converged text when both replicas apply both operations using the `RGA` class of §27.9. (b) Suppose `apply` removed deleted elements from the list instead of marking them. What happens on A when B's insert arrives, and why can no local rule fix it? (c) When could a replica safely discard the tombstone for b? + +
+Solution + +(a) B's clock is 3 after applying A's three inserts, so the operation is `("ins", (4, "B"), (2, "A"), "x")`. On A, b is a tombstone at index 1, so the scan starts at index 2; c's id (3,A) is less than (4,B), so x goes before c. Both replicas hold `a b† x c` and read "axc". + +(b) A's `_find((2, "A"))` fails: the element x is anchored to no longer exists, so A has no way to know where x belongs. Any local fallback (drop x, or put it at the end, or at the start) either loses B's insert or puts it somewhere B did not, and replicas that received the insert before the delete would place it correctly, so the replicas diverge. The anchor carries the position information; deleting it deletes the information. + +(c) Only when no operation that could still arrive refers to (2,A): every replica must have seen the delete, and every insert anchored to b that was issued before that point must have been delivered everywhere. Equivalently, the delete must be causally stable, which requires knowing the full set of replicas and hearing from all of them. In a peer-to-peer editor where a replica can go offline for weeks, that may never be known, which is why tombstones accumulate and why Yjs keeps a small placeholder for deleted items even when it discards their content. + +
+ --- ## Where this connects - [Chapter 19: Emerging and Specialized Structures](../volume-3/ch19-emerging-and-specialized-structures.md). CRDTs in the broader context of emerging structures - [Chapter 17: Persistent Data Structures](../volume-3/ch17-persistent-data-structures.md). The persistence ideas that underpin versioned replicas +- [Chapter 13: String Data Structures](../volume-2/ch13-string-data-structures.md). The single-writer text buffers that a sequence CRDT replicates +- [Chapter 31: Real-World Case Studies](ch31-real-world-case-studies.md). Dynamo's vector clocks and Merkle trees, and Spanner's TrueTime as the hardware alternative to hybrid logical clocks diff --git a/src/volume-5/ch28-network-topology-and-routing-data-structures.md b/src/volume-5/ch28-network-topology-and-routing-data-structures.md index 7639993..a9731f8 100644 --- a/src/volume-5/ch28-network-topology-and-routing-data-structures.md +++ b/src/volume-5/ch28-network-topology-and-routing-data-structures.md @@ -51,14 +51,112 @@ Hierarchical trie for routing: Routing tables map network prefixes to next hops. The data structure must support fast longest prefix match (LPM), the core operation of IP forwarding. -### Trie for Routing +### Longest-Prefix Match -Binary trie for IP addresses: -- Each level represents one bit -- 32 levels for IPv4, 128 for IPv6 -- LPM: traverse bits until reaching longest matching prefix +A route is a prefix and a next hop: `10.20.0.0/16 → C` means "any address whose first 16 bits are those of 10.20.0.0 goes to neighbor C". Prefixes nest, so one address usually matches several routes, and the rule is that the most specific one (the longest prefix) wins. Take this table: -**Memory explosion**: 2^32 possible leaves = 4 billion nodes. Solution: **compressed tries (Radix Tree / Patricia Tree)**. +| prefix | next hop | role | +|---|---|---| +| 0.0.0.0/0 | A | default route: matches every address | +| 10.0.0.0/8 | B | a large block | +| 10.20.0.0/16 | C | one site inside it | +| 10.20.128.0/17 | D | the upper half of that site, routed differently | +| 10.20.200.0/24 | E | one subnet inside the /17 | +| 192.168.0.0/16 | F | an unrelated block | + +| address | routes that match | longest | next hop | +|---|---|---|---| +| 10.20.200.7 | /0, /8, /16, /17, /24 | 10.20.200.0/24 | E | +| 10.20.201.7 | /0, /8, /16, /17 | 10.20.128.0/17 | D | +| 10.20.5.5 | /0, /8, /16 | 10.20.0.0/16 | C | +| 10.99.1.1 | /0, /8 | 10.0.0.0/8 | B | +| 192.168.1.1 | /0, 192.168.0.0/16 | 192.168.0.0/16 | F | +| 8.8.8.8 | /0 | 0.0.0.0/0 | A | + +10.20.5.5 misses the /17 because its third octet, 5 = 00000101, has a 0 in the bit the /17 fixes to 1. "Longest" is what makes the table composable: the /8 can be announced once for a whole block while a more specific route carves out an exception, without either route knowing about the other. A first-match scan in the order listed would send every one of these addresses to the default route A. + +A **binary trie** does LPM directly. A route of length *l* is stored at the node reached by following its first *l* bits from the root, so the root holds the /0 and a node at depth *d* holds the route (if any) whose prefix is the *d*-bit string on its path. A lookup follows the address bit by bit and remembers the last route it passed; when the path runs out, the remembered route is the longest match, because every route that matches the address lies on that path and deeper nodes are longer prefixes. + +```python +import ipaddress +import random + +class TrieNode: + def __init__(self): + self.children = [None, None] + self.next_hop = None # set if a prefix ends here + + +class RoutingTrie: + def __init__(self): + self.root = TrieNode() + + def insert(self, prefix, next_hop): + net = ipaddress.IPv4Network(prefix) + value = int(net.network_address) + node = self.root + for i in range(net.prefixlen): + bit = (value >> (31 - i)) & 1 + if node.children[bit] is None: + node.children[bit] = TrieNode() + node = node.children[bit] + node.next_hop = next_hop + + def lookup(self, addr): + value = int(ipaddress.IPv4Address(addr)) + node, best = self.root, self.root.next_hop + for i in range(32): + node = node.children[(value >> (31 - i)) & 1] + if node is None: + break + if node.next_hop is not None: + best = node.next_hop # longest match so far + return best + + +def lpm_scan(routes, addr): + """Reference answer: test every route and keep the longest that matches.""" + a = ipaddress.IPv4Address(addr) + best, best_len = None, -1 + for prefix, hop in routes: + net = ipaddress.IPv4Network(prefix) + if a in net and net.prefixlen > best_len: + best, best_len = hop, net.prefixlen + return best + + +table = [("0.0.0.0/0", "A"), ("10.0.0.0/8", "B"), ("10.20.0.0/16", "C"), + ("10.20.128.0/17", "D"), ("10.20.200.0/24", "E"), ("192.168.0.0/16", "F")] +t = RoutingTrie() +for prefix, hop in table: + t.insert(prefix, hop) +for addr, want in [("10.20.200.7", "E"), ("10.20.201.7", "D"), ("10.20.5.5", "C"), + ("10.99.1.1", "B"), ("192.168.1.1", "F"), ("8.8.8.8", "A")]: + assert t.lookup(addr) == lpm_scan(table, addr) == want + + +def random_route(rng): + net = ipaddress.IPv4Network((rng.getrandbits(32), rng.randint(0, 32)), strict=False) + return str(net) + +rng = random.Random(28) +for _ in range(200): + routes = list({random_route(rng): hop for hop in range(rng.randint(1, 60))}.items()) + trie = RoutingTrie() + for prefix, hop in routes: + trie.insert(prefix, hop) + for _ in range(100): + if rng.random() < 0.5: # uniform addresses rarely hit long prefixes, + addr = ipaddress.IPv4Address(rng.getrandbits(32)) + else: # so half are drawn from inside a route + net = ipaddress.IPv4Network(rng.choice(routes)[0]) + addr = net.network_address + rng.randrange(net.num_addresses) + assert trie.lookup(str(addr)) == lpm_scan(routes, str(addr)) +``` + +Trace 10.20.201.7: the root gives A, depth 8 gives B, depth 16 gives C and depth 17 gives D. The walk then continues down the path the /24 created, because 201 = 11001001 and 200 = 11001000 agree on their first seven bits, and at depth 23 there is no child for the final 1. Twenty-three nodes visited below the root, answer D. + +**Cost.** Insert and lookup take O(W) time in the worst case, W = 32 for IPv4 and 128 for IPv6, independent of the number of routes N. The trie does not allocate the 2^32 possible addresses: it holds at most 1 + N·W nodes, and the six routes above take 41. Memory is not the problem; speed is. Each step is a dependent memory read, likely a cache miss, and a 100 Gb/s port receiving minimum-size Ethernet frames (64 bytes plus 20 bytes of preamble and inter-frame gap) delivers about 148.8 million packets per second, 6.7 ns per packet. Thirty-two pointer chases do not fit in that. The structures below exist to cut the number of reads: path compression removes nodes that do not branch, and multibit tries (§28.3) read several bits per step. ### Radix Tree (Patricia Tree) @@ -74,7 +172,7 @@ Example: 192.168.0.0/16, 192.168.1.0/24 [.1] ← stores the /24 route (the /16 contains it) ``` -**BSD-derived kernels** use this structure (Sklower's radix tree) for their routing tables. Memory per prefix: O(L) where L is number of bits until first branching. +**BSD-derived kernels** use this structure (Sklower's radix tree) for their routing tables. Every node either holds a prefix or branches, so N prefixes need fewer than 2N nodes, against up to N·W for the plain binary trie. The depth can still reach W, so path compression helps memory more than worst-case lookup time. ### LC-Trie (Level Compressed Trie) @@ -88,15 +186,324 @@ Level 8-15: Second level compression Used in the **Linux kernel's IPv4 forwarding table** (`fib_trie`). Few levels means few memory accesses per lookup, with modest memory. -### Multi-bit Trie +## 28.3 Multibit Tries and Router Lookups + +A binary trie spends one memory read per address bit. A **multibit trie** reads *s* bits at a time, the **stride**: each node is an array of 2^s slots indexed directly by the next *s* bits, so an IPv4 lookup with strides 8-8-8-8 takes at most four reads, and with 16-8-8 at most three. Each slot can hold a next hop and a pointer to a child node. + +### Controlled Prefix Expansion + +The difficulty is prefixes whose length does not fall on a level boundary. With stride 8, the trie can only store prefixes of length 8, 16, 24 and 32 directly; a /17 ends one bit into the third level. **Controlled prefix expansion** (Srinivasan and Varghese, 1999) rewrites each prefix as the set of longer prefixes, of the next allowed length, that together cover exactly the same addresses. A prefix of length *l* that ends inside a level covering bits up to *b* becomes 2^(b−l) slots in that level's node. Two rules make it correct: + +- **Expansion.** 10.20.128.0/17 fixes the top bit of the third octet to 1, so in the level-3 node under 10.20 it fills the 2^(24−17) = 128 slots 128 to 255. +- **Capture.** When expansions of two different prefixes land on the same slot, the longer original prefix wins. 10.20.200.0/24 lands exactly on slot 200, which the /17 also covers, and since 24 > 17 the slot holds E. The slot therefore stores the original length beside the next hop, which also makes the result independent of insertion order. + +
+{{#include ../images/multibit-trie.svg}} +
The same six prefixes in a binary trie and in a stride-2 trie: expansion copies short prefixes into several slots, and the lookup for 1011 drops from a read per bit to a read per level.
+
+ +The figure shows both rules on a toy table of bit strings with 4-bit addresses. For the six-route table of §28.2 with strides 8-8-8-8, the /0 expands into all 256 slots of the root, the /8 sits in root slot 10, the two /16s are aligned and sit in one level-2 slot each (20 under 10, 168 under 192), and the level-3 node under 10.20 holds D in slots 128 to 255 except slot 200, which holds E. Looking up 10.20.201.7 reads root slot 10 (B, follow the child), level-2 slot 20 (C, follow the child) and level-3 slot 201 (D, no child): three reads, against 23 nodes in the binary trie. The price is memory: four nodes of 256 slots, 1,024 slots for six routes, where the binary trie needed 41 nodes of two pointers. + +```python +class MultibitTrie: + """Fixed-stride trie with controlled prefix expansion. + + A node is a list of 2**stride slots; a slot is [next_hop, length, child], + where length is the original prefix length that set next_hop. + """ + + def __init__(self, strides=(8, 8, 8, 8)): + assert sum(strides) == 32 + self.strides = strides + self.root = self._node(0) + + def _node(self, level): + return [[None, -1, None] for _ in range(1 << self.strides[level])] + + def insert(self, prefix, next_hop): + net = ipaddress.IPv4Network(prefix) + value, plen = int(net.network_address), net.prefixlen + node, start = self.root, 0 + for level, stride in enumerate(self.strides): + end = start + stride + index = (value >> (32 - end)) & ((1 << stride) - 1) + if plen <= end: # the prefix ends inside this level: expand it + first = index >> (end - plen) << (end - plen) + for slot in node[first:first + (1 << (end - plen))]: + if slot[1] <= plen: # capture: the longer original prefix wins + slot[0], slot[1] = next_hop, plen + return + if node[index][2] is None: + node[index][2] = self._node(level + 1) + node, start = node[index][2], end + + def lookup(self, addr): + value = int(ipaddress.IPv4Address(addr)) + node, start, best = self.root, 0, None + for stride in self.strides: # one memory read per level + start += stride + hop, _, child = node[(value >> (32 - start)) & ((1 << stride) - 1)] + if hop is not None: + best = hop + if child is None: + break + node = child + return best + + +m = MultibitTrie((8, 8, 8, 8)) +for prefix, hop in table: + m.insert(prefix, hop) +level3 = m.root[10][2][20][2] # the node under 10.20 +assert [level3[i][:2] for i in (127, 128, 200, 201)] == \ + [[None, -1], ["D", 17], ["E", 24], ["D", 17]] + +for strides in [(8, 8, 8, 8), (16, 8, 8), (4,) * 8, (1,) * 32]: + for _ in range(30): + routes = list({random_route(rng): hop for hop in range(rng.randint(1, 50))}.items()) + rng.shuffle(routes) # insertion order must not matter + mt = MultibitTrie(strides) + for prefix, hop in routes: + mt.insert(prefix, hop) + for _ in range(50): + net = ipaddress.IPv4Network(rng.choice(routes)[0]) + addr = str(net.network_address + rng.randrange(net.num_addresses)) + assert mt.lookup(addr) == lpm_scan(routes, addr) +``` + +Like the binary trie, the lookup remembers the best next hop seen on the way down, so an empty slot (slot 5 of the level-3 node for 10.20.5.5) falls back to C from level 2. + +**Cost.** A lookup takes at most k reads for k levels, worst case. Inserting a prefix walks at most k levels and writes up to 2^s slots of one node, so a short prefix in a wide level is expensive: the /0 above writes 256 slots, and in a 16-8-8 trie it would write 65,536. Deletion is harder than insertion, because the slots a deleted prefix captured must revert to the next-longest prefix covering them, and the trie does not record what that was. Implementations keep the original prefixes in a separate table to answer that question. + +### Choosing the Strides + +Bigger strides mean fewer levels and more memory, but how much more depends on the table. A node starting at bit *s* exists for each distinct *s*-bit string that begins some route longer than *s*, so the number of nodes at each possible start position can be counted once from the routes, and the slots of any stride choice are the sum of nodes × 2^stride over its levels. Srinivasan and Varghese observed that the cheapest strides for a given number of levels then follow from a dynamic program over the start positions, O(k·W²) time for k levels: + +```python +from functools import lru_cache + +def level_nodes(routes): + """nodes[s]: trie nodes starting at bit s, one per distinct s-bit string + that begins a route longer than s; nodes[0] = 1, the root.""" + keys = [(int(n.network_address), n.prefixlen) + for n in (ipaddress.IPv4Network(p) for p, _ in routes)] + return [1] + [len({v >> (32 - s) for v, plen in keys if plen > s}) + for s in range(1, 32)] + +def expansion_cost(nodes, strides): + """Slots a fixed-stride trie allocates: sum of nodes[start] * 2**stride.""" + total, start = 0, 0 + for stride in strides: + total += nodes[start] << stride + start += stride + return total + +def best_strides(nodes, levels): + """Cheapest (slots, strides) using at most `levels` levels.""" + @lru_cache(maxsize=None) + def cost(start, left): + if start == 32: + return 0, () + if left == 0: + return float("inf"), () + return min((c + (nodes[start] << (end - start)), (end - start,) + rest) + for end in range(start + 1, 33) + for c, rest in [cost(end, left - 1)]) + return cost(0, levels) + +assert expansion_cost(level_nodes(table), (8, 8, 8, 8)) == 1024 # the four nodes above + + +def synthetic_table(seed=2024, n=50_000): + """BGP-like length mix (60% /24s), clustered in 3,000 random /16 blocks.""" + r = random.Random(seed) + mix = {8: 0.1, 12: 0.2, 14: 0.4, 15: 0.4, 16: 2.5, 17: 1, 18: 1.5, 19: 3, + 20: 4, 21: 5, 22: 11, 23: 9, 24: 60, 25: 0.4, 26: 0.4, 27: 0.3, + 28: 0.3, 29: 0.3, 30: 0.2, 32: 0.1} + blocks = [r.randrange(1 << 8, 224 << 8) for _ in range(3000)] + routes = {} + while len(routes) < n: + plen = r.choices(list(mix), list(mix.values()))[0] + value = (r.choice(blocks) << 16) | r.getrandbits(16) + routes[str(ipaddress.IPv4Network((value, plen), strict=False))] = len(routes) + return list(routes.items()) + +nodes = level_nodes(synthetic_table()) +for strides in [(1,) * 32, (4,) * 8, (8, 8, 8, 8), (16, 8, 8), (24, 8), (16, 16)]: + print(strides, expansion_cost(nodes, strides)) +print(best_strides(nodes, 3), best_strides(nodes, 4)) +``` + +On this synthetic 50,000-route table (real tables differ, but the shape of the trade-off is typical): + +| strides | worst-case reads | slots | +|---|---|---| +| 1 × 32 (binary trie) | 32 | 366,042 | +| 4 × 8 | 8 | 562,832 | +| 8-8-8-8 | 4 | 1,076,736 | +| 16-8-8 | 3 | 1,084,928 | +| 24-8 | 2 | 17,048,320 | +| 16-16 | 2 | 191,627,264 | + +The binary trie is the smallest and the slowest. Going from 32 reads to 4 costs about three times the memory, and going from 4 to 3 costs almost nothing here, because the 65,536-slot root of 16-8-8 replaces the first two levels of 8-8-8-8, which already used 224 nodes and 57,344 slots. Going to 2 levels costs another factor of 16, and the wrong two levels are worse again: 16-16 needs 11 times the memory of 24-8, because it allocates a 65,536-slot node for each of the 2,923 /16 blocks that contain a longer route. The program confirms that 16-8-8 is the cheapest three-level choice and finds 16-6-3-7 (627,928 slots) for four levels. Letting each subtree pick its own strides, which the same paper also optimizes by dynamic programming, does better still. + +### DIR-24-8: Usually One Read + +Gupta, Lin and McKeown (INFOCOM 1998) took the 24-8 row of that table seriously. Their observation was that on a backbone table of the time (MAE-EAST, January 1998), 99.93% of prefixes were 24 bits or shorter, and that 2^24 entries of DRAM was cheap. Their DIR-24-8-BASIC scheme is a two-level multibit trie with strides 24 and 8, laid out as two flat arrays: + +- **TBL24** has 2^24 entries of 2 bytes, 32 MB, indexed by the top 24 bits of the address. An entry whose first bit is 0 holds a next hop in its other 15 bits. An entry whose first bit is 1 holds a 15-bit index into the second table. +- **TBLlong** is made of 256-entry blocks of 1-byte next hops, one block for each /24 that contains a route longer than /24, indexed by the last 8 bits of the address. + +A lookup reads TBL24; only if the flag is set does it make a second read. Instead of remembering the best match on the way down, the scheme pushes it down: when a /24's block is allocated, all 256 entries are first filled with whatever the /24 entry held, so each entry is a complete answer by itself. The paper's example uses 10.54.0.0/16, 10.54.34.0/24 and 10.54.34.192/26: + +```python +from array import array + +EXT = 1 << 31 # flag bit: the low bits index a tbl8 group, not a next hop + +def build_dir_24_8(routes): + """Static build. routes: (prefix, hop), hop an int >= 1; 0 means no route.""" + tbl24 = array("I", [0]) * (1 << 24) + tbl8 = array("I") + nets = sorted(((ipaddress.IPv4Network(p), h) for p, h in routes), + key=lambda r: r[0].prefixlen) # shorter first; longer overwrite + for net, hop in nets: + lo, n = int(net.network_address), net.num_addresses + if net.prefixlen <= 24: + tbl24[lo >> 8:(lo + n) >> 8] = array("I", [hop]) * (n >> 8) + continue + entry = tbl24[lo >> 8] + if not entry & EXT: # first long route under this /24: allocate a group + group = len(tbl8) >> 8 + tbl8.extend(array("I", [entry]) * 256) # push the /24's answer down + entry = tbl24[lo >> 8] = EXT | group + base = ((entry & ~EXT) << 8) | (lo & 0xFF) + tbl8[base:base + n] = array("I", [hop]) * n + return tbl24, tbl8 + +def lookup_dir_24_8(tbl24, tbl8, addr): + a = int(ipaddress.IPv4Address(addr)) + entry = tbl24[a >> 8] # read 1 + if entry & EXT: + entry = tbl8[((entry & ~EXT) << 8) | (a & 0xFF)] # read 2, rarely + return entry + +tbl24, tbl8 = build_dir_24_8([("10.54.0.0/16", 1), ("10.54.34.0/24", 2), + ("10.54.34.192/26", 3)]) +assert lookup_dir_24_8(tbl24, tbl8, "10.54.22.147") == 1 # one read +assert lookup_dir_24_8(tbl24, tbl8, "10.54.34.14") == 2 # two reads +assert lookup_dir_24_8(tbl24, tbl8, "10.54.34.194") == 3 # two reads +assert len(tbl8) == 256 # one group, for 10.54.34 +``` + +The /16 fills the 256 TBL24 entries 10.54.0 to 10.54.255. The /24 overwrites entry 10.54.34, and the /26 then turns that entry into a pointer to group 0, whose entries 0 to 191 hold the /24's next hop and 192 to 255 the /26's. (The code uses 32-bit entries with the flag in the top bit, as DPDK does, rather than the paper's 16.) + +Lookup is at most two reads, worst case, and one read for any address whose /24 has no longer route, which is nearly all of them: most networks do not accept routes longer than /24 from the global table. Because the reads are to fixed locations with no pointer chasing beyond the second, a hardware pipeline can complete one lookup per memory access; the paper estimated 20 million lookups per second with the 50 ns DRAM of the day. The costs are on the other side. TBL24 is 32 MB however small the table is. The 15-bit pointer limits TBLlong to 32,768 blocks; the paper suggested 1 MB of it, 4,096 blocks. And updates are slow: adding a /8 rewrites 65,536 TBL24 entries, a default route all 16.7 million, and a later insertion must not overwrite entries that a longer prefix already set. Exercise 28.7 works through what that requires. -Process multiple bits per step: -- 4-bit trie: Process 4 bits at a time (8 steps for IPv4 vs 32) -- 16-bit trie: Process 16 bits (2 steps for IPv4) +**In production.** DPDK's `rte_lpm` library, used by software routers built on it, is DIR-24-8: a `tbl24` of 2^24 four-byte entries (64 MB) and 256-entry `tbl8` groups whose number is fixed when the table is created. Each entry packs a 24-bit next hop (or group index), a valid bit, a `valid_group` bit that marks an extended entry, and a 6-bit `depth`, the length of the prefix that wrote it; the depth is what lets insertion and deletion run incrementally. **Poptrie** (Asai and Ohara, SIGCOMM 2015) goes the other way and makes the table small enough to stay in CPU cache: a directly indexed first level of 16 or 18 bits, then 64-way nodes (stride 6) that store only their non-empty children contiguously, with a 64-bit bitmap per node; the index of a child is the population count (`popcnt`) of the bitmap bits below it. Both trade update cost for a lookup with few, predictable reads, which is the right trade for a forwarding table that sees millions of lookups per update. -Trade-off: More memory (2^4 = 16 children per node) but faster lookup. +## 28.4 ECMP and Maglev Hashing -## 28.3 BGP Routing Data Structures +The lookup of §28.3 often returns not one next hop but a group of them. In a data-center fabric built as a Clos network, a leaf switch has the same route to every remote rack through each of its spine switches, all at equal cost. **Equal-cost multipath** (ECMP) forwarding spreads traffic across the group, and the data structure question becomes: which packet goes to which member? + +### Per-Flow Hashing + +Sending successive packets to successive members (per-packet spraying) balances perfectly and breaks TCP. The paths have different queueing delays, so the packets of one connection arrive out of order; the receiver acknowledges each out-of-order segment with a duplicate ACK, and the sender treats three duplicate ACKs as a loss, retransmits and halves its congestion window. So routers hash per flow: the flow's 5-tuple (source and destination address, source and destination port, protocol) is hashed, and every packet of the flow takes member `group[hash(5-tuple) mod k]`. One flow stays on one path, in order. Balance is then over flows, not bytes: two large flows that hash to the same member share it while another member idles. + +### The Remapping Problem + +`hash mod k` fails badly when the group changes. If one of k next hops fails, the flows on it must move, 1/k of all flows. But the survivors are renumbered and every flow is now taken mod k − 1, and a flow stays put only if its member under mod k is the same as under mod k − 1. Exactly 1/k of flows stay, whichever member failed (Exercise 28.9), so (k − 1)/k of flows move: 75% with 4 next hops, 99% with 100. For a router the cost is a burst of reordering. For a load balancer that spreads connections over servers by the same hashing, it is worse: a connection moved to a server without its TCP state is reset. + +The fix is a level of indirection: a table of M buckets, M much larger than k, filled with members, and each flow goes to `table[hash mod M]`. When a member fails, only its buckets are reassigned. Many switches and Linux's resilient next-hop groups work this way. The ring of consistent hashing ([§27.3](ch27-distributed-data-structures.md)) is the same idea with buckets placed by hashing: it guarantees that only the failed member's keys move, but the arcs are uneven. For 100 backends with *v* points each on the ring, measured below, the most-loaded backend owns 5.67 times its fair share of the ring with *v* = 1, 2.09 times with *v* = 10 and 1.21 times with *v* = 100. Every backend must be provisioned for the most-loaded one. + +### Maglev Hashing + +Maglev is Google's software network load balancer (Eisenbud et al., NSDI 2016). Its hashing builds the bucket table to be balanced first and stable second. Each backend *i* gets a preference list over the M table positions, a permutation built from two hashes of its name: + +``` +offset = h1(name) mod M +skip = h2(name) mod (M − 1) + 1 +permutation[i][j] = (offset + j × skip) mod M +``` + +M is prime, so every skip in 1..M−1 is coprime to M and the list visits every position exactly once. The backends then take turns: each in round-robin order claims the first position on its list that is still empty, until the table is full. A lookup is one hash and one array read. + +**Worked example.** This is the paper's own: M = 7 and three backends with (offset, skip) = (3, 4), (0, 2) and (3, 1). + +| backend | preference list | +|---|---| +| B1 | 3, 0, 4, 1, 5, 2, 6 | +| B2 | 0, 2, 4, 6, 1, 3, 5 | +| B3 | 3, 4, 5, 6, 0, 1, 2 | + +Round 1: B1 takes 3, B2 takes 0, B3 finds 3 taken and takes 4. Round 2: B1 skips 0 and 4 and takes 1, B2 takes 2, B3 takes 5. Round 3: B1 skips 5 and 2 and takes 6, and the table is full: `[B2, B1, B2, B1, B3, B3, B1]`, three entries for B1 and two for each of the others. Remove B2 and rebuild: B1 takes 3, 0, 1 and 2, B3 takes 4, 5 and 6, giving `[B1, B1, B1, B1, B3, B3, B3]`. Positions 0 and 2 had to change because B2 owned them. Position 6 changed too: without B2 taking turns, B3 reached 6 on its list before B1 did. That is the one extra disruption. + +```python +import hashlib +from collections import Counter + +def h64(text): + return int.from_bytes(hashlib.blake2b(text.encode(), digest_size=8).digest(), "big") + +def populate(prefs, M): + """Maglev's table fill. prefs[i] = (offset, skip) for backend i; M prime.""" + nxt = [0] * len(prefs) # next index into each backend's preference list + entry = [-1] * M + filled = 0 + while True: + for i, (offset, skip) in enumerate(prefs): + c = (offset + nxt[i] * skip) % M + while entry[c] >= 0: # walk i's preference list to a free slot + nxt[i] += 1 + c = (offset + nxt[i] * skip) % M + entry[c] = i + nxt[i] += 1 + filled += 1 + if filled == M: + return entry + +def maglev_table(backends, M=65537): + prefs = [(h64("offset:" + b) % M, h64("skip:" + b) % (M - 1) + 1) for b in backends] + return [backends[i] for i in populate(prefs, M)] + +assert populate([(3, 4), (0, 2), (3, 1)], 7) == [1, 0, 1, 0, 2, 2, 0] # B2 B1 B2 B1 B3 B3 B1 +assert populate([(3, 4), (3, 1)], 7) == [0, 0, 0, 0, 1, 1, 1] # B1 x4, B3 x3 + +backends = [f"backend-{i}" for i in range(100)] +for M in (65537, 655373): + before = maglev_table(backends, M) + after = maglev_table([b for b in backends if b != "backend-37"], M) + counts = Counter(before) + forced = counts["backend-37"] + moved = sum(x != y for x, y in zip(before, after)) + print(M, min(counts.values()), max(counts.values()), forced, moved) + +def ring_shares(backends, vnodes): + """Chapter 27's ring: each point owns the arc back to the previous point.""" + points = sorted((h64(f"{b}#{j}"), b) for b in backends for j in range(vnodes)) + share = Counter() + for k, (p, b) in enumerate(points): + share[b] += (p - points[k - 1][0]) % (1 << 64) + return share + +for v in (1, 10, 100): + print(v, max(ring_shares(backends, v).values()) / ((1 << 64) / len(backends))) +``` + +The hashes are deterministic, so the output is reproducible: + +| table size M | entries per backend | entries of backend-37 | entries changed on removing it | extra | +|---|---|---|---|---| +| 65,537 | 655 or 656 | 655 | 1,009 | 354 (0.54% of the table) | +| 655,373 | 6,553 or 6,554 | 6,554 | 7,572 | 1,018 (0.16%) | + +**Balance.** Because the backends take strict turns and the fill stops when the table is full, every backend owns ⌊M/N⌋ or ⌈M/N⌉ entries, a guarantee rather than an expectation; the paper picks M > 100·N so that this rounding is under 1% of a backend's share. Against the ring's 1.21 with 100 points per backend, Maglev's most-loaded backend here carries 1.001 times its fair share. + +**Disruption.** It is not minimal. Removing one backend of 100 reassigns its 655 entries plus 354 others, so about 1.5% of flows move where 1% must. The extras come from the turn order shifting, as in the worked example, and they shrink as a fraction of the table when M grows, which matches the paper's measurements. Maglev accepts this trade deliberately: over-provisioning every backend for an imbalanced hash costs capacity all the time, while extra moves happen only when backends change, and Maglev also keeps a per-machine connection-tracking table so that packets of an established connection keep going to their backend. The paper reports that, with 1,000 backends and a 65,537-entry table, Karger's ring and rendezvous hashing would have needed backends over-provisioned by 29.7% and 49.5% to absorb their imbalance. + +**Cost.** Lookup is O(1). Building the table takes O(M log M) expected time: when n of M positions are full, a backend expects M/(M − n) tries to find an empty one, and the sum of those terms is M·H_M. The worst case is O(M²), when the backends have nearly identical preference lists and N approaches M, which choosing M ≫ N avoids. The paper reports 1.8 ms to build a 65,537-entry table and 22.9 ms for 655,373, which is why the default is the smaller one. + +## 28.5 BGP Routing Data Structures Border Gateway Protocol (BGP) routes between Autonomous Systems (AS). BGP routing tables are massive (~900K IPv4 prefixes as of 2024). @@ -133,7 +540,7 @@ Per-prefix best-path selection (BGP is path-vector; it runs no Dijkstra): - On UPDATE or WITHDRAW: re-run selection for the affected prefix only ``` -## 28.4 Software-Defined Networking (SDN) Tables +## 28.6 Software-Defined Networking (SDN) Tables OpenFlow switch tables store flow entries with wildcard matching: @@ -171,7 +578,7 @@ Rule 2: 10.0.0.0/16 with action B → Cannot merge (Rule 2 is more specific) ``` -## 28.5 Network Measurement Data Structures +## 28.7 Network Measurement Data Structures ### Count-Min Sketch @@ -230,7 +637,7 @@ class SpaceSaving: return sorted(self.counters.items(), key=lambda x: -x[1])[:self.k] ``` -## 28.6 Gossip Protocol Data Structures +## 28.8 Gossip Protocol Data Structures Gossip-based systems use epidemic algorithms for dissemination. Each node periodically exchanges state with random peers. @@ -292,7 +699,7 @@ The neighbors of C (vertex 2) are `edges[4:6] = [0, 3]`, that is A and D, with w -**28.2 ★★ Longest prefix match on a binary trie.** A router has these routes: 0.0.0.0/0 → D, 10.0.0.0/8 → A, 10.1.0.0/16 → B, 10.1.2.0/24 → C. (a) Give the next hop for 10.1.2.3, 10.1.3.4, 10.2.0.1 and 11.0.0.1. (b) Implement `insert(prefix, next_hop)` and `lookup(addr)` on a one-bit-per-level trie. (c) How many trie nodes does the lookup for 10.1.3.4 visit below the root before it stops? +**28.2 ★★ Longest prefix match on a binary trie.** A router has these routes: 0.0.0.0/0 → D, 10.0.0.0/8 → A, 10.1.0.0/16 → B, 10.1.2.0/24 → C. (a) Give the next hop for 10.1.2.3, 10.1.3.4, 10.2.0.1 and 11.0.0.1. (b) Add a `delete(prefix)` method to the `RoutingTrie` of §28.2 that removes a route and frees the nodes that no longer lead to any route. After deleting 10.1.2.0/24, what does 10.1.2.3 return, and how many nodes are left below the root? (c) How many trie nodes does the lookup for 10.1.3.4 visit below the root before it stops?
Hint @@ -306,55 +713,40 @@ During lookup, remember the last next hop you passed. The answer is that remembe (a) 10.1.2.3 → C (matches /24). 10.1.3.4 → B (the third octet 3 differs from 2, so the /24 does not match, but the /16 does). 10.2.0.1 → A. 11.0.0.1 → D (only the default route matches). -(b) +(b) Record the path on the way down, clear the route, then walk back up unlinking every node that now holds no route and has no children. Stop at the first node that still holds a route or still has a child: everything above it is needed. ```python -import ipaddress - -class TrieNode: - def __init__(self): - self.children = [None, None] - self.next_hop = None # set if a prefix ends here - - -class RoutingTrie: - def __init__(self): - self.root = TrieNode() - - def insert(self, prefix, next_hop): - net = ipaddress.IPv4Network(prefix) - value = int(net.network_address) - node = self.root - for i in range(net.prefixlen): - bit = (value >> (31 - i)) & 1 - if node.children[bit] is None: - node.children[bit] = TrieNode() - node = node.children[bit] - node.next_hop = next_hop - - def lookup(self, addr): - value = int(ipaddress.IPv4Address(addr)) - node, best = self.root, self.root.next_hop - for i in range(32): - node = node.children[(value >> (31 - i)) & 1] - if node is None: - break - if node.next_hop is not None: - best = node.next_hop # longest match so far - return best - +def delete(self, prefix): + net = ipaddress.IPv4Network(prefix) + value = int(net.network_address) + path = [self.root] + for i in range(net.prefixlen): + child = path[-1].children[(value >> (31 - i)) & 1] + if child is None: + return False # no such route + path.append(child) + if path[-1].next_hop is None: + return False + path[-1].next_hop = None + for i in range(net.prefixlen - 1, -1, -1): # path[i + 1] hangs off path[i] + node = path[i + 1] + if node.next_hop is not None or node.children != [None, None]: + break + path[i].children[(value >> (31 - i)) & 1] = None + return True + +RoutingTrie.delete = delete t = RoutingTrie() -t.insert("0.0.0.0/0", "D") -t.insert("10.0.0.0/8", "A") -t.insert("10.1.0.0/16", "B") -t.insert("10.1.2.0/24", "C") -assert t.lookup("10.1.2.3") == "C" -assert t.lookup("10.1.3.4") == "B" -assert t.lookup("10.2.0.1") == "A" -assert t.lookup("11.0.0.1") == "D" +for prefix, hop in [("0.0.0.0/0", "D"), ("10.0.0.0/8", "A"), + ("10.1.0.0/16", "B"), ("10.1.2.0/24", "C")]: + t.insert(prefix, hop) +assert t.delete("10.1.2.0/24") and not t.delete("10.1.2.0/24") +assert t.lookup("10.1.2.3") == "B" ``` +10.1.2.3 now falls back to the /16, B. Before the delete there were 24 nodes below the root, one per bit of the longest route. The /24's nodes at depths 17 to 24 lead to no other route, so all eight are unlinked, and the walk stops at depth 16 because that node holds B. Sixteen nodes remain. Deletion is O(W) in the worst case, like insertion. Nothing has to be rewritten to make the fallback work, because the shorter routes are still on the path; the expanded tables of §28.3 lose exactly that property. + (c) 10.1.3.4 and 10.1.2.0 agree on their first 23 bits (they differ in the last bit of the third octet). The lookup walks 23 nodes along the /24's path, picking up A at depth 8 and B at depth 16, then finds no child for bit 24 and returns B. That is 23 dependent memory reads for one packet, which is the reason routers do not use a plain binary trie.
@@ -387,7 +779,7 @@ Lookups: 10.6.1.1 reads slot 10.6 and returns Y in one access. 10.5.1.1 reads sl -**28.4 ★ Apply BGP best-path selection.** A router has four paths to 203.0.113.0/24. Using the selection order in §28.3, which one wins, and at which step is each loser eliminated? +**28.4 ★ Apply BGP best-path selection.** A router has four paths to 203.0.113.0/24. Using the selection order in §28.5, which one wins, and at which step is each loser eliminated? | path | LOCAL_PREF | AS_PATH | ORIGIN | MED | learned via | |---|---|---|---|---|---| @@ -411,7 +803,7 @@ One real-world detail: routers compare MED by default only between paths receive -**28.5 ★★ Trace a Count-Min sketch.** Use width w = 4 and depth d = 2 with h1(x) = x mod 4 and h2(x) = ⌊x/4⌋ mod 4. Insert the flow IDs 1, 5, 2, 1, 9, 3, 1, 6 (count 1 each). Give the final table and the estimates for 1, 5, 9 and 7. Then size a sketch for ε = 0.001 and δ = 0.01 using the formulas in §28.5. +**28.5 ★★ Trace a Count-Min sketch.** Use width w = 4 and depth d = 2 with h1(x) = x mod 4 and h2(x) = ⌊x/4⌋ mod 4. Insert the flow IDs 1, 5, 2, 1, 9, 3, 1, 6 (count 1 each). Give the final table and the estimates for 1, 5, 9 and 7. Then size a sketch for ε = 0.001 and δ = 0.01 using the formulas in §28.7.
Solution @@ -440,7 +832,7 @@ Sizing: w = ⌈e/ε⌉ = ⌈2718.3⌉ = 2,719 and d = ⌈ln(1/δ)⌉ = ⌈4.61
-**28.6 ★★★ Space-Saving: trace and guarantee.** (a) Trace the `SpaceSaving` class from §28.5 with k = 2 on the stream a, a, b, c, c, c, a, giving the counters after each item, and compare with the true counts. (b) The `add` method pushes a fresh heap entry on every increment and, when evicting, pops until it finds an entry whose count matches the current counter. What would go wrong without that check? (c) Prove that after N items, any item that occurred more than N/k times is in the summary. +**28.6 ★★★ Space-Saving: trace and guarantee.** (a) Trace the `SpaceSaving` class from §28.7 with k = 2 on the stream a, a, b, c, c, c, a, giving the counters after each item, and compare with the true counts. (b) The `add` method pushes a fresh heap entry on every increment and, when evicting, pops until it finds an entry whose count matches the current counter. What would go wrong without that check? (c) Prove that after N items, any item that occurred more than N/k times is in the summary.
Hint @@ -478,9 +870,49 @@ With k counters summing to N, the minimum satisfies m ≤ N/k. If x occurred mor
+**28.7 ★★ Updating a DIR-24-8 table.** Start from the table built in §28.3: 10.54.0.0/16 → 1, 10.54.34.0/24 → 2, 10.54.34.192/26 → 3. (a) The route 10.0.0.0/8 → 4 arrives. Which TBL24 entries must it write, which must it leave alone, and why can't `build_dir_24_8`'s rule (sort by length, later writes overwrite) be applied to a single insertion? (b) Then 10.54.34.0/24 is withdrawn. What must group 0's entries hold afterwards, and what information do the two tables lack to work that out? (c) Show how storing in every entry the length of the prefix that wrote it (its depth, as DPDK does) makes both updates local. + +
+Solution + +(a) The /8 covers TBL24 entries 10.0.0 to 10.255.255, 2^16 = 65,536 of them. The 256 entries 10.54.0 to 10.54.255 were written by longer prefixes (the /16, and at 10.54.34 the /24 and then the /26's group pointer), so they must keep their values; the /8 writes the other 65,280. The static build gets this right only because it processes every shorter prefix before any longer one. A single insertion arrives after the longer routes are in place, and an entry holding 1 looks the same whether a /16 or an /8 wrote it, so a blind write of the range would erase the /16. + +(b) Entries 0 to 191 held 2, the /24's answer pushed down when the group was created. They must now hold 1, from 10.54.0.0/16, the longest remaining route covering them. Entries 192 to 255 keep 3, and TBL24 entry 10.54.34 stays a pointer because the /26 still needs the group. The tables store only next hops: nothing in them says that 2 came from a /24, or that a /16 covers it. The router has to find the replacement in a separate list of the routes themselves, which is why DPDK keeps one beside the tables. + +(c) Give each entry a (next hop, depth) pair. To insert a prefix of length d, write each entry in its range only if the entry is empty or its depth is at most d; when the entry is a group pointer, apply the same test to the group's 256 entries. In (a), the 10.54.x entries have depth 16 or are pointers into a group whose entries have depth 24 and 26, so the /8 (depth 8) skips them all. To delete a prefix P of length d, look up its replacement R, the longest remaining route that covers P, and rewrite only the entries in P's range whose depth equals d, with R's next hop and depth (or empty if there is no R). Entries with greater depth belong to longer routes and are left alone. In (b), the 192 entries with depth 24 become (1, 16) and the 64 with depth 26 are untouched. When every entry of a group ends up with depth 24 or less and the same next hop, the group can be folded back into its TBL24 entry and freed; DPDK's delete does this check. + +
+ +**28.8 ★★ Maglev by hand.** Add a fourth backend B4 with (offset, skip) = (5, 3) to the worked example of §28.4 (M = 7). (a) Write B4's preference list and build the table. (b) How many entries differ from the three-backend table `[B2, B1, B2, B1, B3, B3, B1]`, and what is the fewest any scheme could change while keeping every backend within one entry of the others? (c) Why must M be prime? Show what goes wrong with M = 8 and a backend whose skip is 2. + +
+Solution + +(a) B4's list is (5 + 3j) mod 7 for j = 0 to 6: 5, 1, 4, 0, 3, 6, 2. Round 1: B1 takes 3, B2 takes 0, B3 finds 3 taken and takes 4, B4 takes 5. Round 2: B1 skips 0 and 4 and takes 1, B2 takes 2, B3 skips 5 and takes 6. That is 7 entries, so the fill stops before B4's second turn: `[B2, B1, B2, B1, B3, B4, B3]`, with 2, 2, 2 and 1 entries. + +(b) Two entries changed: position 5 (B3 to B4) and position 6 (B1 to B3). The minimum is one: B4 must get at least ⌊7/4⌋ = 1 entry, and taking one of B1's three gives the balanced 2, 2, 2, 1 with a single change. Maglev spent an extra change because B4 claimed position 5, which B3 used to take in round 2, so B3 went further down its list to 6, which B1 used to take in round 3. The extra moves are the price of building the table from the current backend set alone, with no memory of the previous table. + +(c) The list (offset + j·skip) mod M visits every position exactly when gcd(skip, M) = 1. With M = 8, skip = 2 and offset 0 the list is 0, 2, 4, 6, 0, 2, ..., so the backend can only ever claim even positions. Once those are full, its `while entry[c] >= 0` loop never finds an empty slot and the build never finishes. With M prime, every skip from 1 to M − 1 is coprime to M, so the simple formula is always safe. + +
+ +**28.9 ★★ Why hash mod k moves almost every flow.** An ECMP group has next hops h_0, ..., h_(k−1), and a flow with hash x uses h_(x mod k). Hop h_v fails; the survivors keep their order, are renumbered 0 to k − 2, and flows now use x mod (k − 1). (a) Prove that, over a full period of x, exactly 1/k of flows keep their next hop, whatever v is. (b) A simpler repair keeps k slots and puts some survivor into the dead hop's slot. What fraction of flows move, and what does it cost? (c) How does a table of M ≫ k buckets avoid both problems, and why does Maglev rebuild its table from scratch instead of patching it? + +
+Solution + +(a) Take x over k(k − 1) consecutive values. Because gcd(k, k − 1) = 1, the Chinese remainder theorem says each pair (a, b) = (x mod k, x mod (k − 1)) occurs exactly once. A flow keeps its next hop when a ≠ v and b is the new index of h_a: b = a if a < v, b = a − 1 if a > v. That is exactly one b for each of the k − 1 surviving values of a, so k − 1 of the k(k − 1) pairs, a fraction 1/k. The other (k − 1)/k of flows move, although only the 1/k that were on h_v had to. + +(b) Only the flows of the dead hop move, 1/k, the minimum. But they all land on the one survivor put in the slot, which now carries 2/k of the traffic, twice its share, and a second failure can make it worse. + +(c) With `table[x mod M]` and roughly M/k buckets per hop, the dead hop's buckets can be handed out one at a time across all survivors: only its flows move, and each survivor's share grows by about 1/(k(k − 1)), staying within one bucket (1/M of traffic) of the others. Maglev rebuilds rather than patches because many load-balancer machines must map the same flow to the same backend without talking to each other. A table that depends only on the current set of backends, not on the order in which failures happened, is one every machine computes identically. The cost is the small extra disruption measured in §28.4. + +
+ --- ## Where this connects - [Chapter 11: Graphs—Modeling Relationships](../volume-2/ch11-graphs-modeling-relationships.md). The graph fundamentals underneath routing - [Chapter 13: String Data Structures](../volume-2/ch13-string-data-structures.md). The tries that routing tables actually are +- [Chapter 27: Distributed Data Structures](ch27-distributed-data-structures.md). Ring-based consistent hashing, the minimal-disruption but less balanced alternative to Maglev's table diff --git a/src/volume-5/index.md b/src/volume-5/index.md index 88fa077..c61bc5d 100644 --- a/src/volume-5/index.md +++ b/src/volume-5/index.md @@ -4,9 +4,13 @@ The previous volumes established data structures as fundamental building blocks ## Chapters -- [Chapter 27: Distributed Data Structures](ch27-distributed-data-structures.md) -- [Chapter 28: Network Topology and Routing Data Structures](ch28-network-topology-and-routing-data-structures.md) -- [Chapter 29: System Design as Data Structure Composition](ch29-system-design-as-data-structure-composition.md) -- [Chapter 30: Advanced System Patterns and Case Studies](ch30-advanced-system-patterns-and-case-studies.md) -- [Chapter 31: Real-World Case Studies](ch31-real-world-case-studies.md) -- [Chapter 32: Synthesis and Future Directions](ch32-synthesis-and-future-directions.md) +| Chapter | After it you can | +|---------|------------------| +| [27: Distributed Data Structures](ch27-distributed-data-structures.md) | Explain DHTs and consistent hashing, order events with Lamport, vector and hybrid logical clocks, build CRDTs including a collaborative-text sequence CRDT, and reason about consensus and quorums | +| [28: Network Topology and Routing Data Structures](ch28-network-topology-and-routing-data-structures.md) | Implement longest-prefix match with binary and multibit tries, explain how routers reach one memory access per lookup (DIR-24-8), and balance flows with ECMP and Maglev hashing | +| [29: System Design as Data Structure Composition](ch29-system-design-as-data-structure-composition.md) | Decompose key-value stores, message queues and storage engines into their structures, and choose load-balancing, caching and rate-limiting structures | +| [30: Advanced System Patterns and Case Studies](ch30-advanced-system-patterns-and-case-studies.md) | Explain how a search engine compresses and intersects posting lists, plus vector search, time series storage, event sourcing and sharding | +| [31: Real-World Case Studies](ch31-real-world-case-studies.md) | Trace the structures inside Spanner, Dynamo, Kafka, Delta Lake and Cloudflare's edge cache | +| [32: Synthesis and Future Directions](ch32-synthesis-and-future-directions.md) | Place every structure in the book on one spectrum of trade-offs, and read new research with that map in hand | + +**Before you start.** Volume I and the hash table and graph chapters of Volume II. Chapter 14 (probabilistic structures) and Chapter 16 (external memory) are used heavily in Chapters 29 to 31.