Repository navigation
Description
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
Talha-Dmr commentedon Sep 29, 2026
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:
In the instrumented goto binary (
--keep-temps), the two call sites ofgetdiffer in arity: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_outsideverifies, and its post-loop assertion depends on theget(&j) == iclause. A variant with a false clause (get(&j) == i + 7) still failsCheck 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()orp.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 innerVec::lencall.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.Talha-Dmr commentedon Oct 14, 2026
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.ninstead ofc.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)]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, thencbmc --traceon the kept goto binary),take_oneruns once before the loop head:c.ngoes from 35184372088833 to 35184372088832 insideCounter::take_one, and only then does the trace reach__entered_loop__0=FALSEand__in_base_case=TRUE. The invariant snapshot taken in between callsremaining(), which returns 35184372088832 whileupperis 35184372088833. Soremaining()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:
the same two checks fail (
Check invariant before entry for loop v4_free_fn_option_assert.0andassertion failed: v.is_some()). Withlet _ = take(&mut n);and no assertion, it verifies. Aforloop that decrementsc.ndirectly in the body, with the original invariant written overc.n, also verifies.2. The "not enough arguments" warning is a CBMC DFCC issue. It reproduces without Kani:
ORDINARY_CALLGETTERgetget_inv_onlygetget_inv_onlyFrom reading CBMC 6.11.0: DFCC adds the
__write_set_to_checkparameter to every function it instruments (dfcc_instrument.cpp, theadd_parametercalls at lines 333 and 371), andinstrument_call_instruction(lines 842-865) appends the write set at a call site when the callee is instrumented. The invariant is turned into instructions bygoto_convertindfcc_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 throughinstrument_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_onlyabove). The relevant code is unchanged ondevelop(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
getthat copies*xinto 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.r-near commentedon Oct 28, 2026
Kani's own contract helpers hit this in every
proof_for_contractharness, e.g.:__VERIFIER_kani_{enter,exit}_contract_clausearen't instrumented but callsaturating_add/saturating_sub, which are. Harmless here, but it hides the cases that matter. PR to follow.Avoid saturating method calls in contract clause depth helpers (model…