Skip to content

#[kani::loop_invariant] with a method call lowers the call with "not enough arguments", substituting a non-deterministic value #4796

Open

Description

@kasimte

Calling a method inside a #[kani::loop_invariant] expression makes that part of the invariant evaluate to a fresh non-deterministic value instead of the method's result. The invariant that gets checked is not the one written.

I tried this code:

#![feature(proc_macro_hygiene)]
#![feature(stmt_expr_attributes)]

struct Counter { n: usize }
impl Counter {
    fn remaining(&self) -> usize { self.n }
    fn take_one(&mut self) -> Option<usize> {
        if self.n > 0 { self.n -= 1; Some(self.n) } else { None }
    }
}

#[kani::proof]
fn method_call_in_loop_invariant() {
    let mut c = Counter { n: kani::any() };
    let upper = c.remaining();
    #[kani::loop_invariant(kani::index <= upper && c.remaining() == upper - kani::index)]
    for _ in 0..upper {
        let v = c.take_one();
        assert!(v.is_some(), "invariant guarantees remaining > 0 here");
        let _ = v;
    }
}

using the following command line invocation:

kani repro.rs -Z loop-contracts

with Kani version: built from source at 152c6a8c875d9886a67e229247b4826d6105ccfd (the model-checking/verify-rust-std pin; kani --version reports 0.67.0), CBMC 6.10.0, macOS/aarch64. I have not yet re-tested against current main.

I expected to see this happen: verification succeeds. The invariant is true at entry, since upper is read from c.remaining() on the previous line. It stays true because take_one decrements remaining by exactly one per iteration. And it implies the body's assert.

Instead, this happened: symex prints this three times

file repro.rs line 16 column 52 function method_call_in_loop_invariant::{closure#0}: call to '_RNvMCs7F9CNELb43h_5reproNtB2_7Counter9remaining': not enough arguments, inserting non-deterministic value

and verification fails on the base-case check and the assert:

Check 15: method_call_in_loop_invariant.loop_invariant_base.1
	 - Status: FAILURE
	 - Description: "Check invariant before entry for loop method_call_in_loop_invariant.0"
	 - Location: repro.rs:16:5 in function method_call_in_loop_invariant

Check 24: method_call_in_loop_invariant.assertion.2
	 - Status: FAILURE
	 - Description: ""invariant guarantees remaining > 0 here""
	 - Location: repro.rs:19:9 in function method_call_in_loop_invariant

The base case failing is what points at the lowering: at entry the written invariant is true by construction, so the check must be evaluating c.remaining() as something else. Per the message, an inserted non-deterministic value.

Two more data points from the same build. Replacing the clause with a deliberately false one (c.remaining() == 424242) also fails, so the check does run, just against the substituted value. And a variant whose body doesn't need the method clause verifies SUCCESSFUL while the same message prints, which means a proof can pass with a different invariant than the one written.

The loop-contracts docs say the invariant "accepts a valid Boolean expression cond over the variables visible at the same scope as the loop", with side-effect freedom as the stated restriction. c.remaining() is a side-effect-free call over an in-scope variable, so I would read this usage as supported.

I hit this on <Zip<A, B> as SpecFold>::spec_fold while working on Challenge 16 in model-checking/verify-rust-std: the inner loop's only sound invariant is the TrustedLen relation remaining == upper - index, and remaining is only reachable through size_hint, so that loop cannot carry a working contract. Invariants over fields and locals are the only form I have found that works.

Activity

  1. added
    [C] Bug
    on Sep 15, 2026
  2. added theissue type on Sep 18, 2026
  3. added this to the Contracts milestone on Sep 18, 2026
  4. Talha-Dmr commented on Sep 29, 2026

    @Talha-Dmr
    Contributor

    Some data on when the "not enough arguments" warning appears, and on which argument is missing. Same Kani pin (152c6a8, 0.67.0), CBMC 6.10.0, Arch Linux x86_64.

    The warning appears only when the function called in the invariant is also called from ordinary code in the harness. A helper that is called only from the invariant does not trigger it:

    #![feature(stmt_expr_attributes)]
    #![feature(proc_macro_hygiene)]
    
    fn get(x: &usize) -> usize { *x }
    fn get_only_in_invariant(x: &usize) -> usize { *x }
    
    #[kani::proof]
    fn only_in_invariant() {
        let mut i: usize = 0;
        let mut j: usize = 0;
        #[kani::loop_invariant(i <= 4 && get_only_in_invariant(&j) == i)]
        while i < 4 { i += 1; j += 1; }
        assert!(j == 4); // needs the helper clause
    }
    
    #[kani::proof]
    fn also_called_outside() {
        let mut i: usize = 0;
        let mut j: usize = 0;
        let _ = get(&j);
        #[kani::loop_invariant(i <= 4 && get(&j) == i)]
        while i < 4 { i += 1; j += 1; }
        assert!(j == 4); // needs the helper clause
    }
    kani invariant_call.rs -Z loop-contracts --harness only_in_invariant --exact    # no warning, SUCCESSFUL
    kani invariant_call.rs -Z loop-contracts --harness also_called_outside --exact  # warning x3, SUCCESSFUL
    

    In the instrumented goto binary (--keep-temps), the two call sites of get differ in arity:

    // inside the invariant closure also_called_outside::{closure#0}
    CALL var_4 := get(var_7)
    // ordinary call in the harness body
    CALL var_3 := get(var_4, also_called_outside::__write_set_to_check)
    

    So the argument CBMC replaces with a non-deterministic value is the DFCC write-set parameter that the instrumentation adds to get. The call inside the invariant closure is not rewritten to pass it. In this example the call's return value is still correct: also_called_outside verifies, and its post-loop assertion depends on the get(&j) == i clause. A variant with a false clause (get(&j) == i + 7) still fails Check invariant before entry. For a callee that declares or writes memory, the instrumented body then runs with a nondet write-set pointer, which could explain the spurious base-case failure in the original report.

    This is also why calls to std methods such as v.len(), s.capacity() or p.wrapping_add(j) inside an invariant always warn. The harness or the loop body calls them too, so they are instrumented. A helper used only by the invariant does not avoid the warning if it calls such a method: fn lenof(v: &Vec<u8>) -> usize { v.len() } produces the warning on the inner Vec::len call.

    Workaround that works for us: invariants that use only locals, fields, arithmetic and kani::forall! with the predicate written inline, plus helpers that are called only from invariants.

  5. added
    Z-Contracts
    on Sep 29, 2026
  6. Talha-Dmr commented on Oct 14, 2026

    @Talha-Dmr
    Contributor

    I looked at this again on current main (328e6b8, CBMC 6.11.0). There are two separate things here, and I need to correct the guess in my previous comment.

    1. The failures in the original report do not come from the call in the invariant. With c.n instead of c.remaining() in the invariant there is no "not enough arguments" warning, and the same two checks fail:

    #[kani::loop_invariant(kani::index <= upper && c.n == upper - kani::index)]
     ** 2 of 221 failed
    Failed Checks: Check invariant before entry for loop method_call_in_loop_invariant.0
    Failed Checks: "invariant guarantees remaining > 0 here"
    VERIFICATION:- FAILED
    

    They come from the first statement of the loop body, let v = c.take_one();. In the CBMC trace of the base-case failure (original repro, --keep-temps, then cbmc --trace on the kept goto binary), take_one runs once before the loop head: c.n goes from 35184372088833 to 35184372088832 inside Counter::take_one, and only then does the trace reach __entered_loop__0=FALSE and __in_base_case=TRUE. The invariant snapshot taken in between calls remaining(), which returns 35184372088832 while upper is 35184372088833. So remaining() returns the right value; the state has already changed. This matches the copy of a call that initializes a body local to the loop head described in #4949 (move_storagelive_call_to_loophead); I have not looked at the transformed MIR of this repro to confirm it.

    The method and the struct are not needed. With a free function on a local:

    fn take(n: &mut usize) -> Option<usize> {
        if *n > 0 { *n -= 1; Some(*n) } else { None }
    }
    
    #[kani::proof]
    fn v4_free_fn_option_assert() {
        let n0: usize = kani::any();
        let mut n = n0;
        let mut i: usize = 0;
        #[kani::loop_invariant(i <= n0 && n == n0 - i)]
        while i < n0 {
            let v = take(&mut n);
            assert!(v.is_some());
            i += 1;
        }
    }

    the same two checks fail (Check invariant before entry for loop v4_free_fn_option_assert.0 and assertion failed: v.is_some()). With let _ = take(&mut n); and no assertion, it verifies. A for loop that decrements c.n directly in the body, with the original invariant written over c.n, also verifies.

    2. The "not enough arguments" warning is a CBMC DFCC issue. It reproduces without Kani:

    // kani#4796 at the CBMC level: a function called both from a loop invariant and from ordinary code.
    int get(int *x) { return *x; }
    int get_inv_only(int *x) { return *x; }
    #ifndef ORDINARY_CALL
    #define ORDINARY_CALL 1
    #endif
    void main()
    {
      int i = 0, j = 0, k = 0;
    #if ORDINARY_CALL
      k = get(&j); // makes `get` part of the call graph, so DFCC instruments it
    #endif
      while(i < 4)
        __CPROVER_assigns(i, j)
        __CPROVER_loop_invariant(i <= 4 && GETTER(&j) == i)
      {
        i++;
        j++;
      }
      __CPROVER_assert(j == 4, "needs the invariant's call");
    }
    goto-cc -DORDINARY_CALL=1 -DGETTER=get inv_call.c -o t.gb
    goto-instrument --dfcc main --apply-loop-contracts --disable-loop-contracts-side-effect-check t.gb t.i.gb
    cbmc t.i.gb
    
    ORDINARY_CALL GETTER warnings result
    0 get 0 SUCCESSFUL
    0 get_inv_only 0 SUCCESSFUL
    1 get 3 SUCCESSFUL
    1 get_inv_only 0 SUCCESSFUL
    file inv_call.c line 15 function main: call to 'get': not enough arguments, inserting non-deterministic value
    

    From reading CBMC 6.11.0: DFCC adds the __write_set_to_check parameter to every function it instruments (dfcc_instrument.cpp, the add_parameter calls at lines 333 and 371), and instrument_call_instruction (lines 842-865) appends the write set at a call site when the callee is instrumented. The invariant is turned into instructions by goto_convert in dfcc_instrument_loop.cpp (lines 268-275 for the base-case snapshot, and again for the step case from line 431), and those call instructions are not passed through instrument_call_instruction. A function that is reached only from the invariant is not instrumented at all, so it gets no extra parameter and no warning (get_inv_only above). The relevant code is unchanged on develop (32441ee38f).

    In the examples I tried, the call still returned the right value: the argument that is missing is only the write-set pointer. When the callee itself writes memory, the instrumented callee runs with a nondeterministic write-set pointer. With a get that copies *x into a local through a pointer, CBMC 6.11.0 verifies the variant without the ordinary call, but on the variant with it, CBMC did not finish: it reached a 6 GB memory limit within a minute and was still running after 7 minutes, when I stopped it. I have not found a case where the warning changes a verdict.

    So the fix for the warning would be in CBMC (pass the write set, or NULL, at the call sites generated from loop contract clauses, and treat functions reached from those clauses as part of the instrumented call graph), and the base-case failure in the original report is most likely #4949.

  7. self-assigned this
    on Oct 14, 2026
  8. r-near commented on Oct 28, 2026

    @r-near
    Contributor

    Kani's own contract helpers hit this in every proof_for_contract harness, e.g.:

    #[kani::requires(x < 100)]
    #[kani::ensures(|r: &u8| *r == x + 1)]
    fn inc(x: u8) -> u8 { x + 1 }
    
    #[kani::proof_for_contract(inc)]
    fn check_inc() { inc(kani::any()); }
    function kani::internal::enter_contract_clause: call to '..saturating_add': not enough arguments, inserting non-deterministic value
    function kani::internal::exit_contract_clause: call to '..saturating_sub': not enough arguments, inserting non-deterministic value
    

    __VERIFIER_kani_{enter,exit}_contract_clause aren't instrumented but call saturating_add/saturating_sub, which are. Harmless here, but it hides the cases that matter. PR to follow.

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

Metadata

Metadata

Assignees

Labels

Z-Contracts[C] Bug

Type

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions