Chapter 11Linked searches
Theorem 9 of Bose, Douïeb, Iacono and Langerman (2016) is not about a single BST. It describes a static search structure made of many small trees. For every key there is a tree holding the keys that most often follow in the request sequence, and every node of every tree stores a pointer to the tree of its own key. A search for starts in the tree of the previous request; if is found there, the search follows the stored pointer to the tree of , ready for the next request. If is not found, the search falls back to one shared tree that contains every key. Nothing is ever rotated, and the structure is built once, before the requests, from their transition frequencies.
To state such a theorem, one needs a model of computation in which these searches, and the memory they use, are counted honestly. This chapter defines that model: a linked search in a store of labelled trees, with an explicit cost per visited node and per followed link, and an explicit count of memory words. It is used only by the multiple-tree structure of Chapter 28. A reader who wants to check that chapter’s theorem should read this chapter, since its statement is phrased with LinkedSearch.Execution and Store.words; nothing else in the book depends on it.
The model has two layers. The first is ordinary comparison search in a single tree whose nodes carry arbitrary, sparse keys, not inorder ranks. The second adds the links: each node carries a successor pointer, a store holds many trees, and a request is a search followed by a link. The definitions are in Models/Labelled/Search/Definitions/Abstract.lean and Models/LinkedSearch/Definitions/Abstract.lean, the theorems in the Abstract.lean files next to them.
11.1 Searching a labelled tree
Most of the library works with unlabelled shapes and inorder ranks (Chapter 1). A small tree of the multiple-tree structure, however, contains only some of the keys, so its nodes must carry their keys. It is a LabelledTree over the natural numbers.
/-- Label a shape by an arbitrary inorder key list. Correctness requires matchinglengths; the default label only totalizes malformed preprocessing inputs. -/def Tree.labelWith : Tree → List Nat → LabelledTree Nat | .nil, _ => .nil | .node l r, keys => .node (l.labelWith (keys.take l.size)) ((keys[l.size]?).getD 0) (r.labelWith (keys.drop (l.size + 1)))t.labelWith keys writes the list keys into the shape t in inorder. The root receives the entry at position l.size, the left subtree the first l.size entries, and the right subtree the rest. The construction is meant for a list with exactly one key per node. On a list of the wrong length it is still defined, with take, drop and the default label , but the theorems below never use that case.
Theorem (labelling). If keys has one entry per node of t, then t.labelWith keys has shape t and inorder sequence keys. If moreover keys is strictly increasing, the labelled tree is a search tree (LabelledTree.Ordered, Chapter 4).
/-- Sparse labels preserve shape and exactly the supplied inorder key list. -/theorem labelling (t : Tree) (keys : List Nat) (same : keys.length = t.size) : (t.labelWith keys).erase = t ∧ (t.labelWith keys).inorder = keys := ⟨Tree.labelWith_erase t keys, Tree.labelWith_inorder t keys same⟩theorem ordered (t : Tree) (keys : List Nat) (same : keys.length = t.size) (increasing : keys.Pairwise (· < ·)) : (t.labelWith keys).Ordered := Tree.labelWith_ordered t keys same increasingSearch in such a tree is the textbook comparison search. The library gives it twice: as an executable function, and as a relation that says which searches are legal.
/-- Ordinary comparison search, returning membership and the number of visitednodes. A failed search can visit nodes too; an empty tree visits none. -/def lookup : LabelledTree Nat → Nat → Bool × Nat | .nil, _ => (false, 0) | .node l key r, x => if x < key then let result := lookup l x; (result.1, result.2 + 1) else if x = key then (true, 1) else let result := lookup r x; (result.1, result.2 + 1)lookup t x returns whether x was found, and the number of nodes visited. At each node it compares x with the key and either stops or continues into one child. A failed search visits every node on its path, and searching an empty tree visits none.
/-- A legal static pointer search: compare at the current node, then followonly the child selected by that comparison. Each visited node costs one unit.The zero-cost empty case represents inspecting an already-null child pointer. -/inductive Search : LabelledTree Nat → Nat → Bool → Nat → Prop where | empty (x : Nat) : Search .nil x false 0 | found (l r : LabelledTree Nat) (x : Nat) : Search (.node l x r) x true 1 | left {l r : LabelledTree Nat} {key x : Nat} {found : Bool} {cost : Nat} : x < key → Search l x found cost → Search (.node l key r) x found (cost + 1) | right {l r : LabelledTree Nat} {key x : Nat} {found : Bool} {cost : Nat} : key < x → Search r x found cost → Search (.node l key r) x found (cost + 1)Search t x found cost is the model. A legal search compares at the current node and then follows only the child selected by the comparison: left if x is smaller, right if it is larger, and it stops with true if they are equal. Each visited node costs one unit. Reaching an empty child ends the search with false at no extra cost: the comparison at the parent has already been paid, and finding that the child pointer is null is part of it. The relation does not otherwise say how the search is carried out, so it is the reference against which the executable function is checked.
Theorem (lookup is a legal search). For every labelled tree and key, lookup performs a legal search, with exactly the result and the cost that it reports.
theorem execution (t : LabelledTree Nat) (x : Nat) : Search t x (lookup t x).1 (lookup t x).2 := lookup_search t xTheorem (membership). In a search tree, lookup finds x exactly when x is one of its keys.
theorem membership (t : LabelledTree Nat) (ordered : t.Ordered) (x : Nat) : (lookup t x).1 = true ↔ x ∈ t.inorder := lookup_correct t ordered xTwo cost statements connect the labelled search to the depth Tree.depth of Chapter 1, which is measured in edges and indexed by inorder rank.
Theorem (cost of a hit). Label a shape t with a strictly increasing list keys of the right length. Searching for the key at inorder position i visits exactly nodes.
/-- Actual key comparisons have precisely the ordinary rank-depth hit cost. -/theorem hit_cost (t : Tree) (keys : List Nat) (same : keys.length = t.size) (increasing : keys.Pairwise (· < ·)) (i : Nat) (valid : i < keys.length) : (lookup (t.labelWith keys) keys[i]).2 = Tree.depth t i + 1 := lookup_rank_cost t keys same increasing i validThis is the same “one plus the depth” that StaticTree.cost charges in Chapter 14, so a static labelled tree is charged as in the rest of the library.
Theorem (uniform cost). If every node of a labelled tree has depth at most , then every search, successful or not, visits at most nodes.
/-- The depth bound applies to unsuccessful searches too. -/theorem uniform_cost (t : LabelledTree Nat) (x : Nat) (D : ℝ) (nonnegative : 0 ≤ D) (depths : ∀ i < t.erase.size, (Tree.depth t.erase i : ℝ) ≤ D) : ((lookup t x).2 : ℝ) ≤ D + 1 := lookup_cost_le t x D nonnegative depthsThe hypothesis is about the depths of the shape (t.erase), indexed by rank; it does not need the tree to be ordered. Failed searches matter here, because in the multiple-tree structure a request that is not in the local tree first fails there and only then falls back. A failed search ends below a node of depth at most , so it too visits at most nodes. is a real number so that it can be a logarithm.
11.2 Stores and their memory
A linked search runs in a store of trees whose nodes carry a successor pointer.
/-- A search node carries a comparison key and a stored successor-root pointer.The two child pointers are supplied by `LabelledTree.node`. -/structure Entry (ι : Type) where key : Nat next : ι deriving DecidableEq, ReprA node entry has a comparison key and a stored pointer next of type ι. The two child pointers are not part of the entry: they are the children of the surrounding LabelledTree node. The type ι is the type of root-cell addresses, introduced next.
/-- An immutable finite directory of local roots and one shared fallback root.An index of type `ι` is a root-cell address, not a key used to search the directory.Reading a stored successor pointer and following it costs one in `Request`.The function denotes the contents of a root table in this pointer model;its Lean evaluation or closure allocation is not a machine-cost semantics. -/structure Store (ι : Type) where roots : ι → LabelledTree (Entry ι) fallback : LabelledTree (Entry ι)A store has a finite table of root cells, indexed by ι, each holding the root of one local tree, and one more cell holding the root of a shared fallback tree. An address p : ι is a memory location, not a key: the store is never searched for p, it is entered at the cell p. The function roots describes the contents of the table. As the docstring warns, Lean’s evaluation of that function is not part of the model and not charged; reading a cell is part of following a link, which is charged in requests below.
Memory is counted in two units.
/-- Storage in nodes, counting every local tree and the shared fallback once. -/def Store.nodes {ι : Type} [Fintype ι] (s : Store ι) : Nat := (∑ p, (s.roots p).erase.size) + s.fallback.erase.size/-- Four words per node (key, successor, and two children), one word per localroot cell, and a fallback-root word. The running cursor needs constant space. -/def Store.words {ι : Type} [Fintype ι] (s : Store ι) : Nat := 4 * s.nodes + Fintype.card ι + 1nodes is the number of tree nodes, summed over all local trees and the fallback. Each tree is counted in full, as if it were stored separately. Trees cannot share nodes in this accounting, so it never undercounts memory. words charges four words per node (the key, the successor pointer and the two child pointers), one word per root cell and one for the fallback cell. The constant space of the running search, its current node and current root address, is not counted. The model treats keys and addresses as fitting in a word, as usual for a pointer machine.
11.3 Installing the links
The multiple-tree structure first builds ordinary labelled trees and then stores a successor pointer in each node.
/-- Install successor pointers during preprocessing. They are then explicitfields of stored nodes, not computed from requested keys at query time. -/def attach {ι : Type} (target : Nat → ι) : LabelledTree Nat → LabelledTree (Entry ι) | .nil => .nil | .node l key r => .node (attach target l) ⟨key, target key⟩ (attach target r)attach target t copies the labelled tree t and gives each node the pointer target key, computed from its own key. This happens once, during preprocessing. At query time, the pointer is a field of the node that has been reached; it is not computed from the requested key. In Chapter 28, target sends each key to the root cell of that key’s own tree.
Theorem (attaching links changes nothing else). Attaching pointers preserves the shape. Searching the linked tree visits exactly the nodes that the plain search visits, and a hit returns the pointer target x of the found key.
theorem shape {ι : Type} (target : Nat → ι) (t : LabelledTree Nat) : (attach target t).erase = t.erase := attach_erase target t/-- Links change the returned payload but do not change the search path. -/theorem search {ι : Type} (target : Nat → ι) (t : LabelledTree Nat) (x : Nat) : lookup (attach target t) x = (if (LabelledTree.lookup t x).1 then some (target x) else none, (LabelledTree.lookup t x).2) := attach_lookup target t x11.4 Searching a linked tree
The search in a linked tree is the labelled search of the first section, returning the stored pointer instead of a boolean.
/-- Compare at a node and follow the selected child. A hit returns the storedsuccessor pointer; a miss returns none. Cost counts visited nodes. -/def lookup {ι : Type} : LabelledTree (Entry ι) → Nat → Option ι × Nat | .nil, _ => (none, 0) | .node l entry r, x => if x < entry.key then let result := lookup l x; (result.1, result.2 + 1) else if x = entry.key then (some entry.next, 1) else let result := lookup r x; (result.1, result.2 + 1)/-- Operational search semantics expose only comparisons and child traversals.One node visit charges a constant unit for these primitive operations. -/inductive Search {ι : Type} : LabelledTree (Entry ι) → Nat → Option ι → Nat → Prop where | empty (x : Nat) : Search .nil x none 0 | found (l r : LabelledTree (Entry ι)) (entry : Entry ι) : Search (.node l entry r) entry.key (some entry.next) 1 | left {l r : LabelledTree (Entry ι)} {entry : Entry ι} {x cost : Nat} {next : Option ι} : x < entry.key → Search l x next cost → Search (.node l entry r) x next (cost + 1) | right {l r : LabelledTree (Entry ι)} {entry : Entry ι} {x cost : Nat} {next : Option ι} : entry.key < x → Search r x next cost → Search (.node l entry r) x next (cost + 1)lookup is the executable search and Search the legal one. The rules are those of LabelledTree.Search: compare, follow the selected child, one unit per visited node. A hit returns some entry.next, the found node’s stored pointer, and a miss returns none. As before, the executable search is legal:
theorem traversal {ι : Type} (t : LabelledTree (Entry ι)) (x : Nat) : Search t x (lookup t x).1 (lookup t x).2 := lookup_search t x11.5 Requests and executions
A request is served from the current root address, the address left by the previous request.
/-- A hit follows the found node's successor pointer. A miss first follows theshared fallback pointer, searches there, then follows its found successor. -/inductive Request {ι : Type} (s : Store ι) (current : ι) (x : Nat) : ι → Nat → Prop where | hit {next : ι} {k : Nat} : Search (s.roots current) x (some next) k → Request s current x next (k + 1) | miss {next : ι} {k h : Nat} : Search (s.roots current) x none k → Search s.fallback x (some next) h → Request s current x next (k + h + 2)Request s current x next cost has two cases.
- Hit. The local tree at
roots currentcontainsx. The search visits nodes and finds the pointernext. Following that pointer costs one more unit, so the request costs . - Miss. The local search visits nodes and fails. The search follows the fallback pointer, for one unit, searches the fallback tree, visiting nodes, finds
xthere, and follows its successor pointer, for another unit. The request costs .
In both cases the new current address is the pointer stored in the node where x was found. The failed local search is charged in full. A key that is missing from the fallback tree as well cannot be requested at all: no Request exists for it.
/-- The executable query rule includes a charged fallback on a local miss. -/def request {ι : Type} (s : Store ι) (current : ι) (x : Nat) : Option ι × Nat := let first := lookup (s.roots current) x match first.1 with | some next => (some next, first.2 + 1) | none => let last := lookup s.fallback x; (last.1, first.2 + last.2 + 2)request is the executable query rule, with the same costs. It returns none as the new address when even the fallback search fails.
Theorem (a query is a legal request). Whenever request returns an address, the corresponding legal request exists, with that address and with the cost that request computes.
/-- The executable request follows the returned stored link, charging itslocal search, any fallback search, and the link traversals. -/theorem query {ι : Type} (s : Store ι) (current next : ι) (x : Nat) (success : (request s current x).1 = some next) : Request s current x next (request s current x).2 := request_correct s current next x successinductive Execution {ι : Type} (s : Store ι) : ι → List Nat → ι → Nat → Prop where | nil {p : ι} : Execution s p [] p 0 | cons {p q r : ι} {x k h : Nat} {xs : List Nat} : Request s p x q k → Execution s q xs r h → Execution s p (x :: xs) r (k + h)An execution serves a list of keys in order from an initial address p. Each request starts at the address returned by the previous one, and the costs add up. The initial address is an explicit parameter; in Chapter 28 it is the root cell of a given predecessor of the first request.
- What a request costs. One unit per visited node, in every tree searched, and one unit per followed pointer: the successor pointer always, the fallback pointer on a miss. Comparisons and child traversals at a node are included in its unit. Since a successful search visits at least one node, every request costs at least .
- What is not charged. Building the store, including the choice of the trees and the computation of the pointers, happens before the requests and is not part of any cost. Lean’s evaluation time of
rootsor oflookupis not modelled either. - Static model. Nothing changes during an execution: the store is the same for every request, and only the current address moves. There are no rotations, and the library does not relate this model to the BST models of Chapter 3 and Chapter 7. It is a separate, explicitly specified pointer model, in which the multiple-tree bound is stated.