Manuscript Offprint
arXiv:2610.38616Order Maintenance in Worst-Case Constant Time, Verified
Open access. PaperVantage converted this article to text, so layout and figures may differ from the original.
Abstract
Order maintenance asks for a data structure that keeps a sequence of elements under insertions and deletions and tells which of two elements comes first. We give an algorithm that performs each operation in worst-case constant time, and verify it in Lean 4. The difficulty is to change labels gradually while queries and further insertions continue. The algorithm, assembled from published components, never relabels the members of a full unit in place: they move into fresh neighbouring units. Small groups keep element labels short; groups are collected into larger chunks, which keep accepting insertions while they wait their turn for a shared top tree; and the top tree never changes a label it has assigned. We implement the algorithm as a program for a random-access machine (RAM) deeply embedded in Lean, whose interpreter counts every instruction and allocates a zero-filled array in one step, and prove that the program answers every query as a simple reference specification does and that each operation takes at most a fixed number of steps, independent of the number of elements and of the history. The machine treats arithmetic on unbounded natural numbers as one step, and on such a machine a step bound alone is weak, so we also prove that after operations no value the machine has computed has more than bits, and that the program runs unchanged, with the same answers and step counts, on a machine whose words have that many bits. A verified translation through an intermediate language connects the high-level proofs to the machine program and preserves step counts exactly, so the interpreter is the only cost model to trust; the development has about 78,000 lines of Lean. Rust code transpiled from the program agrees with the machine semantics on all tested traces, and an unverified native implementation shows the algorithm's practical cost.
Keywords: order maintenance, worst-case complexity, word RAM, cost semantics, Lean 4.
Supplementary material. Lean development and transpiled Rust code:
https://github.com/dfirsov/order_maintenance
Interactive visualizer: https://dfirsov.github.io/order_maintenance/viz/
1 Introduction
The order-maintenance problem asks to maintain a sequence under three operations: insert a new element immediately after a given one, delete an element, and decide whether one element precedes another. It is a building block of many dynamic algorithms: fully persistent data structures [24], self-adjusting computation [1], race detection for fork-join programs [11], and incremental topological ordering [32]. The usual approach is labeling: give each element an integer label so that labels increase along the sequence, and answer a query by comparing two labels. The difficulty is the insertion: repeated insertions between the same two neighbours eventually use up the labels between them, and then some labels must change.
The problem goes back to Dietz [20], and constant amortized time per operation is classical [55, 22, 8]. Constant worst-case time has been known since 1987 [22, 23], but the known algorithms are intricate. Kopelowitz [42, Section 1] summarized the state of the art: “to date there is no published version of a worst-case solution for the OMP which is not considered highly complex”. Bender et al. have since simplified worst-case file maintenance [10] (keeping items in sorted order in an array with gaps), the component at the top of Dietz and Sleator’s construction, but as far as we know, no worst-case order-maintenance algorithm has been implemented, and no order-maintenance algorithm has been verified in a proof assistant.
The obstacle to worst-case constant time is unfinished work: to bound every operation, a relabeling must be spread over later insertions. Queries then see a partly changed structure, and further insertions can arrive at the very place being changed, or at other places that also need attention. A worst-case algorithm must explain both why every intermediate state answers queries correctly and why the unfinished work never falls behind.
Our construction answers the two questions separately. For correctness, a unit that fills up is never relabeled in place: it gets two empty neighbours, and its members move into them from its ends a few at a time, so keys stay ordered at every instant; in addition, every write that could break the order is checked in constant time. For timing, each insertion pays a fixed number of steps towards the repairs of the units it makes larger, and a largest-first queue arbitrates the one place where unrelated units compete. The same scheme serves groups of elements, chunks of groups, and the nodes of the top tree. Section 3 develops these ideas.
We assemble the algorithm from published components and implement it in a small imperative language that we deeply embed in Lean 4. The language’s interpreter counts every instruction it executes, so running time is part of the semantics and no part of the computation can escape the count. We prove two theorems about the program: it answers queries correctly (Theorem A), and every operation takes at most a fixed number of steps, independent of the length of the sequence and of the history (Theorem B).
A step bound alone would say little. The machine treats arithmetic on unbounded natural numbers, and allocation, as single steps, and on such a machine order maintenance is easy: labels of unbounded length never run out (Section 2). What makes the problem hard is that labels must stay short. We therefore also prove Theorem W: no value the machine computes, whether stored or intermediate, has more than bits, where is the capacity of the structure, except handles and a few wrapper counters, which are bounded by the number of operations. The capacity is at most linear in the number of operations, so the -th operation computes only values of bits, and a machine with words of that size, but otherwise the same, runs the program with the same answers and step counts. Word size and space thus grow with the number of operations rather than with the length of the sequence. These, and the machine’s one-step allocation of zero-filled arrays, are the gaps to a textbook word RAM (Section 6).
Checking the literature against our own derivations and simulations, we found errors in two papers we build on or compare with: the appendix pseudocode of Dietz and Sleator [23] has easily repaired slips (two swapped boundary tests, and a move after the last child of a node that has none), and the proof of the amortized bound of Bender et al. [8, Lemma 3] miscounts insertions by a constant factor (the bound survives, but their space/time trade-off does not). A pen-and-paper proof, written before the formalization, found a cost bug and two gaps in our own design, all of which extensive testing had missed. The formalization found no further errors, but three parameters had to change: two because the mechanized arguments are coarser, and one so that an inequality could be proved for all sizes at once (Section D).
-
Mechanized correctness, a worst-case bound and short words (Section 4): for every valid operation sequence, the machine program returns the specification's answers (Theorem A), and every operation takes at most a fixed number of machine steps, independent of the length of the sequence and of the history (Theorem B), and computes no value of more than bits, where , except handles and a few wrapper counters, which are bounded by the number of operations (Theorem W); concretely, operation (counting from 0) computes no value of more than bits. Theorems A and B also hold, for a run of operations, on a machine with a fixed word width of at least bits. The development has about 78,000 lines of Lean and uses only Lean's standard axioms.
-
A machine model in which no computation escapes the count (Sections C and 4.1): a small imperative language deeply embedded in Lean, with a total interpreter that counts every step, in the tradition of earlier deeply embedded cost semantics (Section 7).
-
Two executable implementations (Section 5): Rust code produced from the machine program by an unverified transpiler, which matches the Lean semantics step for step on all tested traces; and an unverified native implementation, within a small factor of an AVL tree on insertions and faster on cold order queries.
2 Background
This section recalls the standard solutions for readers new to the problem, explains why constant time on average is easy and constant time in the worst case is not, and states the questions that Section 3 has to answer.
The problem. An order-maintenance structure holds a sequence of elements and supports three operations. The operation insertAfter(x) creates a new element immediately after and returns it; delete(x) removes ; and order(x, y) tells whether comes strictly before . Elements are never looked up by value: each operation receives handles returned by

Figure 1: Labels in [0, 16). Each new element takes the average of the labels around it (16 bounds the sequence on the right). Three insertions in one place use up the gap after ; the elements are then relabeled evenly, and the fourth insertion fits.
earlier insertions, and a valid operation uses only live handles. Starting from the sequence , inserting after gives an element and the sequence ; inserting after again gives and the sequence ; now is true and is false. A fourth operation, , inserts at the front of the sequence. A balanced search tree with parent pointers supports all these operations in steps; it is the AVL tree we compare with in Section 5. The goal is steps for every operation.
Labels with gaps. The usual approach gives every element an integer label, with labels increasing along the sequence, so that is a single comparison. A new element takes the average of its neighbours' labels. Repeated insertions at one place halve the same gap (Figure 1): between 8 and 16, inserting after 8 takes 12, then 10, then 9, and then no integer is left. A label of bits therefore buys only insertions in one place before some labels must be spread out again. Choosing which labels to spread out is the problem of list labeling [41], and a single labeling cannot make this cheap: when labels come from a polynomial range, an insertion by a deterministic algorithm needs relabelings on average [21, 6]. Labels of unbounded length would avoid relabeling altogether, since two binary fractions always have an average, but after insertions in one place a label has bits. Constant time is meant on a word RAM, where a step operates on a word of bits, so labels must fit in a constant number of words (Section 6 relates this to our machine).
Indirection: constant time on average. The standard way around this bound is indirection [22, 8]. The sequence is cut into groups of consecutive elements. Each group has a label in a labeling of the sequence of groups, and each element has a label within its group. The key of an element is the pair (group label, element label), compared lexicographically (Figure 2). Changing a group's label changes the keys of all its elements at once, through one shared field.
An insertion takes a fresh label within its group, in constant time. A group receives insertions in its lifetime, so element labels of bits never run out. When a group becomes too large, it is split in two, both halves are relabeled evenly in steps, and the new group is inserted into the labeling of groups at an amortized cost of . A group splits only after insertions, so each insertion costs on average, and a query still takes two comparisons.
Why constant worst-case time is hard. An amortized bound lets the insertion that triggers a split pay for it. A worst-case bound does not: a repair must start early and

Figure 2: Two-level keys. Group labels order the groups; element labels matter only within a group, so an insertion relabels at most the elements of its own group.
advance by a fixed amount at each later operation. This raises three questions.
-
How can old and new labels coexist? A group that is half split still receives insertions and queries, and keys must increase along the sequence at every instant, not only when the split is complete.
-
Which operations advance a repair, and why does it finish in time? Insertions keep arriving during a split, possibly into the very group being split, and the split must end before the groups receiving its elements run out of room.
-
What happens when repairs compete? Every split needs a label in the labeling of groups. A worst-case labeling, such as Willard's [57] used by Dietz and Sleator, takes steps per insertion, but a new group can appear every insertions, so that cost cannot be paid in constant instalments. The remedy is more grouping: groups are grouped again into larger units, so that the labeling at the top changes rarely enough. Even then, several units may need the top labeling at once, and they keep growing while they wait.
Section 3 answers them with fresh neighbours, local work budgets, and a largest-first queue over an extra level of chunks. Changes in the size of the sequence are handled by global rebuilding [52]: a fresh structure is built in the background, a few elements per operation.
These questions interact. Whether a unit can still accept insertions depends on how long it waits, which depends on how many units compete, which depends on their sizes. Each mechanism is simple to state, but the invariants must hold simultaneously after every operation, and each timing argument assumes that the others held at earlier operations (Section 3.7). This is why the published descriptions are long, and why constant worst-case time is a natural target for a mechanized proof. Earlier constructions are compared with ours in Sections F and 7.
3 The Algorithm
We first explain the layout and a single insertion, then the background work at each level, and finally why it finishes in time.
3.1 Overview
Our structure has four levels (Figure 3). Fix a capacity , and let its bit length be ; all label widths will be . From the bottom up, the levels are:
Elements. The elements of the maintained sequence, in order. Each element carries a label that orders it within its group.
Groups. Consecutive elements form groups of about elements. Each group carries a label that orders it within its chunk.
Chunks. Consecutive groups form chunks of about elements. Each chunk carries a tag that orders it among all chunks.
The top tree. A tree whose leaves are the chunks. The weight of a node is the number of chunks below it, and a node that becomes too heavy is split, which keeps the tree balanced. Each node labels its children, and the tag of a chunk is the sequence of labels on its path from the root. The tree together with the jobs that update it is the top structure.
The key of an element is the triple (tag of its chunk, label of its group, its own label), and an order query compares two keys lexicographically (see Figure 3). An interactive visualizer shows the four levels while insertions, deletions and rebuilds proceed.¹
We call such a four-level structure, built for a fixed capacity , a core. A core holds at most elements and never shrinks: a deleted element stays in it as a tombstone. The data structure the user sees is a wrapper that holds one core, or two while it rebuilds into a core of a different capacity in the background (Section 3.6).
Why four levels. Each level makes the level above it change rarely. An insertion takes a label inside its group, and the groups change only when one splits, about once per insertions into it. Group splits in turn change the chunks only when one splits, about once per insertions into it. Only chunk splits reach the top tree, the one part whose work grows with the size of the sequence: a job there, which enters two new chunks into the tree (Section 3.5), takes steps. If groups sat directly below the top tree, a job would be needed every insertions, about as fast as jobs can be paid for, and groups waiting for one would outgrow their labels. Chunks make jobs rare enough to pay for, with room to wait. Keeping every unit small also keeps every label short: a unit that receives new members in its lifetime needs only -bit labels.
The principle: never relabel in place. When a unit (a group, a chunk, or a node of the top tree) approaches its size limit, we do not relabel its members. Two fresh, empty

Figure 3: The structure. Groups hold about consecutive elements and chunks about . The tag of a chunk is the sequence of labels on its path in the top tree. A key is read top-down: group labels matter only within a chunk, element labels only within a group. On the right, the background work at each level.
¹https://dfirsov.github.io/order_maintenance/viz/
insertAfter(x): -- in a core
g := group(x)
new element y; choose a guarded label for it after x in g
link y after x; size(g) += 1; size(chunk(g)) += 1
if g just reached G and is not splitting: start its split
$K_G$ moves of the split in g's family (if any)
$K_C$ moves of the split in chunk(g)'s family (if any)
$K_R$ steps of the current top job (or start one from the queue)
return y
Figure 4: An insertion. The wrapper (Section 3.6) adds steps of global rebuilding to every user update; queries do no background work.
Table 1: Parameters for a core of capacity , .
| Symbol | Meaning | Value |
|---|---|---|
| group size at which a split starts | ||
| largest chunk size at split start; queue threshold | ||
| split moves per insertion (groups, chunks) | ||
| top job steps per insertion | ||
| branching parameter and height of the top tree | ||
| sweep steps per funding job (Section 3.5) | ||
| label bits per table entry | ||
| label bits within a group, within a chunk | (Section B) | |
| rebuild budget per update |
neighbours are linked on either side of it, and its members migrate into them a few at a time, each getting a fresh label in its new home. The old unit and its new neighbours are adjacent, so keys stay sorted at every instant, and a half-finished split is harmless: a query simply compares the keys as they are. Rebuilding treats a whole core the same way (Section 3.6).
The budget: work follows growth. Figure 4 shows an insertion. It does only one thing for itself: it gives the new element a label in the group of its predecessor and links it into the element list. Every other line is its share of the background work, a fixed number of steps at each level (Table 1): it starts a split if its group has just become full, performs moves of the split in its group's family (the splitting group and its two new siblings, Section 3.3) and in its chunk's family, and steps of the top structure, which works on its current job or starts one for the largest chunk waiting in a queue. The wrapper adds steps of global rebuilding to every insertion and deletion. A deletion marks its element as a tombstone; a query compares two keys and does no background work. So no operation performs a long repair at once, and the proof must show that every repair can wait for later insertions. The units grow with the capacity, so in a larger core the background jobs are longer but proportionally rarer, and the share per operation stays the same. Every line takes constant time, so the cost proof must show that the guards never fail and that every table the top structure touches (Section 3.5) stays of constant size.
The rest of this section explains the lines of Figure 4: labels and guards (Section 3.2), splits (Section 3.3), the queue of chunks waiting for new tags (Section 3.4), the top structure
(Section 3.5), and the rebuilding (Section 3.6).
3.2 Labels and guards
Labels. Labels are numbers of a fixed width, chosen for each core: element labels have bits and lie in , and group labels have bits and lie in . A new label is made in one of three ways: the first member of an empty group (or chunk) gets the middle of the range; a member added at an end gets its neighbour's label plus or minus a fixed step ; a member added between two others gets the average of their labels. A label never changes until a split moves its member to another group or chunk (Section 3.3). Each average halves a gap, so a gap survives only about insertions at the same place. The widths are therefore chosen from the number of new members a unit receives in its lifetime, which the splits keep at : a group receives elements, and a chunk, although it receives elements, receives only groups: moved in by the chunk split that created it, and two for each group split, which happens only after insertions (Section B). All widths are , so a key fits in a constant number of words, and reading a key follows the element's group reference and the group's chunk reference. An order query compares at most three pairs of labels.
Guards. Without guards, whether keys stay in the order of the sequence would depend on the timing analysis: if a group received more insertions than its label width allows, a gap would close. We do not let correctness rest on that analysis. Every write that could break the order is guarded: before writing, it checks the new value against its neighbours, in constant time. A new label must lie strictly between its neighbours' labels and inside its range, a new chunk tag must lie strictly between the tags of the neighbouring chunks, and a split move checks that the destination sibling is still the unit's immediate neighbour. If a guard fails, a fallback rebuilds the core from its element list (all its elements in sequence order, tombstones included, after a sentinel element) in linear time, with evenly spaced labels. The sentinel also gives insertFirst its meaning in a core: it inserts after the sentinel.
This splits the proof in two. The correctness invariant does not need the timing inequalities: it needs only that the label ranges are wide enough for the fallback's evenly spaced labels, and every guarded primitive then preserves order or invokes the fallback. Its reasoning is local to each write, and at the level of the functional implementation it holds whether or not guards fail (Section 4.3). The cost invariant shows that no guard ever fails, so the linear-time fallback never runs. The machine program therefore omits the fallback, and its correctness theorem uses both invariants. What the guards buy is a correctness proof that is local to each write and never mentions sizes or timing, not a correctness theorem that is independent of timing.
3.3 Splitting groups and chunks
A group that reaches elements starts to split (Figure 5): two empty groups and are linked immediately before and after , and from then on every insertion into this family performs moves. A move takes the first element of to the end of , or the last element of to the front of , whichever sibling is smaller, and gives the element a fresh label there. The element list itself never changes; only group membership and labels do. When is empty it is unlinked and its siblings become ordinary groups.
For example, suppose contains . After moving left and right, the three groups contain . Their group labels are in the same order, so a query sees

Figure 5: An incremental split. Each move takes one member from an end of into the adjacent sibling, where it gets a fresh label (hollow circles mark where the moved members land). Keys stay sorted at every instant because , and are consecutive.
regardless of the fresh local labels given to and . Moving an interior element instead would break this argument: it is essential that moves take a prefix to the left or a suffix to the right.
Each insertion into the family adds one element and moves four, so empties after about insertions. By then the family has gained only about elements, so the two siblings together hold about , and moving to the smaller sibling keeps them about equal. So every group stays below a constant times and receives insertions in its lifetime, which is what the label width pays for. If insertions into the family stop, the split can remain unfinished: nothing there is growing, and the keys already give the right answers.
Chunks split in the same way, with groups as members and moves per insertion. The one difference is when a split starts: the new siblings of a chunk need tags from the top structure, so a large chunk first waits in a queue (Section 3.4). Moving a group takes constant time however many elements it has, because elements point to their group and not to their chunk. One refinement keeps the two levels independent: if the group about to leave a chunk belongs to a splitting family, the whole family moves in the same step, so a family never straddles two chunks. Otherwise a later group move could add elements to another chunk without an insertion there, defeating that chunk's growth accounting.
3.4 Waiting for the top: the queue
Splitting a chunk creates two new chunks, which must be entered into the top structure (Section 3.5). Their tags are cheap and are assigned at once. What takes time is the job that records the new chunks in the tree: it updates the weights on the path to the root and rebalances where needed. A job takes steps, every insertion advances it by steps, and only one runs at a time, so that the weights it reads are exact. Chunks therefore have to wait their turn, and the largest is served first, as in the splitting lemma of Levcopoulos and Overmars [43] and the reservation process of Dietz and Sleator [22]. A bucket queue, as in Kopelowitz's construction [42], holds the chunks larger than , keyed by size: one bucket per size, with the non-empty buckets linked in order. A chunk's size changes by one at a time, so it moves to a neighbouring bucket in constant time; the general insertion into the queue scans for the next non-empty bucket, and the cost proof shows that this linear-time path is never taken. Whenever no job is running, the largest chunk is taken from the queue, its two empty siblings are linked and given tags, a job for them starts, and the chunk starts splitting. The new chunks receive elements without waiting for the job to finish.
How large can a chunk grow while it waits? This matters because the size of a chunk bounds the insertions its group labels must absorb. Insertions keep arriving while a job runs, and the user may aim them all at waiting chunks. Dietz and Sleator [22] answer this question with a game, which we call the zeroing game. There are counters, all starting at 0. In each round, the player resets a largest counter to 0, and then an adversary adds a total of at most to the counters, split among them as it likes. Then no counter ever exceeds , where is the -th harmonic number. The bound is reached roughly when the adversary spreads its additions evenly over the counters still in play: with counters left, each gets per round while the player removes one, so the last survivor collects .
In our setting, a counter is the amount by which a chunk exceeds (zero if it does not), a round lasts from one job's start to the next, and the reset is the start of a job for the largest chunk. A chunk that is splitting is not in the queue, and its counter is 0; the local split budget, not the game, bounds its growth. A chunk that has just finished splitting is below , so it re-enters the game at 0. A job takes steps and each insertion advances it by steps, so a round contains insertions, each adding one element to one chunk. There are at most counters, because a chunk is split only after growing from the size of a freshly split chunk to more than , and the core holds fewer than elements; so , and a chunk exceeds by at most before its job starts. The constants are chosen so that this excess is at most , so no waiting chunk exceeds before service. The local split budget then bounds its further growth. This is why chunks hold about elements: one factor of covers the length of a job, and the other the waiting factor , which even largest-first service cannot avoid.
3.5 The top structure
The top structure gives every chunk a tag that can be compared directly. The chunks are the leaves of a weight-balanced tree [4], as in Kopelowitz's construction [42], with branching parameter (Figure 6). The chunks have height 0, and a node has height if its children have height . Recall that the weight of a node is the number of chunks below it, not the number of elements. A non-root node of height is split when its weight exceeds , which keeps its weight at ; a node created by a drain (below) is not split while that drain is unfinished, and Section 3.7 shows that it does not reach the threshold in that time. The height is fixed when the core is created, large enough for the most chunks the core can hold: the tree widens as chunks are added, but never grows taller. Its root has enough room for the core's whole lifetime and never needs to split. Every node has a table: its children in order, each with a -bit label. A chunk stores its path to the root, and its tag is the concatenation of the labels along the path, bits in total. The labels of existing table entries are immutable: a new entry gets the average of its neighbours' labels, and no label ever changes. So a tag changes only when its chunk's path changes.
A job inserts two chunks into the tree and keeps the tree balanced, so that tags stay short and table labels never run out. A job that inserts two chunks around a chunk first gives them tags at once, computed from 's tag (they enter 's lowest-level table right before and after it), then copies 's stored path to them one level at a time, and finally walks up the tree from , one node per step, incrementing weights. Only one job runs at a time, so the weight the walk finds at a node is exact. If it exceeds the threshold, the node is split on the spot by the principle of Section 3.1, here called a drain: two new nodes are inserted right before and after in every table that contains , and becomes a ghost. (A node can sit in more than one table: if its parent is a ghost, the node stays in the ghost's table until the ghost's range is empty, and also appears in the table of one of the parent's new nodes.) The live children of are cut where their weights reach half of v's weight, but never between the two new nodes of a drain still running below v. Each new node gets a fresh, evenly spaced table of its part. A ghost child whose range is not yet empty goes to the side that receives its own left new node. The chunks whose stored paths still pass through the ghost form a contiguous range. A sweep step takes the chunk at the left end of the range if it belongs to v⁻'s part, and otherwise the chunk at the right end, and redirects its path to v⁻ or v⁺, rewriting its tag; the ghost disappears when its range is empty.
During a drain the tree already lists v's children under and , but the stored paths of some chunks, and hence their tags, still pass through v. Queries read only tags. Suppose the parent's table gives , v, the labels 20, 40, 60. Then chunks already swept left have 20 in that position of their tags, the unswept range has 40, and those swept right have 60; the positions further down order the chunks within each part. A sweep step takes a chunk from an end of the 40-range, so the three parts stay in order, and it changes only the affected path entry and two tag fields, not the whole path: the field at height h, which holds the label of v in its parent's table and now gets that of or , and the field below it, which holds the label of the next node down in v's table and now gets its label in the new node's table.
A job whose walk passes or performs s = 11 sweep steps of v; we call it a funding job of the drain. A new chunk copies its neighbour's stored path, so a funding job can add at most two chunks to the ghost's range, while it removes eleven: it reduces the unfinished sweep by at least nine, unless the sweep finishes. Funding jobs are also the only jobs that make and heavier. These start near half their weight limit; they gain only two chunks per funding job and cannot reach that limit before the sweep finishes. If no more such jobs arrive, the drain can remain unfinished safely.
Starting a drain touches only node tables, not all chunks below the node. The weight invariants bound the number of live children of a node by . Ghost entries are bounded too, and the argument runs from weights to tables, not the other way round. An entry is added to a table only by an insertion event (two chunks entering a lowest-level table, or a child being split), each event requires the weight below the table to grow by a fixed amount, and that weight is bounded; so the events are bounded, and with them both the length of the table and the number of times its gaps are halved. For our parameters every table has at most 160 entries, live or ghost, and bits leave room for all its halvings (Section 4.5). Table operations therefore take a fixed number of steps. The potentially large work is the sweep over chunks, which is spread over later jobs. Drains at different heights may coexist without waiting for one another; a job spends at most s sweep steps at each height, so the whole job takes steps. For our parameters the bound proved in Lean is job steps; each job step is a bounded number of machine instructions.
Drains are where we depart from earlier work. Willard's algorithm [57] and Kopelowitz's construction [42] relabel in place, in the background, so the structure passes through states in which some labels are old and some new. Dietz and Sleator keep two time-stamped versions of Willard's file, so that queries see a consistent one [23]; Kopelowitz rewrites the tags below a split node one at a time, with an extra most significant bit that orders the rewritten ones after the others. With immutable labels there is no such window: every chunk's tag is always a valid key, and a sweep step changes one tag, guarded against its two neighbours. The invariant that becomes simpler is the order of tags, which needs no case for a half-rewritten set of labels. What drains add is bookkeeping: ghost entries in tables, stored paths that may pass through ghosts, and the funding jobs that bound how long a drain lasts. The price is label width, one -bit field per level of the tree, and memory for the stored paths and ghost entries.

Figure 6: A ghost drain. The ghost (dashed) still lies on the stored paths of the chunks in its range. A sweep step redirects the chunk at an end of the range to or and rewrites its tag; all table labels stay as they are.
3.6 Deletion and growth
Cores never shrink: a deleted element stays in its core as a tombstone. Deletion and growth are handled by global rebuilding [52]. When the current core is half full (tombstones included), or the sequence has shrunk below an eighth of the capacity, the wrapper creates a new core. Its capacity is four times the sum of the live-element count and a bound on insertions arriving during the copy, with a minimum capacity of 64. The second term matters: even if few elements are live, the copy described below may spend many updates crossing tombstones while new elements arrive (Section D). From then on every user update has a budget of rebuild steps. First the new core's top tree is built, one node per step. Then a cursor walks through the current core's element list and copies each live element to the end of the new core, skipping tombstones. Meanwhile operations go to the current core and are mirrored in the new one when they concern the part already copied: an insertion after a copied element is repeated there, and a deletion of a copied element is marked there too. When the cursor passes the last element, the new core has the same live sequence in the same order, and it replaces the old one in a constant number of steps: the wrapper swaps the roles of its two core slots. The new core may also contain tombstones of elements deleted after they were copied.
The new core is built from scratch: its capacity, label widths and tree height differ, and its groups, chunks and labels are all new. The user does not notice, because a handle does not point into a core. The -th insertion returns the number as its handle, and the wrapper keeps, for each core, an array that maps handles to the elements of that core. A query looks up both handles in the current core's array and compares the keys there. The copy step and the mirrored insertions fill in the new core's array as they go, and when the new core takes over, so does its array. So a handle returned long before a rebuild can be compared with one returned after it: at the time of the query, both are looked up in the same core.
3.7 Why the budgets suffice
Each piece of background work races the unit it serves: it must finish before that unit runs out of room. At the group and chunk levels the race is local: the insertions that fill a split's destinations are the same insertions that drive the split, and each of them moves four members out while adding at most one. The top tree has the same kind of race. When a node is split, its chunks are moved to the two new nodes one at a time by sweep steps, and the new nodes must not become too heavy, and need splitting themselves, before is empty. The only jobs that add chunks below the new nodes are those whose walk passes through them, and each such job also performs sweep steps of , so the move finishes in time. The queue is the one place where unrelated units compete, and there the zeroing game bounds how much a waiting chunk grows. Global rebuilding follows the same pattern at the scale of a core: it starts while the old core is only half full, and the new capacity leaves room for the insertions that arrive during the copy.
The proof turns each race into an inequality between the parameters of Table 1. Seven are needed; Section A lists them all. Their exact forms, with all rounding, are proved in Lean for every ; we show simplified versions. Three of them show the pattern.
- Group splits. A split lasts at most insertions, and moving to the smaller sibling leaves each sibling with about half of elements, which must be below the split size:
So a sibling never needs to split while its own family is still splitting.
- Waiting chunks. A job takes at most steps, so a round of the zeroing game contains at most insertions. With counters, a waiting chunk stays below if
With and we get , and gives , so the left side is at most .
- Drains. A new node starts with half of its source's threshold , plus the weight that the cut cannot divide: one child of , or the two new nodes of a drain still running below . A child may gain weight during its own drain, so this is up to about . The new node then gains 2 per funding job for at most about jobs. It must stay below the threshold:
For and the coefficient is ; with it is 1, and the condition fails.
The invariants depend on one another. The top tree's invariants, which bound the length of a job, need a bound on the number of chunks. That bound holds because a chunk is split only after growing from the size of a freshly split chunk to more than , so it needs the bound on the size of a chunk when its split starts. That bound comes from the zeroing game, whose rounds are as long as top jobs. No invariant can therefore be established on its own. They are proved together, by induction over operations: if all of them hold before an operation, each one holds after it, using the others as they were before. So no invariant ever fails; in particular, no guard fails and the fallback never runs.
4 Formalization
4.1 Specification and machine
The specification is a list of distinct element names and a counter for the next fresh name. insertFirst puts the fresh name at the front of the list, insertAfter(x) right after , delete erases a name, and an order query is answered by
def precedes (l : List Elem) (x y : Elem) : Bool := decide (l idx0f x < l idx0f y)
A sequence of operations is valid if every argument is live when its operation is issued; Spec.run returns the answers.
We define a random-access machine (RAM) in Lean. Its words are unbounded natural numbers (Section 4.6 bounds the values the algorithm stores), its memory is a set of named arrays with explicit capacities, and its programs are structured: assignments, array loads and stores, allocation, conditionals, bounded loops, calls, and fail and catch (Figure 12). Its interpreter exec is a total Lean function that returns the final state, a status and a step count, charging one step for every expression node, assignment, memory access, allocation, branch, loop iteration, call, returned value, skip and handler entry. This deep embedding is deliberate. If the algorithm were ordinary Lean code in a monad that counts designated primitives, it could do uncounted work between them, such as a list traversal hidden in a helper function, and ruling that out would be a matter of reviewing code, not of proof. Here a program has no way to compute outside the interpreter, so a reader only has to check that exec charges every instruction; it and the expression evaluator take 171 lines.
4.2 The main theorem
Figure 7 states the main theorem for the machine program. It combines three statements: the program answers as the specification does (Theorem A), every operation takes at most opB steps (Theorem B), and no operation computes a large value (Theorem W). The initial machine state is arbitrary except for the local kb, which holds the rebuild budget ; the hypothesis only ensures that itself, which the program stores, is small. The program initWS initializes the structure, and runMW then runs the machine procedure for each operation in turn, returning for each operation its answer, its step count and the largest value it computes. For every valid operation sequence the answers are those of Spec.run, and every step count is at most opB , a number that depends on alone: not on , the number of live elements, or the history. The theorem compares the answers of the queries, which ansOf reads from the machine's local r. Handles are not part of the compared answers: in both the specification and the machine program, the k-th insertion returns handle , and the insertion lemma insertW_ok proves that the machine's result local holds exactly the specification's fresh handle. The budget is read from a local so that one theorem covers every budget .
For , initialization takes at most 6,648 steps and every operation at most 1,133,561,742. The bound is deliberately loose: most of it comes from nested traversals of bounded-size top-tree tables, multiplied by the fixed number of core insertions an update can perform (Section C). It shows that a uniform constant exists; it does not predict running time.
For Theorem W, the interpreter records in an extra field, which no instruction reads, the largest value of every expression and subexpression it evaluates, including indices and loop bounds (bump, Figure 13), and dpk c m is that value for a run of c from m. Initialization computes no value of more than 1,029 bits, and operation (counting from 0) none of more than bits. The bound grows with because handles are never reused and because the capacity is bounded only in terms of the number of operations (Section 6).
Words of bounded size. A bound on values matters because a machine with words of that size should then behave the same. execW w is exec with one change: an expression with a value of or more, or a subexpression with one, fails to evaluate (the machine traps on overflow rather than wrapping around), as an out-of-range array access does theorem theoremABW_MW {m₀ : State} {KB : Nat} (hkb : m₀.loc "kb" = KB) (h4 : 4 ≤ KB) (h512 : KB < 2 ^ 512) (ops : List OM.Spec.Op) (hv : OM.Spec.Valid OM.Spec.State.empty ops) : (exec initWS m₀).status = .ok ∧ (exec initWS m₀).cost ≤ initB ∧ -- B (init) dpk initWS m₀ < 2 ^ 1029 ∧ -- W (init) ∃ cs ps, runMW (exec initWS m₀).st ops = some (OM.Spec.run OM.Spec.State.empty ops, cs, ps) ∧ -- A cs.length = ops.length ∧ ps.length = ops.length ∧ (∀ c ∈ cs, c ≤ opB KB) ∧ -- B ∀ i (hi : i < ps.length), ps[i] < 2 ^ (128 * Nat.log2 (i + 1) + 1286) -- W
theorem opB_four : opB 4 = 1133561742 theorem initB_eq : initB = 6648
Figure 7: Theorems A, B and W for the machine program (OM/Impl/PeakRun.lean, OM/Impl/TheoremsM.lean; the comments are ours). exec c m runs c from m and returns a final state (.st), a step count (.cost) and a status; runMW runs the operations in turn and returns their answers, their step counts cs and their largest computed values ps, each measured by dpk. initB and opB are the step bounds of initialization and of an operation. Operations name elements by the specification's handles, the creation indices; insertW_ok shows that the machine's insertion returns exactly these. The axioms used are pronext, Classical.choice and Quot.sound.
(Section C.1). execW_agree says that execW w c s = exec c s, with the same state, step count and status, whenever dpk c s < 2^w. Hence theoremAB_word: for a run of t operations and every w ≥ 128[log₂(t + 1)] + 1286, the machine with w-bit words initializes the structure, answers every query as the specification does, and takes the same number of steps as the unbounded machine, so Theorems A and B hold for it verbatim. The theorem fixes w from the length of the run; the per-operation bound of Figure 7 would also support a machine whose words widen as the run proceeds, which we do not formalize.
4.3 Proof architecture
Proving the machine program directly against the specification would mix the mathematics of the algorithm with memory layout, so the proof goes through three levels below the specification (Figure 8). Level F (functional) is the algorithm written as pure Lean functions on a structured state of records and arrays, with explicit program counters for the background work. All reasoning about the algorithm happens there, in two invariants. The correctness invariant says that keys increase along the element list and that its live elements form the list of the specification; each guarded write keeps it and the fallback restores it, so its proof never mentions sizes or timing. The cost invariant carries the bounds of Section 3.7. It implies that no guard fails, that the queue's linear-time path is never taken, and that every list a top job traverses has at most 160 entries. Level F counts no steps. Theorem B combines the agreement lemmas below, which bound each procedure's steps by a function of the sizes it traverses, with the cost invariant, which bounds those sizes by constants.
Level M (machine) is the machine program, and the cost bound is about it. Relating it to Level F means relating records and lists to flat arrays of numbers: which array holds which field, that a write to one array leaves the others unchanged, and that every index stays within its capacity. Doing this for every procedure would repeat the same memory reasoning each time. Instead, each Level F function is transcribed by hand into a small

Figure 8: The levels of the proof. Level F and its intermediate-language transcription are written by hand; Level M is compiled from the transcription. The exception is the wrapper, which is written directly as machine code and proved against Level F with a weakest-precondition calculus (Section C.2).
intermediate language, whose semantics runs directly on Level F states but charges what the compiled code will cost, and a compiler produces Level M from the transcriptions. The compiler is a verified change of data representation, from records and lists to flat arrays, that preserves states and step counts exactly. The intermediate language is tailored to this algorithm: besides assignments, conditionals, loops and calls, its 24 statement forms include writes to the structure's own lists and records. One theorem, sim, does all the memory reasoning about a core: for every program, the compiled code ends exactly as the intermediate-language semantics says, in the same number of steps, unless the intermediate-language run ends in an internal error (bug), which the agreement lemmas exclude. What remains for each procedure is an agreement lemma with its Level F function, proved purely at Level F. Because sim shows that the costs charged in the intermediate language are met by an actual memory layout on the machine, the interpreter remains the only cost model to trust. The wrapper, which manages the two cores and the handle maps, is written directly as machine code and proved against Level F with a weakest-precondition calculus. Section C gives the details.
4.4 An example: the order query
The order query shows every level on a small scale (Figure 9). At Level F, order x y reads the key of each element, the triple of its chunk's tag, its group's label and its own label, and compares the two keys lexicographically. Its intermediate-language transcription orderP reads the same fields with field reads (.eF, .gF, .cF) and computes the comparison as one expression. The agreement lemma order_agree says that whenever the Level F query returns b and the indices it follows are below the array capacities, the transcription ends in the same state, with b in its result local r, and is charged at most 80 steps. Because both sides are straight-line code, simp unfolds both runs and omega closes the remaining comparison of keys. The caller discharges the capacity hypotheses from the invariants: x and y are listed elements, so their groups and chunks are live units (by the correctness invariant and the chunk part of the cost invariant), and live units lie below the capacities. sim then turns the intermediate-language run into a run of the compiled machine code
-- Level F def key(e : Nat) : CM (Nat × Nat × Nat) := do let x ← getE e let g ← getG x.grp return ((← getC g.chk).tag, g.lab, x.lab) def order (x y : Nat) : CM Bool := return keyLt (← key x) (← key y)
-- intermediate language def keyS (e t g l : Reg) : Stmt := g ::= .eF .grp e ;; l ::= .eF .lab e ;; t ::= .cF .tag (.gF .chk g) ;; g ::= .gF .lab g def orderP : Proc where name := "order" params := ["x", "y"] rets := ["r"] body := keyS "x" "ta" "ga" "ea" ;; keyS "y" "tb" "gb" "eb" ;; "r" ::= (("ta" <e "tb") ||e (("ta" =e "tb") &&e (("ga" <e "gb") ||e (("ga" =e "gb") &&e ("ea" <e "eb"))))
-- agreement (capacity hypotheses on x, y and their group and chunk elided) theorem order_agree ... (h : (order x y).run σ = .ok b σ') : ∃ L' n, evalF κ orderP.body σ L = .ok σ' L' n ∧ L' "r" = b2n b ∧ n ≤ 80
Figure 9: The order query at Level F, in the intermediate language, and the agreement lemma between them. CM is the Level F state and error monad; Stmt is the type of intermediate-language statements, ::= and ;; are assignment and sequencing, and .eF, .gF, .cF read element, group and chunk fields. In order_agree, gives the array capacities, and are Level F states, L and L' the locals before and after (not the bit length L), n the steps charged, and b2n maps a Boolean to 0 or 1 (OM/Model/Core.lean, OM/Impl/Elem.lean).
with the same state and step count, and the wrapper's proof, in the weakest-precondition calculus, adds the steps that translate handles into element indices. Larger procedures follow the same pattern, but their agreement lemmas need loop invariants, and their capacity hypotheses come from the cost invariant.
4.5 A harder example: room in the top tables
The order query’s agreement lemma needs no invariant. The guards of the top tree need one that spans many operations: a new table entry takes the average of its neighbours’ labels, so its guard succeeds only if that gap has not closed, and a job’s traversal of a table is short only if the table is. Both follow from one bound on insertion events. For every table , the Lean invariant Room (Figure 10) keeps two auxiliary, proof-only quantities: the number of entries was created with, and the number of insertion events it has seen since. An event adds two entries, so has at most entries, and every gap of is at least (gaps; the divisions are integer divisions, as in the fresh labels themselves).
The difficulty is to bound , and here the weights enter. At height , an insertion event in is a child of being drained, and the potential pot2 pays for it in one of two ways. Write , where is the threshold above which a child is drained and bounds the weight of a node when it is created. Schematically,
structure Room (s : TS) (cl : List Nat) (dr n0 : Nat → Nat) : Prop where gaps : ∀ X, isN s X → GapsGe s.P.beta (gapB s.P.beta (n0 X) (dr X)) (labs s X) n01e : ∀ X, isN s X → n0 X ≤ n0max s.P (ht s X) pot1 : ∀ X, isN s X → ht s X = 1 → 2 * dr X + (if s.P.H < X then lamd s.P 1 else 1) ≤ ew s cl X pot2 : ∀ X, isN s X → 2 ≤ ht s X → gamd s.P (ht s X - 1) * dr X + growth s cl X
- (if s.P.H < X then lamd s.P (ht s X) else 1)
- gamd s.P (ht s X - 1) * oldLive s X ≤ ew s cl X + gamd s.P (ht s X - 1) * n0 X
-- in a section with (ha : P.a = 8) (hs : P.s = 11) theorem room_8 (hb : P.beta = 64) (h : Nat) (h1 : 1 ≤ h) : 2 ^ Dmax P h * (n0max P h + 1) ≤ 2 ^ P.beta theorem tab_8 (h : Nat) (h1 : 1 ≤ h) : n0max P h + 2 * Dmax P h ≤ 160
Figure 10: Label room in the top tables. s is the state of the top structure (the sweep parameter is s.P.s) and cl its chunks in order; isN s X says that X is a node, live or ghost, ht gives its height and labs its table labels, and GapsGe β B says that every gap is at least B. dr X counts the insertion events of table X, n0 X its initial entries, gapB the resulting gap bound (with integer divisions), ew the effective weight below X (for a node being drained, the weight below its two new nodes), gamd the growth γ that pays for one event, and lamd a lower bound on the weight of a new node. The test s.P.H < X separates nodes created by drains from the initial ones, and pot1 is the height-1 form of pot2. room_8 and tab_8 are stated in a section with the hypotheses P.a = 8 and P.s = 11 (OM/Proof/Top/Inv.lean, OM/Proof/Top/TopParams.lean).
where growth(X) sums, over the live children created after X, their weight above , oldLive(X) counts the live children X was created with, and base is a lower bound on the initial weight of X itself. When a child created after X is drained, it had grown by at least , and its contribution to growth disappears, paying for the new in . A child that X inherited may already be heavy, so its drain cannot be charged to growth; instead oldLive falls by one and releases of the initial credit . The effective weight is the weight below X, or for a node being drained the weight below its two new nodes together, and the cost invariant bounds it, so stays below a constant (Room.dr_1t). Let bound the entries a table of height is created with (n01e). Two conditions on the parameters, proved for every height when and , finish the argument. (room_8) reserves one halving beyond the events already seen: since in every state, every gap is at least two labels wide, so the average taken by the next insertion lies strictly between its neighbours, and every gap is at least one afterwards. (tab_8) bounds the table. So the logical order is: weight growth bounds the events, the events bound the table's length and its halvings, and is chosen to accommodate the halvings. Preserving pot2 is where the drain proofs need most care: a drain start creates two tables at once, a ghost entry goes to the side of its own left new node, and a drained node's effective weight is that of its two new nodes together. Room or its fields are used in 12 of the 46 files of the top-structure proof.
4.6 Memory, value sizes and trust
Two further theorems bound resources. The arrays of a core of capacity have a total capacity of at most cells (a bound on core arrays, not on all memory), and a second core being built has capacity at most ; the handle maps, which grow with the number of insertions, are not included. Theorem W is proved in three steps. The first bounds every value stored in the cores of Level F, other than handles, by , with the larger during a rebuild (theoremW_stored); handles and wrapper counters are bounded by the number of operations. The second bounds the values each intermediate-language procedure computes, through an extension of sim that also relates the largest values, by plus a handle term, where covers both the current core and a core created during the operation. The third extends the bound to the wrapper's machine code with a weakest-precondition calculus that carries a budget for the largest value. A new core has at most 2 larger, and the capacity is at most after operations; together these give the bound of Figure 7 in alone. What remains for a word-RAM result is discussed in Section 6.
The top-level theorems use only Lean's standard axioms propext, Classical.choice and Quot.sound. To assess what they mean, a reader must check the specification, the machine interpreter (OM/Machine/Syntax.lean and Exec.lean), the statements of Figure 7, and the definitions that connect them: runMW runs the operations in turn, opS encodes an operation and its handle arguments as machine code, ansOf reads an answer from the machine state, and dpk reads the largest value the interpreter recorded. The statement on w-bit words adds execW, which repeats exec with a bounded evaluator, and runMw, which runs the operations as runMW does, with execW in place of exec, and returns their answers and step counts; its statement also equates the w-bit run with runM, the run of Figure 7 without the peaks. The model assigns unit cost to arithmetic, shifts and (msb) on unbounded words and to zero-filled allocation [12]; Theorem W bounds the size of those words. The Rust transpiler and runtime are outside the proof. The script scripts/reproduce.sh in the repository repeats the build, the axiom audit of the main theorems, a fresh transpilation and the cross-check of Section E. Section C gives the machine semantics and the size of the development.
4.7 Proof engineering
The development uses Lean 4.35 and Mathlib, for real numbers (the harmonic numbers of the timing inequalities), list lemmas and arithmetic tactics such as ring and norm_num. The proofs are mostly simp, omega and decide (about 11,000, 4,700 and 1,500 uses), and native_decide is never used. A clean build of the development, with Mathlib prebuilt, takes about 8 minutes on 24 cores; the 203 modules the library imports take 13 minutes of CPU time in total, so the build is limited by its longest chain of imports rather than by the cores. Four lessons stand out.
A contract separates the invariants. The invariants of Section 3.7 depend on one another and are proved together. In Lean the argument is ordinary induction over operations, on one invariant, CostInv (Figure 11), which combines the invariant of groups, chunks and the queue, the state of the zeroing game with its accounting of rounds, and an abstract invariant TI of the top structure. The proofs about groups, chunks and the queue are made against a contract, TopContract TI J cap: starting a chunk split yields a job whose remaining work is at most , and every job step keeps TI and decreases . The top structure is proved separately to satisfy the contract, with the number of steps left in its running job. Neither proof looks inside the other, and the two were developed in sequence.
structure CostInv (TI : Core → Prop) (μ : Core → Nat) (J n R : Nat)
(L : List Nat) (s : Core) : Prop where
low : LowInv s L -- groups, chunks, queue; s holds the sequence L
ti : TI s -- the top structure's invariant, abstract
game : ∃ y i a ip js, GameInv n R s y i a ip ∧ RoundOK s.P.K_R J μ s ip js
structure TopContract (TI : Core → Prop) (μ : Core → Nat) (J : Nat)
(cap : Params → Nat) : Prop where
frame : ∀ s s', TopSame s s' → TI s → TI s'
mframe : ∀ s s', TopSame s s' → μ s' = μ s
start : ∀ s A x, INV s A → TI s → s.resJob = none → LiveC s x →
cSt s x = .quiet → s.C.size + 2 ≤ cap s.P →
∃ job s2, (insertAround x ...).run ... = .ok job s2 ∧
1 ≤ μ (markState s2 ...) ∧ μ (markState s2 ...) ≤ J ∧
TI (markState s2 ...)
step : ∀ s A job, INV s A → TI s → s.resJob = some job →
∃ r s', (jobStep job).run s = .ok r s' ∧ TI { s' with resJob := r } ∧
∀ j', r = some j' →
1 ≤ μ { s' with resJob := r } ∧ μ { s' with resJob := r } < μ s
Figure 11: The cost invariant and the contract of the top structure (arguments elided, comments ours). In CostInv, L is the specification's sequence (not the bit length ) and s the core; n and R are the number of counters and the insertions per round of the zeroing game, GameInv is the game's invariant for the current round (round-start values y, the counter i just reset, and the additions a of the ip insertions since), and RoundOK accounts for the js job steps of the round against J. In TopContract, cap bounds the number of chunks the tree has room for, resJob is the running job, and markState is the state after the chunk split starts. frame and mframe: steps that leave the top structure's state unchanged (TopSame) keep TI and μ. start: entering two chunks around a quiet chunk x starts a job with at most J steps of work. step: a job step keeps TI and, unless the job ends, decreases μ. INV is the correctness invariant (OM/Proof/Cost/CoreCost.lean, OM/Proof/Cost/TopIface.lean).
State-based measures cost constants. The pen-and-paper proof bounds label room through the history of each gap. Lean replaces histories by measures of the current state: one halving counter per chunk instead of halving histories per gap, and a potential over table weights instead of the histories of table insertions. Each invariant then becomes a property of one state, preserved by each step, at the price of coarser bounds: group labels grew from about 9L to about 30L bits and from 48 to 64. grew from 4 to 8 for a different reason: with 8, the waiting-chunks inequality follows for every from the bound ; with 4 it holds, but only numerically, with about 5% to spare at .
Prove memory reasoning and peak tracking once. sim is the only theorem about the layout of a core's arrays, and the peak bound reuses its structure: it was extended once (sim_peak) to relate the largest values of the two runs, after which the bounds on computed values are proved, like the agreement lemmas, at the level of the intermediate language. Only the wrapper is reasoned about as machine code.
Where the lines go. The top structure takes 14,807 lines, about half of them for showing that starting and advancing a drain preserves the tree's shape, order and timing invariants: a drain start changes several nodes, tables and paths at once. The bound on computed values takes about 12,000 lines, most of them a second pass over every procedure that
Table 2: Selected measurements in s: mean / 99.99th percentile of a run / slowest repeatable time (the largest per-operation minimum over three runs; see the text). Insertions are those that grow the sequence from to elements; cold queries are 500 random pairs in the same range after random insertions, each measured in two cold runs after a warm run that selects the measured operations (too few for a percentile). For cold queries, the mean is the mean over queries of each query's minimum over the two runs, preferring a run without a page fault and leaving out queries that fault in both, and the slowest time is the largest of these minima; the means of the individual runs are 1.02–1.03 (native), 6.4–6.5 (AVL) and 0.56–0.57 s (amortized). Memory is peak resident bytes per element after random insertions. Hardware: Intel Core Ultra 9 285K, Linux 7.0, one performance core.
| native (unverified) | AVL | amortized | |
|---|---|---|---|
| Random insertion | 1.00 / 5.3 / 12.1 | 0.77 / 5.5 / 7.2 | 0.54 / 12.3 / 15.3 |
| Clustered insertion | 0.085 / 2.9 / 6.3 | 0.030 / 3.2 / 3.6 | 0.022 / 3.4 / 5.050 |
| Cold order query | 0.93 / – / 1.4 | 5.9 / – / 8.4 | 0.50 / – / 0.88 |
| Memory (bytes/element) | 112 | 13 | 21 |
tracks the width of each expression. The guards pay off in the size of the correctness proof: 8,421 lines, against about 29,000 for the costs at Level F, because it never mentions timing.
5 Execution and Practical Cost
Two Rust artefacts serve different purposes. The first is transpiled statement for statement from the verified machine program by an unverified transpiler; it uses arbitrary-precision values, counts machine steps, and agrees with Lean's machine semantics on answers, step counts and the bit lengths of the largest computed values on every cross-checked run (Section E). The second, a native implementation, implements the same algorithm with records and fixed-width labels. It is not verified, but it and Level F both reproduce 28 traces written by our Python prototype, 14.6 million operations including deletion-heavy workloads and repeated rebuilding. This evidence checks the tested executions; it does not prove the transpiler, runtime or native implementation correct.
Table 2 gives representative results. On insertions the native implementation's mean time is 1.3–2.8 times the AVL tree's. At the 99.99th percentile of a run it is as fast as the tree or faster (0.8–1.0 times), but the tree has the lower slowest repeatable insertion time: by that statistic, native insertions take about 1.3–2.3 times as long, a ratio that varies between sessions and seeds. Native cold order queries are 2.2–6.3 times faster than the tree's, by either estimator, and native needs about 8.6 times the memory. Its advantage over the amortized baseline is in the worst case: clustered insertions force that baseline into relabelings of about 5 ms, while on average the amortized baseline is faster than both. The transpiled program, which computes with arbitrary-precision words and counts every step, is much slower than all three (Section E). These are practical trade-offs, not a claim that the asymptotically stronger bound wins at every size or workload.
Each deterministic workload runs three times. The slowest repeatable time takes each operation's minimum over the runs. This removes pauses that hit an operation in only some runs, but it is not a measured worst-case latency: a recurring cost that falls on different operations in different runs is removed too. The maximum of a single run is a different quantity, and it varies from run to run. In the session of the table, it is about 0.3 ms at elements for every implementation in most runs, with occasional runs at
2.7–4.3 ms. At it is 4.3–20.5 ms for native random insertion, 4.3–6.1 ms for the tree and 4.3–7.0 ms for the amortized baseline, and one of three native clustered-insertion runs has a 92 ms outlier that the other two do not show. The same values (0.3, 2.7, 4.3 and 6.1 ms) recur across implementations and workloads, even in order queries. A test that only writes to fresh memory pages shows one source: about one first touch in 2,000 stalls for about 0.3 ms. Native touches about 8.6 times as much memory as the tree and meets more of these stalls: at , 733–900 random insertions per run take over 100 s, against 28–179 for the tree and 111–178 for the amortized baseline. The amortized baseline's relabeling under clustered insertion is the one maximum that recurs at the same operation in every run, which identifies it as algorithmic; we do not claim that every other outlier has a memory-system cause. None of the implementations has a proved wall-clock bound.
With elements and operations, alternating random deletions and insertions, the times per operation stay the same over the whole history, and memory grows by 12 bytes per insertion for native, 13 for the AVL tree and 20 for the amortized baseline: in each case it is the map from handles, which are never reused. Native's cores in use stay below 1 MB through rebuilds.
The transpiled program's largest measured step count grows with the size even though its proved bound is constant: from steps at elements to at , against the proved . The number of top-job steps per operation is fixed, but as the tree gets taller more of them start a drain, the most expensive kind of step. That number is bounded by the job steps per operation, so the growth must stop. The workload definitions, deletion results and the explanation of this growth are in Section E.
6 Limitations
From bounded values to a word RAM. The machine's numbers are unbounded, and unit-cost arithmetic on unbounded words makes random-access machines unrealistically powerful [35]. Theorem W rules this out: after operations no value has more than bits, and a machine with words of that size runs the program with the same results and step counts (theoremAB_word). That machine still has unit-cost multiplication, division, shifts and , which common word-RAM variants provide, and zero-filled allocation of arrays of any size, which they do not (see Allocation below). On a word RAM with words of bits, a value of that size spans a constant number of words (about 128), so each unit-cost operation on it takes a constant number of word operations, with schoolbook multiplication and division; only the constant grows. The constant factor in the word size is large, because the proof bounds every stored value by the same 64L bits, well above the label widths of Section B, and products double that; the native implementation needs far fewer bits (Section E). Only handles and a few wrapper counters grow with the number of operations rather than with the capacity, handles because they are never reused; like any counter that grows by one per operation, they fit in 64 bits for every feasible run [18].
Space and the length of the sequence. The bounds are in terms of the number of operations and the capacity, not the number of live elements. Rebuilding shrinks a core whose live elements fall below an eighth of its capacity, so in practice the capacity follows , but we prove only that it is at most after operations, and no bound in terms of . The handle maps grow with the number of insertions and the cores with the capacity, so the space grows with the number of operations rather than with ; the memory theorem covers the cores only. Words of bits and space would need handles to be reused: a free list of handles, with a per-handle record that a rebuild updates, and a proof that the capacity tracks . We have not attempted either.
Allocation. The machine allocates a zero-filled array of any size in one step, and the program relies on it: a new core allocates arrays for up to 40,000N cells, far more than it uses, and every rebuild allocates handle maps with room for every handle issued so far, about cells after operations, whatever the length of the sequence. A standard word RAM has no such instruction. The usual simulation initializes memory lazily, with constant overhead per access and a constant factor in space [2, 12, 33], but we do not prove it, and the Rust runtime instead relies on lazily mapped operating-system memory. Since every rebuild allocates fresh arrays, the addresses such a simulation touches would grow with the total size allocated over the run unless freed arrays were reused.
From machine steps to execution time. The model gives zero-filled allocation unit cost and does not account for caches, page faults, reclamation or scheduling. The Rust runtime approximates allocation with lazily mapped memory and incremental cleanup; it is unverified. The native implementation and the Rust transpiler are also unverified. The measured native memory includes retained retired cores, which the formal core-memory bound does not cover. Finally, the theorems cover valid histories only: they do not specify behaviour for deleted or foreign handles.
7 Related Work
Dietz and Sleator's worst-case construction supplies the main techniques: incremental splitting, largest-first service and the zeroing game [22, 23]. Bender et al. give a simpler amortized algorithm and connect labeling to weight-balanced trees [8], and Kopelowitz replaces Willard's algorithm at the top by a weight-balanced B-tree [42]. We keep this approach to grouping, scheduling and the top tree, but guard every write and make the tree's labels immutable, with ghost drains instead of relabeling in place. As far as we know, no worst-case order-maintenance algorithm has been implemented before, and no order-maintenance algorithm has been verified in a proof assistant. Section F gives the historical comparison. Guo and Sekerinski face the same need for queries to stay correct while labels are being changed, in a concurrent amortized structure [30]: they relabel in place, installing precomputed labels in an order that keeps every intermediate state sorted, so that order queries can run lock-free. Our construction avoids relabeling in place altogether.
The closest verified relatives are real-time deque: Tóth and Nipkow verify Chuang and Goldberg's deque in Isabelle [54], and Viennot et al. verify Kaplan and Tarjan's catenable deque in Rocq [56]. Tóth and Nipkow argue constant time informally, from the non-recursive operations of their verified deque. Viennot et al. verify functional correctness and separately provide a non-recursive OCaml implementation; their verified code keeps computations on indices, so neither it nor its extraction attains the constant bound, and the two are not formally connected. Madhavan et al. do verify concrete worst-case step bounds for Okasaki's real-time queue and deque, at most 40 and 893 steps, by SMT-based contract checking in Leon against an instrumented source semantics whose soundness is proved on paper [44]. As there, our bound does not follow from the syntax, but here the invariants it rests on concern the whole structure: the loops of a top job are bounded only by invariants on table sizes, which hold because of the timing arguments of Section 3.7 about weights, waiting chunks and drains. We prove it in Lean, from the step counts of a deeply embedded machine. Other frameworks support mechanized cost reasoning through time credits, cost monads or refinement to lower-level code [31, 19, 37, 50]. Like Haslbeck and Nipkow [39], we count steps in the semantics of a deeply embedded language; we do so for a complete data structure, with a verified translation from records to arrays that preserves step counts. Section G compares these proof approaches in more detail.
8 Conclusion
Worst-case constant-time order maintenance has been known for almost four decades, from descriptions that are intricate and, in places, incomplete. We assembled an algorithm from the published components, adapted it for proof by guarding every write and by never changing the labels of existing entries in the top tree's tables, and proved in Lean that a program for it, run on a random-access machine whose interpreter counts every step, answers queries correctly and takes at most a fixed number of steps per operation, and that it runs unchanged on a machine whose words have bits after operations. Checking the literature exposed errors in two of the papers we build on or compare with, and a pen-and-paper proof written before the formalization found a bug and two gaps in our own design that extensive testing had missed. The transpiled program is slow, but the algorithm is not: implemented natively, it stays within a small factor of an AVL tree.
What remains for the textbook word-RAM statement is to replace unit-cost allocation of large arrays, to reuse handles and prove that the capacity tracks the number of live elements, so that word size and space depend on the length of the sequence rather than on the number of operations, and to shrink the constants (Section 6). Beyond that, the native implementation could be verified, by refining it to the machine program or by targeting a lower-level language, and the proved constant could be tightened. More broadly, guarded writes may help with other deamortized structures: they make the correctness invariant a local property of each write, and leave to timing arguments only the cost and the proof that the fallback never runs.
AI Disclosure
This work was done in collaboration with the large language models Claude Opus 5.5 (Anthropic) and Astra 6 (OpenAI), used as coding and writing assistants. They contributed to the design of the algorithm, the pen-and-paper proof, the Lean development, the Python prototype, the Rust implementations, the experiments and the text of this paper. Lean checks the proofs. The author directed the work and checked by hand the trusted parts (the specification, the machine interpreter, the statements of the main theorems and the definitions they rely on; Section 4.6), the claims about earlier work against the original papers, the experimental results and this text.
References
[1] Umut A. Acar, Guy E. Blelloch, and Robert Harper. Adaptive functional programming. ACM Transactions on Programming Languages and Systems, 28(6):990–1034, 2006.
[2] Alfred V. Aho, John E. Hopcroft, and Jeffrey D. Ullman. The Design and Analysis of Computer Algorithms. Addison-Wesley, 1974. Exercise 2.12.
[3] Roberto M. Amadio, Nicolas Ayache, François Bobot, Jaap P. Boender, Brian Campbell, Ilias Garnier, Antoine Madet, James McKinna, Dominic P. Mulligan, Mauro Piccolo, Randy Pollack, Yann Régis-Gianas, Claudio Sacerdoti Coen, Ian Stark, and Paolo Tranquilli. Certified complexity (CerCo). In Foundational and Practical Aspects of Resource Analysis (FOPARA 2013), volume 8552 of LNCS, pages 1–18, 2014.
[4] Lars Arge and Jeffrey Scott Vitter. Optimal external memory interval management. SIAM Journal on Computing, 32(6):1488–1508, 2003.
[5] Robert Atkey. Amortised resource analysis with separation logic. In Programming Languages and Systems – ESOP 2010, volume 6012 of LNCS, pages 85–103, 2010.
[6] Martin Babka, Jan Bulánek, Vladimir Čunát, Michal Koucký, and Michael Saks. On online labeling with polynomially many labels. In Algorithms – ESA 2012, volume 7501 of LNCS, pages 121–132, 2012.
[7] Frank J. Balbach. The Cook–Levin theorem. Archive of Formal Proofs, January 2023. https://isa-afp.org/entries/Cook_Levin.html, Formal proof development.
[8] Michael A. Bender, Richard Cole, Erik D. Demaine, Martin Farach-Colton, and Jack Zito. Two simplified algorithms for maintaining order in a list. In Algorithms – ESA 2002, volume 2461 of LNCS, pages 152–164, 2002.
[9] Michael A. Bender, Alex Conway, Martin Farach-Colton, Hanna Komlós, William Kuszmaul, and Nicole Wein. Online list labeling: Breaking the barrier. In 63rd IEEE Annual Symposium on Foundations of Computer Science (FOCS), pages 980–990, 2022.
[10] Michael A. Bender, Jeremy T. Fineman, Seth Gilbert, Tsvi Kopelowitz, and Pablo Montes. File maintenance: When in doubt, change the layout! In Proceedings of the 28th Annual ACM-SIAM Symposium on Discrete Algorithms (SODA), pages 1503–1522, 2017.
[11] Michael A. Bender, Jeremy T. Fineman, Seth Gilbert, and Charles E. Leiserson. On-the-fly maintenance of series-parallel relationships in fork-join multithreaded programs. In Proceedings of the 16th Annual ACM Symposium on Parallelism in Algorithms and Architectures (SPAA), pages 133–144, 2004.
[12] Preston Briggs and Linda Torczon. An efficient representation for sparse sets. ACM Letters on Programming Languages and Systems, 2(1-4):59–69, 1993.
[13] Jan Bulánek, Michal Koucký, and Michael Saks. Tight lower bounds for the online labeling problem. In Proceedings of the 44th Annual ACM Symposium on Theory of Computing (STOC), pages 1185–1198, 2012.
[14] Quentin Carbonneaux, Jan Hoffmann, Tahina Ramananandro, and Zhong Shao. End-to-end verification of stack-space bounds for C programs. In Proceedings of the 35th ACM SIGPLAN Conference on Programming Language Design and Implementation (PLDI), pages 270–281, 2014.
[15] Quentin Carbonneaux, Jan Hoffmann, and Zhong Shao. Compositional certified resource bounds. In Proceedings of the 36th ACM SIGPLAN Conference on Programming Language Design and Implementation (PLDI), pages 467–478, 2015.
[16] Arthur Charguéraud and François Pottier. Machine-checked verification of the correctness and amortized complexity of an efficient union-find implementation. In Interactive Theorem Proving (ITP 2015), volume 9236 of LNCS, pages 137–153, 2015.
[17] Arthur Charguéraud and François Pottier. Verifying the correctness and amortized complexity of a union-find implementation in separation logic with time credits. Journal of Automated Reasoning, 62(3):331–365, 2019.
[18] Martin Clochard, Jean-Christophe Filliâtre, and Andrei Paskevich. How to avoid proving the absence of integer overflows. In Verified Software: Theories, Tools, and Experiments (VSTTE 2015), volume 9593 of LNCS, pages 94–109, 2016.
[19] Nils Anders Danielsson. Lightweight semiformal time complexity analysis for purely functional data structures. In Proceedings of the 35th ACM SIGPLAN-SIGACT Symposium on Principles of Programming Languages (POPL), pages 133–144, 2008.
[20] Paul F. Dietz. Maintaining order in a linked list. In Proceedings of the 14th Annual ACM Symposium on Theory of Computing (STOC), pages 122–127, 1982.
[21] Paul F. Dietz, Joel I. Seiferas, and Ju Zhang. A tight lower bound for online monotonic list labeling. SIAM Journal on Discrete Mathematics, 18(3):626–637, 2004.
[22] Paul F. Dietz and Daniel D. Sleator. Two algorithms for maintaining order in a list. In Proceedings of the 19th Annual ACM Symposium on Theory of Computing (STOC), pages 365–372, 1987.
[23] Paul F. Dietz and Daniel D. Sleator. Two algorithms for maintaining order in a list. Technical Report CMU-CS-88-113, Carnegie Mellon University, 1988.
[24] James R. Driscoll, Neil Sarnak, Daniel D. Sleator, and Robert E. Tarjan. Making data structures persistent. Journal of Computer and System Sciences, 38(1):86–124, 1989.
[25] Yannick Forster, Fabian Kunze, and Marc Roth. The weak call-by-value -calculus is reasonable for both time and space. Proceedings of the ACM on Programming Languages, 4(POPL):27:1–27:23, 2020.
[26] Lennard Gäher and Fabian Kunze. Mechanising complexity theory: The Cook–Levin theorem in Coq. In 12th International Conference on Interactive Theorem Proving (ITP 2021), volume 193 of LIPIcs, pages 20:1–20:18. Schloss Dagstuhl – Leibniz-Zentrum für Informatik, 2021.
[27] Alejandro Gómez-Londoño. Hood-Melville queue. Archive of Formal Proofs, January 2021. https://isa-afp.org/entries/Hood_Melville_Queue.html, Formal proof development.
[28] Alejandro Gómez-Londoño, Johannes Åman Pohjola, Hira Taqdees Syeda, Magnus O. Myreen, and Yong Kiam Tan. Do you have space for dessert? A verified space cost semantics for CakeML programs. Proceedings of the ACM on Programming Languages, 4(OOPSLA):204:1–204:29, 2020.
[29] Armaël Guéneau, Jacques-Henri Jourdan, Arthur Charguéraud, and François Pottier. Formal proof and analysis of an incremental cycle detection algorithm. In 10th International Conference on Interactive Theorem Proving (ITP 2019), volume 141 of LIPIcs, pages 18:1–18:20. Schloss Dagstuhl – Leibniz-Zentrum für Informatik, 2019.
[30] Bin Guo and Emil Sekerinski. New concurrent order maintenance data structure. Journal of Parallel and Distributed Computing, 211:105238, 2026.
[31] Armaël Guéneau, Arthur Charguéraud, and François Pottier. A fistful of dollars: Formalizing asymptotic complexity claims via deductive program verification. In Programming Languages and Systems – ESOP 2018, volume 10801 of LNCS, pages 533–560, 2018.
[32] Bernhard Haeupler, Telikepalli Kavitha, Rogers Mathew, Siddhartha Sen, and Robert E. Tarjan. Incremental cycle detection, topological ordering, and strong component maintenance. ACM Transactions on Algorithms, 8(1):1–33, 2012.
[33] Torben Hagerup and Frank Kammer. On-the-fly array initialization in less space. In 28th International Symposium on Algorithms and Computation (ISAAC 2017), volume 92 of LIPIcs, pages 44:1–44:12. Schloss Dagstuhl – Leibniz-Zentrum für Informatik, 2017.
[34] Martin A. T. Handley, Niki Vazou, and Graham Hutton. Liquidate your assets: Reasoning about resource usage in Liquid Haskell. Proceedings of the ACM on Programming Languages, 4(POPL):24:1–24:27, 2020.
[35] Juris Hartmanis and Janos Simon. On the power of multiplication in random access machines. In 15th Annual Symposium on Switching and Automata Theory (SWAT), pages 13–23, 1974.
[36] Maximilian P. L. Haslbeck and Peter Lammich. Refinement with time – refining the run-time of algorithms in Isabelle/HOL. In 10th International Conference on Interactive Theorem Proving (ITP 2019), volume 141 of LIPIcs, pages 20:1–20:18, 2019.
[37] Maximilian P. L. Haslbeck and Peter Lammich. For a few dollars more: Verified fine-grained algorithm analysis down to LLVM. In Programming Languages and Systems – ESOP 2021, volume 12648 of LNCS, pages 292–319, 2021.
[38] Maximilian P. L. Haslbeck and Peter Lammich. For a few dollars more: Verified fine-grained algorithm analysis down to LLVM. ACM Transactions on Programming Languages and Systems, 44(3):1–36, 2022.
[39] Maximilian P. L. Haslbeck and Tobias Nipkow. Hoare logics for time bounds: A study in meta theory. In Tools and Algorithms for the Construction and Analysis of Systems – TACAS 2018, volume 10805 of LNCS, pages 155–171, 2018.
[40] Jan Hoffmann, Ankush Das, and Shu-Chun Weng. Towards automatic resource bound analysis for OCaml. In Proceedings of the 44th ACM SIGPLAN Symposium on Principles of Programming Languages (POPL), pages 359–373. ACM, 2017.
[41] Alon Itai, Alan G. Konheim, and Michael Rodeh. A sparse table implementation of priority queues. In Automata, Languages and Programming (ICALP 1981), volume 115 of LNCS, pages 417–431, 1981.
[42] Tsvi Kopelowitz. On-line indexing for general alphabets via predecessor queries on subsets of an ordered list. In Proceedings of the 53rd Annual IEEE Symposium on Foundations of Computer Science (FOCS), pages 283–292, 2012. arXiv:1208.3798.
[43] Christos Levcopoulos and Mark H. Overmars. A balanced search tree with worst-case update time. Acta Informatica, 26(3):269–277, 1988.
[44] Ravichandhran Madhavan, Sumith Kulal, and Viktor Kuncak. Contract-based resource verification for higher-order functions with memoization. In Proceedings of the 44th ACM SIGPLAN Symposium on Principles of Programming Languages (POPL), pages 330–343. ACM, 2017.
[45] John W. McCormick and Peter C. Chapin. Building High Integrity Applications with SPARK. Cambridge University Press, 2015.
[46] Glen Mével, Jacques-Henri Jourdan, and François Pottier. Time credits and time receipts in Iris. In Programming Languages and Systems (ESOP 2019), volume 11423 of LNCS, pages 3–29, 2019.
[47] Tobias Nipkow. Automatic functional correctness proofs for functional search trees. In Jasmin Christian Blanchette and Stephan Merz, editors, Interactive Theorem Proving (ITP 2016), volume 9807 of LNCS, pages 307–322. Springer, 2016.
[48] Tobias Nipkow, editor. Functional Data Structures and Algorithms: A Proof Assistant Approach. ACM Books. ACM, 2025.
[49] Tobias Nipkow and Hauke Brinkop. Amortized complexity verified. Journal of Automated Reasoning, 62(3):367–391, 2019.
[50] Yue Niu, Jonathan Sterling, Harrison Grodin, and Robert Harper. A cost-aware logical framework. Proceedings of the ACM on Programming Languages, 6(POPL):9:1–9:31, 2022.
[51] Chris Okasaki. Purely Functional Data Structures. Cambridge University Press, 1998.
[52] Mark H. Overmars. The Design of Dynamic Data Structures, volume 156 of LNCS. Springer, 1983.
[53] François Pottier, Armaël Guéneau, Jacques-Henri Jourdan, and Glen Mével. Thunks and debits in separation logic with time credits. Proceedings of the ACM on Programming Languages, 8(POPL):1482–1508, 2024.
[54] Balázs Tóth and Tobias Nipkow. Real-time double-ended queue verified (proof pearl). In 14th International Conference on Interactive Theorem Proving (ITP 2023), volume 268 of LIPIcs, pages 29:1–29:18. Schloss Dagstuhl – Leibniz-Zentrum für Informatik, 2023.
[55] Athanasios K. Tsakalidis. Maintaining order in a generalized linked list. Acta Informatica, 21(1):101–112, 1984.
[56] Jules Viennot, Arthur Wendling, Armaël Guéneau, and François Pottier. Verified purely functional catenable real-time deques, 2025. arXiv:2505.07681v4.
[57] Dan E. Willard. A density control algorithm for doing insertions and deletions in a sequentially ordered file in a good worst-case time. Information and Computation, 97(2):150–204, 1992.
[58] Bohua Zhan and Maximilian P. L. Haslbeck. Verifying asymptotic time complexity of imperative programs in Isabelle. In Automated Reasoning – IJCAR 2018, volume 10900 of LNCS, pages 532–548, 2018.
A Parameter Choices and Timing Inequalities
This appendix lists the seven inequalities between the parameters of Table 1 that the timing proof of Section 3.7 needs, in simplified form; the exact forms, with all rounding, are proved in Lean for every .
-
A group split finishes before its siblings fill up (Sections 3.3 and 3.7): with .
-
Labels never run out (Section 3.2). If, in the lifetime of a group or chunk, a gap between two labels can be halved at most times and at most members are pushed at one end, its labels need bits (Section B). The previous item bounds and for groups by ; the next two do so for chunks.
-
A chunk that has just split may wait (Section 3.4). When a chunk's split finishes, each half holds at most elements, where is the number of insertions during a chunk split. This must not exceed the queue threshold:
so a chunk enters the queue only by growing past , and the zeroing game starts with its counter at 0.
-
A waiting chunk is served before it reaches (Sections 3.4 and 3.7): with .
-
A drain finishes before its new nodes are too heavy (Sections 3.5 and 3.7): with .
-
Tables and the tree have room (Section 3.5). A table receives a bounded number of entries between two neighbours before its node drains, so a fixed label width suffices: the proof needs , and we take . The height must leave room for every chunk the core can hold: exceeds the number of chunks, so not even a node of height ever drains.
-
A rebuild finishes before the old core fills (Section 3.6). A rebuild starts by the time the core holds elements and copies at steps per update, so it ends while the core holds at most about . The new core's capacity is chosen so that it holds at most a quarter of it when it takes over, and is at most .
B Label Widths
A label range of bits receives labels by the three primitives of Section 3.2: the centre , a push of next to an end member, and the average of two neighbours. Two counts determine and : the most halvings a gap can suffer, , and the most pushes at one end, . If , a gap of size remains nonzero after at most halvings, and if , pushes never leave the range. proofParams takes the smallest such values, and . The proof keeps auxiliary counters of halvings and pushes per group and per chunk, and shows that they never exceed the bounds below.
Element labels. With (the insertions a split lasts) and (the smallest size of a group after its split), a group suffers at most halvings in its life and at most pushes at one end, so .
Group labels. A chunk receives at most insertions in its life, where bounds the insertions a chunk split lasts. Each split start of a group in the chunk halves at most two gaps. Split starts are of two kinds: child splits, of groups born in the chunk, at most because each is charged insertions; and root splits, of groups that arrived with a chunk split or were the chunk's first, at most , where bounds the moves of a chunk split (each move takes one group, or a whole splitting family of at most three). So , pushes at one end are at most , and . The pen-and-paper proof follows each gap's own halving history and needs only about 9L bits; the Lean proof counts all halvings of a chunk together, which is simpler and still .
Concrete widths. Chunk tags take bits.
| N | L | |||
|---|---|---|---|---|
| < | 8 | 28 | 300 | 192 |
| 24 | 73 | 779 | 576 | |
| 27 | 81 | 869 | 640 | |
| 34 | 99 | 1,079 | 768 |
Asymptotically , and .
C Machine Semantics and Proof Architecture
This appendix gives the details omitted from Section 4: the machine language and its interpreter, the simulation theorem, the program logic of the wrapper, where the numerical bound comes from, and the size of the development.
C.1 The machine
Figure 12 shows the language. Words are natural numbers. Memory is a finite set of named arrays, each with a capacity; an access beyond the capacity is a machine error. Each procedure call has its own frame of local variables. A loop for do evaluates its bound once, before the first iteration. There is no while, and there is no recursion: a call carries the callee's body as a subterm, so a procedure that calls itself would have an infinite syntax tree. Every program therefore terminates, and the interpreter
is a total, structurally recursive Lean function (Figure 13): no fuel, no step-indexed relation. The status is ok, fail (a failed guard, caught by the nearest catch, which runs its handler) or err (a machine error, which the proofs exclude). In the machine program the fallback is omitted and a failed guard aborts the operation; the cost invariant shows that no guard fails.
inductive Expr where | lit (n : Nat) | var (x : Reg) | load (a : Arr) (i : Expr) | bin (op : BinOp) (e₁ e₂ : Expr) | un (op : UnOp) (e : Expr) -- BinOp: + - * / % <<>> < ≤ = ∧ ∨ ; UnOp: ¬ msb
inductive Stmt where | skip | assign (x : Reg) (e : Expr) | store (a : Arr) (i e : Expr) | alloc (a : Arr) (n : Expr) -- capacity n, all cells 0, one step | seq (s t : Stmt) | ite (c : Expr) (s t : Stmt) | loop (x : Reg) (n : Expr) (body : Stmt) -- for x < n do body | call (name : String) (params : List Reg) (body : Stmt) (rets : List Reg) (args : List Expr) (dsts : List Reg) -- the callee's body is a subterm | fail | catch (s h : Stmt)
Figure 12: The machine language (OM/Machine/Syntax.lean, abridged).
def exec : Stmt → State → Out | .assign x e, s => match e.eval s with | some v => ⟨(s.bump (e.maxv s)).setLoc x v, 1 + e.cost, .ok⟩ | none => ⟨s, 1 + e.cost, .err⟩ | .loop x n b, s => match n.eval s with | some k => Out.bind ⟨s.bump (n.maxv s), 1 + n.cost, .ok⟩ (runFor (exec b) x 0 k) | none => ⟨s, 1 + n.cost, .err⟩ ...
Figure 13: Two cases of the interpreter. e.cost is the number of nodes of e; runFor charges one step per iteration plus the body. bump records the largest value computed (Section 4.2).
The machine with w-bit words, execW w (OM/Machine/ExecW.lean, 77 lines), repeats exec case by case. The only change is that it evaluates every expression with
and argument lists likewise, so a value that does not fit in a word is a machine error. Every value the program handles is the value of an evaluated expression (locals and memory cells are read only through expressions, and a loop counter stays below the loop's bound), so execW w never holds a value of or more that it computed.
C.2 From Level F to the machine
The intermediate language has assignments, writes to record fields, appends, sequencing, conditionals, bounded loops, calls, fail and catch. Its semantics evalF runs directly on Level F states and charges for each statement what the compiled machine code will cost. An encoding relation Enc p κ s m states that machine state m holds core s in slot p, one array per record field, with capacities κ. The simulation theorem covers every program:
theorem sim (c : Stmt) : ∀ {s : Core} {L : Loc} {m : State}, Enc p κ s m → m.loc = L → Agree p κ (evalF κ c s L) (exec (c.compile p κ) m)
where Agree says that both end with the same status, the machine state holds the new core, the locals agree, and the step counts are equal, except when evalF ends in bug, for which Agree holds trivially. In words: whatever an intermediate-language program does under evalF, unless it ends in bug, its compiled code does on the machine, in the same number of steps; the agreement lemmas show that the procedures never end in bug.
What remains for each procedure involves no memory. Each Level F function is transcribed into the intermediate language, and an agreement lemma shows, by reasoning purely at Level F, that on every successful run of the function the transcription reaches the same state within a stated number of steps. Combined with sim, this gives the compiled procedure's result and its step count. A write the encoding cannot represent makes evalF return an error, so the agreement lemmas also prove that every index stays within its capacity; the capacities themselves are bounded by functions of that are further invariants (the number of top-tree nodes, for instance, is bounded by a potential argument).
The wrapper and the program logic. The wrapper is written directly as machine code. An encoding WEnc om m p places the current core in slot p, the next core in slot 1 - p, a few scalar cells, and the handle maps; the compiled core code of a slot leaves the other slot untouched. Each wrapper operation is proved against its Level F counterpart, under the Level M invariant MInv om Sp: Level F's invariant relating the wrapper state to the specification state Sp, together with the capacity conditions of both cores. These proofs use a weakest-precondition calculus on the machine. Because exec is total and deterministic, a weakest precondition is simply a predicate on its result:
def wp (c : Stmt) (Q : State → Nat → Prop) (s : State) : Prop := (exec c s).Ok Q
where Out.Ok Q holds if the status is ok and Q holds of the final state and the cost. Each construct has a rule; most are equivalences, those for loops and catch are implications; for example, wp (seq c d) Q s unfolds to wp c (fun s' n => wp d (fun s" m => Q s" (n + m)) s') s. The loop rule takes an invariant indexed by the iteration and a cost bound c for one iteration, and concludes a bound of for a loop whose bound expression e evaluates to k. Arrays are named globals, so there is no aliasing between different arrays and no need for separation logic; aliasing within an array is a case split on indices.
C.3 The numerical bound
The constant is large, and it is worth saying where it comes from. One insertion into a core costs at most 94,462,311 steps. Almost all of it is the steps of the top structure, each bounded by 11,806,996 machine steps, the sum of the bounds of a job step (11,630,300, of which 8,977,738 allow for starting a drain, whose loops nest over tables and child lists of up to 160 entries each) and of the start of a chunk split (176,350). An operation performs its own insertion, possibly a mirrored one, and up to rebuild iterations (the iteration that sets the copy cursor spends no budget), each of which may copy an element by an insertion into the next core; the bound adds the insertion and deletion cases rather than taking their maximum. The measured worst case is about steps (Section E). We made no attempt to tighten the constant: the theorem is about the existence of a bound independent of , and the numeral makes that bound concrete.
C.4 Size of the development
Table 3 breaks down the development. Most of it concerns cost: the cost proofs at Level F and the descent to the machine take about 50,000 lines, the correctness proof about 8,400.
Table 3: Size of the Lean development (lines, including comments). The counts document the scale of the development, not the best possible decomposition.
| Part | Lines |
|---|---|
| Specification | 124 |
| Machine model and program logic | 896 |
| Level F (functional implementation) | 1,545 |
| Correctness (Level F part of Theorem A) | 8,421 |
| Cost, lower levels and wrapper (Level F) | 14,503 |
| Cost, top structure (Level F) | 14,807 |
| Intermediate language, compiler, machine program and its proofs (Level M) | 20,787 |
| Stored-value bound (Theorem W, Level F) | 4,227 |
| Computed-value bound and w-bit words (Theorem W, Level M) | 12,293 |
| Rust transpiler and cross-check | 232 |
| Tests | 134 |
| Total | 77,969 |
D Errors and Gaps Found
In the literature. We checked every claim below against the originals: the technical report version of Dietz and Sleator [23], which has the appendix with pseudocode, the ESA version of Bender et al. [8] and the arXiv version of Kopelowitz [42].
-
Dietz and Sleator, appendix. PlaceAfter(x,y) gives y a slot after its sibling x; it tests whether x is the first child of its parent where it must test for the last, so with x last it reads the slot of a sibling that does not exist, and with x first it can compute a slot beyond the next sibling's (their Fig. 3, p. 17). The test reads "if x = first(children(p)) then index(y) ← index(x) + 1". PlaceBefore has the symmetric error. IncrementalSplit(x) moves the first child of x after the last child of pred(x) (their Fig. 5, p. 18), but on the first move pred(x) is the empty node just created by SetUpSplit (their Fig. 4) or, at depth one, by the reservation process (their Fig. 6), which has no last child. Each error is easy to repair once seen; we mention them because the appendix is, as far as we know, the only published pseudocode of a worst-case O(1) algorithm.
-
Bender et al., Lemma 3. Write for their density parameter (their ). After a range of labels is relabeled, each half holds at most elements and overflows above , so the number of insertions guaranteed before the next relabeling at that level is , not as stated: too large by a factor , which is 5 at . A simulation confirms it: with and insertions at the front, the fewest insertions between two relabelings at level 37 were 33,707, below the stated bound (52,438) and above the corrected one (10,488). The amortized bound survives, with cost per level instead of , but the space/time trade-off of their Section 4.2 does not: the corrected bound first falls and then rises with , with its minimum near . Their experiments count actual relabelings and are unaffected. The sentence in question reads: "This requires at least insertions, thus yielding an amortized insertion cost of " (proof of Lemma 3); it also calls a number of insertions a cost. The simulation is experiments/bender-lemma3 in the repository.
-
Gaps. Bender et al. defer their worst-case algorithm to a full paper (Section 1), and leave a case of their file-maintenance algorithm and the proof of its Lemma 6 to the full version (Section 5); as of 2012 that version had not appeared [42]. Kopelowitz's deterministic worst-case construction (his Theorem 4.2) omits several details (Sections 4.1.2–4.1.5: "details are omitted", "details are standard and are thus omitted"), and handles deletions only in a footnote, by marking and rebuilding, as we do; the bounds that hold in expectation in his paper are those of a generalization with subsets.
In our own design. Before the formalization we wrote a pen-and-paper proof. It found one real bug and two gaps, all of which a testing campaign had missed (16 workloads, about 5,300 random-parameter fuzz trials with every invariant checked after every operation, and mutation testing). The campaign was then extended to 23 workloads, about 28,000 further fuzz trials and a checker that measures every quantitative bound of the proof on every core.
-
Rebuild sizing (a cost bug). The prototype sized a new core by the number of live elements. But a rebuild lasts in proportion to the old core's size, tombstones included, and the user can insert throughout. An adversary fills a core to half, deletes every live element during the copy, and then inserts at the front: the next core, sized for no elements, receives every insertion while the copy crawls over the tombstones. At elements its top table overflowed and single operations took 4,115 prototype steps instead of about 100. The fix sizes the new core for everything it can receive during the copy (Section 3.6).
-
Element label width (a gap). The bound on insertions into one gap of a group allowed about of them, but the label width paid for about halvings. Not observable at testable sizes; the width was increased.
-
Families split across chunks (a gap). A chunk split could separate a splitting group from its siblings, so elements flowed into a chunk without insertions there, which breaks the accounting of the zeroing game. The fix moves whole families (Section 3.3); as a side effect, two code paths became unreachable.
Completing the pen-and-paper proof and an independent adversarial review of each of its parts, checked against the prototype, found further false steps, none of them in a final conclusion: a lemma about group labels used an upper bound where it needed a lower one, two claims about the nesting depth of label gaps were false as written (with counterexamples on the real code), the rebuild inequality was off by one or two, and the rebuild needed a condition on that was not stated (with it produced equal tags). The formalization then changed three parameters, not because a paper argument was false: and the group label width because the mechanized arguments are coarser, and so that the waiting-chunks inequality, which holds numerically with about 5% to spare at and 2% at , could be proved for every at once. went from 48 to 64, from 4 to 8, and the group label width from about 9L to about 30L bits (Section B).
E Transpilation and Evaluation
Transpiler and runtime. A Lean program of 186 lines transpiles the machine program to Rust statement for statement: a machine local becomes a Rust variable, an array an index into the runtime's memory, a call a Rust function call, and fail an error value propagated to the nearest catch. Every statement adds the cost that exec charges for it to a counter, so the generated code counts machine steps exactly. The runtime implements words as arbitrary-precision naturals and provides the constant-time zero-filled allocation that the model assumes (Section 6), using lazily zeroed memory and releasing retired cores a few blocks per operation. Neither is verified. Instead, a Lean executable running exec and the generated code run the same operation files and print, for every operation, its status, step count, answer and the bit length of the largest value computed so far. The outputs agree byte for byte on nine operation files (13,920 operations, 7.7 million steps, with many rebuilds). The larger tests compare the generated code with the specification rather than with Lean: it agrees on 3.3 million random operations, 1,100 fuzz traces (4.5 million records) and the 23 stress workloads of the prototype (9.0 million records). The generated code is byte-identical to a fresh transpilation of the current program, and the logs of all these runs are in rust/results.
Benchmarks. We compare with two baselines, written by us in Rust: the amortized algorithm of Bender et al. [8] (groups of at most 64 elements, , 62-bit tags), and an AVL tree that stores the sequence in order. The insertion workloads insert after a random element, after the first element (clustered insertion, the classic adversary for relabeling), at the end and at the front; Table 4 reports the first two, together with workloads that mix deletions and queries. The machine is an Intel Core Ultra 9 285K under Linux 7.0, one performance core per run. Every operation is timed, and each configuration runs alone. Each workload is deterministic and runs three times. We report the mean, the 99.99th percentile of each run (the median over the runs), and the slowest repeatable time: each operation's minimum over the runs, of which we take the largest. Only the operation itself is timed; its arguments are chosen beforehand. The minimum removes pauses that hit an operation in only some runs, and so also recurring costs that move between operations; the per-run percentile keeps them, which is why it can exceed the slowest repeatable time. The means of configurations whose code did not change differ by up to 5% between sessions and seeds, and the slowest repeatable time by up to about 90%. One pass is excluded from the tables: the first warm-query pass of the final session, run directly after the insertions, was 4% (native) to 30% (AVL) slower than the pass we report, which changes the ratios between the implementations. A rerun matched the earlier sessions, so we report the rerun; both passes are kept with the results. The excluded pass suggests that the machine's state after a large run matters, which our procedure did not control for. Every driver gives the three implementations the same bound on the number of insertions: the native implementation reserves its handle table from it (a mapping that grows one page at a time), while its cores are sized from the current number of elements and rebuilt as the sequence grows and shrinks; the AVL tree and the amortized baseline size their arrays from it.
The transpiled program. Both baselines are much faster on average: the program performs about 1,100–1,500 machine steps per insertion on average, computes with arbitrary-precision words and counts every step. Its slowest insertion grows from 0.12–0.14 ms at elements to 0.29–0.37 ms at . The figures are similar on all four workloads up to elements and on the two workloads run at . The amortized baseline's slowest insertion, by contrast, grows linearly under clustered insertion, to about 5 ms at . In machine steps, the slowest insertion took at elements and at , against the proved bound of . It grows because, as the top tree gets taller, more of
Table 4: The native implementation of our algorithm (not verified) against the baselines, in s: mean / 99.99th percentile of a run / slowest repeatable time (Section E, Benchmarks). Insertions: those that grow the sequence from to elements. Churn: rounds of one deletion and one insertion in a sequence of elements, at random positions, or as a queue (insertion at the end, deletion at the front). Teardown: random deletions down to the empty sequence. Warm queries: one query on a random pair after each insertion, at – elements. Cold queries: random pairs at – elements after random insertions, with cold caches, measured and aggregated as in Table 2. Memory: peak resident bytes per element after random insertions / peak over churn and teardown.
| native | AVL | amortized | |||
|---|---|---|---|---|---|
| random insertion | 1.00 / 5.3 / 12.1 | 0.77 / 5.5 / 7.2 | 0.54 / 12.3 / 15.3 | ||
| clustered insertion | 0.085 / 2.9 / 6.3 | 0.030 / 3.2 / 3.6 | 0.022 / 3.4 / 5.050 | ||
| random churn: deletion | 0.29 / 3.7 / 11.0 | 0.71 / 4.0 / 7.0 | 0.19 / 1.2 / 0.39 | ||
| insertion | 0.73 / 4.2 / 5.3 | 0.68 / 5.4 / 6.0 | 0.33 / 9.8 / 12.1 | ||
| queue churn: deletion | 0.051 / 2.5 / 3.9 | 0.019 / 0.47 / 0.83 | 0.011 / 0.15 / 0.30 | ||
| insertion | 0.053 / 2.3 / 5.6 | 0.027 / 3.4 / 3.4 | 0.022 / 3.7 / 557 | ||
| teardown: deletion | 0.39 / 3.1 / 7.8 | 0.73 / 4.2 / 5.9 | 0.19 / 1.3 / 0.76 | ||
| order query, warm | 0.44 / 1.6 / 0.76 | 0.40 / 1.9 / 1.4 | 0.13 / 1.1 / 0.37 | ||
| order query, cold | 0.93 / - / 1.4 | 5.9 / - / 8.4 | 0.50 / - / 0.88 | ||
| memory (bytes per element) | 112 / 250 | 13 / 26 | 21 / 42 | ||
the fixed number of job steps per operation start a drain; that number is bounded, so the maximum is bounded too. An order query always takes 65 machine steps in all, wrapper included; the bound of 80 in order_agree is not tight.
The native implementation. The native implementation (experiments/lean-design in the repository) has the same core, wrapper and parameters, but uses records, fixed-width labels (128-bit element labels and 1,024-bit group labels, wide enough for the proof's widths at every measured size) and no step counting; it is not verified. Level F and the native implementation both reproduce 28 prototype traces exactly (handles, keys, query answers, rebuild counters and key digests): 14.6 million operations, with up to 804 rebuilds in one trace. Across sizes and workloads its mean insertion time is 1.3–2.8 times the AVL tree's, its 99.99th percentile 0.8–1.0 times and its slowest repeatable insertion about 1.3–2.3 times (Table 4). Under churn and teardown its mean times are 0.4–2.7 times the tree's. Its cold order queries are about 6.3 times faster than the tree's after random insertions and 2.2–2.3 times faster after clustered ones, by either estimate of the mean (Table 2). It needs 112 bytes per element, against 13 for the tree and 21 for the amortized structure, partly because retired cores are kept for reuse.
F Earlier Worst-Case Constructions
Dietz and Sleator [22, 23] gave the first worst-case algorithm, and, as far as we know, the only one with published pseudocode (in the appendix of the technical report); the pseudocode treats Willard's algorithm as a black box and omits the time-stamping of its labels. Their structure is a tree of height four whose leaves are the elements; an internal node of height has at most leaves, overfull nodes split incrementally, and the children of the root are positions in Willard's file. Willard's algorithm alone takes 54 pages, as Bender et al. point out [8]. We keep the overall shape of this construction (levels, incremental splitting and the zeroing game) and replace Willard's algorithm.
Bender et al. [8] gave a simpler amortized algorithm, relating list labeling to weight-balanced trees, and announced a simpler worst-case algorithm, obtained by deamortizing it, for a full paper that, as of 2012, had not appeared [42]. Our top tree is weight-balanced too.
Kopelowitz [42] gave a deterministic worst-case construction, with some details omitted, as the basis of a generalization with subsets whose bounds hold in expectation. Its shape is close to ours: chunks of elements, split largest-first, are labeled by a weight-balanced B-tree [4] instead of Willard's algorithm, and each insertion into the tree is spread over the following insertions. His tree relabels in place, in the background, with an extra most significant bit that keeps the order during a rewrite.
In list-labeling terms, both top trees label the chunks from a universe polynomial in . Our tags have bits, so the universe has roughly labels. This leaves room for a separate label field per level of the tree: draining a node changes only two fields in the tag of each chunk below it, and a weight-balanced node of weight gains chunks before it splits again [4], so the rewrite can be paid in constant instalments. Willard's algorithm solves file maintenance, whose universe is linear in the number of items and leaves no such room. The price is width: about bits per tag instead of , still a constant number of words.
Bender et al. [8] had already sketched a simpler worst-case file-maintenance algorithm, leaving a case and a proof to the full version (Section D). Bender et al. [10] later gave a simpler deamortized algorithm for sequential file maintenance, which could take the place of Willard's at the top of Dietz and Sleator's construction. Like Willard's, it moves elements, that is, it relabels in place; our top tree avoids this with immutable tables.
G Related Techniques and Verified Complexity
Order maintenance and list labeling. We build on Dietz and Sleator's incremental splitting and zeroing game [22, 23], on the labeling perspective of Bender et al. [8], and on Kopelowitz's weight-balanced top tree [42]. Order maintenance is closely related to online list labeling, where labels come from a fixed range: with a range linear in , amortized relabelings per insertion are sufficient [41] and, for deterministic algorithms, necessary [13], and randomized algorithms do better [9]. Bender et al. compared amortized order-maintenance structures experimentally [8]; our top tree is a weight-balanced tree in the sense used by Arge and Vitter [4]. As far as we know, no worst-case order-maintenance algorithm has been implemented before, and no order-maintenance algorithm has been verified in a proof assistant.
Deamortization. Our algorithm turns every expensive step into background work spread over later operations: splits move a few members per insertion, top jobs advance a few steps per insertion, and the structure itself is replaced by global rebuilding [52]. The same idea underlies real-time functional data structures, where scheduled lazy evaluation pays for expensive operations in advance [51]. Real-time deques are the closest verified relatives of our structure. Tóth and Nipkow verify the correctness of Chuang and Goldberg's real-time double-ended queue in Isabelle [54], and Viennot et al. that of Kaplan and Tarjan's catenable deques in Rocq [56]. Tóth and Nipkow argue the worst-case bound informally, from the absence of recursion. Viennot et al. make that argument for a separate, hand-written OCaml implementation; their verified Rocq code keeps index computations, so it does not attain the constant bound, and the OCaml code is not formally related to it. The Hood–Melville queue of the Archive of Formal Proofs is likewise verified for correctness only [27]. Madhavan et al. prove concrete worst-case step bounds for Okasaki's real-time queue and deque with an SMT-based verifier, against an instrumented semantics whose soundness is proved on paper [44]; their bounds rest on invariants of the memoization cache and the schedule.
Verified data structures. The correctness of many functional search trees has been verified, largely automatically, in Isabelle/HOL [47], and a textbook develops correctness and running-time proofs for a broad collection of functional data structures [48]. Charguéraud and Pottier verify an imperative union-find structure, with its amortized complexity, in separation logic [17]. Our cost proof must maintain interacting size and scheduling invariants by induction over time (Section 3.7).
Verified complexity. Most mechanized complexity results are amortized or asymptotic, and most attach costs to a program logic for a real language. Time credits in separation logic, introduced by Atkey for amortized resource analysis [5], are used in CFML for amortized [16, 17] and asymptotic [31] bounds, including those of an incremental cycle detection algorithm [29], and time receipts in Iris bound counters by the elapsed time [46]. In Isabelle/HOL, Nipkow and Brinkop verify the amortized complexity of self-adjusting data structures [49], Haslbeck and Nipkow study Hoare logics for time bounds [39], Zhan and Haslbeck verify asymptotic bounds of imperative programs [58], and Haslbeck and Lammich refine running times from abstract algorithms to imperative code [36] and down to LLVM [37]. In type theory, Danielsson analyses lazy functional data structures with a cost monad [19], and calf is a framework for cost-aware programs [50]. Automatic amortized resource analysis infers bounds for OCaml programs in RAML [40], and Liquid Haskell checks resource bounds of programs annotated with explicit ticks [34]. Our setting differs from most of these in two ways. The bound is a concrete worst-case constant, as in Madhavan et al.'s work [44], not an amortized or asymptotic one, and it rests on a timing argument across operations about invariants of the whole structure rather than on the shape of the code. And the cost comes from the interpreter of a deeply embedded language, as in Haslbeck and Nipkow's Hoare logics for time [39], rather than from a cost monad with explicit ticks, between which uncounted work is possible. Time credits also rule out uncounted work, charged at every function call rather than at every instruction. The price of our choice is a compiler from a structured language to the machine. CerCo's cost-annotating compiler [3] compiles C to assembly and must account for the cost of each source fragment; ours maps between two languages designed so that step counts correspond exactly, which makes that correspondence provable. Quantitative CompCert preserves stack-space bounds through a realistic compiler [14], and Carbonneaux et al. infer certified resource bounds for C automatically, by amortized analysis with potentials [15]; our bound needs coupled structural and scheduling invariants beyond a local amortized analysis. Pottier et al. reconstruct Okasaki's debits with time credits [53]; the bounds remain amortized.
Value sizes and machine models. Theorem W answers a question that verified cost models usually settle in other ways. Forster, Kunze and Roth show that the weak call-by-value -calculus, with -steps as time and term size as space, is a reasonable machine model [25], and mechanizations of the Cook–Levin theorem either build on such an invariance result [26] or work with Turing machines directly [7]. They settle the question once for a model; we prove a bound on value sizes for one program on a unit-cost machine. CakeML's space cost semantics is the closest analogue: it proves at the source level that a program's heap and stack fit the machine, so that compiler correctness holds without the out-of-memory exception [28]. Haslbeck and Lammich implement natural numbers by 64-bit words and exclude overflow by size preconditions that propagate to the program's precondition [38]; we instead let the word size grow with the number of operations and prove how large it must be. Deductive verifiers prove the absence of overflow operation by operation, as SPARK does for run-time errors [45]. Clochard et al. avoid such proofs for counters that grow by one per step, which cannot overflow in feasible time [18]; time receipts mechanize the same argument [46], and it is the one that applies to our handles.