Suppose tasks A and B enter a work queue in order. If A is popped and C is pushed next, the next item to come out must be B, still waiting in line, rather than C. Whenever a pop command arrives while the queue is empty, we should record that moment in the log as well, because logging only successful pops would lose track of when the queue was empty during replay.
FIFO stands for first in, first out: the item that joined the line first leaves it first. Here Push joins the back of the line and Pop takes from the front. The order in which the rear list stores items can differ from the order callers observe.
A reference specification is easy to write with a single list: append new items at the back and pop from the front. Appending to the end of a singly linked list, however, has to walk past every item already waiting.
Here we replace the internal representation with two lists, prove in Rocq that replaying any sequence of commands produces the exact same results as the single-list reference model, and compile the extracted code into an OCaml executable.
1. How Two Lists Represent a Single Waiting Line
The front list holds the items ready to be popped in order, while newly pushed items are prepended onto the head of the rear list. Reversing the rear list and appending it after the front list therefore reconstructs the entire queue in order. In the formula below, is the front list, is the rear list, and is list concatenation.1
To see why the second line of the formula, , holds. Suppose the front list has remaining and the rear list is empty when we push and then . Because each new item is prepended to the head of the rear list, the most recently pushed item sits at the head, giving .
Reversing the rear list () and concatenating it () after the front list therefore reconstructs the exact queue order ! In the code below, view is this observation function , and list_push and list_pop define the single-list reference model.
Create a working directory where Rocq 9.2, GNU Make, and ocamlc are available. Append the next three code blocks in order into a single file named QueueModel.v; the first block defines the single-list reference model and the tail-recursive helper that reverses the rear list one item at a time.
Arguments make_queue {A} _ _. sets up how to call the constructor. {A} is the element type Rocq infers from the lists; the two _ slots are arguments you supply explicitly, one for the front list and one for the rear. That's why calls to make_queue can go straight to the two lists.
From Stdlib Require Import List.
Import ListNotations.
Record queue (A : Type) := make_queue {
front : list A;
rear : list A
}.
Arguments make_queue {A} _ _.
Arguments front {A} _.
Arguments rear {A} _.
Definition empty {A : Type} : queue A := make_queue [] [].
Definition view {A} (q : queue A) : list A :=
front q ++ rev (rear q).
Definition list_push {A} (xs : list A) (x : A) : list A :=
xs ++ [x].
Definition list_pop {A} (xs : list A) : option A * list A :=
match xs with
| [] => (None, [])
| x :: rest => (Some x, rest)
end.
Fixpoint reverse_into {A} (xs acc : list A) : list A :=
match xs with
| [] => acc
| x :: rest => reverse_into rest (x :: acc)
end.reverse_into xs acc peels the head off xs and prepends it onto the accumulator acc. Because moving the first item changes the accumulator list for the recursive call, we use revert acc before inducting so our induction hypothesis holds for any accumulator.
acc is the accumulator, the list we've reversed so far. The call reverse_into rest (x :: acc) passes that work along and returns the recursive result directly. A call in that position is called tail recursion.
We reverse the rear list only when the front list is empty. After popping one item from the reversed list, the remaining elements become the new front list and the rear list is cleared to []. When both lists are empty, queue_pop returns (None, empty), leaving a clean state for the next command.2
The semicolons in induction xs ...; intros acc; simpl. apply the next tactic to every goal produced by the preceding one. Here both list cases get an acc argument and both goals are simplified before the bullets finish each case.
Lemma reverse_into_correct {A} (xs acc : list A) :
reverse_into xs acc = rev xs ++ acc.
Proof.
revert acc.
induction xs as [| x rest IH]; intros acc; simpl.
- reflexivity.
- rewrite IH. rewrite <- app_assoc. reflexivity.
Qed.
Lemma reverse_empty {A} (xs : list A) : reverse_into xs [] = rev xs.
Proof. rewrite reverse_into_correct, app_nil_r. reflexivity. Qed.
Definition queue_push {A} (q : queue A) (x : A) : queue A :=
make_queue (front q) (x :: rear q).
Definition queue_pop {A} (q : queue A) : option A * queue A :=
match front q with
| x :: rest => (Some x, make_queue rest (rear q))
| [] =>
match reverse_into (rear q) [] with
| [] => (None, empty)
| x :: rest => (Some x, make_queue rest [])
end
end.
Definition materialize {A} (q : queue A) : list A :=
front q ++ reverse_into (rear q) [].Finally, we prove that pushing and popping on our two-list queue match the single-list reference model under view. In push_view, an item prepended to the head of the rear list appears at the very end of the observed queue, while pop_view checks both the popped value and the observed order of the next state at once, ruling out any buggy implementation that returns the right item but scrambles the remaining queue.
In option A * queue A, * builds the type of a pair. The notation let '(x, next) := queue_pop q in ... takes that pair apart so the popped result has the name x and the remaining queue has the name next.
Lemma materialize_correct {A} (q : queue A) : materialize q = view q.
Proof. unfold materialize, view. now rewrite reverse_empty. Qed.
Lemma push_view {A} (q : queue A) (x : A) :
view (queue_push q x) = list_push (view q) x.
Proof.
destruct q as [f r].
cbn [view queue_push list_push front rear rev].
apply app_assoc.
Qed.
Lemma pop_view {A} (q : queue A) :
let '(x, next) := queue_pop q in
(x, view next) = list_pop (view q).
Proof.
destruct q as [[| x rest] r].
- cbn [queue_pop view front rear app].
rewrite reverse_empty.
destruct (rev r); cbn [empty view front rear list_pop app rev];
rewrite ?app_nil_r; reflexivity.
- reflexivity.
Qed.2. If One Step Agrees, Does the Entire Command Sequence Agree?
Writing two separate replay loops would risk introducing discrepancies in how commands are traversed between the implementation and the reference model. Instead, we define replay once, parameterized over a state type S and its push and pop operations: passing a single list yields the reference specification, and passing our two-list queue yields the executable implementation.
Every Pop contributes either Some value or None to the event log. Save the code below as the start of a new file named QueueReplay.v. This file imports QueueModel. Save it for now; in Section 4, make will use _CoqProject to compile the files in dependency order.
From Stdlib Require Import List.
From VerifiedQueue Require Import QueueModel.
Import ListNotations.
Inductive command (A : Type) : Type :=
| Push (x : A)
| Pop.
Arguments Push {A} _.
Arguments Pop {A}.
Fixpoint replay {A S : Type}
(push : S -> A -> S) (pop : S -> option A * S)
(commands : list (command A)) (state : S) :
list (option A) * S :=
match commands with
| [] => ([], state)
| Push x :: rest => replay push pop rest (push state x)
| Pop :: rest =>
let '(item, next) := pop state in
let '(events, final) := replay push pop rest next in
(item :: events, final)
end.Write for the command list, and suppose replaying on a concrete queue produces the event log and final queue . Replaying the same commands on the single-list model starting from must satisfy:
When the first command is Push, we apply push_agrees, which says both representations observe the next state as the same list. When the first command is Pop, we use pop_agrees to align the popped value and the next state first, and then apply the induction hypothesis to the remaining commands, having generalized the starting state at the beginning of the proof with revert start.
Inside the proof, cbn [fn...] unfolds only the listed functions cleanly, and destruct (pop start) as [item next] eqn:E splits the pair returned by pop start into (item, next) while recording the equation E : pop start = (item, next) in the context.
Next, pose proof (...) as name brings an existing lemma into the context as a new hypothesis, and specialize (IH next) instantiates the induction hypothesis IH at the next state next. Then rewrite <- IH aligns the remaining replay results on both sides, and reflexivity closes the goal. Proving that a concrete internal representation produces the exact same observable behavior as a reference specification is called refinement.3
Append the code below to QueueReplay.v. The exported entry point replay_from_empty also materializes the final queue into an ordinary list so callers can read it directly, and Print Assumptions replay_from_empty_correct. at the bottom verifies that the theorem depends on no extra axioms (Axiom) or unfinished proofs (Admitted), printing Closed under the global context.
Inside Section Refinement, Context introduces the state type and its operations, and Hypothesis states the equalities those operations are assumed to satisfy. At End Refinement., the types, operations, and assumptions used by replay_refines become parameters of the theorem. That's why the call to @replay_refines supplies the actual queue operations along with the earlier proofs push_view and pop_view.
In the last proof, in H |- * tells a tactic to work on both hypothesis H and the current goal. destruct ... in H |- * exposes the pair returned by replay in both places, and cbn in H |- * reduces the expressions using that pair so you can use H to finish.
Section Refinement.
Context {A S : Type}
(push : S -> A -> S) (pop : S -> option A * S)
(observe : S -> list A).
Hypothesis push_agrees :
forall s x, observe (push s x) = list_push (observe s) x.
Hypothesis pop_agrees :
forall s, let '(item, next) := pop s in
(item, observe next) = list_pop (observe s).
Lemma replay_refines (commands : list (command A)) (start : S) :
let '(events, final) := replay push pop commands start in
(events, observe final) =
replay list_push list_pop commands (observe start).
Proof.
revert start.
induction commands as [| cmd rest IH]; intros start.
- reflexivity.
- destruct cmd as [x |].
+ cbn [replay]. rewrite <- push_agrees. apply IH.
+ cbn [replay].
destruct (pop start) as [item next] eqn:E.
pose proof (pop_agrees start) as step.
rewrite E in step. cbn in step.
rewrite <- step.
specialize (IH next).
destruct (replay push pop rest next) as [events final].
cbn in IH. rewrite <- IH. reflexivity.
Qed.
End Refinement.
Definition replay_from_empty {A} (commands : list (command A)) :
list (option A) * list A :=
let '(events, final) := replay queue_push queue_pop commands empty in
(events, materialize final).
Theorem replay_from_empty_correct {A} (commands : list (command A)) :
replay_from_empty commands = replay list_push list_pop commands [].
Proof.
unfold replay_from_empty.
pose proof (@replay_refines A (queue A) queue_push queue_pop view
push_view pop_view commands empty) as H.
destruct (replay queue_push queue_pop commands empty) as [events final] in H |- *.
cbn in H |- *.
rewrite materialize_correct. exact H.
Qed.
Example sample :
replay_from_empty [Push 10; Push 20; Pop; Push 30; Pop; Pop; Pop; Push 40]
= ([Some 10; Some 20; Some 30; None], [40]).
Proof. reflexivity. Qed.
Print Assumptions replay_from_empty_correct.3. Why We Reverse Only When the Front List Is Empty
Consider an execution that starts from an empty queue and threads the latest state into each subsequent command. Charge a base cost of 1 for each queue operation plus 1 for each element reversed. If we treat the rear list length as stored potential (prepaid reversal work), the amortized cost of a single operation is:
Pushing an item adds one element to the rear list for an amortized cost of , and popping directly from a non-empty front list costs . When the front list is empty and we reverse items from the rear list to pop, the actual cost is , but moving the reversed items to the front leaves the new rear list empty so the potential drops from to , bringing the amortized cost back to .
Even if an occasional pop does a batch reversal, across the entire command sequence starting from an empty queue each element is moved from rear to front at most once.4
That formula counts the cost of operating the queue itself. When the batch finishes and we want to display all remaining items on screen, materialize joins the two remaining lists once, taking time proportional to the number of items left waiting.
4. Running the Verified Queue in OCaml
Create a _CoqProject file in the same directory with the three lines below. The flag -Q . VerifiedQueue binds the current directory to the logical module prefix VerifiedQueue, allowing QueueReplay.v to import QueueModel through that logical name.5
-Q . VerifiedQueue
QueueModel.v
QueueReplay.vNext is Extract.v. We extract replay_from_empty and import ExtrOcamlBasic so Rocq’s list, option, and pairs map directly to OCaml’s built-in types. Because our command type is polymorphic, OCaml can pass task IDs as native strings without extracting Rocq’s own number or string representations.67
From Corelib Require Import ExtrOcamlBasic.
From VerifiedQueue Require Import QueueReplay.
Extraction Language OCaml.
Set Extraction Output Directory ".".
Extraction "verified_queue.ml" replay_from_empty.driver.ml parses command-line tokens into Push and Pop commands and prints the pair returned by the extracted replay_from_empty function, without re-implementing any queue logic in OCaml:
When the program starts, OCaml evaluates the let () = block at the bottom of this file. The first entry of Sys.argv is the program name. Array.to_list Sys.argv |> List.tl turns the array into a list and drops that first entry, so parse_all receives only user arguments such as push:A and pop.
open Verified_queue
let parse token =
let prefix = "push:" in
let n = String.length prefix in
if token = "pop" then Ok Pop
else if String.length token > n && String.sub token 0 n = prefix then
Ok (Push (String.sub token n (String.length token - n)))
else Error ("expected push:ID or pop: " ^ token)
let rec parse_all = function
| [] -> Ok []
| token :: rest ->
match parse token with
| Error message -> Error message
| Ok command -> Result.map (fun tail -> command :: tail) (parse_all rest)
let quote id = Printf.sprintf "%S" id
let show_event = function None -> "None" | Some x -> "Some " ^ quote x
let show_list show xs = "[" ^ String.concat "; " (List.map show xs) ^ "]"
let () =
match parse_all (Array.to_list Sys.argv |> List.tl) with
| Error message -> prerr_endline message; exit 2
| Ok commands ->
let events, waiting = replay_from_empty commands in
Printf.printf "popped = %s\nwaiting = %s\n"
(show_list show_event events) (show_list quote waiting)Run the commands below to check the proofs in both Rocq modules, extract the OCaml code, and compile the executable:
ocamlc compiles the OCaml sources into a runnable program. Below, -o queue_demo sets its file name, and the interface and implementation from extraction go before driver.ml, which calls them. ./queue_demo runs that file from the current directory.
rocq makefile -f _CoqProject -o Makefile
make
rocq compile -Q . VerifiedQueue Extract.v
ocamlc -o queue_demo verified_queue.mli verified_queue.ml driver.ml
./queue_demo push:A push:B pop push:C pop pop pop push:DOutput:
popped = [Some "A"; Some "B"; Some "C"; None]
waiting = ["D"]Walking through the eight commands push:A push:B pop push:C pop pop pop push:D step by step traces how both output lines arise. (1) First, push:A and push:B stack ["B"; "A"] onto the rear list. (2) When the first pop arrives, the front list is empty, so the rear list is reversed into the front list as ["A"; "B"], popping Some "A" and leaving ["B"] in the front list.
(3) Next, push:C places ["C"] into the rear list, and (4) the second pop immediately pops Some "B" from the front list without any reversal (which is why B comes out before C!).
(5) On the third pop, the front list is now empty again, so ["C"] is moved to the front and popped as Some "C". (6) On the fourth pop, both lists are empty, recording None in the log. (7) Finally, push:D pushes "D" and the program finishes, printing popped = [Some "A"; Some "B"; Some "C"; None] on the first line and waiting = ["D"] on the second.
Footnotes
- Chris Okasaki, Purely Functional Data Structures, PhD thesis (CMU-CS-96-177, 1996), §3.1.1. Explains representing a FIFO queue with an in-order front list and a reversed rear list and amortizing the reversal cost across operations. ↩
- The Rocq Prover Reference Manual 9.2. Reasoning with Inductive Types: Induction. Explains generalizing accumulator parameters that change across recursive calls before applying induction. ↩
- The Rocq Prover Reference Manual 9.2. Inductive Types: The match … with … end Construction · Reasoning with Inductive Types: Induction. Covers branching by constructor and applying the induction hypothesis to the remaining command sequence. ↩
- Chris Okasaki, Purely Functional Data Structures, §3.1 and §3.1.1. Presents the physicist’s potential method and the two-list queue analysis using rear-list length as potential. ↩
- The Rocq Prover Reference Manual 9.2. Building Rocq Projects: Logical Paths and the Load Path. Explains binding a physical directory to a logical module prefix with
-Q. ↩ - Rocq Core Library 9.2. Corelib.extraction.ExtrOcamlBasic. Maps
bool,option,list, and pairs to native OCaml types during extraction. ↩ - The Rocq Prover Reference Manual 9.2. Program Extraction: Generating ML Code. Covers generating OCaml source and interface files for a target definition. ↩