Chapter 39 · Saving trees in their nodes · Section 39.2Snapshots
The combined search tree of Section 29.1 runs two online BST algorithms in alternating rounds. Each round starts from the same initial tree : when a round runs out of budget, the structure transforms whatever tree it has back into , and the other algorithm takes over. A BST cannot keep a second copy of on the side. Demaine, Iacono, Langerman and Özkan (2013) therefore store inside the tree itself, in the bits of augmented data that every node may carry. Their tree state buffer (TSB, Section 3 of the paper) supports two operations. SaveState() records the current tree in the buffer, and LoadState() transforms the current tree, whatever it is, into the recorded one. The encoding is simple. Run a linear-time algorithm that rotates the tree into a path, and record its operations. To load, rotate the current tree into the same path, then undo the recorded operations. Lemma 10 of the paper says that both operations take steps.
This section formalizes the tree state buffer on the cells and scans of Section 39.1, with explicit constants and with a payload of twelve bits per node.
Consider a tree with nodes and one data cell per node, indexed by inorder rank, as in the buffers of Section 39.1. Two fingers share the tree: a tree finger that moves and rotates, and a buffer finger that walks from cell to cell and reads or writes the cell under it.
Save. Starting from a tree , with both fingers at the root and arbitrary initial cell contents, there is a save execution that ends with the same tree and the tree finger at its root, and that leaves in the cells the snapshot of : a fixed value below in every cell, determined by (CellIO.Stored). It costs at most . The cost counts every tree-finger instruction and every buffer-finger move, read and write.
Load. Suppose the cells hold the snapshot of a tree , and the current tree has the same number of nodes, with both fingers at its root. Then there is a load execution that ends with the tree and the tree finger at its root, at cost at most , counted in the same way. The load never writes a cell, and its steps depend only on the current tree and on the cell contents; appears only in the conclusion.
The Lean statements
/-- Recording followed by streaming restoration is a shape-preserving save costing at most 72n. -/theorem save (tree : Tree) (data : Nat → Nat) : ∃ finalData cost, Save data tree finalData cost ∧ CellIO.Stored tree finalData ∧ cost ≤ 72 * tree.size := … Recording.save tree dataModels.Rotation, Models.Pointer.Machine, Models.Pointer.Walk.Definitions, Models.Multifinger.Program.Definitions, Models.Multifinger.Program.Replay.Definitions, Bounds.StaticTree.Definitions, Bounds.LazyFinger.Definitions, Models.Labelled.Metadata.Definitions, Structures.TreeBuffer.Scan.Definitions, Structures.TreeBuffer.Cells.Definitions, Structures.TreeBuffer.Snapshot.Definitions, Structures.TreeBuffer.Snapshot.CellIO.Definitions, Structures.TreeBuffer.Snapshot.Controller.Definitions, Structures.TreeBuffer.Snapshot.Streaming.Definitions, Structures.TreeBuffer.Snapshot.Recording.Definitions/-- Normalization followed by streaming restoration costs at most 56n. -/theorem load (saved current : Tree) (same : current.size = saved.size) (data : Nat → Nat) (stored : CellIO.Stored saved data) : ∃ cost, Load data current saved cost ∧ cost ≤ 56 * current.size := … Streaming.load saved current same data storedModels.Rotation, Models.Pointer.Machine, Models.Pointer.Walk.Definitions, Models.Multifinger.Program.Definitions, Models.Multifinger.Program.Replay.Definitions, Bounds.StaticTree.Definitions, Bounds.LazyFinger.Definitions, Models.Labelled.Metadata.Definitions, Structures.TreeBuffer.Scan.Definitions, Structures.TreeBuffer.Cells.Definitions, Structures.TreeBuffer.Snapshot.Definitions, Structures.TreeBuffer.Snapshot.CellIO.Definitions, Structures.TreeBuffer.Snapshot.Controller.Definitions, Structures.TreeBuffer.Snapshot.Streaming.DefinitionsThe two theorems are the abstract counterpart of Lemma 10. The save executes the formal Recording.Save, and the load executes Streaming.Load; both are defined in Section 39.2.9. Rotations performed by the tree finger are charged once, as tree-finger instructions; the buffer finger is not charged for them, but the detours they force on it are charged as buffer moves.
Read it if you want to see how the combined tree returns to its initial state between rounds. The restart of a worker in Section 29.4 (Results.restart) and the one-time preparation before the first request (Online.Prepared) both call the machinery of this section, through the shared-node versions of Section 39.2.10. A reader who only wants to check the combining theorem can skip it: what that theorem needs is stated in its own hypotheses and conclusions in Section 29.1. The Lean sources are in Structures/TreeBuffer/Snapshot.
39.2.1 Overview
The development has three layers.
Instruction streams. The first layer works with lists of the six primitive opcodes of the multi-finger model (Multifinger.Opcode): move to the left or right child, move up from a left or right child, rotate the focused left or right child over its parent. Multifinger.replay runs such a list on a pointer cursor, and Multifinger.undo inverts it. Section 39.2.2 defines the normalizer that rotates any tree into the right path on its keys, the vine, and its log Snapshot.record. Save is “normalize, then undo the log”. Load is “normalize the current tree, then undo the saved log”. The log identifies the tree, has at most opcodes, and fits four opcodes into each of the cells, as base-seven digits of a twelve-bit number (Section 39.2.4).
Machines. The second layer turns these streams into machines that keep only bounded working storage. A local controller computes the normalization log one opcode at a time from the focused subtree, a mode and a depth counter (Section 39.2.6). Recording runs the controller and, after every four opcodes, lets the buffer finger write the packet into the next cell (Section 39.2.7). Streaming restoration reads the cells in descending order and undoes each packet locally, so it never needs the reversed log as a whole (Section 39.2.5 and Section 39.2.8). The buffer finger’s walk is charged with the scan potential of Section 39.1, which absorbs the rotations made by the other finger, as in Lemma 9 of the paper.
Shared nodes. The third layer places both fingers on one labelled tree of Section 39.1, with routing words and payload fields in every node (Section 39.2.10). Its theorems are internal; the combining construction uses them.
The headline theorems belong to the second layer. Their cost is the sum of three counts: tree-finger instructions, buffer-finger moves and buffer-finger cell visits.
39.2.2 Normalizing to a vine
The target shape is the vine, the tree whose nodes all lie on the right spine:
/-- Canonical right path on the same inorder keys. -/def vine : Nat → Tree | 0 => .nil | n + 1 => .node .nil (vine n)vine n has nodes, all with empty left subtrees. Its root has key . The paper flattens the tree into a left path; the right path is the mirror image and changes nothing.
The normalizer walks down the right spine. At a node with an empty left subtree, it moves to the right child, normalizes there, and moves back up. At a node with a nonempty left subtree, it moves to the left child and rotates it over its parent, which moves one node from the left subtree to the spine; the cursor is then back at the same depth, on the rotated node, and the normalizer continues there.
/-- Each normalization rotation or advance decreases this measure by one. -/def work : Tree → Nat | .nil => 0 | .node l r => 2 * l.size + 1 + work r/-- Recorded normalization instructions. The fuel is sufficient when it bounds`work`; exhausted fuel only totalizes malformed calls to the helper. -/def recordFuel : Nat → Tree → List Opcode | 0, _ => [] | _ + 1, .nil => [] | _ + 1, .node .nil .nil => [] | fuel + 1, .node .nil (.node a b) => .downRight :: (recordFuel fuel (.node a b) ++ [.upRight]) | fuel + 1, .node (.node a b) c => .downLeft :: .rotateLeftChild :: recordFuel fuel (.node a (.node b c))/-- A snapshot contains only primitive opcodes, not a copy of the saved tree. -/def record (t : Tree) : List Opcode := recordFuel (work t) trecordFuel fuel t returns the opcodes this procedure emits on t:
- on an empty tree or a leaf, nothing;
- on
node nil (node a b),downRight, then the opcodes for the right subtree, thenupRight; - on
node (node a b) c,downLeft,rotateLeftChild, then the opcodes for the rotated treenode a (node b c).
The recursion on the rotated tree is not structural, so it is driven by a fuel argument. work t is a measure that decreases by one at every recursive call: for the root with left subtree , plus the work of the right subtree. A descent drops the root’s term; a rotation of node (node a b) c into node a (node b c) replaces by . record t uses exactly work t as fuel, which is enough, so the fuel only totalizes the helper. The log contains opcodes only. It does not contain the tree, or any key.
Theorem (normalization). From any cursor focused on the root of a subtree , under any ancestor context, replaying record t turns the subtree into the vine on nodes, with the cursor back on its root in the same context. The log has at most opcodes.
Theorem (the log identifies the tree). Two trees with the same number of nodes and the same log are equal.
/-- A linear-length normalization log with exact cursor/context preservation. -/theorem normalization (t : Tree) (cs : List Pointer.Frame) : replay (record t) ⟨t, cs⟩ = some ⟨vine t.size, cs⟩ ∧ (record t).length ≤ 4 * t.size := ⟨record_replay t cs, record_length t⟩/-- The log and universe size determine the entire saved tree. -/theorem identifies (s t : Tree) (same : s.size = t.size) (logs : record s = record t) : s = t := record_injective s t same logsThe ancestor context cs in normalization is the zipper context of Chapter 7 (Pointer.Frame): normalization is a local computation that never leaves the subtree. The length bound has a simple reason: every opcode pair is either a rotation (downLeft, rotateLeftChild) or a spine descent (downRight with its later upRight), there are fewer than rotations, since each puts a new node on the spine, and fewer than descents. identifies is the reason why the log is a faithful snapshot. Intuitively, undoing the log from the vine returns the tree, the vine is fixed by , and the undo is fixed by the log.
A three-node example
Let be the balanced tree on keys , with root . The root has a nonempty left subtree, so the normalizer emits downLeft and rotateLeftChild: node becomes the root, and the tree is already the vine . It then descends the spine twice and climbs back:
record t = [downLeft, rotateLeftChild, downRight, downRight, upRight, upRight]
Six opcodes, within the bound . Undoing reverses the list and inverts each opcode, where the inverse of a rotation takes three instructions (see Section 39.2.3):
undo (record t) = [downRight, downRight, upRight, upRight,
downRight, rotateRightChild, downLeft, upLeft]
From the vine, the first four opcodes walk down to key and back. Then downRight moves to key , rotateRightChild rotates it over key , which restores the balanced tree with the cursor on its root , and downLeft, upLeft visit key and come back.
39.2.3 Save and load as instruction streams
The inverse of a single opcode is the move in the opposite direction, or, for a rotation, three instructions: the rotated node is now the parent of its old parent, so the cursor steps down to the old parent, rotates it back up, and steps down again (Opcode.inverse). undo reverses a list and inverts each opcode.
/-- Run normalization and immediately undo it, leaving the saved tree in place.The normalization prefix is the retained snapshot. -/def saveProgram (t : Tree) : List Opcode := record t ++ undo (record t)/-- Normalize the current tree, then undo the saved log. The target tree is notan argument: its structure is recovered solely from the recorded instructions. -/def loadProgram (current : Tree) (saved : List Opcode) : List Opcode := record current ++ undo savedsaveProgram t normalizes and immediately undoes. Its first half, record t, is the part that the snapshot retains. loadProgram current saved normalizes the current tree with its own log and then undoes a saved log. The saved tree is not an argument: only its log is.
Theorem (save as a stream). The stream saveProgram t is a legal pointer-machine trace from , with the cursor at the root, back to , with the cursor at the root. It has at most instructions.
Theorem (load as a stream). If the current tree and the saved tree have the same number of nodes, the stream loadProgram current (record s) is a legal pointer-machine trace from the current tree to , root to root, with at most instructions.
/-- Save without changing the tree. This bound counts pointer instructions,with the cost of writing the retained log to node cells accounted separately. -/theorem save (t : Tree) : Pointer.Trace ⟨t, []⟩ ⟨t, []⟩ (saveProgram t).length ∧ (saveProgram t).length ≤ 16 * t.size := ⟨save_trace t, save_length t⟩/-- Restore using only the current tree and a saved instruction stream. -/theorem load (current saved : Tree) (same : current.size = saved.size) : Pointer.Trace ⟨current, []⟩ ⟨saved, []⟩ (loadProgram current (record saved)).length ∧ (loadProgram current (record saved)).length ≤ 16 * current.size := ⟨load_trace current saved same, load_length current saved same⟩The traces are Pointer.Traces of Chapter 7, whose count is the number of instructions. The bound is for the log plus for its undo, since each opcode expands into at most three. These two theorems say nothing about storing the log: in this layer the stream is simply a list. Storing it in the nodes is the subject of the next two sections, and its cost is counted in Section 39.2.7.
39.2.4 Packing the log into the nodes
The log has at most opcodes and the tree has nodes, so four opcodes per node suffice.
/-- Pack at most four opcodes into each of a fixed number of inorder cells.Unused cells are empty; inputs exceeding capacity are truncated by the helper. -/def pack : Nat → List Opcode → List (List Opcode) | 0, _ => [] | n + 1, ops => ops.take 4 :: pack n (ops.drop 4)/-- The saved instruction stream occupies exactly one bounded packet per node. -/def cells (t : Tree) : List (List Opcode) := pack t.size (record t)pack n ops cuts ops into packets of at most four opcodes, in order. Packets past the end of the list are empty, and opcodes beyond capacity would be dropped; for a log this never happens. cells t is the packing of record t into exactly packets, one per node. Packet belongs to the node of inorder rank . Since rotations preserve the inorder, that node keeps its packet whatever the shape becomes.
Each packet is encoded as a number:
/-- Nonzero base-seven digits reserve zero for the end of a packet. -/def opcodeDigit : Opcode → Nat | .downLeft => 1 | .downRight => 2 | .upLeft => 3 | .upRight => 4 | .rotateLeftChild => 5 | .rotateRightChild => 6def digitOpcode : Nat → Option Opcode | 1 => some .downLeft | 2 => some .downRight | 3 => some .upLeft | 4 => some .upRight | 5 => some .rotateLeftChild | 6 => some .rotateRightChild | _ => nonedef encodeCell : List Opcode → Nat | [] => 0 | op :: ops => opcodeDigit op + 7 * encodeCell ops/-- Four decoding rounds suffice for every stored cell. -/def decodeFuel : Nat → Nat → List Opcode | 0, _ => [] | fuel + 1, code => match digitOpcode (code % 7) with | none => [] | some op => op :: decodeFuel fuel (code / 7)def decodeCell (code : Nat) : List Opcode := decodeFuel 4 codeThe six opcodes are the digits to in base seven, and the digit marks the end of a packet. encodeCell writes the first opcode as the least significant digit. decodeCell reads at most four digits and stops at the first (or at an invalid digit, which digitOpcode maps to none). A packet of at most four opcodes is a number below , and decoding it returns the packet.
def encodedCells (t : Tree) : List Nat := (cells t).map encodeCelldef decodeCells (codes : List Nat) : List Opcode := (codes.map decodeCell).flattendef loadEncoded (current : Tree) (codes : List Nat) : List Opcode := loadProgram current (decodeCells codes)encodedCells t is the list of the cell values, in inorder. decodeCells decodes a list of values and concatenates the packets. loadEncoded current codes is the load stream computed from encoded cells: normalize current, then undo the decoded log.
Theorem (twelve bits per node). The snapshot of has exactly values, each below , and decoding them returns the log record t.
Theorem (restoring from the encoded cells). If the current tree and have the same number of nodes, the load stream computed from the current tree and the encoded snapshot of turns the current tree into , under any unchanged ancestor context, with at most instructions.
/-- One twelve-bit payload per node suffices, including unused zero packets. -/theorem storage (t : Tree) : (encodedCells t).length = t.size ∧ (∀ code ∈ encodedCells t, code < 2 ^ 12) ∧ decodeCells (encodedCells t) = record t := ⟨encodedCells_length t, encodedCells_bound t, decodeCells_encoded t⟩/-- The packed payloads restore the exact tree in any unchanged ancestor context.The target appears only in the specification, not as an input to `loadEncoded`. -/theorem encoded_restore (current saved : Tree) (same : current.size = saved.size) (cs : List Pointer.Frame) : replay (loadEncoded current (encodedCells saved)) ⟨current, cs⟩ = some ⟨saved, cs⟩ ∧ (loadEncoded current (encodedCells saved)).length ≤ 16 * current.size := ⟨loadEncoded_replay current saved same cs, loadEncoded_length current saved same⟩In encoded_restore, the target saved occurs only in the specification: the stream is computed from current and the list of numbers. Because of the context cs, the restoration also works on a subtree, as long as nothing above it changes.
39.2.5 Snapshot cells and inversion
The machines below do not handle lists of cells. They have a cell field in each node, modelled as a function from keys to values, as in Cells.State.
/-- The snapshot's desired node fields. Indexing is a layout specification;the operational implementation accepts and returns scalar values at its cursor. -/def payload (saved : Tree) (key : Nat) : Nat := ((encodedCells saved)[key]?).getD 0/-- The finite node universe contains this snapshot, regardless of its currentshape. Values outside the saved tree's key universe are not constrained. -/def Stored (saved : Tree) (data : Nat → Nat) : Prop := ∀ key, key < saved.size → data key = payload saved keypayload saved key is the value that the snapshot of saved puts in the cell of rank key, and beyond the end of the list. Stored saved data says that a cell function holds the snapshot of saved: it agrees with payload saved on every rank below . Values at larger ranks are unconstrained, since no node has them. Stored speaks only about the cells. It says nothing about the current shape, which may be anything: this is the situation of the combined tree in the middle of a round, after a worker has rotated the tree for a while without touching the snapshot cells.
Restoring requires the log undone, that is reversed and inverted. A machine with bounded storage cannot reverse a list of opcodes. It does not need to: undoing a concatenation of packets is the concatenation of the undone packets in reverse order, so reading the cells backwards and undoing each packet on its own produces exactly the undo of the whole log.
/-- Consume cells in descending key order, undoing each four-opcode packetlocally. This is the emitted instruction stream, not an extra stored log. -/def inverseCells (codes : List Nat) : List Multifinger.Opcode := codes.flatMap fun code => Multifinger.undo (decodeCell code)inverseCells codes decodes each value, undoes the packet, and concatenates. Applied to the cell values in descending rank order, it is undo (record saved). For the three-node example, the cells are (packets [downLeft, rotateLeftChild, downRight, downRight], [upRight, upRight] and the empty packet). Reading them as and undoing each gives [], then [downRight, downRight], then [upRight, upRight, downRight, rotateRightChild, downLeft, upLeft], which concatenate to the undo stream shown above. An undone packet has at most opcodes, which is the bound on retained storage in Section 39.2.8.
39.2.6 A local normalizer
The normalizer of Section 39.2.2 is a recursive function on the whole tree. The controller computes the same opcodes as a finite-state machine that looks only at the subtree under its cursor.
inductive Mode where | scan | promote | ascend deriving DecidableEq/-- A cursor, one spine-depth counter, and a finite control mode. The tree inthe cursor is the machine's tree, not an additional saved copy. -/structure State where cursor : Pointer.Config depth : Nat mode : Mode deriving DecidableEqThe state is a pointer cursor (Pointer.Config), a counter depth and a mode. The cursor’s tree is the machine’s tree, not a saved copy. depth counts the right-spine descents not yet climbed back. The three modes are scan (decide what to do at the current spine node), promote (the cursor has just moved to a left child, which must now be rotated up) and ascend (normalization is finished, climb back to the root).
/-- Select the next action using only the current focus, mode, and depth counter.`none` as the opcode is a control-only transition into the return phase. -/def choose (s : State) : Option (Option Opcode × Mode × Nat) := match s.mode, s.cursor.focus, s.depth with | .scan, .nil, d => some (none, .ascend, d) | .scan, .node .nil .nil, d => some (none, .ascend, d) | .scan, .node .nil (.node _ _), d => some (some .downRight, .scan, d + 1) | .scan, .node (.node _ _) _, d => some (some .downLeft, .promote, d) | .promote, _, d => some (some .rotateLeftChild, .scan, d) | .ascend, _, 0 => none | .ascend, _, d + 1 => some (some .upRight, .ascend, d)/-- Execute the selected pointer instruction. A failed instruction is notsilently converted into a state change. -/def tick (s : State) : Option (Option Opcode × State) := (choose s).bind fun (op, mode, depth) => match op with | none => some (none, ⟨s.cursor, depth, mode⟩) | some instruction => (perform instruction s.cursor).map fun cursor => (some instruction, ⟨cursor, depth, mode⟩)choose is the transition table, and it reads only the mode, the shape of the focused subtree near its root, and whether depth is zero:
| mode | focus | action | next mode | depth |
|---|---|---|---|---|
scan |
empty or a leaf | none | ascend |
unchanged |
scan |
empty left, nonempty right | downRight |
scan |
|
scan |
nonempty left | downLeft |
promote |
unchanged |
promote |
any | rotateLeftChild |
scan |
unchanged |
ascend |
any, depth | upRight |
ascend |
|
ascend |
any, depth | halt |
The pending upRights of the recursive normalizer all come at the end of its output, so a counter can replace the recursion. tick performs the chosen instruction with Multifinger.perform. A transition without an opcode only changes the mode. A failing instruction makes tick return none, so failure cannot pass for a step.
/-- Exact emitted log, including the control-only transition separately fromthe physical instruction count. A run may end at an intermediate state. -/inductive Run : State → List Opcode → State → Prop where | refl {s : State} : Run s [] s | silent {s t u : State} {ops : List Opcode} : tick s = some (none, t) → Run t ops u → Run s ops u | instruction {s t u : State} {op : Opcode} {ops : List Opcode} : tick s = some (some op, t) → Run t ops u → Run s (op :: ops) uRun s ops u is a sequence of ticks from s to u whose emitted opcodes are ops. Silent transitions emit nothing. A run may stop anywhere; this is what lets the recording interleave it with cell writes.
Theorem (the controller normalizes). From the root of any tree , in mode scan with counter , the controller emits exactly record t and reaches the root of the vine, in mode ascend with counter , where it halts. Every run replays its emitted opcodes on the cursor. Along every run from the root of , the counter is at most ; more precisely, the counter plus the size of the focused subtree is at most .
/-- A local controller emits exactly the normalizing instruction stream. -/theorem normalizes (t : Tree) : Run ⟨⟨t, []⟩, 0, .scan⟩ (record t) ⟨⟨vine t.size, []⟩, 0, .ascend⟩ := normalization ttheorem halts (t : Tree) : tick ⟨⟨vine t.size, []⟩, 0, .ascend⟩ = none := normalized_halts t/-- Every emitted opcode has the existing physical pointer semantics. -/theorem replay {s t : State} {ops : List Multifinger.Opcode} (run : Run s ops t) : Multifinger.replay ops s.cursor = some t.cursor := run.replay/-- All prefixes use a counter bounded by the node count, in addition to afinite mode and cursor. The recorded log is separate from the controller. -/theorem counter (t : Tree) {s : State} {ops : List Multifinger.Opcode} (run : Run ⟨⟨t, []⟩, 0, .scan⟩ ops s) : s.depth ≤ t.size := counter_bound t run/-- The focused subtree reserves room for the next right-descent increment. -/theorem counter_focus (t : Tree) {s : State} {ops : List Multifinger.Opcode} (run : Run ⟨⟨t, []⟩, 0, .scan⟩ ops s) : s.depth + s.cursor.focus.size ≤ t.size := counter_focus_bound t runSo the controller needs a cursor, two bits of mode and a counter of bits; these are the constant number of registers that the paper allows. The log it emits is not kept: the recording stores it in the cells as it is produced.
39.2.7 Recording
Recording runs the controller and the buffer finger on the same tree. The controller emits four opcodes; the buffer finger walks to the next cell and writes their encoding there; and so on.
/-- The normalizer and buffer finger share the tree. A packet is retainedonly within the bounded packet-producing operation below. -/structure State where control : Controller.State scan : Scan.State data : Nat → Natdef State.Valid (s : State) : Prop := s.control.cursor.tree = s.scan.tree ∧ s.scan.ValidA recording state has the controller state, the buffer finger’s scan state (Scan.State: the tree, the finger’s key, the next cell and a direction bit) and the cell contents. It is valid when the two components see the same tree and the scan state is valid. No packet is stored in the state: a packet lives only inside one step of the run below.
/-- A recording execution alternates local normalization of at most fouropcodes with one charged cell write. Packet production stops at capacity orcontroller halt. After halt, empty packets pad the remaining node fields.All lists in this relation are execution witnesses, not accumulated storage. -/inductive Run : State → State → List Opcode → Nat → Nat → Prop where | done {s : State} {control : Controller.State} : Controller.Run s.control [] control → Controller.tick control = none → s.scan.requests = [] → Run s ⟨control, s.scan, s.data⟩ [] 0 0 | packet {s u : State} {control : Controller.State} {chunk tail : List Opcode} {rotations work later more : Nat} {scan : Scan.State} {data : Nat → Nat} {key : Nat} : Controller.Run s.control chunk control → chunk.length ≤ 4 → (chunk.length = 4 ∨ Controller.tick control = none) → Scan.Trace s.scan { s.scan with tree := control.cursor.tree } 0 rotations → rotations ≤ chunk.length → Cells.Trace ⟨{ s.scan with tree := control.cursor.tree }, s.data⟩ ⟨scan, data⟩ [.write key (encodeCell chunk)] work 0 → Run ⟨control, scan, data⟩ u tail later more → Run s u (chunk ++ tail) (work + later) (rotations + more)def initial (tree : Tree) (data : Nat → Nat) : State := ⟨⟨⟨tree, []⟩, 0, .scan⟩, ⟨tree, Streaming.rootPosition tree, 0, false⟩, data⟩Run s u ops work rotations is a recording execution from s to u. ops is the controller’s output, work the buffer finger’s charged steps and rotations the rotations it witnessed. It is built from packets:
packet: the controller runs until it has emitted a chunk of exactly four opcodes, or fewer if it has halted. The scan state follows the tree through the chunk’s rotations, at most one per opcode, without moving (Scan.Tracewith work ). Then the buffer finger performs a cell trace (Cells.Trace) whose only event is one write ofencodeCell chunk, at a costworkthat pays for its moves and the write.done: the controller has halted (after silent transitions only) and no cell remains to be written.
After the controller halts, further packets are empty, so the remaining cells receive the value . initial tree data puts the controller at the root in mode scan, and the buffer finger at the root’s key, as a forward scan from cell , over arbitrary initial contents data.
Theorem (recording). The following hold for a recording run that emits with buffer work , from a valid state .
- Production. If the controller can run from and halt, emitting at most four opcodes per remaining cell, then there is a recording run that emits these opcodes and ends in that controller state.
- Projections. The controller part of the run is a controller run emitting ; the buffer part is a scan trace with the same work and rotations; and at the end the controller is halted and every cell has been visited.
- Cost. , where is the number of nodes.
- Contents. The writes are exactly the packed and encoded opcodes, one per remaining cell, in scan order.
- Snapshot. From
initial tree dataon a nonempty tree, a run that emitsrecord treeleaves the snapshot oftreein the cells. Such a run exists, ends with the controller halted at the root of the vine, and costs .
/-- Record a fitting local-controller stream one bounded packet at a time. -/theorem produce (s : State) (valid : s.Valid) (final : Controller.State) (ops : List Opcode) (normal : Controller.Run s.control ops final) (halt : Controller.tick final = none) (capacity : ops.length ≤ 4 * s.scan.requests.length) : ∃ t w r, Run s t ops w r ∧ t.control = final := Recording.produce s valid final ops normal halt capacityModels.Rotation, Models.Pointer.Machine, Models.Pointer.Walk.Definitions, Models.Multifinger.Program.Definitions, Models.Multifinger.Program.Replay.Definitions, Bounds.StaticTree.Definitions, Bounds.LazyFinger.Definitions, Models.Labelled.Metadata.Definitions, Structures.TreeBuffer.Scan.Definitions, Structures.TreeBuffer.Cells.Definitions, Structures.TreeBuffer.Snapshot.Definitions, Structures.TreeBuffer.Snapshot.CellIO.Definitions, Structures.TreeBuffer.Snapshot.Controller.Definitions, Structures.TreeBuffer.Snapshot.Streaming.Definitions, Structures.TreeBuffer.Snapshot.Recording.Definitions/-- The controller emits exactly the recorded opcode stream. -/theorem controller {s t : State} {ops : List Opcode} {w r : Nat} (run : Run s t ops w r) : Controller.Run s.control ops t.control := run.controllerModels.Rotation, Models.Pointer.Machine, Models.Pointer.Walk.Definitions, Models.Multifinger.Program.Definitions, Models.Multifinger.Program.Replay.Definitions, Bounds.StaticTree.Definitions, Bounds.LazyFinger.Definitions, Models.Labelled.Metadata.Definitions, Structures.TreeBuffer.Scan.Definitions, Structures.TreeBuffer.Cells.Definitions, Structures.TreeBuffer.Snapshot.Definitions, Structures.TreeBuffer.Snapshot.CellIO.Definitions, Structures.TreeBuffer.Snapshot.Controller.Definitions, Structures.TreeBuffer.Snapshot.Streaming.Definitions, Structures.TreeBuffer.Snapshot.Recording.Definitions/-- The buffer projection includes every normalization rotation and charged write. -/theorem buffer {s t : State} {ops : List Opcode} {w r : Nat} (run : Run s t ops w r) : Scan.Trace s.scan t.scan w r := run.scanModels.Rotation, Models.Pointer.Machine, Models.Pointer.Walk.Definitions, Models.Multifinger.Program.Definitions, Models.Multifinger.Program.Replay.Definitions, Bounds.StaticTree.Definitions, Bounds.LazyFinger.Definitions, Models.Labelled.Metadata.Definitions, Structures.TreeBuffer.Scan.Definitions, Structures.TreeBuffer.Cells.Definitions, Structures.TreeBuffer.Snapshot.Definitions, Structures.TreeBuffer.Snapshot.CellIO.Definitions, Structures.TreeBuffer.Snapshot.Controller.Definitions, Structures.TreeBuffer.Snapshot.Streaming.Definitions, Structures.TreeBuffer.Snapshot.Recording.Definitions/-- Completed recording halts the controller and fills every pending cell. -/theorem finished {s t : State} {ops : List Opcode} {w r : Nat} (run : Run s t ops w r) : Controller.tick t.control = none ∧ t.scan.requests = [] := run.finishedModels.Rotation, Models.Pointer.Machine, Models.Pointer.Walk.Definitions, Models.Multifinger.Program.Definitions, Models.Multifinger.Program.Replay.Definitions, Bounds.StaticTree.Definitions, Bounds.LazyFinger.Definitions, Models.Labelled.Metadata.Definitions, Structures.TreeBuffer.Scan.Definitions, Structures.TreeBuffer.Cells.Definitions, Structures.TreeBuffer.Snapshot.Definitions, Structures.TreeBuffer.Snapshot.CellIO.Definitions, Structures.TreeBuffer.Snapshot.Controller.Definitions, Structures.TreeBuffer.Snapshot.Streaming.Definitions, Structures.TreeBuffer.Snapshot.Recording.Definitionsproduce builds recording runs from controller runs. Its hypothesis capacity asks that the remaining cells can hold the opcodes; for a full recording from cell it is the bound record t . controller, buffer and finished read the run back: whatever happened in between, the opcodes are the controller’s, and the buffer finger’s steps form a legal scan trace in the sense of Section 39.1.
/-- Recording combines linear scan accounting with the emitted opcode count. -/theorem cost {s t : State} {ops : List Opcode} {w r : Nat} (run : Run s t ops w r) (valid : s.Valid) : w + ops.length ≤ 4 * s.scan.tree.size + 4 * ops.length := run.cost validModels.Rotation, Models.Pointer.Machine, Models.Pointer.Walk.Definitions, Models.Multifinger.Program.Definitions, Models.Multifinger.Program.Replay.Definitions, Bounds.StaticTree.Definitions, Bounds.LazyFinger.Definitions, Models.Labelled.Metadata.Definitions, Structures.TreeBuffer.Scan.Definitions, Structures.TreeBuffer.Cells.Definitions, Structures.TreeBuffer.Snapshot.Definitions, Structures.TreeBuffer.Snapshot.CellIO.Definitions, Structures.TreeBuffer.Snapshot.Controller.Definitions, Structures.TreeBuffer.Snapshot.Streaming.Definitions, Structures.TreeBuffer.Snapshot.Recording.Definitions/-- Writes store the canonical packed stream in initial scan order. -/theorem cells {s t : State} {ops : List Opcode} {w r : Nat} (run : Run s t ops w r) (valid : s.Valid) : Cells.Trace ⟨s.scan, s.data⟩ ⟨t.scan, t.data⟩ (List.zipWith Cells.Event.write s.scan.requests ((pack s.scan.requests.length ops).map encodeCell)) w r := run.cells validModels.Rotation, Models.Pointer.Machine, Models.Pointer.Walk.Definitions, Models.Multifinger.Program.Definitions, Models.Multifinger.Program.Replay.Definitions, Bounds.StaticTree.Definitions, Bounds.LazyFinger.Definitions, Models.Labelled.Metadata.Definitions, Structures.TreeBuffer.Scan.Definitions, Structures.TreeBuffer.Cells.Definitions, Structures.TreeBuffer.Snapshot.Definitions, Structures.TreeBuffer.Snapshot.CellIO.Definitions, Structures.TreeBuffer.Snapshot.Controller.Definitions, Structures.TreeBuffer.Snapshot.Streaming.Definitions, Structures.TreeBuffer.Snapshot.Recording.Definitions/-- A completed normalizer recording stores the exact snapshot payloads. -/theorem stored (tree : Tree) (data : Nat → Nat) {t : State} {work rotations : Nat} (run : Run (initial tree data) t (record tree) work rotations) (nonempty : tree ≠ .nil) : CellIO.Stored tree t.data := Run.stored tree data run nonemptyModels.Rotation, Models.Pointer.Machine, Models.Pointer.Walk.Definitions, Models.Multifinger.Program.Definitions, Models.Multifinger.Program.Replay.Definitions, Bounds.StaticTree.Definitions, Bounds.LazyFinger.Definitions, Models.Labelled.Metadata.Definitions, Structures.TreeBuffer.Scan.Definitions, Structures.TreeBuffer.Cells.Definitions, Structures.TreeBuffer.Snapshot.Definitions, Structures.TreeBuffer.Snapshot.CellIO.Definitions, Structures.TreeBuffer.Snapshot.Controller.Definitions, Structures.TreeBuffer.Snapshot.Streaming.Definitions, Structures.TreeBuffer.Snapshot.Recording.Definitions/-- Online packet production and writes cost at most 20n. -/theorem snapshot (tree : Tree) (data : Nat → Nat) : ∃ t work rotations, Run (initial tree data) t (record tree) work rotations ∧ t.control = ⟨⟨vine tree.size, []⟩, 0, .ascend⟩ ∧ CellIO.Stored tree t.data ∧ work + (record tree).length ≤ 20 * tree.size := record_snapshot tree dataModels.Rotation, Models.Pointer.Machine, Models.Pointer.Walk.Definitions, Models.Multifinger.Program.Definitions, Models.Multifinger.Program.Replay.Definitions, Bounds.StaticTree.Definitions, Bounds.LazyFinger.Definitions, Models.Labelled.Metadata.Definitions, Structures.TreeBuffer.Scan.Definitions, Structures.TreeBuffer.Cells.Definitions, Structures.TreeBuffer.Snapshot.Definitions, Structures.TreeBuffer.Snapshot.CellIO.Definitions, Structures.TreeBuffer.Snapshot.Controller.Definitions, Structures.TreeBuffer.Snapshot.Streaming.Definitions, Structures.TreeBuffer.Snapshot.Recording.Definitionscost is the scan bound Results.total of Section 39.1, the formal Lemma 9: a scan over cells costs at most plus per rotation performed by the other finger, and the rotations are among the emitted opcodes. With , this gives the of snapshot. cells describes the writes as Cells.Events: the keys are the scan’s remaining requests, in order, and the values are pack of the opcodes, encoded. stored excludes the empty tree, where there are no cells and the initial buffer position is only a totalized value; snapshot has no such hypothesis, because Stored is vacuous on the empty tree.
39.2.8 Streaming restoration
Restoration starts from the vine, which recording leaves behind and which normalization produces from any tree. It runs the undo stream of the saved log, read from the cells as it goes.
/-- Two persistent cursors share the tree: the replay cursor and the bufferscan cursor. Only one decoded packet is retained between cell reads. -/structure State where cursor : Pointer.Config scan : Scan.State packet : List Opcodedef State.Valid (s : State) : Prop := s.cursor.tree = s.scan.tree ∧ s.scan.Valid ∧ s.packet.length ≤ 12/-- Specification of the still-unexecuted stream; it is not stored by themachine. The retained `packet` alone is bounded working storage. -/def remaining (data : Nat → Nat) (s : State) : List Opcode := s.packet ++ CellIO.inverseCells (s.scan.requests.map data)A streaming state has two cursors on the same tree, the replay cursor (a Pointer.Config) and the buffer finger (a scan state), and the current packet, the opcodes of one undone cell not yet executed. Validity asks for the common tree, a valid scan, and a packet of at most opcodes. remaining data s is the stream still to be executed: the packet, followed by the undone packets of the cells the scan has not read yet, in its order. It is a specification of what the machine will do. The machine does not store it.
/-- Navigation and reads pause replay. Executing one opcode updates the commontree and preserves the buffer cursor key. The scan trace certifies the samezero or one rotation as the replay step, including its effect on routing. -/inductive Step (data : Nat → Nat) : State → State → Nat → Nat → Nat → Prop where | navigate {s : State} {t : Scan.State} : s.packet = [] → Cells.Step ⟨s.scan, data⟩ ⟨t, data⟩ none 1 0 → Step data s ⟨s.cursor, t, []⟩ 1 0 0 | read {s : State} {t : Scan.State} {x value : Nat} : s.packet = [] → Cells.Step ⟨s.scan, data⟩ ⟨t, data⟩ (some (.read x value)) 1 0 → Step data s ⟨s.cursor, t, undo (decodeCell value)⟩ 1 0 0 | execute {s : State} {op : Opcode} {ops : List Opcode} {cursor : Pointer.Config} {rotations : Nat} : s.packet = op :: ops → perform op s.cursor = some cursor → Scan.Trace s.scan { s.scan with tree := cursor.tree } 0 rotations → rotations ≤ 1 → Step data s ⟨cursor, { s.scan with tree := cursor.tree }, ops⟩ 0 1 rotationsinductive Trace (data : Nat → Nat) : State → State → Nat → Nat → Nat → Prop where | refl {s : State} : Trace data s s 0 0 0 | step {s t u : State} {w p r v q h : Nat} : Step data s t w p r → Trace data t u v q h → Trace data s u (w + v) (p + q) (r + h)A step is one of three kinds, and each applies only in its own situation.
navigate: the packet is empty, and the buffer finger takes one step toward its next cell, by the cell rule of Section 39.1. One unit of buffer work.read: the packet is empty, and the buffer finger is on its next cell. It reads the value and the packet becomes the undone decoded packet. One unit of buffer work.execute: the packet is nonempty. The replay cursor performs its first opcode, the scan state follows the tree through the zero or one rotation this causes, and the buffer finger stays on its key. One unit of replay work.
Trace data s t w p r composes steps, adding the buffer work w, the replay instructions p and the rotations r seen by the scan. The cells are the same data throughout: restoration never writes.
/-- Each replay instruction can increase scan potential by at most three;four units per unexecuted instruction therefore fund all interruptions. -/def potential (data : Nat → Nat) (s : State) : Nat := 4 * (remaining data s).length + Scan.potential s.scandef State.Done (s : State) : Prop := s.packet = [] ∧ s.scan.requests = []/-- Begin descending-cell replay with an empty packet and the replay cursorat the root. Buffer cursor initialization is an explicit input position. -/def initial (tree : Tree) (position : Nat) : State := ⟨⟨tree, []⟩, ⟨tree, position, tree.size, true⟩, []⟩/-- The key of the buffer finger initialized at the current root. Zero onlytotalizes the empty tree, where no cell access is performed. -/def rootPosition (tree : Tree) : Nat := (Pointer.Config.key? ⟨tree, []⟩).getD 0The potential is four units per remaining opcode plus the scan potential Scan.potential, the cost of the rest of the scan if no further rotation occurred. Executing an opcode uses one unit and can raise the scan potential by at most three, since a rotation lengthens the scan’s remaining route by at most a constant; navigating and reading lower the scan potential. Done means the packet is empty and every cell has been read. initial tree position puts the replay cursor at the root, the buffer finger on key position, the scan descending from the last cell, and the packet empty. rootPosition tree is the key of the root, for the empty tree, where no cell is ever accessed.
Theorem (streaming). Let be a valid streaming state whose remaining stream replays legally from its cursor to some target.
- Progress and termination. If is not done, some step applies. Some trace from reaches a done state with at most the potential of .
- Amortization. Along every trace from a valid state, .
- Projections. The replay cursor of every trace performs a
Pointer.Traceof exactly instructions, and the buffer finger a scan trace with work and the rotations. - Completion. A trace that ends in a done state has executed exactly the remaining stream of , and is its length.
- Space. Along every trace from a valid state, the packet has at most opcodes, and the scan’s counter and position stay below the number of nodes.
/-- Every unfinished state with a legal remaining stream has a next primitive. -/theorem progress (data : Nat → Nat) (s : State) (valid : s.Valid) (target : Pointer.Config) (executable : replay (remaining data s) s.cursor = some target) (unfinished : ¬ s.Done) : ∃ t w p r, Step data s t w p r := next_exists data s valid target executable unfinishedModels.Rotation, Models.Pointer.Machine, Models.Pointer.Walk.Definitions, Models.Multifinger.Program.Definitions, Models.Multifinger.Program.Replay.Definitions, Bounds.StaticTree.Definitions, Bounds.LazyFinger.Definitions, Models.Labelled.Metadata.Definitions, Structures.TreeBuffer.Scan.Definitions, Structures.TreeBuffer.Cells.Definitions, Structures.TreeBuffer.Snapshot.Definitions, Structures.TreeBuffer.Snapshot.CellIO.Definitions, Structures.TreeBuffer.Snapshot.Controller.Definitions, Structures.TreeBuffer.Snapshot.Streaming.Definitions/-- The joint machine finishes within its initial potential. -/theorem finish (data : Nat → Nat) (s : State) (valid : s.Valid) (target : Pointer.Config) (executable : replay (remaining data s) s.cursor = some target) : ∃ t w p r, Trace data s t w p r ∧ t.Done ∧ w + p ≤ potential data s := Streaming.finish data s valid target executableModels.Rotation, Models.Pointer.Machine, Models.Pointer.Walk.Definitions, Models.Multifinger.Program.Definitions, Models.Multifinger.Program.Replay.Definitions, Bounds.StaticTree.Definitions, Bounds.LazyFinger.Definitions, Models.Labelled.Metadata.Definitions, Structures.TreeBuffer.Scan.Definitions, Structures.TreeBuffer.Cells.Definitions, Structures.TreeBuffer.Snapshot.Definitions, Structures.TreeBuffer.Snapshot.CellIO.Definitions, Structures.TreeBuffer.Snapshot.Controller.Definitions, Structures.TreeBuffer.Snapshot.Streaming.Definitions/-- Buffer work and replay work share one decreasing potential. -/theorem cost {data : Nat → Nat} {s t : State} {w p r : Nat} (trace : Trace data s t w p r) (valid : s.Valid) : w + p + potential data t ≤ potential data s := trace.amortized validModels.Rotation, Models.Pointer.Machine, Models.Pointer.Walk.Definitions, Models.Multifinger.Program.Definitions, Models.Multifinger.Program.Replay.Definitions, Bounds.StaticTree.Definitions, Bounds.LazyFinger.Definitions, Models.Labelled.Metadata.Definitions, Structures.TreeBuffer.Scan.Definitions, Structures.TreeBuffer.Cells.Definitions, Structures.TreeBuffer.Snapshot.Definitions, Structures.TreeBuffer.Snapshot.CellIO.Definitions, Structures.TreeBuffer.Snapshot.Controller.Definitions, Structures.TreeBuffer.Snapshot.Streaming.Definitionsprogress and finish assume that the remaining stream is executable (executable), which is the case for a stream of undone cells started on the right tree; without it, an execute step could fail.
/-- Replay projection uses exactly the charged pointer-instruction count. -/theorem physical {data : Nat → Nat} {s t : State} {w p r : Nat} (trace : Trace data s t w p r) : Pointer.Trace s.cursor t.cursor p := trace.physicalModels.Rotation, Models.Pointer.Machine, Models.Pointer.Walk.Definitions, Models.Multifinger.Program.Definitions, Models.Multifinger.Program.Replay.Definitions, Bounds.StaticTree.Definitions, Bounds.LazyFinger.Definitions, Models.Labelled.Metadata.Definitions, Structures.TreeBuffer.Scan.Definitions, Structures.TreeBuffer.Cells.Definitions, Structures.TreeBuffer.Snapshot.Definitions, Structures.TreeBuffer.Snapshot.CellIO.Definitions, Structures.TreeBuffer.Snapshot.Controller.Definitions, Structures.TreeBuffer.Snapshot.Streaming.Definitions/-- Buffer projection includes the rotations performed during replay. -/theorem buffer {data : Nat → Nat} {s t : State} {w p r : Nat} (trace : Trace data s t w p r) : Scan.Trace s.scan t.scan w r := trace.scanModels.Rotation, Models.Pointer.Machine, Models.Pointer.Walk.Definitions, Models.Multifinger.Program.Definitions, Models.Multifinger.Program.Replay.Definitions, Bounds.StaticTree.Definitions, Bounds.LazyFinger.Definitions, Models.Labelled.Metadata.Definitions, Structures.TreeBuffer.Scan.Definitions, Structures.TreeBuffer.Cells.Definitions, Structures.TreeBuffer.Snapshot.Definitions, Structures.TreeBuffer.Snapshot.CellIO.Definitions, Structures.TreeBuffer.Snapshot.Controller.Definitions, Structures.TreeBuffer.Snapshot.Streaming.Definitions/-- Completion executes exactly the originally specified stream. -/theorem completed {data : Nat → Nat} {s t : State} {w p r : Nat} (trace : Trace data s t w p r) (done : t.Done) : replay (remaining data s) s.cursor = some t.cursor ∧ p = (remaining data s).length := Streaming.completed trace doneModels.Rotation, Models.Pointer.Machine, Models.Pointer.Walk.Definitions, Models.Multifinger.Program.Definitions, Models.Multifinger.Program.Replay.Definitions, Bounds.StaticTree.Definitions, Bounds.LazyFinger.Definitions, Models.Labelled.Metadata.Definitions, Structures.TreeBuffer.Scan.Definitions, Structures.TreeBuffer.Cells.Definitions, Structures.TreeBuffer.Snapshot.Definitions, Structures.TreeBuffer.Snapshot.CellIO.Definitions, Structures.TreeBuffer.Snapshot.Controller.Definitions, Structures.TreeBuffer.Snapshot.Streaming.Definitions/-- Every prefix retains at most twelve opcodes and bounded scan counters. -/theorem space {data : Nat → Nat} {s t : State} {w p r : Nat} (trace : Trace data s t w p r) (valid : s.Valid) : t.packet.length ≤ 12 ∧ t.scan.next ≤ s.scan.tree.size ∧ t.scan.position < s.scan.tree.size := trace.space validModels.Rotation, Models.Pointer.Machine, Models.Pointer.Walk.Definitions, Models.Multifinger.Program.Definitions, Models.Multifinger.Program.Replay.Definitions, Bounds.StaticTree.Definitions, Bounds.LazyFinger.Definitions, Models.Labelled.Metadata.Definitions, Structures.TreeBuffer.Scan.Definitions, Structures.TreeBuffer.Cells.Definitions, Structures.TreeBuffer.Snapshot.Definitions, Structures.TreeBuffer.Snapshot.CellIO.Definitions, Structures.TreeBuffer.Snapshot.Controller.Definitions, Structures.TreeBuffer.Snapshot.Streaming.Definitionscompleted is what makes the existential statements below meaningful: every completed trace from a given state ends with the cursor where the remaining stream leads, so all completed restorations agree. space is the bounded working storage: one packet of at most twelve opcodes, the buffer finger’s key and its counter.
Theorem (restoration from the vine). If the cells hold the snapshot of , the streaming machine started on the vine with nodes, with the buffer finger at its root, completes and ends with the tree and the cursor at its root. It executes exactly the undo of the log of , and its total work is at most .
/-- Streaming restoration from the common vine costs at most 52n. -/theorem restore (saved : Tree) (data : Nat → Nat) (stored : CellIO.Stored saved data) : ∃ t w p r, Trace data (initial (vine saved.size) 0) t w p r ∧ t.Done ∧ t.cursor = ⟨saved, []⟩ ∧ p = (undo (record saved)).length ∧ w + p ≤ 52 * saved.size := Streaming.restore saved data storedModels.Rotation, Models.Pointer.Machine, Models.Pointer.Walk.Definitions, Models.Multifinger.Program.Definitions, Models.Multifinger.Program.Replay.Definitions, Bounds.StaticTree.Definitions, Bounds.LazyFinger.Definitions, Models.Labelled.Metadata.Definitions, Structures.TreeBuffer.Scan.Definitions, Structures.TreeBuffer.Cells.Definitions, Structures.TreeBuffer.Snapshot.Definitions, Structures.TreeBuffer.Snapshot.CellIO.Definitions, Structures.TreeBuffer.Snapshot.Controller.Definitions, Structures.TreeBuffer.Snapshot.Streaming.DefinitionsThe constant is the initial potential: for the undo stream and at most for the scan.
39.2.9 Save and load
The two operations of the tree state buffer combine the machines above.
/-- Record the current tree into its node fields, then restore its shape bystreaming those fields backwards. Switching phases resets scalar scan control;both cursor locations are preserved. -/def Save (data : Nat → Nat) (tree : Tree) (finalData : Nat → Nat) (cost : Nat) : Prop := ∃ recorded ops work rotations restored reads instructions replayRotations, Run (initial tree data) recorded ops work rotations ∧ recorded.control.cursor = ⟨recorded.scan.tree, []⟩ ∧ Streaming.Trace recorded.data (Streaming.initial recorded.scan.tree recorded.scan.position) restored reads instructions replayRotations ∧ restored.Done ∧ restored.cursor = ⟨tree, []⟩ ∧ finalData = recorded.data ∧ cost = ops.length + work + reads + instructionsSave data tree finalData cost says: a recording run from initial tree data ends with the controller at the root, a streaming restoration from the resulting cells and the resulting tree (the vine) is done, its cursor is at the root of tree again, and finalData is what the recording wrote. The cost is the controller’s opcodes, the recording’s buffer work, the restoration’s buffer work and its replay instructions. At the change of phase, the buffer finger stays on its key, and only its scan direction and counter are reset.
/-- A load first runs the local normalizer while the buffer finger stays onits original key, then starts descending-cell replay. The target shape occursonly as the final result, never as an input to the operational choices.The normalization log and scan trace are proof witnesses, not stored data. -/def Load (data : Nat → Nat) (current final : Tree) (cost : Nat) : Prop := ∃ ops normalRotations t w p r, Controller.Run ⟨⟨current, []⟩, 0, .scan⟩ ops ⟨⟨vine current.size, []⟩, 0, .ascend⟩ ∧ Scan.Trace ⟨current, rootPosition current, current.size, true⟩ ⟨vine current.size, rootPosition current, current.size, true⟩ 0 normalRotations ∧ normalRotations ≤ ops.length ∧ Trace data (initial (vine current.size) (rootPosition current)) t w p r ∧ t.Done ∧ t.cursor = ⟨final, []⟩ ∧ cost = ops.length + w + pLoad data current final cost says: the controller normalizes current into the vine, while the buffer finger stays on the root’s original key and only follows the rotations; then the streaming machine runs from the vine with the buffer finger at that key, until it is done with its cursor at the root of final. The cost is the normalizer’s opcodes plus the restoration’s buffer work and instructions. The saved tree does not appear among the inputs of the machines. It is final, an output.
Theorem (shape-preserving save). For every tree with nodes and all initial cell contents, there is a save of whose final cells hold the snapshot of , at cost at most .
/-- Recording followed by streaming restoration is a shape-preserving save costing at most 72n. -/theorem save (tree : Tree) (data : Nat → Nat) : ∃ finalData cost, Save data tree finalData cost ∧ CellIO.Stored tree finalData ∧ cost ≤ 72 * tree.size := Recording.save tree dataModels.Rotation, Models.Pointer.Machine, Models.Pointer.Walk.Definitions, Models.Multifinger.Program.Definitions, Models.Multifinger.Program.Replay.Definitions, Bounds.StaticTree.Definitions, Bounds.LazyFinger.Definitions, Models.Labelled.Metadata.Definitions, Structures.TreeBuffer.Scan.Definitions, Structures.TreeBuffer.Cells.Definitions, Structures.TreeBuffer.Snapshot.Definitions, Structures.TreeBuffer.Snapshot.CellIO.Definitions, Structures.TreeBuffer.Snapshot.Controller.Definitions, Structures.TreeBuffer.Snapshot.Streaming.Definitions, Structures.TreeBuffer.Snapshot.Recording.DefinitionsThe constant is for the recording plus for the restoration.
Theorem (streaming load). Let the cells hold the snapshot of a tree , and let the current tree have as many nodes as , say . Then a load from the current tree ends in , at cost at most .
/-- Normalization followed by streaming restoration costs at most 56n. -/theorem load (saved current : Tree) (same : current.size = saved.size) (data : Nat → Nat) (stored : CellIO.Stored saved data) : ∃ cost, Load data current saved cost ∧ cost ≤ 56 * current.size := Streaming.load saved current same data storedModels.Rotation, Models.Pointer.Machine, Models.Pointer.Walk.Definitions, Models.Multifinger.Program.Definitions, Models.Multifinger.Program.Replay.Definitions, Bounds.StaticTree.Definitions, Bounds.LazyFinger.Definitions, Models.Labelled.Metadata.Definitions, Structures.TreeBuffer.Scan.Definitions, Structures.TreeBuffer.Cells.Definitions, Structures.TreeBuffer.Snapshot.Definitions, Structures.TreeBuffer.Snapshot.CellIO.Definitions, Structures.TreeBuffer.Snapshot.Controller.Definitions, Structures.TreeBuffer.Snapshot.Streaming.DefinitionsThe constant is for the normalization plus for the restoration. The normalization costs the buffer finger nothing, since it does not move. These are the two theorems of the headline.
39.2.10 On shared nodes
In the machines above, the cells are a function from keys to values, and each finger is described by its own view of the tree. The combined tree runs on a single labelled tree whose nodes carry both routing words and payload fields, with two fingers on it: Shared.State of Section 39.1, with values in Nat and two fingers. Finger is the tree finger (the normalizer, or the replay cursor), and finger is the buffer finger.
/-- Finger 0 runs the local normalizer and finger 1 scans the buffer cells.The represented data changes after each packet write. -/def Represents (actual : Shared.State Nat 2) (model : State) : Prop := actual.Valid model.data ∧ actual.tree.erase = model.control.cursor.tree ∧ model.control.cursor.key? = some (actual.position 0) ∧ actual.position 1 = model.scan.position/-- The two persistent fingers are replay (0) and buffer scan (1). Both referto the same labelled nodes throughout reads, writes, and maintained rotations. -/def Represents (actual : Shared.State Nat 2) (model : State) (data : Nat → Nat) : Prop := actual.Valid data ∧ actual.tree.erase = model.cursor.tree ∧ model.cursor.key? = some (actual.position 0) ∧ actual.position 1 = model.scan.position/-- Restoration observes only correct reads; it never rewrites saved cells. -/def Reads (data : Nat → Nat) (events : List (Cells.Event Nat)) : Prop := ∀ event ∈ events, ∃ key, event = .read key (data key)The two Represents relations couple a shared state to a recording state or to a streaming state: the shared state is valid for the cells, its tree without labels is the model’s tree, finger is on the key of the model’s tree cursor, and finger on the buffer finger’s key. Reads data events says that every cell event of an execution is a read returning the value in data. Restorations, and the worker instructions of the combined tree, satisfy it, so they never overwrite the snapshot.
/-- Initialization followed by a shared-node snapshot operation. Both fingersstart at the original root. The initializer returns there before the secondphase, which uses exactly its output tree. `n` is the supplied universe size. -/def Execution (tree : Tree) (n : Nat) (fields : Nat → IntervalMetadata.Bounds) (data : Nat → Nat) (final : Shared.State Nat 2) (events : List (Cells.Event Nat)) (total : Nat) : Prop := ∃ ready setupCost work, Nodes.Initialization.runFuel (8 * n) (Nodes.Initialization.initial (Nodes.Initialization.raw fields data tree 0) n) = some (setupCost, ready) ∧ Nodes.Initialization.Run (Nodes.Initialization.initial (Nodes.Initialization.raw fields data tree 0) n) ready setupCost ∧ Nodes.Initialization.tick ready = none ∧ ready.cursor.context = [] ∧ Shared.Trace ⟨ready.cursor.tree, fun _ => Streaming.rootPosition tree⟩ final events work ∧ total = setupCost + workStartup.Execution tree n fields data final events total is the composition used once, before the first request: the node initialization of Section 39.1 (Nodes.Initialization, with fuel ) computes the routing words of every node from arbitrary initial ones fields, returns to the root, and halts; then an arbitrary shared trace runs from the initialized tree, with both fingers at the original root, to final, with cell events events and cost work. The total cost is the sum. The definition does not say what the second phase does. The theorems that use it do.
Those theorems are internal to the library, in the proof files of Structures/TreeBuffer/Snapshot. On a valid shared state with both fingers at the root of a nonempty tree, a shared-node save (Recording.Refinement.save) costs at most and a shared-node load (Streaming.Refinement.load) at most , including routing and the maintenance of routing words through rotations. With initialization, Startup.save and Startup.load cost at most and . Through them, Results.restart restores a worker’s initial tree at cost at most , and Online.Prepared records the bound for the one-time save before the first request (Section 29.4).
- Two fingers. Lemma 10 gives TSB(M) fingers for a structure M with fingers. Here the snapshot operations use two fingers on the shared tree. In the combined tree, the worker’s instructions also run on finger , and a finger hand (Section 35.2) simulates the two-finger machine with the single cursor of the pointer machine (Section 29.4).
- Twelve bits. The paper allows bits per node and suggests packing or multiple buffers when cells are not enough. The normalization log has at most opcodes, so a constant twelve bits per node suffice, and a single buffer.
- Cost model. The headline costs count the tree finger’s instructions and the buffer finger’s moves and cell visits, in the buffer model of Section 39.1. The constants and are not optimized. The shared-node constants are larger, since each routing step and rotation update has its own cost there.
- Existence of executions. The theorems state that an execution exists. The machines are local: the controller is a function of its state, and a streaming step applies only in its own situation. The theorem
completedshows that every completed restoration ends in the same tree. - Storage beyond the snapshot. The storage clauses of the combining theorem (that the whole structure fits in bits per node and registers) are not formalized (Section 29.1). This section only bounds the snapshot payload, the packet and the counters.