Binary Search Trees in Lean Check a result Declarations Bibliography Lean source

Chapter 26 · Tango trees · Section 26.2The Tango BST

No online BST algorithm is known to be dynamically optimal, that is, within a constant factor of the best offline execution on every sequence. Any balanced tree is O(log⁡n)O(\log n)-competitive, and for twenty years after splay trees nothing better was proved. Tango trees were the first online BST with a better ratio: O(log⁡log⁡n)O(\log\log n). This section formalizes them.

Section 26.1 did the counting. It followed the preferred paths of a fixed reference tree as requests arrive, and showed that the number of preference changes is Wilber’s interleave quantity, up to an additive nn for first settings. This section builds the BST that tracks those paths, pays O(log⁡log⁡n)O(\log\log n) per change, and so proves the competitive bound.

Key result · Demaine et al. 2007
Tango trees are O(log⁡log⁡n)O(\log\log n)-competitive

For every nn there is an online BST algorithm, fixed before any request is known, with the following property. Start from any tree on nn keys and serve any sequence XX of keys from {0,…,n−1}\{0,\dots,n-1\}. Every request is a legal access by rotations, and the total cost (rotations plus one per request) is at most

(56 L+16) (OPT+∣X∣)  +  (14 L+6) n,L=log⁡2(⌊log⁡2n⌋+1),\bigl(56\,L + 16\bigr)\,(\mathrm{OPT} + |X|) \;+\; \bigl(14\,L + 6\bigr)\,n, \qquad L = \log_2(\lfloor\log_2 n\rfloor + 1),

where OPT\mathrm{OPT} is the number of rotations of any offline execution that serves XX from the same initial tree. So the algorithm is O(log⁡log⁡n)O(\log\log n)-competitive.

In Lean, the algorithm is an Algorithm, the online algorithms of Chapter 5: a step function that sees only the past requests, the current tree and the new request, certified to perform a legal Access at the cost it reports. The cost is its totalCost, and the comparator is any Execution.

The Lean statement
theoremTango.Algorithm.Results.exists_competitivepropext · Classical.choice · Quot.soundAlgorithms/Tango/Algorithm/Abstract.lean:49
/-- **Tango trees are `O(log log n)`-competitive.** Some online BST algorithm,fixed before any request is known, serves every request sequence from everyinitial tree on `n` keys at total cost (one per request plus rotations) within`O(log log n)` times the cost of any offline execution from the same tree, plus`O(n log log n)` for initialization. It is Tango: a `Policy` run from thebalanced reference tree, after rotating the initial tree into it. -/theorem exists_competitive (n : Nat) :    ∃ A : Algorithm, ∀ {start finish : Tree} {xs : List Nat} {offline : Nat},      start.size = n → Execution start xs finish offline →        (A.totalCost start xs : ℝ) ≤          (56 * Real.logb 2 (Nat.log2 n + 1) + 16) * (offline + xs.length : Nat) +            (14 * Real.logb 2 (Nat.log2 n + 1) + 6) * n := …  Tango.exists_online_bound n
10 definitions in 4 chapters · reading list

The section has two layers. To confirm the result, the box above is enough: its statement uses only the rotation model and the online algorithms of Part I, and the checking page lists those definitions. You never need to know how Tango trees work. To see why the result holds, read on. The section describes the algorithm with its Lean definitions, and states the full theorem again, in English and in Lean, in Section 26.2.7. Section 26.2.1 and Section 26.2.2 build the auxiliary trees and their three operations, Section 26.2.3 the state of the data structure, Section 26.2.4 the interface that any implementation must satisfy, Section 26.2.5 the implementation itself, Section 26.2.6 the bound for every policy, and Section 26.2.7 how a policy becomes an ordinary online algorithm.

The construction is that of Demaine, Harmon, Iacono and Pătraşcu (2007). The BST is a tree of auxiliary trees, one per preferred path. Each auxiliary tree is a BST on the keys of its path, so it has at most hh nodes, where hh is the height of the reference tree. The empty subtrees of an auxiliary tree are not empty in the whole BST: each holds the auxiliary trees of the paths that hang below, in key order. A search for xx walks down through a sequence of auxiliary trees, one per preferred path it crosses. Crossing from one path to the next is a preference change. To keep the structure in sync with the preferences, Tango cuts and joins auxiliary trees, which takes O(log⁡h)O(\log h) per change.

The library follows this plan with one difference. The original paper uses red-black trees with worst-case O(log⁡h)O(\log h) split and concatenate. The library uses splay trees as auxiliary trees and analyses them with the splay potential, so the per-request bound is amortized. The definitions are in Algorithms/Tango/Auxiliary/Definitions/Abstract.lean, State/Abstract.lean, Algorithm/Definitions/Abstract.lean, Algorithm/Request/Abstract.lean and Algorithm/Executable/Abstract.lean; the theorems are in Auxiliary/Abstract.lean and Algorithm/Abstract.lean.

26.2.1 Auxiliary trees inside a BST

An auxiliary tree, together with everything hanging below it, is exactly a rooted region of the BST in the sense of Chapter 8: a Region (the skeleton of Lazy.Skeleton). Its nodes are the active nodes, here the keys of one preferred path. Its holes hold the untouched subtrees below, here the other auxiliary trees. Rotations among the active nodes move the holes as blocks, so they are rotations of the whole BST that never enter a lower auxiliary tree.

Four small functions translate between a region and the plain binary tree of its active part:

defRegion.shapeno axiomsAlgorithms/Tango/Auxiliary/Definitions/Abstract.lean:10
/-- Shape of an auxiliary tree: each attached auxiliary subtree is a leaf. -/def shape : Region → Tree  | .hole _ => .nil  | .node l r => .node (shape l) (shape r)
defRegion.inflateno axiomsAlgorithms/Tango/Auxiliary/Definitions/Abstract.lean:23
/-- Fill a shape's external leaves with fringe subtrees in inorder. -/def inflate : Tree → List Tree → Region  | .nil, fringe => .hole (fringe.headD .nil)  | .node l r, fringe => .node (inflate l fringe) (inflate r (fringe.drop (l.size + 1)))
defRegion.indexpropext · Classical.choice · Quot.soundAlgorithms/Tango/Auxiliary/Definitions/Abstract.lean:15
/-- Rank among the active keys, ignoring all attached fringe subtrees. -/def index (s : Region) (lo key : Nat) : Nat := ((keys s lo).filter (· < key)).card

shape keeps the active nodes and turns every hole into nil. The result is the auxiliary tree itself, as an ordinary Tree whose ranks are ranks among the active keys. inflate goes back: it fills the external leaves of a shape, in inorder, with a list of fringe subtrees. It uses headD .nil and drop so that it is total on lists of the wrong length; the theorems below only apply it to the region’s own fringe, which has exactly one subtree per leaf. index s lo key converts an absolute key of the whole BST into its rank among the active keys of s, by counting the active keys below it. The offset lo is the absolute rank of the region’s first key, as usual.

defRegion.auxiliaryRunno axiomsAlgorithms/Tango/Auxiliary/Definitions/Abstract.lean:28
/-- Splay an auxiliary rank while retaining the complete fringe. The count isonly the actual rotations; reconstruction is a pure presentation of their result. -/def auxiliaryRun (s : Region) (k : Nat) : Region × Nat :=  let result := Splay.run (shape s) k  (inflate result.1 s.fringe, result.2)
defRegion.auxiliaryPotentialpropext · Classical.choice · Quot.soundAlgorithms/Tango/Auxiliary/Definitions/Abstract.lean:18
/-- Potential of the active auxiliary shape. Attached subtrees contribute nomass, because they belong to other auxiliary components. -/noncomputable def auxiliaryPotential (s : Region) : ℝ :=  Splay.potential (fun _ => 1) (shape s) 0

auxiliaryRun s k splays the active rank k with the ordinary Splay.run of Section 24.1 applied to shape s, then re-inflates the result with the original fringe. The rotation count is the count returned by the splay. Splaying the shape and splaying the active part of the full tree perform the same rotations, because a hole is never rotated. auxiliaryPotential s is the splay potential of Section 24.2 with unit weights, applied to the active shape only: ∑vlog⁡2∣active subtree of v∣\sum_v \log_2 |\text{active subtree of } v|. Attached subtrees contribute no mass, because they belong to other auxiliary trees, whose potential is counted separately.

26.2.2 Three amortized operations

Tango needs three operations on auxiliary trees: access a key, cut off a contiguous piece of keys as a separate auxiliary tree, and join an attached auxiliary tree back in. Each is a few splays, and the access lemma gives each an amortized cost of 3log⁡2(size)+13\log_2(\text{size}) + 1. Since an auxiliary tree holds one preferred path, its size is at most the reference height hh, so each operation costs O(log⁡h)=O(log⁡log⁡n)O(\log h) = O(\log\log n) amortized.

Access. Splaying a key of an auxiliary tree brings it to the root of the whole region, without disturbing anything attached below.

Theorem (auxiliary access). Let ss be a region with ∣s∣|s| active keys, and let xx be one of them. Splaying xx within the auxiliary tree is a legal access of xx in the region’s subtree, leaves every attached subtree in place, and has amortized cost at most 3log⁡2∣s∣+13\log_2|s| + 1.

theoremTango.Auxiliary.Results.accesspropext · Classical.choice · Quot.soundAlgorithms/Tango/Auxiliary/Abstract.lean:10
/-- Auxiliary splaying preserves every attached subtree and serves the selectedglobal key. Its amortized cost depends only on the active auxiliary size. -/theorem access (s : Region) (x : Nat) (valid : x ∈ s.keys 0) :    let result := auxiliaryRun s (index s 0 x)    s.fringe = result.1.fringe ∧ Access s.tree result.1.tree x result.2 ∧      (result.2 : ℝ) + auxiliaryPotential result.1 - auxiliaryPotential s ≤        3 * Real.logb 2 s.size + 1 :=  ⟨(auxiliaryRun_correct s _ (index_valid valid)).2.1, auxiliaryRun_access s x valid,    auxiliaryRun_bound s _ (index_valid valid)⟩

For a region s and an active key x, where s.keys 0 means the region’s keys counted from offset 00, the result of splaying x’s active rank:

  1. has the same fringe, in the same order, so every attached auxiliary tree is intact;
  2. is a legal Access of x in the rotation model, so x ends at the root and the count is an exact rotation count; and
  3. satisfies the amortized bound cost+Φ′−Φ≤3log⁡2∣s∣+1\text{cost} + \Phi' - \Phi \le 3\log_2 |s| + 1, where ∣s∣|s| counts active nodes only.

The bound is the access lemma (Results.access_lemma) with unit weights. The root’s mass is ∣s∣|s| and xx’s subtree mass is at least 11. It does not depend on the sizes of the attached subtrees.

Split. Cutting a preferred path at some depth turns its deeper part into a separate auxiliary tree. In key order, the keys of a path below a given depth form a contiguous interval of the path’s keys, so a cut separates a prefix, a suffix, or an interior interval of the active keys. The library states the suffix case.

Theorem (auxiliary split). Let ss be a region and 0<k≤∣s∣0 < k \le |s|. Rotations bring the kk-th active key to the root of the region, with the earlier active keys in a region aa on its left and the later ones in a region bb on its right, and the attached subtrees unchanged. Counting bb from then on as a separate auxiliary tree, the amortized cost is at most 3log⁡2∣s∣+13\log_2|s| + 1.

theoremTango.Auxiliary.Results.splitpropext · Classical.choice · Quot.soundAlgorithms/Tango/Auxiliary/Abstract.lean:20
/-- Mark a suffix as a separate component, retaining all keys in the BST. -/theorem split (s : Region) (k : Nat) (positive : 0 < k) (valid : k ≤ s.size) :    ∃ a b : Region, ∃ cost,      a.size + 1 = k ∧ a.size + b.size + 1 = s.size ∧      s.fringe = (Pointer.Lazy.Skeleton.node a b).fringe ∧      Rotations s.tree (.node a.tree b.tree) cost ∧      (cost : ℝ) + auxiliaryPotential (.node a (.hole b.tree)) + auxiliaryPotential b - auxiliaryPotential s ≤        3 * Real.logb 2 s.size + 1 := auxiliary_cut_suffix s k positive valid

For 0<k≤∣s∣0 < k \le |s|, there are regions a and b such that rotations turn s.tree into node a.tree b.tree. The root of the result is the kk-th active key, a holds the k−1k-1 active keys before it and b the rest, and the fringe is unchanged. The potential afterwards treats b as a separate auxiliary tree: the root component is node a (hole b.tree), in which b is a hole, and b carries its own potential. The amortized cost is again at most 3log⁡2∣s∣+13\log_2|s| + 1. The proof splays the kk-th key to the root. Detaching b only lowers the potential, since it removes b’s mass from the root’s subtree. Prefix and interior cuts are symmetric, or take two such splays. They are internal operations, used by the policy below.

Join. The inverse operation merges an auxiliary tree back into the one above it.

Theorem (auxiliary join). Let right\mathit{right} be a region attached at the last hole of a region left\mathit{left}. Rotations turn left\mathit{left}'s subtree into a single region uu whose active keys are those of both, with the other attached subtrees unchanged, at amortized cost at most 3log⁡2(∣left∣+∣right∣)+13\log_2(|\mathit{left}| + |\mathit{right}|) + 1.

theoremTango.Auxiliary.Results.joinpropext · Classical.choice · Quot.soundAlgorithms/Tango/Auxiliary/Abstract.lean:29
/-- Merge adjacent components, including their actual rotations in the BST. -/theorem join (left right : Region) (attached : left.fringe.getLast? = some right.tree) :    ∃ u cost, u.fringe = left.fringe.dropLast ++ right.fringe ∧      Rotations left.tree u.tree cost ∧      (cost : ℝ) + auxiliaryPotential u - auxiliaryPotential left - auxiliaryPotential right ≤        3 * Real.logb 2 (left.size + right.size : Nat) + 1 := auxiliary_join_bound left right attached

The hypothesis attached says that right hangs from the last hole of left, meaning it is the rightmost attached subtree. The result u has left’s fringe with that last hole replaced by right’s fringe, so right’s active nodes become active in u. It is reached from left.tree by legal rotations, at amortized cost at most 3log⁡2(∣left∣+∣right∣)+13\log_2(|left| + |right|) + 1. The proof splays the maximum of left, which exposes right as its right subtree, and merges.

Reading the Lean

All three statements place the region at offset 00 and conclude Access or Rotations on s.tree, the region’s own subtree. Inside a larger BST, a region sits at some position, and the rotations are lifted there by Rotations.inLeft and Rotations.inRight at the same cost.

26.2.3 Marked trees

The state of the data structure is a BST with one extra bit per child edge, saying whether the edge leaves the current auxiliary tree. The library calls this a marked tree:

inductiveTango.MarkedTreeno axiomsAlgorithms/Tango/State/Abstract.lean:15
/-- A BST with marked child edges. A mark starts a new auxiliary component;unmarked edges connect nodes within the same component. -/inductive MarkedTree where  | nil  | node (left right : MarkedTree) (cutLeft cutRight : Bool)  deriving DecidableEq, Repr
defTango.MarkedTree.treeno axiomsAlgorithms/Tango/State/Abstract.lean:24
def tree : MarkedTree → Tree  | .nil => .nil  | .node l r _ _ => .node l.tree r.tree

The two booleans cutLeft and cutRight belong to the two child edges. A marked edge starts a new auxiliary tree, and an unmarked edge stays inside the current one. tree forgets the marks and returns the plain Tree.

The components are the maximal pieces connected by unmarked edges. Each is viewed as a Region whose holes are the marked subtrees below it:

defTango.MarkedTree.regionno axiomsAlgorithms/Tango/State/Abstract.lean:28
/-- The auxiliary component at the root, with marked subtrees as holes. -/def region : MarkedTree → Region  | .nil => .hole .nil  | .node l r cl cr => .node      (if cl then .hole l.tree else l.region)      (if cr then .hole r.tree else r.region)
defTango.MarkedTree.rootComponentno axiomsAlgorithms/Tango/State/Abstract.lean:35
/-- A nonempty root component, with its global inorder offset. -/def rootComponent (s : MarkedTree) (lo : Nat) : List (Nat × Region) :=  match s with  | .nil => []  | .node _ _ _ _ => [(lo, s.region)]
defTango.MarkedTree.detachedno axiomsAlgorithms/Tango/State/Abstract.lean:41
/-- All components strictly below the root component. -/def detached : MarkedTree → Nat → List (Nat × Region)  | .nil, _ => []  | .node l r cl cr, lo =>      (if cl then l.rootComponent lo else []) ++ l.detached lo ++      (if cr then r.rootComponent (lo + l.tree.size + 1) else []) ++      r.detached (lo + l.tree.size + 1)
defTango.MarkedTree.componentsno axiomsAlgorithms/Tango/State/Abstract.lean:49
def components (s : MarkedTree) (lo : Nat) : List (Nat × Region) :=  s.rootComponent lo ++ s.detached lo

region is the component containing the root: it follows unmarked edges and turns each marked subtree into a hole. rootComponent s lo is that region with its inorder offset lo, or nothing for an empty tree. detached s lo collects, in inorder, the root components of all marked subtrees and, recursively, everything below them, with their offsets. components is the root component followed by the detached ones, so every node lies in exactly one component.

defTango.MarkedTree.potentialpropext · Classical.choice · Quot.soundAlgorithms/Tango/State/Abstract.lean:52
/-- Total potential, summed over actual auxiliary components of the BST. -/noncomputable def potential (s : MarkedTree) : ℝ :=  ((s.components 0).map fun p => Region.auxiliaryPotential p.2).sum
defTango.MarkedTree.initialno axiomsAlgorithms/Tango/State/Abstract.lean:56
/-- Initially every reference node is its own component. -/def initial : Tree → MarkedTree  | .nil => .nil  | .node l r => .node (initial l) (initial r) true true

The potential of a marked tree is the sum of Region.auxiliaryPotential over its components. initial reference is the reference tree with every edge marked. Every node is its own component, which matches the all-singleton preferred paths before any request, and the potential is 00, since a singleton contributes log⁡21\log_2 1.

The invariant ties the marked tree to Section 26.1. Its first half says that the components are the preferred paths:

defTango.MarkedTree.Representspropext · Classical.choice · Quot.soundAlgorithms/Tango/State/Abstract.lean:61
/-- The marked components realize the preferred-path partition. Components arecompared as sets because auxiliary rotations change their depth order. Theroot component must be the preferred path starting at the reference root. -/def Represents (s : MarkedTree) (reference : Tree) (past : List Nat) : Prop :=  s.tree.size = reference.size ∧    ((s.components 0).map fun p => p.2.keys p.1).Perm      ((preferredPaths reference past).map List.toFinset) ∧    s.region.keys 0 = (decomposePaths reference 0 past).1.toFinset

The trees have the same size, the key sets of the components are exactly the key sets of Tango.preferredPaths reference past (as a permutation of lists of finite sets, since rotations change the order in which components are listed), and the root component holds the preferred path that starts at the reference root.

Its second half prescribes the nesting of the components: which component hangs in which hole of which other component, in key order. Shapes inside a component are deliberately forgotten, since splaying changes them.

inductiveTango.ComponentNestingno axiomsAlgorithms/Tango/State/Abstract.lean:72
/-- Ordered nesting of auxiliary components. A branch's children are its fringecomponents, in key order; auxiliary BST shape is deliberately absent. -/inductive ComponentNesting where  | empty  | branch (children : List ComponentNesting)  deriving Repr
defTango.ComponentNesting.fringeno axiomsAlgorithms/Tango/State/Abstract.lean:79
/-- An empty BST is one empty fringe slot. -/def ComponentNesting.fringe : ComponentNesting → List ComponentNesting  | .empty => [.empty]  | .branch children => children
defTango.MarkedTree.nestingno axiomsAlgorithms/Tango/State/Abstract.lean:86
def nesting : MarkedTree → ComponentNesting  | .nil => .empty  | .node l r cl cr => .branch      ((if cl then [nesting l] else (nesting l).fringe) ++       (if cr then [nesting r] else (nesting r).fringe))
defTango.MarkedTree.canonicalno axiomsAlgorithms/Tango/State/Abstract.lean:92
/-- The reference tree with exactly the preferred edges left unmarked. Thisspecifies the component nesting independently of auxiliary-tree rotations. -/def canonical : Tree → Nat → List Nat → MarkedTree  | .nil, _, _ => .nil  | .node l r, lo, past =>      let left := canonical l lo past      let right := canonical r (lo + l.size + 1) past      match (labels lo (lo + l.size) (lo + l.size + 1 + r.size) past).getLast? with      | none => .node left right true true      | some true => .node left right false true      | some false => .node left right true false
defTango.MarkedTree.Maintainspropext · Classical.choice · Quot.soundAlgorithms/Tango/State/Abstract.lean:104
/-- Full maintenance invariant: the preferred-path partition, its root path,and the ordered nesting prescribed by the reference tree. -/def Maintains (s : MarkedTree) (reference : Tree) (past : List Nat) : Prop :=  Represents s reference past ∧ s.nesting = (canonical reference 0 past).nesting

nesting keeps only the tree of components: a branch per component, whose children are the components in its holes, in inorder. canonical reference lo past is the reference tree with exactly the preferred edges left unmarked: at each node, the last label of the node’s interval (from Wilber’s Wilber.labels) says which child is preferred. Maintains asks that the components represent the preferred paths and that their nesting is the nesting of canonical.

Under this invariant the marks carry no information beyond the BST and the history: an edge is marked exactly when its two endpoints lie on different preferred paths. Section 26.2.7 uses exactly this to run Tango without storing the marks.

26.2.4 The online policy

The library does not fix one implementation in its statements. It defines an interface that any Tango-style implementation must satisfy, and proves the competitive bound for every implementation of it:

structureTango.Policypropext · Classical.choice · Quot.soundAlgorithms/Tango/Algorithm/Definitions/Abstract.lean:9
/-- An online marked-BST policy. A step sees only the current state, the past,and the current request, and implements the preference-update/access bound. -/structure Policy (reference : Tree) where  step : List Nat → MarkedTree → Nat → MarkedTree × Nat  correct : ∀ past s x, MarkedTree.Maintains s reference past →    (∀ y ∈ past, y < reference.size) → x < reference.size →    Access s.tree (step past s x).1.tree x (step past s x).2 ∧      MarkedTree.Maintains (step past s x).1 reference (past ++ [x]) ∧      ((step past s x).2 : ℝ) + (step past s x).1.potential - s.potential ≤        (preferenceUpdates reference 0 past x).length * (14 * Real.logb 2 (height reference) + 4) +          (3 * Real.logb 2 (height reference) + 1)

A Policy reference is a step function together with a certificate, in the style of Algorithm. The step receives the past requests, the current marked tree and the request, and returns the next marked tree and a rotation count. It receives nothing about the future. Its certificate correct says that whenever the invariant holds and all requests are valid ranks, the step:

  1. is a legal root access of x in the rotation model, as in every algorithm of Chapter 5;
  2. re-establishes the invariant for the extended history past ++ [x]; and
  3. has amortized cost at most $U⋅(14log⁡2h+4)+3log⁡2h+1,U \cdot (14\log_2 h + 4) + 3\log_2 h + 1,$ where UU is the number of preference updates the request causes, (preferenceUpdates reference 0 past x).length from Section 26.1, and hh is the reference height.

Each preference update is repaired by a few auxiliary splays, cuts and joins, each with amortized cost 3log⁡2h+13\log_2 h + 1 or less, and the final access of xx is one more splay. The constants 1414 and 44 come from the library’s case analysis of a single update.

defTango.Policy.runFrompropext · Classical.choice · Quot.soundAlgorithms/Tango/Algorithm/Definitions/Abstract.lean:21
/-- Execute an online policy, retaining marks as the data structure's state. -/def Policy.runFrom {reference : Tree} (policy : Policy reference) (past : List Nat)    (s : MarkedTree) : List Nat → MarkedTree × Nat  | [] => (s, 0)  | x :: xs =>      let (t, a) := policy.step past s x      let (u, b) := policy.runFrom (past ++ [x]) t xs      (u, a + b)
defTango.Policy.runpropext · Classical.choice · Quot.soundAlgorithms/Tango/Algorithm/Definitions/Abstract.lean:30
/-- Start with singleton preferred paths on the fixed reference tree. -/def Policy.run {reference : Tree} (policy : Policy reference) (xs : List Nat) : MarkedTree × Nat :=  policy.runFrom [] (MarkedTree.initial reference) xs

runFrom threads the marked tree and the history through a request sequence, exactly as Algorithm.runFrom does, and adds the counts. run starts from MarkedTree.initial reference, so the policy starts from the reference tree itself, with every node its own auxiliary tree.

Reading the Lean

Policy is not an Algorithm: its state is a marked tree, not a bare tree. Under the invariant the marks are determined by the tree and the history, so this is a matter of presentation, and the cost counts only rotations, as for algorithms. The library does not package a Policy as an Algorithm.

26.2.5 Serving a request

The executable implementation serves a request in two phases:

defTango.MarkedTree.servepropext · Classical.choice · Quot.soundAlgorithms/Tango/Algorithm/Request/Abstract.lean:9
/-- Serve a request by compiling the reference preference changes, then splayingthe requested key in the resulting root component. Only the past is inspected. -/def serve (s : MarkedTree) (reference : Tree) (past : List Nat) (x : Nat) : MarkedTree × Nat :=  let updated := s.updatePreferences (canonical reference 0 past) (preferenceUpdates reference 0 past x)  let accessed := updated.1.splayRoot (Region.index updated.1.region 0 x)  (accessed.1, updated.2 + accessed.2)

First, updatePreferences replays the update log Tango.preferenceUpdates of the request. For each entry it locates the reference node in the current marked tree and changes the marks of its component. A first setting joins the newly preferred child’s auxiliary tree into the node’s. A switch cuts the old preferred side off as a new auxiliary tree and joins the new one. The canonical marking is passed along so that each edit can find the right component and the interval boundaries of the cut from the reference tree. After the log, the root component is the preferred path from the reference root, which passes through x (Section 26.1.4).

Second, splayRoot splays x, at its active rank in the root component, to the root of the whole BST. The cost is the sum of the two phases’ rotation counts. The function only inspects the past, the current tree and the request.

defTango.policypropext · Classical.choice · Quot.soundAlgorithms/Tango/Algorithm/Executable/Abstract.lean:10
/-- The executable causal policy: compile preference edits and splay the key. -/def policy (reference : Tree) : Policy reference where  step past s x := s.serve reference past x  correct past s x maintained history valid := serve_spec s reference past x maintained history valid

policy reference packages serve as a Policy. Its certificate is the following theorem, which states the three conditions of the contract for serve itself.

Theorem (serving a request). Suppose the marked tree ss satisfies the invariant for the past requests, and all requests so far, and xx, are keys of the reference tree. Then serve performs a legal access of xx in the rotation model, the new marked tree satisfies the invariant for the past requests followed by xx, and the amortized cost is at most U(14log⁡2h+4)+3log⁡2h+1U(14\log_2 h + 4) + 3\log_2 h + 1, where UU is the number of preference updates that xx causes and hh is the reference height.

The library proves this as Tango.Algorithm.Executable.Results.request. Its statement unfolds serve, so it reads the internal definitions of the state machine (component paths, contexts, cuts, joins and splays). It is therefore an internal contract in Algorithm/Executable/Results.lean, not part of the reading interface: the theorems below need only the Policy interface, and Section 26.2.7 needs only that some policy exists. So the interface is not vacuous.

Theorem (a policy exists). For every reference tree there is a policy.

The witness is the executable policy reference. The proof ⟨policy reference⟩ is visible in the source.

26.2.6 Competitiveness

Every policy, run on a valid sequence, performs a legal execution of the rotation model and ends with the preferred paths of the whole history.

Theorem (Tango’s runs are executions). Let pp be a policy for a reference tree PP, and let XX be a sequence of keys of PP. The run of pp on XX is a legal execution of XX from PP whose rotation count is the count that pp reports. The final marked tree satisfies the invariant for XX.

theoremTango.Algorithm.Results.executionpropext · Classical.choice · Quot.soundAlgorithms/Tango/Algorithm/Abstract.lean:12
/-- Every requested rank is actually accessed, and the final marking realizesthe canonical preferred paths and nesting. -/theorem execution {reference : Tree} (p : Policy reference) (xs : List Nat)    (valid : ∀ x ∈ xs, x < reference.size) :    Execution reference xs (p.run xs).1.tree (p.run xs).2 ∧      MarkedTree.Maintains (p.run xs).1 reference xs :=  ⟨(p.run_spec xs valid).1, (p.run_spec xs valid).2.1⟩

The execution starts from reference, which is where run starts. Its cost is the policy’s own count (p.run xs).2. This theorem is what gives meaning to that count in the bounds below: it is the exact number of rotations of an Execution.

The main theorem compares the policy’s total cost with every offline execution.

Theorem (Tango is competitive). Let pp be a policy for a reference tree of height hh on nn keys. Take any offline execution that serves a sequence XX of mm requests with RR rotations, starting from any tree on nn keys. Then pp serves XX with total cost, rotations plus mm, at most (56log⁡2h+16)(R+m)+(14log⁡2h+4) n(56\log_2 h + 16)(R + m) + (14\log_2 h + 4)\,n.

theoremTango.Algorithm.Results.competitivepropext · Classical.choice · Quot.soundAlgorithms/Tango/Algorithm/Abstract.lean:20
/-- The policy is fixed independently of the offline comparator and its requestsequence. Cost includes one unit per request, with a separate initialization term. -/theorem competitive {reference : Tree} (p : Policy reference)    {start finish : Tree} {xs : List Nat} {offline : Nat}    (size : reference.size = start.size) (comparator : Execution start xs finish offline) :    ((p.run xs).2 : ℝ) + xs.length ≤      (56 * Real.logb 2 (height reference) + 16) * (offline + xs.length : Nat) +        (14 * Real.logb 2 (height reference) + 4) * reference.size :=  p.competitive_bound size comparator

Write L=log⁡2hL = \log_2 h, mm for the number of requests, and RR for the rotations of any offline execution comparator of the same requests, from any start tree of the same size as the reference. Then $TTango  =  rotations+m  ≤  (56L+16)(R+m)+(14L+4) n.T_{\text{Tango}} \;=\; \text{rotations} + m \;\le\; (56L + 16)(R + m) + (14L + 4)\,n.$ The left side is the conventional total cost. The right side is O(log⁡h)O(\log h) times the comparator’s total cost, plus an initialization term.

The proof composes three facts. Summing the per-request contract and telescoping the potential, which starts at 00 and is never negative, gives at most ∣log∣⋅(14L+4)+m(3L+1)|\text{log}| \cdot (14L + 4) + m(3L + 1) rotations. The log has at most interleave+n\text{interleave} + n entries (Results.preference_settings and Results.interleave_switches). Wilber’s bound gives interleave≤4R+2m\text{interleave} \le 4R + 2m (Results.rotation_lower_bound). Multiplying out, RR gets the coefficient 4(14L+4)=56L+164(14L + 4) = 56L + 16, and mm gets less than that.

Reading the Lean
  • The comparator is arbitrary: any offline strategy, from any start tree of the right size, with any final tree. The bound holds against all of them at once, and in particular against the optimum.
  • The theorem is about every p : Policy reference, not only the executable policy. The bound follows from the contract alone.
  • The hypothesis size fixes the key universe. Validity of the requests is not assumed: it follows from the existence of the comparator (execution_exists_iff).

For the classical reference trees the height is logarithmic, so the factor is doubly logarithmic.

Corollary (perfect reference tree). On n=2h−1n = 2^h - 1 keys, with the perfect reference tree, the bound holds with factor 56log⁡2h+1656\log_2 h + 16 and additive term (14log⁡2h+4) n(14\log_2 h + 4)\,n.

Corollary (every nn). For every nn, with the balanced reference tree on nn keys, the bound holds with hh replaced by ⌊log⁡2n⌋+1\lfloor\log_2 n\rfloor + 1. With the reset of Section 26.2.7, this gives the result stated at the top of the section.

theoremTango.Algorithm.Results.perfect_competitivepropext · Classical.choice · Quot.soundAlgorithms/Tango/Algorithm/Abstract.lean:30
/-- On `2^h - 1` keys the factor is logarithmic in `h`. -/theorem perfect_competitive (h : Nat) (p : Policy (perfect h))    {start finish : Tree} {xs : List Nat} {offline : Nat}    (size : (perfect h).size = start.size) (comparator : Execution start xs finish offline) :    ((p.run xs).2 : ℝ) + xs.length ≤      (56 * Real.logb 2 h + 16) * (offline + xs.length : Nat) +        (14 * Real.logb 2 h + 4) * (2 ^ h - 1 : Nat) :=  p.perfect_competitive_bound h size comparator
theoremTango.Algorithm.Results.balanced_competitivepropext · Classical.choice · Quot.soundAlgorithms/Tango/Algorithm/Abstract.lean:39
/-- The doubly logarithmic coefficient holds for every universe size, using anexecutable balanced reference tree with exactly `n` keys. -/theorem balanced_competitive (n : Nat) (p : Policy (balanced n))    {start finish : Tree} {xs : List Nat} {offline : Nat}    (size : start.size = n) (comparator : Execution start xs finish offline) :    ((p.run xs).2 : ℝ) + xs.length ≤      (56 * Real.logb 2 (Nat.log2 n + 1) + 16) * (offline + xs.length : Nat) +        (14 * Real.logb 2 (Nat.log2 n + 1) + 4) * n :=  p.balanced_competitive_bound n size comparator

perfect_competitive is competitive for perfect h, rewritten with Results.perfect_reference: on n=2h−1n = 2^h - 1 keys the factor is 56log⁡2h+1656\log_2 h + 16, with h=log⁡2(n+1)h = \log_2(n+1). balanced_competitive covers every nn with the executable Tree.balanced reference tree. Its height is at most ⌊log⁡2n⌋+1\lfloor\log_2 n\rfloor + 1, so $TTango≤(56log⁡2(⌊log⁡2n⌋+1)+16)(R+m)+(14log⁡2(⌊log⁡2n⌋+1)+4) n.T_{\text{Tango}} \le \bigl(56\log_2(\lfloor\log_2 n\rfloor + 1) + 16\bigr)(R + m) + \bigl(14\log_2(\lfloor\log_2 n\rfloor + 1) + 4\bigr)\,n.$ This is the O(log⁡log⁡n)O(\log\log n)-competitiveness of Tango trees, with explicit constants.

Compared with the paper
  • Initial tree. A policy starts from its reference tree, while the comparator starts from any tree of the same size. The next section removes this difference.
  • Amortized auxiliary trees. The bound is amortized over the whole sequence, through the splay potential. The original analysis with red-black auxiliary trees bounds each request separately. The competitive ratio is the same, O(log⁡log⁡n)O(\log\log n).
  • Uncharged planning. As everywhere in the rotation model, only rotations and requests are charged. Locating reference nodes, computing the update log and finding cut boundaries are computation on the history, and are free.
  • Constants. The constants are explicit and not optimized. Only the order O(log⁡log⁡n)O(\log\log n) is meaningful.
  • Not dynamic optimality. The factor grows with nn, so this is not a proof that any algorithm is TotallyDynamicallyOptimal.

26.2.7 From a policy to an algorithm

A policy is not literally an online algorithm in the sense of Chapter 5. Its state is a marked tree rather than a tree, it starts from its own reference tree, and its contract only holds while the invariant does. All three differences disappear in one construction.

  • The marks are recomputed. An Algorithm sees the past requests, and the marks are a function of them: the run of the policy on the past requests ends in a marked tree that satisfies the invariant. So the algorithm replays the policy on the past requests to recover its marked tree. If the given tree is that marked tree’s plain tree, the algorithm takes the policy’s step. Otherwise it splays the request, which is always a legal access. In a run from the reference tree the first case always applies, so the algorithm performs exactly the policy’s rotations. Replaying is free, like all planning in the rotation model.
  • The start is reset. On the first request, the algorithm rotates whatever tree it is given into the reference tree, using at most 2n2n rotations (Geometry.reset), and then continues as above. This is the same wrapper that makes the geometric simulation of Section 25.2 work from every initial tree.

With the balanced reference tree, the 2n2n rotations of the reset raise the additive term from (14L+4) n(14L + 4)\,n to (14L+6) n(14L + 6)\,n.

Theorem (Tango trees are O(log⁡log⁡n)O(\log\log n)-competitive). For every nn there is an online algorithm such that, for every initial tree on nn keys and every offline execution that serves a sequence XX of mm requests from that tree with RR rotations, the algorithm’s total cost on XX is at most (56L+16)(R+m)+(14L+6) n(56L + 16)(R + m) + (14L + 6)\,n, where L=log⁡2(⌊log⁡2n⌋+1)L = \log_2(\lfloor\log_2 n\rfloor + 1).

theoremTango.Algorithm.Results.exists_competitivepropext · Classical.choice · Quot.soundAlgorithms/Tango/Algorithm/Abstract.lean:49
/-- **Tango trees are `O(log log n)`-competitive.** Some online BST algorithm,fixed before any request is known, serves every request sequence from everyinitial tree on `n` keys at total cost (one per request plus rotations) within`O(log log n)` times the cost of any offline execution from the same tree, plus`O(n log log n)` for initialization. It is Tango: a `Policy` run from thebalanced reference tree, after rotating the initial tree into it. -/theorem exists_competitive (n : Nat) :    ∃ A : Algorithm, ∀ {start finish : Tree} {xs : List Nat} {offline : Nat},      start.size = n → Execution start xs finish offline →        (A.totalCost start xs : ℝ) ≤          (56 * Real.logb 2 (Nat.log2 n + 1) + 16) * (offline + xs.length : Nat) +            (14 * Real.logb 2 (Nat.log2 n + 1) + 6) * n :=  Tango.exists_online_bound n

This is the result stated at the top of the section. The comparator now starts from the same tree as the algorithm, as in the definition of competitiveness (TotallyDynamicallyOptimal, Chapter 5), except that the factor is O(log⁡log⁡n)O(\log\log n) instead of a constant. The statement mentions only the rotation model and the online algorithms of Part I. The proof is in Algorithms/Tango/Algorithm/Online.lean; the reset wrapper is in Models/Online/Reset.lean.

The startup term (14L+6) n(14L + 6)\,n is O(nlog⁡log⁡n)O(n \log\log n). Section 26.3 brings it down to O(n)O(n) by updating preferences from the bottom of the search path upwards. That linear startup is what the combined bound of Iacono and Langerman needs (Chapter 31).