Skip to content

Challenge 22: Verify the safety of str iter functions with Kani - #764

Open
DevinWatson wants to merge 5 commits into
model-checking:mainfrom
DevinWatson:ch22-str-iter-solution
Open

DevinWatson wants to merge 5 commits into
model-checking:mainfrom
DevinWatson:ch22-str-iter-solution

Conversation

@DevinWatson

@DevinWatson DevinWatson commented Nov 17, 2026 •

Copy link
Copy Markdown

Resolves #279

This pull request verifies Challenge 22 (library/core/src/str/iter.rs) with Kani over strings of unbounded symbolic length (0..=2^51 - 1 bytes) and arbitrary usize counts and byte offsets. It proves memory safety, pointer provenance, slice/char-boundary invariants, and safety postconditions for all 15 safe target functions with unsafe blocks, verifies Bytes::__iterator_get_unchecked against its safety contract via #[kani::proof_for_contract] (including arbitrary byte subslices starting mid-multibyte character, and additionally checked under -Z uninit-checks), checks initial constructor invariants across all 13 public &str iterator constructors (check_str_iter_initial_invariants), and adds harnesses for CharIndices::{next, next_back} and symbolic caller Chars::nth.

Key properties of the solution:

  • Zero production statement edits and zero #[cfg(not(kani))] body swaps: The diff adds +1,596 / -0 lines across library/core/src/str/iter.rs (+1,347 / -0), library/core/src/array/iter/iter_inner.rs (+239 / -0), and library/core/src/slice/iter.rs (+10 / -0). Only #[cfg(kani)] bindings/assertions, #[safety::loop_invariant] / #[cfg_attr(kani, kani::loop_modifies(...))] attributes on Chars::advance_by, and verification modules/helpers are added; library/core/src/ops/index_range.rs and every workflow/script are untouched.
  • Zero #[kani::unwind] attributes and zero static mut variables: All four loops in Chars::advance_by (the 32-byte chunk loop, its 32-element start_bytes fill loop, the continuation-byte skip loop, and the trailing char-by-char loop) are discharged inductively via loop invariants, and ModelSearcher stores its call/result bookkeeping in safe struct fields (nmb_calls, nmb_res) with zero global mutable statics.
  • Pure side-effect-free Chars::advance_by loop invariants & local state: Entry state (initial_remainder, original, original_ptr, original_full) is captured locally under #[cfg(kani)] inside Chars::advance_by so external callers (s.chars().nth(k), core::fmt, etc.) compose without harness setup. kani_char_loop_inv contains zero kani::assume calls; Challenge Assumption (4) is instantiated outside the invariant predicate on the immutable entry slice original (assume_original_utf8_at).
  • No core::slice::Iter method stubs: check_chars_advance_by runs the real shipped slice::Iter implementation (as_chunks::<32>(), chunks.next(), as_slice(), next(), advance_by()); slice/iter.rs adds only a read-only #[cfg(kani)] projection Iter::kani_parts_for_ch22 for loop invariants, and all 72/72 existing slice::iter harnesses pass.
  • Exact SWAR PolymorphicIter::kani_fold_arity32 & exact per-chunk tally (M3 and M5 closed): kani_fold_arity32 computes the exact Boolean sum of the 32-element chunk via branch-free row-first SWAR [u64; 4] read_unaligned (0 kani::any() nondeterminism) and drains self.alive to end..end identically to real PolymorphicIter::fold. check_kani_fold_arity32_soundness proves bit-for-bit equality against both real PolymorphicIter::fold and .into_iter().map(|v| v as u8).sum::<u8>() across all 2^32 [bool; 32] arrays and all valid subranges 0 <= start <= end <= 32 (16.64 s, 6/6 covers). Inside Chars::advance_by, the fill loop verifies start_bytes[i] == !utf8_is_cont_byte(chunk[i]) and the chunk step verifies remainder == rem_before_chunk - sum_bool32(&start_bytes), catching both fill-loop corruption (M5) and per-chunk under-counting (M3: remainder -= 1).
  • Explicit scalar/memory checks & -Z uninit-checks on Bytes: any_alloc initializes symbolic allocations via write_bytes + __CPROVER_havoc_slice, every char-producing harness explicitly asserts Unicode scalar validity (u <= 0x10FFFF && !(0xD800..=0xDFFF).contains(&u)), and check_bytes_iterator_get_unchecked also passes under -Z uninit-checks (0/323 failed, 3/3 covers, 3.36 s).

Disclosure: this solution was produced with AI assistance and verified against the repository's CI checks and fault-injection suite.

Rebase update (2026-11-23, commit f0bb11e63ce)

  • Rebased cleanly onto main (1feeadd9379, pinned to nightly-2026-11-19 and Kani 9834c96ce90f) with zero conflicts.
  • Updated impl Pattern for ModelPattern in library/core/src/str/iter.rs to unsafe impl Pattern for ModelPattern with a // SAFETY: justification for rust-lang/rust#165681 / verify-rust-std#753.
  • Keeps strict +1,596 / -0 zero production edits (str/iter.rs +1,347 / -0, array/iter/iter_inner.rs +239 / -0, slice/iter.rs +10 / -0); all harnesses, loop invariants, and postconditions are unchanged from 8276932eda2 below and re-checked on nightly-2026-11-19 / Kani 9834c96ce90f via CI.

Hardening update (2026-11-19, commit 8276932eda2)

Addressing every remaining gap from the 2026-11-18 revision (6fd1aafd04c) while keeping strict +N / -0 zero production edits, 0 unwinds, and 0 static mut:

  1. Closed M3 (remainder -= 1 per-chunk tally) and M5 (fill-loop inversion) on unbounded strings: Replaced the nondeterministic kani_fold_arity32 over-approximation with an exact row-first SWAR [u64; 4] sum (bool32_valid, sum_bool32, and kani_fold_arity32), proved bit-for-bit equal to real PolymorphicIter::fold and Iterator::sum over all 2^32 inputs and all subranges 0 <= start <= end <= 32 (check_kani_fold_arity32_soundness, 16.64 s, 6/6 covers). Both M3 and M5 are now caught directly by explicit CBMC property failures on check_chars_advance_by.
  2. Removed kani::assume from kani_char_loop_inv: kani_char_loop_inv is now completely side-effect-free (checking kani_valid_utf8_step(original, cur) purely), with Challenge Assumption (4) (assume_original_utf8_at) applied outside the invariant predicate on the immutable entry slice original (at loop-4 entry and after the unsafe step). This also reduced check_chars_nth_caller from 129 s / 6.69 GiB to 85.64 s / 6.20 GiB.
  3. Strengthened Bytes::__iterator_get_unchecked (proof_for_contract) & -Z uninit-checks: Upgraded to an arbitrary byte subslice s.as_bytes()[lo..hi] (0 <= lo <= hi <= s.len()), explicitly covering mid-multibyte cursors (lo > 0 && !s.is_char_boundary(lo)), and verified under -Z uninit-checks (0/323 failed, 3/3 covers, 3.36 s).
  4. Strengthened Chars::advance_by & SplitInternal postconditions: check_chars_advance_by now also asserts chars.as_str() length (total_len - consumed) and pointer (s.as_ptr().add(consumed)); SplitInternal::{next, next_inclusive, next_back, next_back_inclusive} now additionally verify exact matcher.front / matcher.back cursor transitions on both match and exhausted arms.

Re-verification on the exact pushed bytes (8276932eda2) (same pins and flags: nightly-2026-10-23, Kani c5e65fdfc3e1, CBMC 6.11.0, exact scripts/run-kani.sh flags, --object-bits 12, 8 GiB per CBMC process, --jobs=2):

  • str::iter::verify:: (--jobs=2): 25 / 25 SUCCESSFUL, 0 / 10,555 checks failed, 109 / 109 covers satisfied, wall 6m37.90s, peak RSS 6.20 GiB (down from 7m13s / 6.68 GiB).
  • array::iter::iter_inner::check_kani_fold_arity32_soundness: 1 / 1 SUCCESSFUL, 0 / 437 checks failed, 6 / 6 covers satisfied, 16.64 s, 1.67 GiB RSS.
  • slice::iter::verify:: (--jobs=2): 72 / 72 SUCCESSFUL, 0 / 26,932 checks failed, wall 4m40.92s, max 11.56 s, peak RSS 2.77 GiB.
  • Bytes::__iterator_get_unchecked with -Z uninit-checks: 1 / 1 SUCCESSFUL, 0 / 323 checks failed, 3 / 3 covers satisfied, 3.36 s.
  • ./scripts/check_rustc.sh (./x fmt --check on nightly-2026-10-23, 7,389 files): exit 0 (0:43).
  • Non-Kani RUSTC_BOOTSTRAP=1 cargo check -p core -p alloc: exit 0.

Fault injection on exact final bytes (8276932eda2, 6 / 6 caught strictly by explicit CBMC property failures, 0 survivors):

Mutant Line / Change Harness Result
M2 bytes_skipped += CHUNK_SIZE -> += CHUNK_SIZE - 1 check_chars_advance_by CAUGHT (407.19 s, Check invariant after step for loop advance_by.1)
M3 remainder -= start_bytes.into_iter()...sum::<u8>() as usize -> remainder -= 1 check_chars_advance_by CAUGHT (202.37 s, chunk remainder decremented by exact start_bytes count)
M4 let slurp = super::validations::utf8_char_width(b) -> let slurp = 1usize check_chars_advance_by CAUGHT (145.35 s, Check invariant after step for loop advance_by.3)
M5 start_bytes[i] = !utf8_is_cont_byte(chunk[i]) -> utf8_is_cont_byte(chunk[i]) check_chars_advance_by CAUGHT (235.16 s, fill loop records !utf8_is_cont_byte(chunk[i]))
M6 SplitInternal::next: self.start = b -> self.start = a check_split_internal_next CAUGHT (10.19 s, assertion failure)
M7 Bytes::__iterator_get_unchecked: #[requires(idx < self.0.len())] -> <= check_bytes_iterator_get_unchecked CAUGHT (3.24 s, dereference / out-of-bounds failure)

(Plus the 27-mutant baseline suite across all targets from the initial verification.)

What is assumed

All target harnesses construct strings using any_haystack(), allocating a symbolic byte length 0..=(1 << 51) - 1 (MAX_ALLOCATION_BYTES, matching --cbmc-args --object-bits 12; check_str_iter_initial_invariants also includes cover!(s.len() > (1usize << 48))) initialized via write_bytes(p, 0, len) followed by __CPROVER_havoc_slice(p, len) (check_arbitrary_initialized_buffer). No harness assumes a maximum string length or concrete byte content (see Limits for the 8-byte symbolic caller buffer in check_chars_nth_caller).

Where Challenge 22 permits assumptions 1–4 (doc/src/challenges/0022-str-iter.md), they are scoped as follows:

  1. Assumption 1 (slice module is safe and functionally correct): Real slice::Iter methods run unstubbed everywhere. Only the read-only accessor Iter::kani_parts_for_ch22(&self) -> (*const T, *const T) is added under #[cfg(kani)] in library/core/src/slice/iter.rs so Chars::advance_by loop invariants can state pointer arithmetic obligations. All 72/72 slice::iter harnesses pass.
  2. Assumption 2 (str::pattern is safe and functionally correct): SplitInternal, MatchIndicesInternal, and MatchesInternal harnesses instantiate Pattern with ModelPattern / ModelSearcher, a nondeterministic over-approximation yielding arbitrary ranges [a, b) that satisfy Searcher and ReverseSearcher safety contracts (lo <= a <= b <= hi, is_char_boundary(a) && is_char_boundary(b), zero-width matches/rejects permitted, Done allowed only once front == back). Inductive preservation of the searcher range invariant across all 4 operations is verified by check_model_searcher_step, and base-case initialization across all 13 public &str iterator constructors is verified by check_str_iter_initial_invariants. Compatibility with real CharSearcher (0..=4 bytes) and StrSearcher (1..=2 byte needles) was separately cross-checked in isolated out-of-patch bounded harnesses (9/9 passing).
  3. Assumption 3 (str::validations is functionally correct): Chars::{next, next_back}, CharIndices::{next, next_back}, and Chars::advance_by execute real next_code_point, next_code_point_reverse, and utf8_is_cont_byte. Only validations::utf8_char_width is stubbed in check_chars_advance_by and check_chars_nth_caller by the assumption-free branch table stub_utf8_char_width, proved identical to validations::utf8_char_width for all 256 possible u8 values by check_utf8_char_width_refinement.
  4. Assumption 4 (all str::iter iterators derive from valid UTF-8 &str): Harnesses encode local valid-UTF-8 facts at the cursor positions inspected:
    • Chars::next / CharIndices::next: is_valid_first_utf8_char (RFC 3629 Table 3-7 at the current front cursor).
    • Chars::next_back / CharIndices::next_back: is_valid_last_utf8_char (RFC 3629 Table 3-7 within the last 1..=4 bytes).
    • Chars::advance_by: entry byte 0 (if non-empty) is not a continuation byte (assume_original_utf8_at(&original, 0)), and assume_original_utf8_at is invoked outside the invariant predicate at loop-4 entry and after each unsafe step on the immutable entry slice original captured at entry (never consulting mutated self.iter, slurp, or remainder). kani_char_loop_inv itself is pure and side-effect-free. Out-of-patch bounded checks verified that core::str::from_utf8 implies assume_original_utf8_at and is_valid_{first,last}_utf8_char at every char boundary across all 0..=6 byte buffers.

Per-function results (8276932eda2, --jobs=2, 8 GiB CBMC cap)

Target / Helper Harness What is proved --jobs=2 (s)
Chars::next str::iter::verify::check_chars_next No UB; valid Unicode scalar value; consumed 1..=4 bytes matches ch.len_utf8(); equals RFC-3629 decode_first; covers None and widths 1..=4 2.33
Chars::advance_by str::iter::verify::check_chars_advance_by Unbounded string & arbitrary remainder: usize; inductive invariants on all 4 loops (pure kani_char_loop_inv); exact fill-loop check (M5) & exact SWAR chunk tally (M3); consumed <= len; tail.len() & tail.as_ptr(); Ok(()) => consumed >= remainder, Err(n) => len == 0 && remainder - n.get() <= len; 6/6 covers (4.73 GiB solo RSS) 236.33
Chars::advance_by (caller) str::iter::verify::check_chars_nth_caller Symbolic k: usize = kani::any() passed to .chars().nth(k) on 8-byte buffer populated from two arbitrary kani::any::<char>() scalars at offsets 0 and 4 plus symbolic ASCII fill bytes; scalar validity & membership; 6/6 covers (85.64 s / 6.20 GiB solo) 86.64
Chars::next_back str::iter::verify::check_chars_next_back No UB; valid Unicode scalar value; consumed 1..=4 bytes matches last_char_len and ch.len_utf8(); equals decode_first; covers None and widths 1..=4 30.80
Chars::as_str str::iter::verify::check_chars_as_str Subslice from arbitrary char-boundary [start, end) preserves valid slice range, pointer, length, and boundaries 2.79
SplitInternal::get_end str::iter::verify::check_split_internal_get_end Preserves split_invariant; sets finished = true; exact trailing slice [start, end) iff !was_finished && (allow_trailing_empty || end > start) 7.25
SplitInternal::next str::iter::verify::check_split_internal_next Preserves split_invariant, allow_trailing_empty, end, matcher.back; yields exact prefix/trailing slice [so, a) or [so, eo) and exact matcher.front cursor 17.90
SplitInternal::next_inclusive str::iter::verify::check_split_internal_next_inclusive Same invariants with inclusive piece [so, b) and exact matcher.front / matcher.back transitions 12.49
SplitInternal::next_match_back (next_back)* str::iter::verify::check_split_internal_next_back_via_matcher Preserves split_invariant; matches assert_next_back_spec via safe struct fields (nmb_calls/nmb_res) including !allow_trailing_empty empty-tail skip (2nd search) and exact matcher.front/matcher.back transitions; idempotent once finished 23.38
SplitInternal::next_back_inclusive str::iter::verify::check_split_internal_next_back_inclusive Same invariants for inclusive reverse piece [b, eo) / [b, e1), exact matcher cursors, and idempotence once finished 24.78
SplitInternal::remainder str::iter::verify::check_split_internal_remainder Exact slice [start, end) iff !finished on valid pointer and char boundaries 17.59
MatchIndicesInternal::next str::iter::verify::check_match_indices_internal_next Preserves searcher_invariant; returned (idx, sub) matches reported (a, b) at s.as_ptr().add(idx) on char boundaries 5.27
MatchIndicesInternal::next_back str::iter::verify::check_match_indices_internal_next_back Reverse match (idx, sub) equals (a, s[a..b]) on valid char boundaries 6.76
MatchesInternal::next str::iter::verify::check_matches_internal_next Preserves searcher_invariant; returned sub equals s[a..b] on valid char boundaries 5.06
MatchesInternal::next_back str::iter::verify::check_matches_internal_next_back Reverse substring sub equals s[a..b] preserving searcher_invariant 7.27
SplitAsciiWhitespace::remainder str::iter::verify::check_split_ascii_whitespace_remainder Exact [start, end) view iff !finished over valid subslice 1.54
Bytes::__iterator_get_unchecked str::iter::verify::check_bytes_iterator_get_unchecked (proof_for_contract) Satisfies #[requires(idx < self.0.len())] over arbitrary byte subslice s.as_bytes()[lo..hi] (covering mid-multibyte !is_char_boundary(lo)) and returns s.as_bytes()[lo + idx]; also passes under -Z uninit-checks (3.36 s) 2.29
13 public &str iterator constructors str::iter::verify::check_str_iter_initial_invariants Base-case initial invariants (start == 0, end == s.len(), !finished) and O(1) .as_ptr()/.len() remainder()/as_str() equality + s.len() > 2^48 witness 2.41
CharIndices::next (extra) str::iter::verify::check_char_indices_next Valid Unicode scalar value, exact byte offset start, updated offset() == start + ch.len_utf8(), RFC-3629 decode_first 25.94
CharIndices::next_back (extra) str::iter::verify::check_char_indices_next_back Valid Unicode scalar value, exact reverse offset end - k, remaining byte count (end - start) - k, RFC-3629 decode_first 56.40
PolymorphicIter::kani_fold_arity32 array::iter::iter_inner::check_kani_fold_arity32_soundness Exact bit-for-bit equality between real PolymorphicIter::fold, kani_fold_arity32, and Iterator::sum across all 2^32 [bool; 32] arrays and all subranges 0 <= start <= end <= 32, exact drained end..end, and surjectivity (6/6 covers) 16.64 (solo)
bool32_valid equivalence str::iter::verify::check_bool32_valid_equivalence SWAR [u64; 4] ((w[0] | w[1] | w[2] | w[3]) & 0xFEFE_FEFE_FEFE_FEFE) == 0 equals kani::mem::can_dereference::<[bool; 32]> (5/5 covers) 1.25
utf8_char_width refinement str::iter::verify::check_utf8_char_width_refinement Exact equality of validations::utf8_char_width(b) and raw_utf8_char_width(b) for all 256 u8 values 0.29
ModelSearcher step invariant str::iter::verify::check_model_searcher_step Inductive step proof across next, next_back, next_match, next_match_back 9.44
Pointer arithmetic helper str::iter::verify::check_chunk_pointer_expression Equivalence of arith_offset and wrapping_add over symbolic offsets 0.03
Symbolic allocation reachability str::iter::verify::check_arbitrary_initialized_buffer Witness covers for empty, multi-byte, distinct-byte symbolic any_alloc buffers 0.14

*Note: doc/src/challenges/0022-str-iter.md lists SplitInternal::next_match_back; in library/core/src/str/iter.rs, the corresponding method calling self.matcher.next_match_back() is SplitInternal::next_back, which is the method verified here.

Proof of Chars::advance_by (zero unwinds, zero globals, pure invariants)

  1. Loop 1 (chunk loop): Uses #[safety::loop_invariant] reading (cp, ce) = chunks.kani_parts_for_ch22() (read-only pointer accessor in library/core/src/slice/iter.rs) to track bytes_skipped % 32 == 0, bytes_skipped <= original_full, exact arith_offset pointer endpoints, and initial_remainder - remainder <= bytes_skipped.
  2. Loop 1 inner 32-element fill loop: Uses #[cfg_attr(kani, kani::loop_modifies(&raw mut start_bytes))] and #[cfg_attr(kani, kani::loop_invariant(... && verify::bool32_valid(&raw const start_bytes)))] (SWAR [u64; 4] validity predicate proved equal to kani::mem::can_dereference on [bool; 32]), plus an in-body kani::assert(start_bytes[i] == !utf8_is_cont_byte(chunk[i])) catching fill-loop corruption (M5), avoiding any #[kani::unwind(32)].
  3. Exact 32-element bool/u8 fold: Calls #[cfg(kani)] PolymorphicIter::kani_fold_arity32 (library/core/src/array/iter/iter_inner.rs, avoiding index_range.rs edits or kani#4084 generic-trait contract issues), computing the exact row-first SWAR Boolean sum over self.data[start..end] and draining self.alive to end..end, proved bit-for-bit identical to real PolymorphicIter::fold and Iterator::sum in check_kani_fold_arity32_soundness. Immediately after the subtraction, kani::assert(remainder == rem_before_chunk - sum_bool32(&start_bytes)) catches per-chunk tally bugs (M3).
  4. Loop 2 (continuation skip) & Loop 3 (remaining char steps): Discharged inductively by kani_cont_loop_inv (cur >= skipped && cur <= total_len) and the pure side-effect-free kani_char_loop_inv (cur <= total_len, kani_valid_utf8_step(original, cur), and initial_remainder - remainder <= cur), with Challenge Assumption (4) (assume_original_utf8_at) instantiated outside the invariant predicate on the immutable entry slice original.

Not proved, and limits

  1. String length ceiling (2^51 - 1 bytes): CBMC's pointer offset model under --cbmc-args --object-bits 12 limits allocations to (1 << 51) - 1 bytes on 64-bit targets. All lengths are symbolic below this bound and no arithmetic assumes a smaller bound. Termination is not proved.
  2. Local UTF-8 assumptions rather than whole-string construction: is_valid_{first,last}_utf8_char, assume_original_utf8_at, and kani_valid_utf8_step encode Assumption (4) locally on inspected cursor bytes rather than asserting whole-string UTF-8 well-formedness; kani_valid_utf8_step constrains leading-byte width to the next boundary without trailing-byte surrogate checks (sufficient for advance_by, and cross-checked out-of-patch up to 6 bytes against core::str::from_utf8).
  3. Fill-loop abstraction boundary: Because Kani's -Z loop-contracts requires a loop contract on the inner for i in 0..32 loop nested inside the contracted chunk loop, start_bytes is havoced to arbitrary valid [bool; 32] at fill-loop exit: every fill-loop iteration is verified to write !utf8_is_cont_byte(chunk[i]) (catching M5), and the subsequent fold/subtraction is verified to decrement remainder by the exact sum of start_bytes (catching M3), while full end-to-end whole-string exact character counting across an unbounded number of 32-byte chunks is not claimed (the challenge criteria are memory safety and contract compliance).
  4. Caller harness check_chars_nth_caller: Tests symbolic unbounded k: usize = kani::any() against .chars().nth(k) over an 8-byte malloc(8) buffer containing two arbitrary kani::any::<char>() Unicode scalars (c0 at offset 0, c1 at offset 4) and symbolic ASCII fill bytes (kani::any::<u8>() & 0x7F), keeping constant length 8 < 32 so Chars::advance_by's local loop invariants and Chars::next decoding compose without concrete literals (Iterator::nth is not a Challenge 22 target, and Chars::advance_by itself is verified over unbounded symbolic strings up to MAX_ALLOCATION_BYTES in check_chars_advance_by).
  5. Pattern model and inductive Split*/Match* proofs: Split*, Matches*, and MatchIndices* are proved inductively for one arbitrary transition from any invariant-satisfying state (next_back also proves idempotence when finished == true) against ModelPattern/ModelSearcher, while check_str_iter_initial_invariants proves the base-case initial invariants across all 13 public &str iterator constructors. Real CharSearcher (0..=4 bytes) and StrSearcher (1..=2 byte needles) compatibility was cross-checked out-of-patch (9/9 passing).
  6. Checks disabled in CI & pre-existing contract scope: Like all Kani harnesses in scripts/run-kani.sh, -Z valid-value-checks, -Z uninit-checks, and aliasing checks are not passed in CI (#733); allocations are explicitly zero-initialized and havoced, char validity is asserted explicitly, and check_bytes_iterator_get_unchecked was additionally verified under -Z uninit-checks (3.36 s, 0/323 failed). Pre-existing Bytes::__iterator_get_unchecked carries #[requires(idx < self.0.len())] only without #[ensures], while check_bytes_iterator_get_unchecked asserts val == s.as_bytes()[lo + idx] inside proof_for_contract. Also slice/iter.rs (+10 lines) and array/iter/iter_inner.rs (+239 lines) carry #[cfg(kani)] helpers/proofs outside str/iter.rs.

By submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0 and MIT licenses.

@DevinWatson
DevinWatson requested a review from a team as a code owner November 17, 2026 05:41
@feliperodri feliperodri added the Challenge Used to tag a challenge label Nov 18, 2026
…13-constructor invariants)

- Replace ModelSearcher global static mut NMB_CALLS/NMB_RES with safe struct fields
- Replace string literal in check_chars_nth_caller with symbolic 8-byte buffer (2 arbitrary chars + symbolic ASCII tail)
- Add check_str_iter_initial_invariants covering all 13 public &str iterator constructors and len > 2^48 witness
- Add exact 0..=32 range surjectivity covers to check_kani_fold_bounded32_soundness and remove internal helper cover
…at they actually do

Two verification-only renames, no semantic change to any proof:

- array/iter/iter_inner.rs: kani_fold_bounded32 -> kani_fold_arity32, and
  check_kani_fold_bounded32_soundness -> check_kani_fold_arity32_soundness. The
  32 is the chunk ARITY of as_chunks::<32>(), not a bound on the input string;
  Chars::advance_by still runs on a str of symbolic length up to
  MAX_ALLOCATION_BYTES. The doc comment now says so, and says the model is an
  over-approximation of the per-chunk reduction whose output range 0..=32 is
  still exact (soundness + range surjectivity in the same harness).
- str/iter.rs: check_split_internal_next_match_back ->
  check_split_internal_next_back_via_matcher, with a comment naming the arm it
  covers (self.matcher.next_match_back() inside SplitInternal::next_back).
  SplitInternal has no method of that name; issue model-checking#279 notes the page's wording.

Re-verified on the new bytes at the pinned tools (nightly-2026-10-23, Kani
c5e65fdfc3e1, CI flags, --object-bits 12, 8 GiB per CBMC process): 26/26
SUCCESSFUL (25 str::iter::verify + array::iter), 7m13s wall, 6.68 GB peak RSS.
…loop invariant, and arbitrary-subslice Bytes proof
@DevinWatson
DevinWatson force-pushed the ch22-str-iter-solution branch 2 times, most recently from 726126f to f0bb11e Compare November 23, 2026 17:03

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

Challenge Used to tag a challenge

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Challenge 22: Verify the safety of str iter functions

2 participants