A sorting specification needs permutation
A type says that a sorting function receives and returns a list:
List Nat → List Nat
It does not say which output is correct. A first attempt at a specification might require only that every result is sorted:
def Sorted (xs : List Nat) : Prop :=
xs.Pairwise (· ≤ ·)
def SortedOutput (sort : List Nat → List Nat) : Prop :=
∀ xs, Sorted (sort xs)
That condition is necessary, but not sufficient. The empty list is sorted, so a function that discards every input satisfies it:
def discardAll : List Nat → List Nat := fun _ => []
theorem discardAll_satisfies_sortedOutput :
SortedOutput discardAll := by
intro xs
exact List.Pairwise.nil
Lean accepts the proof. The implementation is useless, but the theorem is true because the specification never says that the output must contain the input elements.
Add the missing property
A sorting specification needs two independent requirements:
- the output is ordered;
- the output is a permutation of the input.
List.Perm expresses the second requirement: the lists contain the same elements with the same multiplicities, possibly in a different order.
def SortSpec (sort : List Nat → List Nat) : Prop :=
∀ xs, Sorted (sort xs) ∧ (sort xs).Perm xs
Now Lean can prove that discardAll does not satisfy the specification:
theorem discardAll_fails_sortSpec : ¬ SortSpec discardAll := by
intro h
have hperm : (discardAll [0]).Perm [0] := (h [0]).2
have hlen : (discardAll [0]).length = [0].length :=
List.Perm.length_eq hperm
exact Nat.noConfusion hlen
The witness [0] is enough. discardAll [0] reduces to [], and [] is not a permutation of [0].
Check the complete example
The exact source shown above is in verification/specification-sort/SortingSpec.lean. CI builds it on the pinned Lean toolchain and checks its axioms. From the site repository:
cd verification/specification-sort
lake build
lake env lean Axioms.lean
The build checks both the misleading theorem and the corrected rejection theorem with Lean 4.33.1. The second command reports no axioms for the first theorem and only Lean’s standard propext axiom for the second. That dependency comes from the standard-library theorem List.Perm.length_eq, not from an assumption added by this example.
The lesson is not specific to sorting: every allowed output must be intended. If a property rules out bad ordering but says nothing about lost, duplicated, or invented data, an agent can satisfy the theorem without solving the task.