Repository navigation
Challenge 16: Unbounded verification of core::iter::adapters (25/25 active targets, 292 Kani harnesses) - #807
Open
EmreKaplaner wants to merge 2 commits into
Open
EmreKaplaner wants to merge 2 commits into
EmreKaplaner wants to merge 2 commits into
Conversation
This was referenced Dec 4, 2026
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Implements unbounded Kani formal verification contracts (
#[requires],#[ensures],#[kani::proof_for_contract]), loop invariants (#[safety::loop_invariant]), and verification harnesses (#[kani::proof]) for Challenge 16:core::iter::adapters(resolvingmodel-checking/verify-rust-std#280).core::iter::adapters(8 unsafe functions + 17 safe abstractions; the remaining 2 items from the original issue list,Cloned::next_uncheckedandMap::next_unchecked, were removed upstream in#687/nightly-2026-09-25).92#[kani::proof_for_contract]+200#[kani::proof]), all unbounded with0#[kani::unwind]attributes,0assume(false),0#[cfg(not(kani))], and0loop_invariant(true).cargo check --manifest-path library/core/Cargo.toml -Z build-std=corebuilds cleanly with 0 new warnings;./scripts/check_rustc.shpasses with 0 formatting diff against upstreamrust-lang/rust./x fmt --check.Verification Matrix (All 25 Active Targets)
Cloned::__iterator_get_unchecked#[requires]+#[kani::modifies(self)]; includes mutatingSideEffectSliceIter&TrackedDropCopied::__iterator_get_unchecked#[requires]+#[kani::modifies(self)]; includesSideEffectSliceIterEnumerate::__iterator_get_unchecked#[requires(idx < self.iter.size_hint().0 && self.count.checked_add(idx).is_some())](see Disclosures)Fuse::__iterator_get_unchecked#[requires]covering bothSome(iter)andNonefused statesMap::__iterator_get_unchecked#[requires]+#[kani::modifies(self)]; includesStatefulMapper { calls: usize }Skip::__iterator_get_unchecked#[requires]+ prefix-drop loop invariant; includes mutatingSideEffectSliceIter&Cloned<slice::Iter<TrackedDrop>>Zip::__iterator_get_unchecked#[requires]+#[kani::modifies(self)]ZipImpl::get_unchecked#[requires(idx < ZipImpl::size_hint(self).0 && ...)]; covers forward-advanced and backward-trimmed(index, len)ArrayChunks::next_back_remainderarray::write)core::array::writesupporting arbitraryTakequota (init_n >= len) and genericTrustedLen(e.g.Range<usize>)ArrayChunks::foldSideEffectSliceIter&OnlyTraNoCoerceIterCopied::spec_next_chunkOk([T; N])and shortErr(IntoIter)Filter::next_chunk_dropless#153803)*mut MaybeUninit<u8>RAII ghost state; includes re-entrant nested predicate harnessFilterMap::next_chunk#153803)*mut MaybeUninit<u8>RAII ghost state; includesCountedDropexact drop-count verificationMapWindows::Buffer::as_array_ref(),AlignedZst,u8,bool,NonZero<u8>,[u8; 3],Padded,AlignedWord,[u8; 17],TrackedDrop)MapWindows::Buffer::as_uninit_array_mutMapWindows::Buffer::push[u8; 17](N = 2) detects exactN - 1 -> NOOBcopy_nonoverlappingMapWindows::Buffer::dropCloneTokenDrop(NonZero<u8>)withDROPPED_TOKEN_MASKbitmask proving 1-to-1 bijection (zero double-drops, zero leaks, zero uninit drops)StepBy::original_stepStepBy::new->original_step) +#[ensures]postconditionTake::spec_foldnand slice lengthTake::spec_for_eachnand slice lengthZip::foldloop_modifies(&accum, &f, &self.a, &self.b)with statefulmoveclosure + mutatingSideEffectSliceIterZip::next(index, len)covering active and exhausted statesZip::nthMAY_HAVE_SIDE_EFFECT = falseandtruepaths across unboundedn(uses non-mutatingNthSideEffectSliceIter, see Disclosures)Zip::next_back#161266)#161266)Zip::spec_foldTrustedLenSliceIter,SymbolicTrustedLenIter,WideTrustedLenIter(u128 > usize::MAX,more == true), and stdlibRepeatN<u8>kani-list.json(2,253totalverify-rust-stdharnesses)Transparent Disclosures & Upstream Tool / Std Limitations
Filter::next_chunk_dropless&FilterMap::next_chunk(rust-lang/rust#153803) — Partial / Conditional Classification:Upstream
corecurrently exhibits two soundness issues inFilter::next_chunk_droplessandFilterMap::next_chunk(rust-lang/rust#153803): (a)N == 0on a nonempty input reaches an unchecked output write, and (b) forN >= 1, safety depends on the underlying iterator honoringControlFlow::BreakinIterator::try_for_each(which safe Rust may override). In compliance withdoc/src/general-rules.md(do not alter shipped runtime logic to patch std bugs in a verification PR), both targets are verified forN ∈ {1, 2, 3, 4}under cooperativetry_for_each(including re-entrant nested predicate calls and counted drops) and classified transparently as conditional on an upstream fix to#153803.Zip::spec_fold#[inline(always)] fn fold_chunkhelper (library/core/src/iter/adapters/zip.rs:735-770, called at:789):Pinned Kani's loop-contract MIR transform (
move_storagelive_call_to_loophead) hoistskani_into_iter(0..upper)across the nested loop when both the outerwhileand innerfor _ in 0..uppercarry loop invariants in the same function body. Extracting the inner loop into a private local#[inline(always)] fn fold_chunkpreserves the exact sequence of iterator and closure calls while enabling unbounded verification of both loops without modifying Kani. We flag this semantics-preserving extraction explicitly for maintainer review underdoc/src/general-rules.md.--object-bits 12Non-ZST Slice Ceiling (see committee unboundedness discussion inverify-rust-std#632):Under CBMC
--object-bits 12(52-bit pointer offsets),SymbolicSlice::any()bounds non-ZST backing allocations tobacking_len <= (1 << 48) / size_of::<T>()to avoid CBMC offset overflow. ZST slices ((),AlignedZst) span full0..=usize::MAX, andWideTrustedLenIterexercisesu128logical lengths exceedingusize::MAX.T&const N(verify-rust-std#734):Kani verifies concrete monomorphizations rather than polymorphic
T/N. Harnesses cover 11 concrete layout/niche/alignment/padding/drop classes ((),AlignedZst,u8,bool,NonZero<u8>,[u8; 3],Padded,AlignedWord,[u8; 17],TrackedDrop/CountedDrop,TokenDrop), chunk/window sizesN ∈ {1, 2, 3, 4}, element poking for non-uniform values, and distinct linearTokenDropownership tokens.verify-rust-std#733):#733): Not modeled by Kani/CBMC (no Stacked/Tree Borrows checker); disclosed as unproven by the pinned tool. Likewise,TrustedRandomAccessaccess-history obligations (no duplicate index access for!Cloneiterators such asslice::IterMut) are not modeled in contracts.-Z valid-value-checks,-Z uninit-checks): Standardscripts/run-kani.shCI omits these flags. Across all 25 active targets under-Z valid-value-checks,21 / 25PASS (4Kani unsupported-type diagnostics forcopy_nonoverlappingon*const MaybeUninit<...>,0real failures); under-Z uninit-checks,12 / 25PASS (12unsupported diagnostics +1symbolic-slice timeout,0real failures). Combining both flags triggers Kani's internalMemoryInitializationState/ closure-layout bug. Where the pinned checker cannot decide init/validity automatically, harnesses enforceValidFill::slot_is_valid, exact element-wise assertions, andTokenDrop1-to-1 bitmask accounting (FilterMapremainder usesCountedDrop+ explicit drain/forget due toarray::IntoIter::drop's unannotated slice loop).Enumerate::__iterator_get_uncheckedOverflow Precondition,MapContract Frame &Zip::nthFixture:Enumerate::__iterator_get_unchecked(enumerate.rs:167) requiresself.count.checked_add(idx).is_some()alongside the memory-safety preconditionidx < self.iter.size_hint().0to prevent debug-mode arithmetic overflow panics under Kani's default overflow checks.Map::__iterator_get_unchecked(andCloned,Copied, etc.) uses#[cfg_attr(kani, kani::modifies(self))](coveringself.iterand statefulself.f, verified viaStatefulMapper { calls: usize }); external writes outsideself(e.g., captured&CellorRcrefcount) cannot be expressed in Kani's generic function-contract frame.Zip::nthside-effect harnesses use non-mutatingNthSideEffectSliceIter(mod.rs:708-750) because mutatingself.effectsinsidesuper_nth -> ZipImpl::next's conditional&mutcall triggers Kani'scar_set_insertauto-assigns bug; all other side-effect adapters (Cloned,Copied,Enumerate,Fuse,Map,Skip,Take,ArrayChunks::fold,Zip::fold,Zip::next,Zip::next_back) use mutatingSideEffectSliceIter(self.effects += 1).Zip::next_backMixed Side-Effect Orientation (rust-lang/rust#161266):Both mixed side-effect harnesses (
check_zip_next_back_mixed_a_effect_u8,check_zip_next_back_mixed_b_effect_u8,zip.rs:1265-1285) cover the orientation where the effecting side is at least as long (len_effect >= len_plain), explicitly excluding the shorter-side-has-effects orientation viakani::assumebecause it hits the upstreamdebug_assert_eq!panic atzip.rs:471(rust-lang/rust#161266).CI & Verification Results
./scripts/check_rustc.shon Ubuntu 24.04 x86_64): PASS (exit 0, 0 diff against upstreamrust-lang/rust./x fmt --check).verify-rust-stdLinux Kani Suite (./scripts/run-kani.sh,WORKER_TOTAL=4,KANI_JOBS=6on Ubuntu 24.04c7i.8xlarge):0failures,16m 11s,3.32 GiBpeak RSS)0failures,25m 25s,4.07 GiBpeak RSS)0failures,19m 58s,4.04 GiBpeak RSS)0failures,24m 16s,4.05 GiBpeak RSS)0failures,0regressions, max partition peak RSS4.07 GiB<<7 GiB)aarch64-apple-darwin): 292 / 292 PASS, 724 / 724 cover properties satisfied (0failures,0unsatisfied covers).0survivors,0timeouts/errors) with strict failure-property verification (VERIFICATION:- FAILED+Failed Checks:+ non-timeout), including exactMapWindows::Buffer::pushN - 1 -> NOOBcopy_nonoverlappingdetection (memcpy source region readable) and linearTokenDropdouble-drop/uninit-drop detection.