Skip to content

Loop contract: get_unchecked precondition not discharged when the slice element is passed into a closure #4911

Description

@kasimte

I tried this code:

// loop_invariant is a statement attribute, so both features are required to compile.
#![feature(stmt_expr_attributes)]
#![feature(proc_macro_hygiene)]

use std::cmp::Ordering; // == core::cmp::Ordering; single-file kani is edition 2015

// binary_search_by's loop: the comparator closure receives the get_unchecked
// element by shared reference. The loop invariant implies `mid < len`.
fn search<F: FnMut(&u8) -> Ordering>(s: &[u8], mut f: F) {
    let len = s.len();
    if len == 0 {
        return;
    }
    let mut size = len;
    let mut base = 0usize;
    #[kani::loop_invariant(1 <= size && size <= len && base <= len - size)]
    while size > 1 {
        let half = size / 2;
        let mid = base + half; // invariant => mid = base + size/2 < len
        let cmp = f(unsafe { s.get_unchecked(mid) });
        base = if cmp == Ordering::Greater { base } else { mid };
        size -= half;
    }
}

// Same loop, element discarded (no closure): verifies.
fn search_no_closure(s: &[u8]) {
    let len = s.len();
    if len == 0 {
        return;
    }
    let mut size = len;
    let mut base = 0usize;
    #[kani::loop_invariant(1 <= size && size <= len && base <= len - size)]
    while size > 1 {
        let half = size / 2;
        let mid = base + half;
        let _ = unsafe { s.get_unchecked(mid) };
        base = if kani::any() { base } else { mid };
        size -= half;
    }
}

// Same loop and same closure call, but the value is copied out first: verifies.
fn search_copyval<F: FnMut(&u8) -> Ordering>(s: &[u8], mut f: F) {
    let len = s.len();
    if len == 0 {
        return;
    }
    let mut size = len;
    let mut base = 0usize;
    #[kani::loop_invariant(1 <= size && size <= len && base <= len - size)]
    while size > 1 {
        let half = size / 2;
        let mid = base + half;
        let v = unsafe { *s.get_unchecked(mid) };
        let cmp = f(&v);
        base = if cmp == Ordering::Greater { base } else { mid };
        size -= half;
    }
}

#[kani::proof]
fn check_with_closure() {
    let a: [u8; 8] = kani::any();
    let s: &[u8] = kani::slice::any_slice_of_array(&a);
    search(s, |_| if kani::any() { Ordering::Less } else { Ordering::Greater });
}

#[kani::proof]
fn check_no_closure() {
    let a: [u8; 8] = kani::any();
    let s: &[u8] = kani::slice::any_slice_of_array(&a);
    search_no_closure(s);
}

#[kani::proof]
fn check_copyval() {
    let a: [u8; 8] = kani::any();
    let s: &[u8] = kani::slice::any_slice_of_array(&a);
    search_copyval(s, |_| if kani::any() { Ordering::Less } else { Ordering::Greater });
}

using the following command line invocation:

kani search.rs -Z function-contracts -Z loop-contracts

with Kani version: 0.67.0 (release toolchain; CBMC 6.8.0).

I expected to see this happen: all three harnesses verify. The loop invariant proves mid < len, so get_unchecked(mid)'s precondition holds.

Instead, this happened: only check_with_closure fails.

Check ...: <usize as std::slice::SliceIndex<[u8]>>::get_unchecked.assume.1
 - Status: FAILURE
 - Description: "Rust intrinsic assumption failed"
 - Location: library/core/src/slice/index.rs:252:13   (path prefix elided)

Complete - 2 successfully verified harnesses, 1 failures, 3 total.

The loop_invariant base and step checks both pass. check_no_closure and check_copyval verify. The only change in check_copyval is that the element is copied out before the closure call, so no slice reference reaches the closure. The result is also the same across invariant forms (subtraction, addition, or a direct hint::assert_unchecked(mid < len)) and for both a concrete [u8] and a generic fn<T>. So the difference is the slice reference flowing into the closure, not the closure call itself.

This blocks a genuine-unbounded (loop-invariant rather than kani::unwind) proof of core::slice::binary_search_by, whose comparator is FnMut(&T) and must receive the element by reference.

An explicit #[kani::loop_modifies(...)] can't scope this either: the loop body's compiler temporaries are not nameable in such a clause (#4906), so a valid modifies set can't be formed.

Related but distinct from #4796: that is a method call in a loop-contract body being mis-lowered ("not enough arguments", nondet substitution); here the call succeeds and check_copyval (same closure call) verifies, so the trigger is the escaping slice reference rather than the call.

With a fix, check_with_closure should verify. Is this expected (a conservative over-approximation when a shared reference escapes into a closure), or a bug? Full harness and logs available.

Activity

  1. added
    Z-Contracts
    on Sep 30, 2026
  2. added this to the Contracts milestone on Sep 30, 2026
  3. kasimte commented on Oct 2, 2026

    @kasimte
    ContributorAuthor

    Root cause, from @tautschnig's review of #4938 (#4938 (review)): move_storagelive_call_to_loophead copies f(get_unchecked(mid)) to the loop head, so the precondition is checked there instead of at the call site. That explains both harnesses here: search fails (its cmp = f(..) call is moved), search_no_closure passes (let _ binds no variable for the pass to start from).

    Reproduces on 0.68 with no loop_modifies clause, so it is independent of explicit-clause handling (#4906). This issue can serve as the standalone tracker @tautschnig asked for.

  4. added
    [C] Bug
    [F] Spurious Failure
    on Nov 6, 2026
  5. added theissue type on Nov 6, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Z-Contracts[C] Bug[F] Spurious Failure

    Type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions