Repository navigation
Challenge 31: Verify the safety of BinaryHeap functions with Kani - #754
albertwujj wants to merge 4 commits into
Conversation
Contracts on Hole::{new, get, move_to}, sift_up, sift_down_range, sift_down and sift_down_to_bottom, loop contracts on the six loops that they and the safe methods run, and harnesses for every function of the challenge. Heaps have a symbolic capacity and length, every comparison returns an arbitrary result, and no harness has an unwinding bound.
The changes to shipped code are attributes only. The harnesses and two helper methods are under cfg(kani).
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
…t type The comparison operators of the zero-sized element type now copy one byte between two locals before they return an arbitrary result. This does not change what is proved. It keeps CBMC's write-set table constrained under formula slicing: without a real write in a loop with a contract, each checked write of that loop costs about half a million solver variables. The loop harnesses of the zero-sized type go from about 8.7 to 3.6 million variables, and run three to four times faster. Only harness code changes; the shipped code is untouched. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
…nners Kani compiles all the harnesses of a crate in one compiler process, and `kani list`, the first step of every partition job (and of the metrics and list jobs), compiles every harness of the library. On the 7 GB macOS runners the compiler of `core` is killed when the compiler of another crate with many harnesses runs beside it: with the BinaryHeap harnesses in `alloc`, in about one partition job out of three, before any harness runs. scripts/run-kani.sh now sets CARGO_BUILD_JOBS=1 on macOS once Kani is built, so cargo compiles the crates of the library one after the other. The Linux runners (16 GB) are not changed. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
|
Two follow-up commits
|
There was a problem hiding this comment.
🟡 Changes recommended
The comparator frames exclude legal Ord implementations that mutate external state, while proof gaps remain for arbitrary-length inputs and element validity after sifting.
3 open issues
What changed in this PR
This PR adds Kani verification for BinaryHeap toward Challenge 31, covering unsafe-function contracts, safe operations, and sorted-iterator length guarantees without changing runtime function bodies.
Changes:
- Adds proof harnesses across multiple element layouts, with loop contracts and zero-sized-type overflow cases.
- Documents the verification model, coverage argument, and limitations.
- Enables loop-contract macros and serializes library compilation on macOS runners to reduce memory pressure.
| File | Description |
|---|---|
scripts/run-kani.sh |
Limits macOS Cargo builds to one concurrent job. |
library/alloc/src/lib.rs |
Enables proc_macro_hygiene for Kani builds. |
library/alloc/src/collections/binary_heap/mod.rs |
Adds safety contracts, loop annotations, proof harnesses, and verification documentation. |
Review effort: Balanced
…Hole moves Answers the automatic review. Zero-sized heaps. One length was in no harness: pop, PeekMut::pop, into_sorted_vec and the two sorted iterators sift in a heap that is one element shorter, so nothing overflows up to MAX_SIFT_DOWN_LEN + 1, and their harnesses stopped one length early. They now take MAX_POP_LEN. For every function that can overflow, a should_panic harness now takes all the inputs that its harness excludes (long_zst_*, 13 harnesses; panic_append_overflow replaces panic_append_too_long). In them some executions return and others panic on an overflow. On the executions that return, the result is checked as in the other harnesses, with a check that should_panic cannot take for the expected panic, and a cover shows that such executions exist. Hole. Three harnesses, for u8 and for bool elements of any value, show which element each step moves: Hole::new takes out the element at pos, Hole::move_to puts the element of index into the slot that the hole leaves, and Drop for Hole writes back the element that was taken out. Documentation of mod verify: writes of a comparison to other memory are left out of the model, and why that is sound; and the argument that a call leaves a heap of valid elements, which Kani does not carry through the loops. 269 harnesses (was 251). Only harness code and its documentation change.
feliperodri
left a comment
There was a problem hiding this comment.
Requesting changes. One gap keeps this from meeting the arbitrary-length requirement, and one change is outside the challenge's scope. Everything else checks out locally.
The long_zst_* harnesses accept any panic, including the bounds checks in Hole. Hole::get and Hole::move_to check index < self.data.len() with debug_assert!, and a failed debug_assert! is a panic, which should_panic accepts. So for a zero-sized heap longer than isize::MAX, a sift that passes an out-of-bounds index to get_unchecked, which is UB, still verifies.
I checked this by making sift_down_range loop while child <= end.saturating_sub(1), so it reads child + 1 == end:
- 9 of the normal
t_u8harnesses fail, as they should; - 12 of the 13
long_zst_*harnesses still pass (onlylong_zst_into_sorted_vecfails).
The module doc relies on "Kani lists the panics, and they are all overflows", but that is a manual reading of the output. Neither the harness verdict nor CI checks it.
For the arbitrary-length clause to hold, these harnesses need to tell the overflow panic apart from a failed bounds check. I'm open to how. One thing to try: verify the long-heap calls against Hole::get/Hole::move_to's contracts (stub_verified), so the index < len precondition becomes a check that isn't a panic. Please confirm that Kani doesn't count a failed precondition as a panic.
scripts/run-kani.sh belongs in its own PR. The macOS change affects every PR's CI, so it needs its own review, separately from Challenge 31. You offered to split it; please do.
What I verified locally (Kani c5e65fd, CI flags, 3 harnesses at a time):
- Full suite: all 269 harnesses at
c10390b(1 h 59 min; slowestt_cell::append, 417 s). - Five injected bugs (
sift_down_range's loop bound,sift_uppast position 0,Hole::move_tonot updatingpos, andsize_hintoff by one for each sorted iterator): every one makes harnesses fail ont_u8(andt_zstforsift_up): 9, 20, 11, 1 and 1.
The move_to bug only duplicates an element, with no out-of-bounds access. hole_move_to and the functions built on it catch it, which shows the harnesses check more than memory safety.
Two items depend on committee rulings and don't block this round. You already list both as not proven, which is the right call:
FYI, not blocking: sized element types are covered up to 2^48 bytes, which is CBMC's object limit with --object-bits 12. Longer heaps of a sized type aren't covered; the zero-sized harnesses cover the index arithmetic. That's a tool limit, and it applies to every Kani solution.
To flip this to approval: make the long_zst_* harnesses fail on an out-of-bounds Hole index, and move the run-kani.sh change to its own PR.
|
|
||
| #[kani::proof] | ||
| #[kani::should_panic] | ||
| fn long_zst_sift_down_range() { |
There was a problem hiding this comment.
Soundness: should_panic accepts the debug_assert!(index < self.data.len()) in Hole::get/move_to as the expected panic. With sift_down_range changed to loop while child <= end.saturating_sub(1), this harness still passes, as do 11 more of the 13 long_zst_* harnesses (only long_zst_into_sorted_vec fails). On these lengths an out-of-bounds index into get_unchecked, which is UB, isn't detected.
| //! harnesses pass when some execution panics and no check other than a panic fails, | ||
| //! on the executions that return as on those that panic. On those that return they | ||
| //! also check the result (`must_hold`). (`should_panic` cannot require that the panic | ||
| //! is an overflow. Kani lists the panics, and they are all overflows.) |
There was a problem hiding this comment.
Question: "Kani lists the panics, and they are all overflows" is true at this head, but it's a manual reading of the output. With the injected bound bug the list gains the debug_assert! panic, and the harnesses still pass. Can this be made part of the verdict, so CI would catch it?
| /// The end of a harness in which every execution panics before this point. Kani reports | ||
| /// reaching it as a failure that is not a panic, so the `should_panic` harness then | ||
| /// fails: it passes only if no execution returns from the call under test. | ||
| fn must_have_panicked() -> ! { |
There was a problem hiding this comment.
Praise: must_have_panicked and must_hold close the two usual should_panic loopholes, a harness that never panics and an assert! counted as the expected panic. Good pattern.
| # On macOS, compile the library one crate at a time. Kani compiles all the harnesses of a | ||
| # crate in one compiler process, and the 7 GB macOS runners kill the compiler of `core` | ||
| # when the compiler of another crate with many harnesses (`alloc`) runs beside it. | ||
| if [[ "$(uname)" == "Darwin" ]]; then |
There was a problem hiding this comment.
Suggestion: this fixes a CI problem every PR can hit on the macOS runners, so it deserves its own PR and review, separately from Challenge 31. Please move it out of this one.
|
We've accepted #758 as the solution for Challenge 31 (see #758 (comment)). We decided on the merits: #758 fixed the zero-sized Thank you for the work here. Several parts of it are stronger than #758: the eleven element types, including |


Resolves #746. Challenge 31: Verify the safety of BinaryHeap functions: contracts and proof_for_contract harnesses for the 7 unsafe functions, safety harnesses for the 16 safe functions, and harnesses that check size_hint is exact for the two TrustedLen implementations. No function body is changed, nothing is stubbed, and no harness has an unwinding bound. All changes are in
library/alloc/src/collections/binary_heap/mod.rs, plus#![cfg_attr(kani, feature(proc_macro_hygiene))]inlibrary/alloc/src/lib.rsto allow loop contract attributes.Added one CI change: scripts/run-kani.sh compiles the library one crate at a time on the macOS runners (see my first comment below).
What is verified
Hole::new,Hole::get,Hole::move_to,sift_up,sift_down_range,sift_down,sift_down_to_bottom#[requires]is the function's# Safetysection. One#[kani::proof_for_contract]harness per element type.TrustedLenforIntoIterSortedandDrainSortedn,size_hintis(n, Some(n));nextreturnsSomeand leavesn - 1elements, or returnsNonewhenn == 0. By induction onnthe iterator yields exactlynelements.push,pop,peek_mut,PeekMut::deref,PeekMut::deref_mut,PeekMut::pop,PeekMut::refresh,Drop for PeekMut,rebuild,rebuild_tail,append,into_sorted_vec,From<Vec<T>>,IntoIterSorted::next,DrainSorted::next,Drop for Hole#[kani::proof]harness each per element type, running the shipped function with its callees.Drop for PeekMut,PeekMut::pop,PeekMut::refreshin either statePeekMutin either state that safe code can reach (before or afterderef_mut).PeekMutleaked afterderef_mutpeek_mut_deref_mut_leak: the heap keeps its buffer and capacity with length 1, andpop,pushandpeek_mutthen run on it.Ord, including inconsistent onesAnyOrd). InCellOrdit also overwrites both operands.usizelength for a zero-sized type, any buffer of up to 2^48 bytes otherwise (CBMC's object model under--object-bits 12). Six loop contracts.Tand the child-index overflowTElement types
Each proof is written once as
check_*::<T>()and instantiated by two macros.t_zstAnyOrd<()>isize::MAXt_u8AnyOrd<u8>min_non_zero_cap; 1-byte swap tailt_boolAnyOrd<bool>Option<T>storesNonein one)t_dropAnyOrd<DropFails>t_u32AnyOrd<u32>t_u64AnyOrd<u64>t_u128AnyOrd<u128>t_cellCellOrdt_bigAnyOrd<[u64; 256]>min_non_zero_cap(over 1 KiB), in every function includingappendt_bytes6AnyOrd<[u8; 6]>t_paddedAnyOrd<Padded>The documentation of
mod verifyholds the full argument. In short:T.binary_heap/mod.rsnever asks for the size or alignment ofT. It moves elements whole and calls only<,<=and>=. It never drops, clones or creates an element.popreturns anOption<T>, which storesNonein an invalid bit pattern ofTwhen there is one; that is the only way the bytes of an element are read.RawVecInner,ptr::swap_nonoverlapping, the allocator, the precondition checks);raw_vec::min_non_zero_cap(size 1, up to 1 KiB, larger);ptr::swap_nonoverlapping_bytes(words only, tail only, both).kani::covershows thatpushandappendreach the reallocation. One arm is not reached: the "capacity overflow" panic for a sized type needs a buffer aboveisize::MAXbytes.buffer + index * size_of::<T>(), each access hasindex < len, andVecguaranteeslen <= capacity, a buffer ofcapacityelements that is at mostisize::MAXbytes and aligned forT.T; the zero-sized type runs for everyusizelength.Vec::pushandVec::append, which the challenge allows to assume correct and whichverifast-proofs/alloc/raw_vecverifies for any element layout.Tthat the heap runs. A comparison receives two&Tto live elements and has no access to the heap itself, so letting it return anything and overwrite both operands (AnyOrd,CellOrd) covers everyOrd.t_bytes6andt_paddedtypes have the 18 harnesses of the functions that access elements themselves. The other five functions (rebuild,rebuild_tail,append,into_sorted_vec,From<Vec<T>>) reach elements only through those,ptr::swapandVec::append, which have no branch that separates these sizes from 2, 4 or 16 bytes.Zero-sized types
A heap of a zero-sized type can be longer than
isize::MAX. Then2 * pos + 1can overflow in the sift-down loops (the FIXME insift_down_range),2 * lenandtail_len * 11can overflow inrebuild_tail, and a full vector cannot grow. The challenge accepts an overflow panic there.#[kani::should_panic]harnesses take all the other inputs: onelong_zst_*harness per function that can overflow (13), withpanic_push_fullandpanic_append_overflow. In them some executions return and others panic on an overflow. A harness passes only if no check other than a panic fails, and it checks the result of the executions that return. Together the two sets cover every length of a zero-sized heap.Assumptions in the harnesses
All
kani::assumeandkani::any_wherein the (non-panic) harnesses. All are followed bykani::coverstatements. For a sized type only the first two rows exclude anything.cap <= 2^48 / size_of::<T>(),len <= capHole::get,Hole::move_to,Drop for Hole, and the harnesses on the value aHolemovespos < len(andindex != pos && index < lenfor the optional move)HolewithHole::new, whose precondition this issift_down_rangeend <= isize::MAX + 1Tonly)len <= isize::MAX + 1, orisize::MAX + 2for the functions that remove an element first (pop,PeekMut::pop,into_sorted_vec, the sorted iterators)pushlen < usize::MAXTonly)rebuild_tailstart <= len, and no overflow in2 * len,tail_len * 11or a child indexstart <= lenholds at every call site; the rest only fails for a zero-sizedTappendusize, andrebuild_tail's heuristic does not overflowTonlyFrom<Vec<T>>len <= isize::MAX + 1Notes
Option<T>thatpopreturns, for a type with invalid bit patterns (bool). When the buffer was filled with an arbitrary valid byte (ptr::write_bytes), CBMC ran out of memory while reporting the results of theboolharnesses built onpop, so the buffer is allocated zeroed instead.hole_u8::*,hole_bool::*) check which element each step of aHolemoves. The module documentation uses them in the argument that a call leaves a heap of valid elements, which Kani does not carry through the loops.scripts/run-kani.shenables neither-Z uninit-checksnor-Z valid-value-checks, and at the pinned Kani neither gets through these harnesses (the first overflows inside Kani's own model or exhausts a 16 GB runner; the second stops at unsupportedmutable castandcopy_nonoverlapping). In their place: in aVec, a read of uninitialized memory is a read at or pastlen, which is out of bounds whencapacity == len; and the functions create no element, they only move whole ones.debug_assert!s ofHoleandPeekMutremoved.By submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0 and MIT licenses.