Repository navigation
Challenge 8: bounded Kani proofs of SmallSort memory safety and sorting correctness, with helper contracts - #752
Conversation
Add Kani harnesses in core::slice::sort::shared::smallsort::verify, and safety contracts (requires/modifies, under cfg(kani)) on the real swap_if_less, insertion_sort_shift_left, insert_tail, sort4_stable and bidirectional_merge. Existing function bodies and signatures are unchanged; smallsort.rs only gains contract attributes, comments and three cfg(kani) helper predicates used by the contracts. The write sets in these contracts list element and destination memory only, so they apply to comparators that write nowhere else. A comment above swap_if_less and the module docs in verify.rs state this, and a negative control checks that a comparator writing a captured counter is rejected. Order contracts are also checked on proof-owned profiles that forward a fixed element type and comparator to the real helpers, and on N=2 wrappers that call the three small_sort trait entry points. 235 harnesses are ordinary. The 13 negative controls stay behind cfg(kani_smallsort_controls), which CI never sets.
There was a problem hiding this comment.
🟡 Changes recommended
Sorting contracts omit required slice-length domains, and CI proofs exclude checks for uninitialized reads, invalid values, and mutation of immutable bytes, leaving critical correctness and memory-safety requirements unmet.
2 open issues
What changed in this PR
This PR adds bounded Kani verification for SmallSort toward Challenge 8 (#56), covering memory safety, sorting correctness, and helper contracts without changing the sorting implementations’ runtime logic.
Changes:
- Adds bounded proofs across sorting routes, dispatch boundaries, element types, and comparator behaviors.
- Adds helper safety contracts, two-element sorting contracts, and verified-contract consumers.
- Documents verification limits and adds opt-in negative controls.
| File | Description |
|---|---|
library/core/src/slice/sort/shared/smallsort/verify/types.rs |
Checks logical sorting properties for Cell and Drop types. |
library/core/src/slice/sort/shared/smallsort/verify/tag_permutation.rs |
Checks network identity-tag preservation. |
library/core/src/slice/sort/shared/smallsort/verify/smoke.rs |
Checks the swap-size heuristic across types. |
library/core/src/slice/sort/shared/smallsort/verify/scratch_geometry.rs |
Checks stable sorting with minimal scratch space. |
library/core/src/slice/sort/shared/smallsort/verify/network.rs |
Adds network, insertion, dispatch, and comparator proofs. |
library/core/src/slice/sort/shared/smallsort/verify/mutations.rs |
Supplies a deliberately incorrect swap for negative controls. |
library/core/src/slice/sort/shared/smallsort/verify/merge/profiles.rs |
Defines ordered helper contracts and full-value models. |
library/core/src/slice/sort/shared/smallsort/verify/merge.rs |
Adds merge, general-route, fallback, and Drop proofs. |
library/core/src/slice/sort/shared/smallsort/verify/insert_tail_contracts.rs |
Checks tail-insertion contracts over bounded positions. |
library/core/src/slice/sort/shared/smallsort/verify/helper_contracts.rs |
Pairs helper contract proofs with consumers and controls. |
library/core/src/slice/sort/shared/smallsort/verify/helper_contracts_wide.rs |
Adds wider allocation proofs and network/sort8 consumers. |
library/core/src/slice/sort/shared/smallsort/verify/forwarding_contracts.rs |
Adds two-element sorting contracts around trait entries. |
library/core/src/slice/sort/shared/smallsort/verify/fixed_inputs.rs |
Adds focused helper checks and zero-sized-type proofs. |
library/core/src/slice/sort/shared/smallsort/verify/comparators.rs |
Provides a zero-sized-type-aware comparator. |
library/core/src/slice/sort/shared/smallsort/verify.rs |
Registers proof modules and documents scope and limitations. |
library/core/src/slice/sort/shared/smallsort.rs |
Adds helper contracts, geometry predicates, and proof registration. |
library/core/Cargo.toml |
Registers the optional negative-control configuration. |
Review effort: Balanced
| //! invoking the callback. | ||
| //! | ||
| //! Not covered: | ||
| //! - Uninitialized-memory, value-validity, and immutable-byte permission checks, or unwinding. |
| // Raw pair arguments avoid conflicting generated captures of an &mut slice in the contract | ||
| // macros. The raw span is always exactly N2; these adapters use the same pure checker as the | ||
| // corruption control. Only the scalar count is captured in old(). |
|
On the two review findings: 1. Uninitialized-memory, validity and immutable-byte checks. Agreed; the Limitations section says the same. The blocker is tool support: 2. Slice lengths. Agreed for the sorting contracts. Memory safety is checked at lengths that reach every dispatch boundary up to 32. Sortedness and multiset preservation are checked up to length 9 for the general and stable sorts and up to 6 for the insertion-sort fallback; the network sort is checked for sortedness up to 13. We are extending the sorting proofs to every length that One question about the challenge text. The network sort and the unstable general sort abort above 32 elements, so their valid lengths are bounded. The insertion-sort fallback, the stable general sort (given enough scratch) and Kani version. Contracts on the three trait methods themselves need the fixes for model-checking/kani#4908 and model-checking/kani#5116, which are in Kani Disclosure: this comment was prepared with the help of AI assistants. |
…eck GO [skip ci]
…3 summary [skip ci]
…ispatch [skip ci]
…atch [skip ci]
Adds ensures clauses to the stable, unstable and Freeze small_sort implementations, including their specialization defaults, with bounded proof_for_contract checks for fixed comparators and fixture types.
Collapses the identical per-entry length check in the u64 model and rewords the module docs and safety comments for the trait-method contract checks.
Drops a comment that restated the u64 guard, says where the enabled domains are listed, and calls the general sort scratch local. Comments only.
|
Follow-up to the second review finding (sorting contracts for the trait entries) and the Kani version note in my
The length part of that finding is unchanged by this update: the trait-method contracts are checked at these small Two scope questions are still open, and their answers decide how far we extend the sorting proofs:
The unchanged Kani workflow passes in our fork on |

This PR adds bounded Kani checks for the
smallsortmodule (#56): memory safety of the threesmall_sorttraitentries and the helpers behind them, sorting correctness on the general, fallback and network routes,
requires/modifiescontracts on five helpers, and conditional sorting contracts on all sixsmall_sortimplementations. 245 harnesses pass on each OS in the repository's unchanged Kani workflow, and 17 negative controls
fail their designated checks. The sorting code and its signatures are unchanged; the workflow and tool pins are those
of the merged
main.Highlights
fallback and network routes behind them are checked unmodified, at representative lengths that include every dispatch boundary up
to N32. Comparators return arbitrary answers or mutate through a
Cell; element types include a Drop type, a ZSTand sizes of 1, 8, 16, 17, 85 and 86 bytes, which select every size-dependent branch.
symbolic value: it occurs as often after the sort as before. Some families sort by a key (
x >> 1) under whichdistinct values tie, so a key-only oracle would miss payload corruption; the network and logical-model families use
the ordinary
<. Covered on the general and stable routes at u8 and u64 N0..9, on the fallback route at N0..6, andon the network route (sortedness at u8 N0..7, 9..13 and u64 N0..7, 9, multiset preservation below the network width, and permutation of
distinct tags at N9 and N13 for an arbitrary comparator).
requires/modifiesonswap_if_less,insert_tail,insertion_sort_shift_left,sort4_stableandbidirectional_merge, proved by 16proof_for_contractharnesseswith an arbitrary-answer comparator, and used by four
stub_verifiedconsumers at real call sites with the sameelement type, comparator and allocation as the proof (the u8 networks at N9, N13 and N32; u64
sort8_stable).ensures(nondecreasing order, preserved full-valuecount) on all six
small_sortimplementations, including the three specialization defaults, active for the coveredfixtures and checked by
proof_for_contracton the real bodies; the unstable entry and a plain forwarding calleralso use the Freeze contract through
stub_verified.swap_if_less, payload corruptions, wrongcomparators,
requiresviolations, a comparator writing outside the write set, a duplicated tag, and four controlsfor the trait-method contracts. Each fails exactly its designated check (see Negative controls below).
Challenge criteria
small_sorttrait entriesswap_if_less,insertion_sort_shift_left,sort4_stable,has_efficient_in_place_swapinsertion_sort_shift_leftbody at every offset for u64 N1..20; predicate on 12 typessmall_sortsortsensureson the six trait-method implementations, checked at the fixtures under Contracts; sorting proved by harness oracles at the lengths belowWhat is checked (245 harnesses, run with
--no-assert-contracts)small_sort_general*)small_sort_fallbacksmall_sort_networkinsertion_sort_shift_leftfrom offset 9 or 13[u8; 16/17/85/86], a Drop type, ZST (stable trait entry,()),Cell; dispatch to N32; insertion at every offset for u64 N1..20 andCellN1..5, N20; stable route with minimal scratch at N2small_sortCell<u8>, Drop keyhas_efficient_in_place_swap,sort4_stable,swap_if_lessat equal positions, helper pairsswap_if_less14,sort4_stable2,insert_tail5,bidirectional_merge12, N2 forwarding wrappers 3proof_for_contract16,stub_verifiedconsumers 4requiresandmodifieson the executed domainsmall_sortof the stable, unstable and Freeze implementations and their defaults:proof_for_contract9, forwarding consumer 1Cell<u8>N2; non-CopyFreeze key N2For multiset preservation, the harnesses pick an arbitrary value and check that it occurs as often after the sort as
before; the
Cell<u8>and Drop fixtures compare the byte stored in each element. The tag harnesses sort fixeddistinct u8 tags with an arbitrary comparator. Extending that result to other payloads is a source-level argument: it
assumes that the route moves whole elements and decides moves only from comparator answers and positions.
Contracts
On the real helpers. Safety contracts:
requireson pointer validity and allocation geometry,modifieson theelement or destination memory. The contract proofs use the following inputs:
swap_if_less: u8, u64 and[u8; 17]in a 4-element allocation; u8 in 9- and 13-element allocations; u8 and u64in a 32-element allocation with any base and any two positions, equal positions included.
insert_tail: u64, tail 1..4 in a 5-element allocation, and tail 1..15 from the start of a 17-element allocation.insertion_sort_shift_left: u64 arrays of lengths 2 and 3, every valid offset. The body itself is also checkeddirectly at every offset for lengths 1 through 20.
sort4_stable: u64, disjoint 4-element source and destination.bidirectional_merge: u64 of length 2 and 4, and of length 8 at the geometry of the 48-element stable scratch.Each consumer replaces the real call with the proved contract through
stub_verified, with the same element type,comparator and allocation domain as the contract proof: the unstable u8 network at N9, N13 and N32 with
swap_if_less, and u64sort8_stablewithbidirectional_merge. The same routes are also checked with their realbodies. Proofs on the real helpers use one comparator function item per harness that returns an arbitrary answer, so
no ordering law is assumed. Only the executed domains are claimed.
On the trait methods. All six
small_sortimplementations declare a write set and a conditional sortingpostcondition: with one of the listed read-only comparators, the slice returns in nondecreasing order with the same
values, duplicates included. The checks use
u64at lengths 2 and 3 for the stable, unstable and Freezespecializations,
Cell<u8>at length 2 for the stable and unstable defaults, and a non-CopyFreezebyte key atlength 2 for the Freeze default. The specialized unstable checks and a separate forwarding harness use the verified
Freeze contract for the forwarded call; the Freeze implementation itself is checked separately on the same inputs.
Verification wrappers. Wrappers that fix the element type and require one comparator function pointer forward
to the real helpers; their
ensureschecks ordering and preserved value counts against a model, and a preconditionrejects any other comparator. Three further N2 wrappers check the trait entry points.
Negative controls (17, behind
cfg(kani_smallsort_controls), which CI never sets)swap_if_lesscopy;requires: out-of-allocationswap_if_less,insert_tailwithbegin == tail, andbidirectional_mergeinto an overlapping destination;swap_if_lesscontract proof with a comparator that increments a captured counter, which must fail the write-setcheck;
with changed value counts, and two that show the Freeze stub may return unsorted data when its postcondition does
not apply (a reversed function-pointer comparator and a function-item comparator).
We ran the first thirteen on the previous head with the then-pinned Kani (
cd355b0b), outside GitHub Actions: eachfails exactly one check, the designated one (report).
The four trait-method controls fail exactly their designated assertion on this head with the current pin (
9834c96c).CI
This head merges
mainwith the current Kani pin (9834c96c, from #784). We ran the upstream Kani workflow unchangedin our fork via
workflow_dispatch(a fork run, not an upstream PR check) on1d2706e31f, the parent of the lastcommit, which changes only comments:
run 45140203972:
successon Ubuntu andmacOS, including all 8 partition jobs, autoharness, metrics and
Build JSON from logs, in attempt 1. The otherupstream workflows (Rust Tests, Flux, RAPx, KMIR, VeriFast, VeriFast (negative), GOTO Transcoder, Book and Testable
SIMD) passed on an earlier head in the same way.
In the partition jobs all 245 SmallSort harnesses are
SUCCESSFULon each OS, with zero failed checks and1028/1028 satisfied covers (counted from the logs; the workflow does not enforce covers). SmallSort's summed
verification time is 6,151 s on Ubuntu and 11,395 s on macOS, about 65% and 67% of the jobs' manual-harness totals;
the longest proof takes 183 s on Ubuntu and 306 s on macOS, and the longest partition job takes 84 minutes.
At this base the autoharness job runs on a pull request only with the
run-autoharnesslabel (or in the merge queueor on dispatch); we would appreciate the label on this PR.
Limitations
element and destination memory only, since Kani cannot state the footprint of an arbitrary
FnMut; the contractsare claimed for comparators that write nowhere else (a comment above
swap_if_lesssays so, and the counter controlchecks it).
comparators, lengths and layouts, and unwinding, remain open.
tree also ran into
kani-drivermemory use (kani#5117).panic_on_ord_violationwithassume(false); the other 174 use the original function. Comparator panics and panic unwinding are not covered.instrumentation on these routes:
-Z uninit-checksreports unsupported operations here(kani#3300) and
-Z valid-value-checksdoes not yet supportcopy_nonoverlapping(kani#3762), which these routes use.Writes to immutable bytes and aliasing beyond Kani's pointer checks are not modelled.
failed on the previous Kani pin
cd355b0b(pin-check report),
and the issue is still open. The four array-valued fixtures
network::swap_contract_bytes16_n2,network::swap_contract_bytes17_n2,merge::sort4_contract_bytes16_n4andmerge::sort4_arbitrary_comparator_bytes16_n4use related pointer-selection code, so we keep that caveat for them.(). The public sortentry points short-circuit ZSTs, and
select_nth_unstableskips selection work for them after validating theindex. ZST comparators read with
ptr::read, sinceread_volatileon a ZST gives spurious dereference failures(kani#5072). The stable Freeze route is checked with a separate
48-element scratch and with the minimal scratch at N2. Tie stability is not proved separately.
Note for maintainers. The
sort4_stablecontract makes source/destination non-overlap explicit. The existingSAFETY comment mentions validity for four reads and writes but does not state this condition; the implementation uses
copy_nonoverlapping.Source. The original commit, a merge of
mainatb5adb2c5c9, one commit with the trait-method contracts, and one commit that simplifies their model and comments, followed by one comment-only commit: againstmain, 19 files underlibrary/, +4511/−0. The harnesseslive in
core::slice::sort::shared::smallsort::verify(verify.rsopens with a module map).smallsort.rsgains onlythe contract attributes, a comment on their write sets, three
cfg(kani)geometry predicates used by the contracts andthe
mod verifyregistration;library/core/Cargo.tomlgets acheck-cfgentry for the controls cfg.This contribution was prepared with the help of AI assistants.
By submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0 and MIT
licenses.