Skip to content

Challenge 16: Unbounded verification of core::iter::adapters (25/25 active targets, 292 Kani harnesses) - #807

Open
EmreKaplaner wants to merge 2 commits into
model-checking:mainfrom
EmreKaplaner:ch16-iter-adapters
Open

EmreKaplaner wants to merge 2 commits into
model-checking:mainfrom
EmreKaplaner:ch16-iter-adapters

Conversation

@EmreKaplaner

Copy link
Copy Markdown

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 (resolving model-checking/verify-rust-std#280).

  • Active target coverage: All 25 active targets in core::iter::adapters (8 unsafe functions + 17 safe abstractions; the remaining 2 items from the original issue list, Cloned::next_unchecked and Map::next_unchecked, were removed upstream in #687 / nightly-2026-09-25).
  • Total harnesses added: 292 (92 #[kani::proof_for_contract] + 200 #[kani::proof]), all unbounded with 0 #[kani::unwind] attributes, 0 assume(false), 0 #[cfg(not(kani))], and 0 loop_invariant(true).
  • Normal (non-Kani) build & upstream formatting: cargo check --manifest-path library/core/Cargo.toml -Z build-std=core builds cleanly with 0 new warnings; ./scripts/check_rustc.sh passes with 0 formatting diff against upstream rust-lang/rust ./x fmt --check.

Verification Matrix (All 25 Active Targets)

# Target Category Harnesses Contract Proof Notes
1 Cloned::__iterator_get_unchecked Unsafe fn 10 10 0 #[requires] + #[kani::modifies(self)]; includes mutating SideEffectSliceIter & TrackedDrop
2 Copied::__iterator_get_unchecked Unsafe fn 9 9 0 #[requires] + #[kani::modifies(self)]; includes SideEffectSliceIter
3 Enumerate::__iterator_get_unchecked Unsafe fn 10 10 0 #[requires(idx < self.iter.size_hint().0 && self.count.checked_add(idx).is_some())] (see Disclosures)
4 Fuse::__iterator_get_unchecked Unsafe fn 10 10 0 #[requires] covering both Some(iter) and None fused states
5 Map::__iterator_get_unchecked Unsafe fn 11 11 0 #[requires] + #[kani::modifies(self)]; includes StatefulMapper { calls: usize }
6 Skip::__iterator_get_unchecked Unsafe fn 15 15 0 #[requires] + prefix-drop loop invariant; includes mutating SideEffectSliceIter & Cloned<slice::Iter<TrackedDrop>>
7 Zip::__iterator_get_unchecked Unsafe fn 9 9 0 #[requires] + #[kani::modifies(self)]
8 ZipImpl::get_unchecked Unsafe fn 10 10 0 #[requires(idx < ZipImpl::size_hint(self).0 && ...)]; covers forward-advanced and backward-trimmed (index, len)
9 ArrayChunks::next_back_remainder Safe (+ array::write) 13 0 13 Unbounded loop invariant in core::array::write supporting arbitrary Take quota (init_n >= len) and generic TrustedLen (e.g. Range<usize>)
10 ArrayChunks::fold Safe 12 0 12 Unbounded chunk loop + inner array-build; includes mutating SideEffectSliceIter & OnlyTraNoCoerceIter
11 Copied::spec_next_chunk Safe 10 0 10 Unbounded slice backing; covers full Ok([T; N]) and short Err(IntoIter)
12 Filter::next_chunk_dropless Safe (conditional, see #153803) 11 0 11 Provenance-preserving *mut MaybeUninit<u8> RAII ghost state; includes re-entrant nested predicate harness
13 FilterMap::next_chunk Safe (conditional, see #153803) 13 0 13 Provenance-preserving *mut MaybeUninit<u8> RAII ghost state; includes CountedDrop exact drop-count verification
14 MapWindows::Buffer::as_array_ref Safe 12 0 12 Exact element-wise window assertions across 10 type layouts ((), AlignedZst, u8, bool, NonZero<u8>, [u8; 3], Padded, AlignedWord, [u8; 17], TrackedDrop)
15 MapWindows::Buffer::as_uninit_array_mut Safe 12 0 12 Exact initialized-slot write and invariant preservation assertions
16 MapWindows::Buffer::push Safe 12 0 12 Covers shift + non-shift paths; [u8; 17] (N = 2) detects exact N - 1 -> N OOB copy_nonoverlapping
17 MapWindows::Buffer::drop Safe 14 0 14 Linear non-Clone TokenDrop(NonZero<u8>) with DROPPED_TOKEN_MASK bitmask proving 1-to-1 bijection (zero double-drops, zero leaks, zero uninit drops)
18 StepBy::original_step Safe (+ contract) 16 8 8 Constructor-to-invariant proof (StepBy::new -> original_step) + #[ensures] postcondition
19 Take::spec_fold Safe 10 0 10 Unbounded loop invariant across arbitrary n and slice length
20 Take::spec_for_each Safe 10 0 10 Unbounded loop invariant across arbitrary n and slice length
21 Zip::fold Safe 11 0 11 Expanded loop_modifies(&accum, &f, &self.a, &self.b) with stateful move closure + mutating SideEffectSliceIter
22 Zip::next Safe 10 0 10 Arbitrary reachable (index, len) covering active and exhausted states
23 Zip::nth Safe 14 0 14 Both MAY_HAVE_SIDE_EFFECT = false and true paths across unbounded n (uses non-mutating NthSideEffectSliceIter, see Disclosures)
24 Zip::next_back Safe (see #161266) 16 0 16 Unbounded backward trim loop invariant; mixed side-effect harnesses exclude shorter-side-effect orientation (#161266)
25 Zip::spec_fold Safe 12 0 12 Covers TrustedLenSliceIter, SymbolicTrustedLenIter, WideTrustedLenIter (u128 > usize::MAX, more == true), and stdlib RepeatN<u8>
TOTAL 25 Active Targets 292 92 200 Exact inventory from kani-list.json (2,253 total verify-rust-std harnesses)

Transparent Disclosures & Upstream Tool / Std Limitations

  1. Filter::next_chunk_dropless & FilterMap::next_chunk (rust-lang/rust#153803) — Partial / Conditional Classification:
    Upstream core currently exhibits two soundness issues in Filter::next_chunk_dropless and FilterMap::next_chunk (rust-lang/rust#153803): (a) N == 0 on a nonempty input reaches an unchecked output write, and (b) for N >= 1, safety depends on the underlying iterator honoring ControlFlow::Break in Iterator::try_for_each (which safe Rust may override). In compliance with doc/src/general-rules.md (do not alter shipped runtime logic to patch std bugs in a verification PR), both targets are verified for N ∈ {1, 2, 3, 4} under cooperative try_for_each (including re-entrant nested predicate calls and counted drops) and classified transparently as conditional on an upstream fix to #153803.
  2. Zip::spec_fold #[inline(always)] fn fold_chunk helper (library/core/src/iter/adapters/zip.rs:735-770, called at :789):
    Pinned Kani's loop-contract MIR transform (move_storagelive_call_to_loophead) hoists kani_into_iter(0..upper) across the nested loop when both the outer while and inner for _ in 0..upper carry loop invariants in the same function body. Extracting the inner loop into a private local #[inline(always)] fn fold_chunk preserves 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 under doc/src/general-rules.md.
  3. CBMC --object-bits 12 Non-ZST Slice Ceiling (see committee unboundedness discussion in verify-rust-std#632):
    Under CBMC --object-bits 12 (52-bit pointer offsets), SymbolicSlice::any() bounds non-ZST backing allocations to backing_len <= (1 << 48) / size_of::<T>() to avoid CBMC offset overflow. ZST slices ((), AlignedZst) span full 0..=usize::MAX, and WideTrustedLenIter exercises u128 logical lengths exceeding usize::MAX.
  4. Monomorphization / Generic 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 sizes N ∈ {1, 2, 3, 4}, element poking for non-uniform values, and distinct linear TokenDrop ownership tokens.
  5. Four UB Classes & Kani Flag / Aliasing Limits (verify-rust-std#733):
    • Spatial / pointer safety & bounds / alignment / arithmetic overflow: Verified across all 292 harnesses in standard CI.
    • Mutating immutable bytes / aliasing (#733): Not modeled by Kani/CBMC (no Stacked/Tree Borrows checker); disclosed as unproven by the pinned tool. Likewise, TrustedRandomAccess access-history obligations (no duplicate index access for !Clone iterators such as slice::IterMut) are not modeled in contracts.
    • Invalid-value & uninitialized-memory checks (-Z valid-value-checks, -Z uninit-checks): Standard scripts/run-kani.sh CI omits these flags. Across all 25 active targets under -Z valid-value-checks, 21 / 25 PASS (4 Kani unsupported-type diagnostics for copy_nonoverlapping on *const MaybeUninit<...>, 0 real failures); under -Z uninit-checks, 12 / 25 PASS (12 unsupported diagnostics + 1 symbolic-slice timeout, 0 real failures). Combining both flags triggers Kani's internal MemoryInitializationState / closure-layout bug. Where the pinned checker cannot decide init/validity automatically, harnesses enforce ValidFill::slot_is_valid, exact element-wise assertions, and TokenDrop 1-to-1 bitmask accounting (FilterMap remainder uses CountedDrop + explicit drain/forget due to array::IntoIter::drop's unannotated slice loop).
  6. Enumerate::__iterator_get_unchecked Overflow Precondition, Map Contract Frame & Zip::nth Fixture:
    • Enumerate::__iterator_get_unchecked (enumerate.rs:167) requires self.count.checked_add(idx).is_some() alongside the memory-safety precondition idx < self.iter.size_hint().0 to prevent debug-mode arithmetic overflow panics under Kani's default overflow checks.
    • Map::__iterator_get_unchecked (and Cloned, Copied, etc.) uses #[cfg_attr(kani, kani::modifies(self))] (covering self.iter and stateful self.f, verified via StatefulMapper { calls: usize }); external writes outside self (e.g., captured &Cell or Rc refcount) cannot be expressed in Kani's generic function-contract frame.
    • Zip::nth side-effect harnesses use non-mutating NthSideEffectSliceIter (mod.rs:708-750) because mutating self.effects inside super_nth -> ZipImpl::next's conditional &mut call triggers Kani's car_set_insert auto-assigns bug; all other side-effect adapters (Cloned, Copied, Enumerate, Fuse, Map, Skip, Take, ArrayChunks::fold, Zip::fold, Zip::next, Zip::next_back) use mutating SideEffectSliceIter (self.effects += 1).
  7. Zip::next_back Mixed 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 via kani::assume because it hits the upstream debug_assert_eq! panic at zip.rs:471 (rust-lang/rust#161266).

CI & Verification Results

  • Format Check (./scripts/check_rustc.sh on Ubuntu 24.04 x86_64): PASS (exit 0, 0 diff against upstream rust-lang/rust ./x fmt --check).
  • Full verify-rust-std Linux Kani Suite (./scripts/run-kani.sh, WORKER_TOTAL=4, KANI_JOBS=6 on Ubuntu 24.04 c7i.8xlarge):
    • Partition 1/4: 564 / 564 PASS (0 failures, 16m 11s, 3.32 GiB peak RSS)
    • Partition 2/4: 564 / 564 PASS (0 failures, 25m 25s, 4.07 GiB peak RSS)
    • Partition 3/4: 564 / 564 PASS (0 failures, 19m 58s, 4.04 GiB peak RSS)
    • Partition 4/4: 561 / 561 PASS (0 failures, 24m 16s, 4.05 GiB peak RSS)
    • Total: 2,253 / 2,253 PASS (0 failures, 0 regressions, max partition peak RSS 4.07 GiB << 7 GiB)
  • Dedicated Challenge 16 Sweep:
    • Local macOS (aarch64-apple-darwin): 292 / 292 PASS, 724 / 724 cover properties satisfied (0 failures, 0 unsatisfied covers).
  • Negative-Test Perturbation Verification (26 perturbations across all 25 active targets): 26 / 26 detected (0 survivors, 0 timeouts/errors) with strict failure-property verification (VERIFICATION:- FAILED + Failed Checks: + non-timeout), including exact MapWindows::Buffer::push N - 1 -> N OOB copy_nonoverlapping detection (memcpy source region readable) and linear TokenDrop double-drop/uninit-drop detection.

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

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant