The Kubernetes API server has an open bug that Functorial's high precision spec engineering methodology would have prevented. The bug is in APF (API Priority and Fairness), which keeps, say, a buggy client that spams an API Server with a bunch of list requests from overwhelming the cluster.
panic: runtime error: slice bounds out of range [3:2]
...queueset.removeQueueAndUpdateIndexes(...)
...queueset.(*queueSet).removeQueueIfEmptyLocked(...)
The panic happens when a timer fires for a request that still holds seats in a queue the server has already removed. The timer runs in its own goroutine, so nothing recovers the panic, and the whole API server process exits. The component whose job is to keep the API server up under load is what brings it down.
Sai krishna Bodapati reported the bug on November 12, 2026, along with a one-line fix. We wrote the part of the Kubernetes contract that the bug breaks as a specification in Lean, and proved that a model of the fixed code satisfies it in every execution. We then ran the real Go code hundreds of times and checked each recording against the model. Finally, we generated the fix from the specification, and the result was byte-for-byte identical to the fix in the pull request.
We did not prove anything about the Go code directly. The proof is about the model, and the recordings are the evidence that the model is a faithful representation of the code.
Where verification can go wrong
At a NATO conference in Rome in 1969, Edsger Dijkstra said "Testing shows the presence, not the absence of bugs." A test checks one execution, and a typical concurrent program has far more executions than anyone can test. A proof covers all of them. That is formal verification: you state exactly what a system must do, and a machine checks a mathematical argument that it does it.
In 1977, Donald Knuth said "Beware of bugs in the above code; I have only proved it correct, not tried it." A proof is about a mathematical object, and the program running on your servers is a different object, so whether the mathematical object faithfully represents the other object is a separate question.
On June 4, 1996, the first Ariane 5 destroyed itself 37 seconds after launch. Its guidance software converted a 64-bit floating point number to a 16-bit integer, and the number didn't fit. The same code had flown on Ariane 4 for years, where the value was always small enough. The inquiry board found that the software relied on assumptions that held for Ariane 4 and not for Ariane 5.
So a verified system can be wrong in its specification, its proof, or its model:
- The specification: you proved a statement, but not the one you needed. This is what happened to Ariane 5.
- The proof: the argument has a gap. Lean's kernel rules this out, so it is the least of the worries.
- The model: the proof is about the model, not the running code. This is Knuth's warning.
AI models can now write plausible code quickly and find proofs about it when you ask, so the scarce skill is knowing what a system should do and stating it without ambiguity. We call that specification engineering, and Functorial lives out these three principles of specification engineering.
Why the API server needs APF
Every component of a Kubernetes cluster talks to the API server. Kubelets report node health through it, the scheduler and controllers renew their leader leases through it, and operators list and watch resources through it.
Because every client shares the API server, one client can starve the others. A buggy client that relists every object in a loop can take every request slot, and then the API server rejects the lease renewals and heartbeats that keep the cluster healthy.
On December 11, 2024, OpenAI was down for more than four hours. Their post-mortem blames "a new telemetry service deployment that unintentionally overwhelmed the Kubernetes control plane". Every node sent expensive API requests at once, the control plane failed, and DNS-based service discovery failed with it.
Kubernetes' answer is API Priority and Fairness, which has been stable since 1.29 and is on by default. It sorts each request into a priority level with its own concurrency budget, so workload traffic can't starve leader election or node heartbeats. Within a level, APF spreads requests from different clients over queues and serves them fairly, so a noisy client mostly waits behind its own requests.
APF measures concurrency in seats. Most requests take one seat, and a large list takes several.
A write keeps costing the server after it returns, because the server still has to notify every watcher of the changed object. APF accounts for this:
To account for this work, API Priority and Fairness considers every write request to spend some additional time occupying seats after the actual writing is done.
So a request can finish and still hold its seats. Its handler has returned and its client has the response, but its seats stay in use until a timer releases them. The code calls this state lingering.
The BeginConfigChange contract
An administrator can change the number of queues while the server is running. Adding queues is simple, but removing them is not, because a queue may still have requests in it. APF removes queues by attrition: an excess queue stays until it drains, and then APF removes it.
The design proposal says "When an undesired queue becomes empty it is deleted". A comment in the code says removal is "handled by attrition, removing a queue when it goes empty and there are too many". The Go interface that the rest of the API server uses states it as a guarantee:
In any case, reconfiguration does not discard any queue unless and until it is undesired and empty.
The Kubernetes authors wrote this sentence, and it is the specification. It looks obviously true, but you can't check it until you know what "empty" means, and the interface doesn't say.
What does "empty" mean?
A queue holds the requests waiting in it and tracks the ones it dispatched that are still executing. A few lines further down, the same interface defines a related word: "Idle means the QueueSet has zero requests queued and zero executing." The natural reading is that a queue is empty when nothing in it is waiting or executing.
A lingering request is neither waiting nor executing, and it is not in any of the queue's lists. It shows up only in the queue's seatsInUse counter, which still includes its seats, and as a timer that holds a pointer back to the queue so it can return those seats later.
Whether a queue with a lingering request in it is empty is a decision someone has to make, and that decision determines what the theorem says.
How the bug happens
The function that removes an unwanted queue checks that nothing is waiting and nothing is executing, and it never checks the seats. If the last executing request in a queue finishes while another request in that queue is lingering, the function removes the queue even though the lingering request still holds seats in it.
Each queue also stores its own position in the list of queues, and nothing updates that position after the function removes the queue. When the lingering request's timer fires, it returns its seats and calls the same function again. The function finds the queue empty and removes the entry at the stale position, which can be past the end of the list.
Sai krishna Bodapati reported this as Kubernetes issue #144077 and opened pull request #144078, which adds the missing check:
if len(qs.queues) > qs.qCfg.DesiredNumQueues &&
r.queue.requestsWaiting.Length() == 0 &&
r.queue.requestsExecuting.Len() == 0 &&
r.queue.seatsInUse == 0 {
As of this writing, the issue is waiting for triage and nobody has merged the fix. We pinned the commit the report names, dbe731cf4b0, and ran the reporter's regression test. It fails with the message from the report:
queueset_test.go:1678: got 2 queues while the lingering request still holds seats, want 3
--- FAIL: TestRemoveQueueOnlyWhenNoSeatsInUse (0.00s)
With the fix, the test passes. Without the fix, if the scenario runs a little longer, you get the panic at the top of this post.
The report also describes a second outcome. If the stale position still falls inside the list, nothing panics, and the function removes a different queue that is still in use. We reproduced that as well. When the queue it removed by mistake had a request waiting in it, the server never served that request, and the next dispatch crashed on a nil pointer. We saw this in a test harness with a fake clock, not on a real server. Every command and its output is in go/RESULTS.md.
The regression test shows that the fix works for one sequence of events. We wanted to know whether, with the fix, the sentence holds for every order of arrivals, finishes, timers and reconfigurations, and that requires a proof.
Making the word "empty" precise
We chose the strict reading:
A queue is empty when no request assigned to it is waiting, executing, or lingering.
The documentation supports it. A lingering request still occupies seats, its queue counts those seats, and the request will come back to that queue to release them, so the queue isn't safe to remove.
In Lean, the reading becomes two short definitions:
def Phase.live : Phase → Bool
| .waiting | .executing | .lingering => true
| _ => false
/-- `safe_retirement`: the system never discarded a queue with a live
request in it, and every live request's queue is still there. -/
def SafeRetirement (s : St Q R) : Prop :=
s.discarded = false ∧ ∀ r, (s.phase r).live → s.rq r ∈ s.slice
Removing .lingering from the first definition gives the naive reading and a different theorem. No tool will flag that difference, so a person has to notice it.
We proved three more properties alongside it, because the proof of the first depends on them and the system needs them anyway:
- Conservation: each queue's seat counter equals the seats that the requests executing or lingering in it hold, and it never goes negative.
- Release once: no request gives its seats back twice.
- Index integrity: each queue's stored position is its actual position, and nothing indexes past the end of the list, so the panic can't happen.
The model
A theorem prover can't take 1,029 lines of concurrent Go and tell you whether a sentence holds for them. Instead you build a small mathematical object that behaves like the code in the ways you care about, and prove things about that object. That object is the model, and it is where Knuth's warning applies.
Our model has five actions, one for each operation in queueset.go that changes a queue. In the real code each of these runs while holding the queue set's lock, which is why the model can treat each one as a single step.
| Action | Go function | What it does |
|---|---|---|
reconfigure | setConfiguration | Sets the desired number of queues. Adds queues if needed. Never removes one. |
arrive | shuffleShardAndRejectOrEnqueueLocked | A request joins a queue and waits. |
dispatch | dispatchLocked | A waiting request starts executing and takes its seats. |
finish | finishRequestLocked | The handler is done. The request lingers, or gives its seats back now. |
timerFire | the timer callback | A lingering request gives its seats back. |
Right after a request gives its seats back, the code checks whether to remove its queue. The model comes in an affected version and a corrected version, which differ exactly where the Go code and the fix differ:
def removeGuard (rs : List R) (corrected : Bool) (s : St Q R) (q : Q) : Bool :=
decide (s.desired < s.slice.length) &&
rs.all (fun x => !(s.rq x == q && s.phase x == .waiting)) &&
rs.all (fun x => !(s.rq x == q && s.phase x == .executing)) &&
(!corrected || s.seats q == 0)
Two choices in the model matter. First, a queue is not its position. The model treats a queue as an object that stores its own position, and that stored position can go stale. The bug confuses the two, so a model that identified them could not express it.
Second, the model allows more than the code does. The real code carefully computes which queue a request joins, which request it dispatches next, and whether there is room, and the model allows any choice. Every schedule the real code can produce is in the model, along with many it never would, so a safety property that holds for all of them holds for the real ones. The cost is that the model can't say anything about fairness.
We wrote the model twice: once in Veil, a Lean framework for state machines that includes a model checker and an automated prover, and once in plain Lean, which we call the mirror, where Lean's kernel checks every proof without an external solver.
Results
A model checker explores every state that a small instance of the model can reach. On the affected model with two queues and two requests, Veil's model checker found a counterexample seven actions long: two requests arrive in one queue and start, one finishes and lingers, the desired number of queues drops, the other finishes, and its finish step removes the queue while the lingering request still holds its seats. We gave the model checker the specification and not the bug report, and it found the reported bug.
We also proved in Lean that the exact sequence from the issue ends in a panic in the affected model.
The main result is about the corrected model:
theorem ApfQueueSet.Mirror.corrected_safe :
∀ {Q R : Type} [DecidableEq Q] [DecidableEq R] (rs : List R),
(∀ (r : R), r ∈ rs) → rs.Nodup →
∀ {s : St Q R}, Reachable rs true s →
Conservation rs s ∧ ReleaseOnce s ∧ SafeRetirement s ∧ IndexIntegrity s
In words: for any queues and any finite set of requests, starting from a fresh queue set and applying the five actions in any order and any number of times, all four properties hold in every reachable state. There is no bound on the number of queues, the size of a request, or the length of a run. Lean's kernel checked the proof using only the three standard axioms that nearly all Lean mathematics uses, and there is no sorry (Lean's placeholder for an unproved step) anywhere.
AI agents wrote the proofs. Nobody has to review them line by line, because the kernel checked them. The definitions are different: a person has to read them, which is why we kept them short.
In the Veil model, all 72 verification conditions pass. The cvc5 solver discharges 69 of them, and Lean reconstructs a proof from each answer. We proved the other 3 by hand, where the solver timed out. Veil's model checker also explored the corrected model exhaustively up to 4 queues and 4 requests, 5,753,283 states in the largest run, and found no violation. Conservation is a statement about a sum over requests, which the solver can't express, so the Veil proof assumes one consequence of conservation and the mirror proves conservation in full. We checked that the two models describe the same system by reading them side by side. Lean did not check that.
Testing the model against the code
A proof that the model and the Go code agree on every execution is a refinement proof, and we didn't write one. We tested the agreement instead.
We added tracing to the real queueset.go. At the end of each of the five operations, while still holding the lock, it records what happened and a snapshot of every queue. The patch changes no behavior, and the package's own Kubernetes tests still pass with it. We then ran the real code through four hand-written scenarios and 300 random ones, with random arrivals, random request sizes, queue counts going up and down, and the clock advancing by random amounts.
A small Lean program, tracecheck, replays each recording. For each step it checks that the action was possible in the model at that point, that the model's predicted state matches the snapshot queue by queue and seat by seat, and that the four properties hold. It uses the same step function that the theorem is about.
| Recordings of | Files | Verdict |
|---|---|---|
| the corrected Go code | 304 | 304 conform |
| the affected Go code | 304 | 80 rejected, 224 conform |
| conforming traces that we deliberately corrupted | 30 | 30 rejected |
The 80 recordings that the checker rejected are exactly the runs in which the Go harness, using its own separate bookkeeping, observed the bug. In the other 224 runs the affected code happened not to hit it. The Go harness and the Lean checker agreed on all 304.
In every rejected run, the checker rejects the trace at the step that removes the queue with a lingering request still in it, before any crash. In 59 of those 80 runs the program ends normally and shows no error even though it has broken the guarantee, so a test that waits for a panic would have passed them.
The last row tests the checker itself. We corrupted conforming recordings in five ways (dropping a timer, firing one twice, deleting a busy queue, miscounting a seat, and swapping two indexes), and the checker rejected all of them.
Generating the fix from the specification
So far a person wrote the fix and we checked it. Next I wanted to see whether we could derive the fix from the specification.
The first step is to make the disputed word into data. A reading of "empty" is the list of request phases that make a queue non-empty. The two candidate readings differ by one element:
def naiveReading : Reading := [.waiting, .executing]
def strictReading : Reading := [.waiting, .executing, .lingering]
def EmptyOf (ps : Reading) (rs : List R) (s : St Q R) (q : Q) : Prop :=
∀ r ∈ rs, s.rq r = q → s.phase r ∉ ps
Next we write down what the Go code can observe. The queue struct has a list of waiting requests, a set of executing requests, and a seat counter, but no list of lingering requests. A lingering request is visible only through the seats it holds. That is the root of the bug, and in Lean it is one line of a table:
def detector : Phase → Option Obs
| .waiting => some .noWaiting -- r.queue.requestsWaiting.Length() == 0
| .executing => some .noExecuting -- r.queue.requestsExecuting.Len() == 0
| .lingering => some .noSeatsInUse -- r.queue.seatsInUse == 0
| .fresh | .released => none
def derive (ps : Reading) : Guard := .excess :: ps.filterMap detector
derive turns a reading into a guard: first the check that the queue is undesired, then one test per phase. A forty-line printer turns the guard into Go. The code is in Synth.lean, and docs/spec-to-go.md has the details.
We proved that the guard derive produces from the strict reading is the corrected model's guard, so the main theorem covers it. We then proved that in every reachable state the guard is true exactly when the queue is undesired and empty:
theorem derived_strict_iff_spec (h : Reachable rs true s) (q : Q) :
Guard.eval rs s q (derive strictReading) = true ↔ MayDiscard strictReading rs s q
Read left to right, this says the guard never removes a queue that is in use. Read right to left, it says the guard never keeps a queue that the specification allows it to remove. The fix is safe, and it is no stricter than the contract requires.
Running the generator gives:
$ make gen-fix
naive reading: regenerates the upstream function byte for byte
strict reading: +2 -1 lines in queueset.go
generated queueset.go is byte-identical to queueset.go with PR #144078 applied
The strict reading produces a file byte-identical to the one in PR #144078, and the naive reading reproduces the buggy upstream function byte for byte. The bug is the difference between the two lists.
The generated code passes the PR's regression test, all 304 scenarios run cleanly and replay through the model, and Kubernetes' flow-control tests pass.
This derives one condition in one function, and it is not a Lean-to-Go compiler. We trust the four-line table that says which Go expression reads which quantity, and the generator copies the rest of the function from upstream. The output is the same two lines a careful person already wrote. What the derivation adds is a proof that those two lines are right.
What this would have caught
This method doesn't stop anyone from writing the bug, but it catches the bug at three points.
Someone has to write the meaning down. In the Go code, the meaning of "empty" exists only as the shape of an if statement, and nobody decided whether lingering requests count. Here the decision is a named list, and a reviewer who sees [.waiting, .executing] next to a type with a .lingering case will ask the right question.
The wrong meaning fails before the code ships. If someone writes the short list anyway, the model checker returns the seven-step counterexample on a laptop. It is the same failure as the issue, and the checker finds it before any cluster runs the code.
Nobody can ignore a new state. detector is a function on Phase, and Lean rejects a function that misses a case. If someone adds a sixth phase, the file won't compile until they say how the Go code observes it, and the proofs about emptiness fail until they handle the new case.
That last point covers a whole class of bugs. A data structure gains a new state, and every check that someone wrote against the old states still compiles but now means something slightly different. "Empty", "idle", "done" and "safe to delete" are all words of this kind.
The method also reaches related bugs, with different strength for each:
- The symptoms: the panic, the removal of the wrong queue, the silent early removal and the nil pointer look like separate bugs, but in the model they are consequences of one broken property, and the proof rules them all out. A fix that only targets the panic, such as a bounds check, would have hidden the most visible symptom and left the guarantee broken.
- Neighboring bugs: the same theorem covers seats released twice, seats leaking, and positions going stale. We know of no case of these in Kubernetes today, but in the model each would now fail the build.
- Other copies of the check: someone wrote the same two-part test by hand in
advanceEpoch,getVirtualTimeRatioLockedandenqueueToBoundLocked, andisIdleLockedapplies it to the whole queue set. We haven't shown that any of these is a bug, and we didn't model them. For virtual-time bookkeeping the two-part meaning may be the right one, but in each place someone chose a meaning of "empty" without saying which or why.
The method would not catch everything. If we had believed the naive reading was the contract, every proof would have gone through for it. If the four-line table were wrong about what a Go field holds, the proofs would be about a different program. The proofs don't cover anything outside the five actions we modeled. The method moves the risk to the points where a person decides what a word means, but it still needs that person.
How the principles apply
1. Make the claim inspectable
A checked proof establishes a precise statement under stated assumptions.
A headline saying "We formally verified Kubernetes flow control" would be false. The claim is the theorem above, and you can check it without trusting us:
- The definitions: the four properties are about twenty lines of Lean in
Mirror.lean. If you read those, you know what we proved without reading the proofs. - The status:
proof-status.mdlists every theorem and whether the kernel, a solver, or a bounded model checker established it.axioms.txthas Lean's#print axiomsoutput for each one. - The run:
make verifyrebuilds everything, andmake check-tracesreplays every recording. The repository pins the Kubernetes commit and includes the patches.
2. State the conditions and the scope
A guarantee applies only when its assumptions hold and its model fits the situation. Make its conditions and scope explicit.
Ariane 5's software was correct for Ariane 4. Our theorem holds under these conditions:
- There is one queue set in one API server.
- No client cancels a request, and no request times out, while it waits. The real code has a cancellation path, and we didn't model it.
- The caller finishes every request that starts exactly once. The interface requires this of callers, and we assume they comply.
- Each timer fires at most once.
- The desired number of queues is always positive, which excludes the exempt and no-queue modes.
Outside these conditions the theorem says nothing. It also says nothing about fairness, starvation, or whether requests ever return their seats. A system that freezes forever satisfies every property we proved.
3. Own the meaning
You can delegate finding a proof, but not understanding what is to be proved.
Suppose we had used the naive reading of "empty", where nothing is waiting and nothing is executing. That is what the code does, and it matches the definition of "idle" a few lines away, so it is a reasonable choice.
We checked what it would have caught. Take the sequence from the bug report and stop right after the server removes the queue. Under the naive reading nothing has gone wrong yet, because the queue had nothing waiting or executing, and Lean confirms this (issue_144077_first_bad_step_is_naive_ok). The naive reading only fails later, at some other queue, as a symptom. We also proved (clean_until_strict_discard) that in the affected model, no panic, stale position, or violation of either reading can occur until the server removes a queue with a waiting, executing or lingering request in it. The strict reading flags the cause at the step where it happens, and the naive reading flags a consequence later, and only sometimes.
An AI will find a proof or a counterexample if you ask, but it can't tell you what you meant by "empty". Someone has to read the documentation, notice the request that has finished but still holds seats, and decide. That decision is small, and it is the most valuable thing in the repository.
What we proved, checked, and trust
| What | How we know | |
|---|---|---|
| proved | The corrected model satisfies all four properties in every reachable state. | Lean's kernel |
| proved | The affected model reaches a panic by the reported sequence. | Lean's kernel |
| proved | The derived guard is true exactly when a queue is undesired and empty. | Lean's kernel |
| checked | The Veil model passes 72 of 72 conditions, given one assumption. | cvc5, and Lean rebuilds the proofs |
| checked | No violation in the corrected model at small sizes. | exhaustive model checking |
| observed | The reported failure occurs on the pinned Kubernetes commit, and not with the fix. | running the Go code |
| observed | 608 recordings of the real code match the model's verdict. | tracecheck |
| trusted | The model abstracts the Go code faithfully. | we read both. The recordings are evidence, not proof. |
| trusted | The Veil model and the plain Lean mirror are the same system. | we read both |
| trusted | The table from model observations to Go expressions. | four lines, which we read by hand |
| trusted | The tracing reports the truth. Lean, Veil and cvc5 are sound. | |
| not shown | That every execution of the Go code satisfies the properties. | would need a refinement proof |
| not shown | Fairness. Liveness. Cancellation. A real server on a real clock. | out of scope |
Before this work, the evidence that the fix was right was one regression test covering one sequence. Now there is a proof covering every sequence in a model, and 608 recordings of the real code that agree with the model, including every run where the bug occurred. That is not certainty about the Go code, and any verification claim that says otherwise should come with a ledger like this one.
Other work comes closer to proving the code itself. Anvil builds Kubernetes controllers and verifies their implementations, and Kivi model-checks how the scheduler and controllers behave across a cluster. Neither targets API Priority and Fairness. As of November 25, 2026, we found no public formal model of APF's queue removal and seat accounting. That is the result of a search on one date, not a claim that none exists.
Where this is going
AI agents wrote the proofs, and Lean's kernel checked them. Agents also wrote the model from the two-page contract, along with the Go harness, the tracing patch, the 300 random runs and the generator. The part a person had to do was the sentence that defines "empty".
We built Functorial around that division of work. Our goal is to get the spec right, and sleep at night: engineers and applied mathematicians spend their attention on stating what must be true, machines find the proofs, and a checker has the last word.
We are not there yet. We proved a model, and faithfulness of the link from the model to the code is not proven, but we have gathered enough evidence to believe it. The results speak for themselves.
It took a couple of days to turn a one-sentence promise in a comment in k8s into a checked theorem that we tested against the real code. The proof was not the expensive part. Knowing what to ask was.
If you want to learn to write specifications like this, Functorial Academy teaches Lean from the first definition, and Specification Engineering ends with writing specifications in Lean about real programs. If you have a system with a sentence like this one in it, tell us about it.
You can rerun everything in this post from the GitHub repository: the model, the proofs, the generator, the Kubernetes patches, the harness and every recording.