Skip to content

Challenge 8: bounded Kani proofs of SmallSort memory safety and sorting correctness, with helper contracts - #752

Open
Tiramisu-Cake wants to merge 5 commits into
model-checking:mainfrom
Tiramisu-Cake:submission/ch8-smallsort
Open

Tiramisu-Cake wants to merge 5 commits into
model-checking:mainfrom
Tiramisu-Cake:submission/ch8-smallsort

Conversation

@Tiramisu-Cake

@Tiramisu-Cake Tiramisu-Cake commented Nov 10, 2026 •

Copy link
Copy Markdown

This PR adds bounded Kani checks for the smallsort module (#56): memory safety of the three small_sort trait
entries and the helpers behind them, sorting correctness on the general, fallback and network routes,
requires/modifies contracts on five helpers, and conditional sorting contracts on all six small_sort
implementations. 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

  • Memory safety on the real routes. All three trait entries (stable, unstable, unstable-Freeze) and the general,
    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 ZST
    and sizes of 1, 8, 16, 17, 85 and 86 bytes, which select every size-dependent branch.
  • Sorting correctness with a full-value oracle. Sortedness plus multiset preservation, stated for an arbitrary
    symbolic value: it occurs as often after the sort as before. Some families sort by a key (x >> 1) under which
    distinct 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, and
    on 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).
  • Contracts on the real helpers. requires/modifies on swap_if_less, insert_tail,
    insertion_sort_shift_left, sort4_stable and bidirectional_merge, proved by 16 proof_for_contract harnesses
    with an arbitrary-answer comparator, and used by four stub_verified consumers at real call sites with the same
    element type, comparator and allocation as the proof (the u8 networks at N9, N13 and N32; u64 sort8_stable).
  • Sorting contracts on the trait methods. A conditional ensures (nondecreasing order, preserved full-value
    count) on all six small_sort implementations, including the three specialization defaults, active for the covered
    fixtures and checked by proof_for_contract on the real bodies; the unstable entry and a plain forwarding caller
    also use the Freeze contract through stub_verified.
  • Calibrated negative controls. Seventeen harnesses: a mutant swap_if_less, payload corruptions, wrong
    comparators, requires violations, a comparator writing outside the write set, a duplicated tag, and four controls
    for the trait-method contracts. Each fails exactly its designated check (see Negative controls below).

Challenge criteria

Criterion In this PR
No UB: the three small_sort trait entries real routes at representative lengths up to N32 on the type matrix below, Kani default checks
No UB: swap_if_less, insertion_sort_shift_left, sort4_stable, has_efficient_in_place_swap contracts proved on the listed domains (first three); real bodies with arbitrary comparators; insertion_sort_shift_left body at every offset for u64 N1..20; predicate on 12 types
Contracts showing that small_sort sorts ensures on the six trait-method implementations, checked at the fixtures under Contracts; sorting proved by harness oracles at the lengths below
Lengths bounded as listed; correctness to N9 (general, stable), N13 (network sortedness), N6 (fallback)
UB classes dangling, misaligned and out-of-bounds accesses on every path above; see Limitations for the rest
What is checked (245 harnesses, run with --no-assert-contracts)
Group Harnesses Route / function T, N Property
General / stable entries 25 general route (small_sort_general*) u8, u64; N0..9 key order + full-value count
Fallback insertion 7 small_sort_fallback u8, u64; N0..6 key order + full-value count
Network entry 16 small_sort_network u8 N0..7, 9..13; u64 N0..7, 9 order; count only for N < 9
Insertion phase 5 insertion_sort_shift_left from offset 9 or 13 u8 N10, 11, 14; u64 N10, 14 whole-array count, any input
Safety 92 all routes and dispatch u64, u8, [u8; 16/17/85/86], a Drop type, ZST (stable trait entry, ()), Cell; dispatch to N32; insertion at every offset for u64 N1..20 and Cell N1..5, N20; stable route with minimal scratch at N2 Kani default checks up to normal return
Drop / tag 19 fallback, insertion, general and network routes selected N; fixed distinct u8 tags on network N9, N13 drop counts and tag permutation at normal return
Trait entries, logical model 6 small_sort Cell<u8>, Drop key logical order + count
Helpers 9 has_efficient_in_place_swap, sort4_stable, swap_if_less at equal positions, helper pairs type matrix; N2, N4, N10 predicate; safety + value preservation
Contract proofs on profiles 36 swap_if_less 14, sort4_stable 2, insert_tail 5, bidirectional_merge 12, N2 forwarding wrappers 3 exact listed allocations order contract on the executed domain
Contracts on the real helpers 20 proof_for_contract 16, stub_verified consumers 4 see Contracts requires and modifies on the executed domain
Contracts on the trait methods 10 small_sort of the stable, unstable and Freeze implementations and their defaults: proof_for_contract 9, forwarding consumer 1 u64 N2, N3; Cell<u8> N2; non-Copy Freeze key N2 order + full-value count, write set on the active slice

For 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 fixed
distinct 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: requires on pointer validity and allocation geometry, modifies on the
element 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 u64
    in 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 checked
    directly 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 u64 sort8_stable with bidirectional_merge. The same routes are also checked with their real
bodies. 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_sort implementations declare a write set and a conditional sorting
postcondition: with one of the listed read-only comparators, the slice returns in nondecreasing order with the same
values, duplicates included. The checks use u64 at lengths 2 and 3 for the stable, unstable and Freeze
specializations, Cell<u8> at length 2 for the stable and unstable defaults, and a non-Copy Freeze byte key at
length 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 ensures checks ordering and preserved value counts against a model, and a precondition
rejects any other comparator. Three further N2 wrappers check the trait entry points.

Negative controls (17, behind cfg(kani_smallsort_controls), which CI never sets)
  • a negated swap_if_less copy;
  • two checks that the oracle sees a changed payload;
  • the canonical-comparator guard of the wrappers;
  • four consumers that use a profile contract with a wrong comparator, so the comparator precondition must fail;
  • three calls that violate a real helper's requires: out-of-allocation swap_if_less, insert_tail with
    begin == tail, and bidirectional_merge into an overlapping destination;
  • a swap_if_less contract proof with a comparator that increments a captured counter, which must fail the write-set
    check;
  • a duplicated tag on the network N9 tag harness;
  • for the trait-method contracts: two checks that feed the postcondition a sorted result with a changed high bit or
    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: each
fails 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 main with the current Kani pin (9834c96c, from #784). We ran the upstream Kani workflow unchanged
in our fork via workflow_dispatch (a fork run, not an upstream PR check) on 1d2706e31f, the parent of the last
commit, which changes only comments:
run 45140203972: success on Ubuntu and
macOS, including all 8 partition jobs, autoharness, metrics and Build JSON from logs, in attempt 1. The other
upstream 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 SUCCESSFUL on each OS, with zero failed checks and
1028/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-autoharness label (or in the merge queue
or on dispatch); we would appreciate the label on this PR.

Limitations

  • Scope. Results hold for the listed types, comparators, lengths and allocation layouts. The write sets list
    element and destination memory only, since Kani cannot state the footprint of an arbitrary FnMut; the contracts
    are claimed for comparators that write nowhere else (a comment above swap_if_less says so, and the counter control
    checks it).
  • Trait-method contracts. Claimed only for the fixtures listed under Contracts, on normal return. Other types,
    comparators, lengths and layouts, and unwinding, remain open.
  • Lengths. Wider domains are limited by verification time; an extended u64 N10 composition on an earlier research
    tree also ran into kani-driver memory use (kani#5117).
  • Panics. Seventy-one harnesses cut the explicit comparator-order panic by stubbing panic_on_ord_violation with
    assume(false); the other 174 use the original function. Comparator panics and panic unwinding are not covered.
  • UB classes. As in the repository's Kani profile, there is no uninitialized-memory or value-validity
    instrumentation on these routes: -Z uninit-checks reports unsupported operations here
    (kani#3300) and -Z valid-value-checks does not yet support
    copy_nonoverlapping (kani#3762), which these routes use.
    Writes to immutable bytes and aliasing beyond Kani's pointer checks are not modelled.
  • Model trust. The array-select reproducer from kani#5104
    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_n4 and
    merge::sort4_arbitrary_comparator_bytes16_n4 use related pointer-selection code, so we keep that caveat for them.
  • ZST and geometry. ZST coverage consists of direct stable SmallSort trait-entry checks on (). The public sort
    entry points short-circuit ZSTs, and select_nth_unstable skips selection work for them after validating the
    index. ZST comparators read with ptr::read, since read_volatile on 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_stable contract makes source/destination non-overlap explicit. The existing
SAFETY 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 main at b5adb2c5c9, one commit with the trait-method contracts, and one commit that simplifies their model and comments, followed by one comment-only commit: against main, 19 files under library/, +4511/−0. The harnesses
live in core::slice::sort::shared::smallsort::verify (verify.rs opens with a module map). smallsort.rs gains only
the contract attributes, a comment on their write sets, three cfg(kani) geometry predicates used by the contracts and
the mod verify registration; library/core/Cargo.toml gets a check-cfg entry 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.

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.
@Tiramisu-Cake
Tiramisu-Cake requested a review from a team as a code owner November 10, 2026 14:38
@feliperodri feliperodri added the Challenge Used to tag a challenge label Nov 14, 2026
@feliperodri
feliperodri requested a balanced review from Copilot November 14, 2026 18:47

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 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.
Comment on lines +92 to +94
// 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().
@Tiramisu-Cake

Copy link
Copy Markdown
Author

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: -Z uninit-checks rejects the MaybeUninit scratch buffers these functions use (model-checking/kani#5151), and -Z valid-value-checks does not support copy_nonoverlapping (model-checking/kani#3762). We are working on the first one upstream; model-checking/kani#5172 is the first PR. On a development build of Kani with those changes and a model for select_unpredictable, separate harnesses for bidirectional_merge, sort4_stable and swap_if_less verify at small sizes with -Z uninit-checks enabled, and a control that leaves one sort4_stable input element uninitialized is rejected (run). Once the Kani changes land, we plan to add these checks as a separate CI step. Kani does not check writes to immutable bytes yet, so that remains a limitation of this PR.

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 core passes to the small sorts: up to small_sort_threshold(), which is 16 for the fallback and 32 otherwise.

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 insertion_sort_shift_left accept any length. Does "arbitrary valid length" mean every length they are called with in core, or every length they accept?

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 0aac16e and later. Could the repository's Kani version be updated to 0aac16e or newer? Once main has it, we will merge main into this PR and add the sorting contracts to the trait methods.

Disclosure: this comment was prepared with the help of AI assistants.

Tiramisu-Cake added a commit to Tiramisu-Cake/verify-rust-std that referenced this pull request Nov 21, 2026
Tiramisu-Cake added a commit to Tiramisu-Cake/verify-rust-std that referenced this pull request Nov 21, 2026
Tiramisu-Cake added a commit to Tiramisu-Cake/verify-rust-std that referenced this pull request Nov 22, 2026
Tiramisu-Cake added a commit to Tiramisu-Cake/verify-rust-std that referenced this pull request Nov 22, 2026
Tiramisu-Cake added a commit to Tiramisu-Cake/verify-rust-std that referenced this pull request Nov 22, 2026
Tiramisu-Cake added a commit to Tiramisu-Cake/verify-rust-std that referenced this pull request Nov 22, 2026
Tiramisu-Cake added a commit to Tiramisu-Cake/verify-rust-std that referenced this pull request Nov 22, 2026
Tiramisu-Cake added a commit to Tiramisu-Cake/verify-rust-std that referenced this pull request Nov 22, 2026
Tiramisu-Cake added a commit to Tiramisu-Cake/verify-rust-std that referenced this pull request Nov 22, 2026
Tiramisu-Cake added a commit to Tiramisu-Cake/verify-rust-std that referenced this pull request Nov 22, 2026
Tiramisu-Cake added a commit to Tiramisu-Cake/verify-rust-std that referenced this pull request Nov 22, 2026
Tiramisu-Cake pushed a commit to Tiramisu-Cake/verify-rust-std that referenced this pull request Nov 22, 2026
Tiramisu-Cake added a commit to Tiramisu-Cake/verify-rust-std that referenced this pull request Nov 22, 2026
Tiramisu-Cake added a commit to Tiramisu-Cake/verify-rust-std that referenced this pull request Nov 22, 2026
Tiramisu-Cake added a commit to Tiramisu-Cake/verify-rust-std that referenced this pull request Nov 22, 2026
Tiramisu-Cake added a commit to Tiramisu-Cake/verify-rust-std that referenced this pull request Nov 22, 2026
Tiramisu-Cake pushed a commit to Tiramisu-Cake/verify-rust-std that referenced this pull request Nov 22, 2026
Tiramisu-Cake added a commit to Tiramisu-Cake/verify-rust-std that referenced this pull request Nov 22, 2026
Tiramisu-Cake pushed a commit to Tiramisu-Cake/verify-rust-std that referenced this pull request Nov 22, 2026
Tiramisu-Cake added a commit to Tiramisu-Cake/verify-rust-std that referenced this pull request Nov 22, 2026
Tiramisu-Cake added a commit to Tiramisu-Cake/verify-rust-std that referenced this pull request Nov 22, 2026
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.
@Tiramisu-Cake

Copy link
Copy Markdown
Author

Follow-up to the second review finding (sorting contracts for the trait entries) and the Kani version note in my
earlier reply. Now that main carries Kani 9834c96c (#784), the branch merges main and adds the contracts to the
trait methods themselves (head dab03cf510, fast-forward from 872d5a4338):

  • All six small_sort implementations, including the three specialization defaults, now declare a write set and a
    conditional ensures: nondecreasing order and the same values with duplicates. Before, these contracts were only
    on verification wrappers of the three trait entries at N2.
  • proof_for_contract checks them on the real bodies for u64 at lengths 2 and 3 and for Cell<u8> and a
    non-Copy Freeze key at length 2. This adds 10 harnesses (235 → 245) and 4 negative controls (13 → 17).

The length part of that finding is unchanged by this update: the trait-method contracts are checked at these small
lengths, and the harness oracles still prove sortedness to N9 for the general and stable sorts, N6 for the fallback and
N13 for the network sort. The first finding (initialization, validity and immutable bytes) also stands as described
in the Limitations section.

Two scope questions are still open, and their answers decide how far we extend the sorting proofs:

  • Lengths. Does "arbitrary valid length" mean every length the small sorts are called with in core (at most
    small_sort_threshold(): 16 for the fallback, 32 otherwise), or every length the fallback, the stable general sort
    and insertion_sort_shift_left accept? We asked this in our
    reply to the review.
  • Element types and comparators. Is a set of representative element types that exercises every specialization
    enough, or is a proof generic over T expected? Must the no-UB proofs also cover comparators that panic? We asked
    this on #56.

The unchanged Kani workflow passes in our fork on 1d2706e31f, the parent of the last, comment-only commit
(run 45140203972): all 245 SmallSort
harnesses are SUCCESSFUL on Ubuntu and macOS. The description is updated to match.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Challenge Used to tag a challenge

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants