Skip to content

Challenge 18: Unbounded verification for Slice Iter safety with Kani - #744

Open
v3risec wants to merge 9 commits into
model-checking:mainfrom
v3risec:challenge-18-slice-iter
Open

v3risec wants to merge 9 commits into
model-checking:mainfrom
v3risec:challenge-18-slice-iter

Conversation

@v3risec

@v3risec v3risec commented Nov 3, 2026 •

Copy link
Copy Markdown

Summary

The suite checks all 82 distinct listed methods present in this Std snapshot across seven concrete element types. The audited local results record passes for 785 typed harnesses and 14 auxiliary proofs, including all 63 typed nth_back harnesses. Slice lengths, chunk sizes, cursor positions and skip counts are symbolic.

The changes are confined to library/core/src/slice/iter.rs, library/core/src/slice/iter/macros.rs and library/core/src/ptr/mut_ptr.rs. The first two files hold the iterator harnesses, contracts and loop annotations. The third adds the contract for the raw split callee. All 208 production iterator bodies match the base after stripping proof annotations and Kani-only ghost state. The raw split body also matches the base.

Two groups in the local suite depend on Kani fixes for ZST offset lowering and native assertion failures. Kani #5202 · Kani #5203

Element types

Type Size / alignment on the local target What it exercises
u8 1 / 1 Ordinary byte access and unit stride
bool 1 / 1 Restricted scalar representations, including validity after a modeled write
[u8; 3] 3 / 1 Non-power-of-two element stride in pointer arithmetic
Padded 8 / 4 A repr(C) layout with padding and distinct size and alignment
AlignedWord 32 / 32 A nonzero-sized element with 32-byte stride and alignment
() 0 / 1 Zero byte displacement with lengths up to usize::MAX
AlignedZst 0 / 16 Alignment requirements when the element has no storage

The harness macros share the proof logic across these layouts. [u8; 3] is the element type. Its slice length remains symbolic.

Harnesses

Each listed method executes its real implementation. The table counts method-and-implementation pairs. Each pair has evidence at all seven element types. The ArrayWindows instantiations also vary the const width.

Part 1 — Iterator macros

Implementation Methods Count
Iter and IterMut from iterator! make_slice, len, is_empty, next, size_hint, count, nth, advance_by, last, fold, for_each, position, rposition, next_back, nth_back, advance_back_by 32
SplitN, SplitNMut, RSplitN and RSplitNMut from forward_iterator! next and size_hint for each implementation 8

check_new_and_queries checks construction and the cursor queries on Iter and IterMut. The step and loop harnesses check the remaining view, the returned reference or exhaustion, and the admissible writes. Separate ZST size_hint harnesses exercise the checked-overflow path for unfinished splits with maximal length.

Part 2 — Safe methods

Implementation Methods Count
Iter new 1
IterMut new, into_slice, as_mut_slice 3
Split next, next_back 2
Chunks next_back 1
ChunksMut next, nth, next_back, nth_back 4
ChunksExact and RChunksExact new for each implementation 2
ChunksExactMut and RChunksExactMut new, next, nth, next_back, nth_back for each implementation 10
ArrayWindows next, nth, next_back, nth_back, at widths 1, 2 and 4 4
RChunks next, next_back 2
RChunksMut next, nth, last, next_back, nth_back 5
Total 34

These proofs cover in-range and exhausted calls. Where applicable, they check the returned pointer and length, containment within the input, disjoint mutable regions and access to the returned elements.

Part 2 — Unchecked getters

Eight existing listed implementations of __iterator_get_unchecked have native proof_for_contract harnesses named check_get_unchecked_contract in their corresponding type and iterator modules. The implementations are Windows, Chunks, ChunksMut, ChunksExact, RChunks, RChunksMut, RChunksExact and RChunksExactMut. The proofs supply the legal index, execute the getter, and check its return region and write frame.

The challenge table has two ChunksExact rows. ArrayChunks and ArrayChunksMut are absent from this snapshot. Additional coverage includes a native contract proof for ChunksExactMut and direct body proofs for the ArrayWindows getter at widths 1, 2 and 4.

Upstream harness coverage

The upstream suite had 72 Iter harness instances. The symbolic suite replaces 28 for () and u8. Of these, 22 exercise 11 methods listed in Challenge 18, including Iter::new. The other six exercise the internal contracts for next_back_unchecked, post_inc_start and pre_dec_end.

The 44 retained regressions cover the original fixed-size char and (char, u8) cases and the direct Default, Clone, as_slice and AsRef checks for () and u8. These runs supplement the symbolic Challenge 18 matrix.

Symbolic inputs and loop proofs

  • SymbolicSlice starts from initialized backing storage and selects an arbitrary aligned interior start and admissible length. The harnesses exercise empty and interior views, full chunks, partial chunks and remainders where applicable. Non-ZST allocations follow Rust's layout limit and CBMC's representable object-offset range with --object-bits 12. ZST lengths span usize.
  • fold, for_each, position and rposition use inductive loop contracts. The invariants track the cursor and unconsumed range. The write frames account for the accumulator, callback state and writable elements where applicable. All 56 primary loop harnesses record loop contracts in the native results. Unwinding checks stay enabled and the suite supplies no explicit unwind limits.
  • There are 45 explicit assume or any_where sites in the iterator proof module, each immediately followed by a cover. The proof templates also cover relevant success, exhaustion, boundary and maximal-ZST paths. check_bool_validity_predicate checks valid and invalid raw encodings. check_observed_invalid_write_is_detected checks that writing an invalid byte at the observed index is detected.

Verified callees

The stub_verified uses below bind to independently proved callee contracts. Kani checks the preconditions at each summarized call.

Callee Callers using the summary Independent evidence
size_hint on ChunksMut, ChunksExactMut, RChunksMut and RChunksExactMut 28 typed nth_back proofs Each family's check_size_hint_contract runs the real method at the same type. It proves equal lower and upper hints. The ChunksExactMut contract also bounds the lower hint by the slice length.
<*mut [[u8; 3]]>::split_at_mut_unchecked Six triplet step proofs across ChunksMut, ChunksExactMut and RChunksExactMut check_triplet_split_at_mut_unchecked_contract runs the raw split and checks the returned pointers, lengths, writeability and empty write frame.
triplet_chunk_region Four triplet exact-getter proofs check_triplet_chunk_region proves same-allocation and access facts for a complete subregion of an accessible input slice.

The size_hint contracts admit more results than the actual methods return. Mutable nth_back proofs therefore audit checked panics separately from memory-safety properties. In the six CVC5 ChunksExactMut::nth_back replays, the recorded panics are the checked multiply, checked add and split-bound assertion.

Proof cost

The four exact [u8; 3] getter harnesses describe the main view and remainder in byte coordinates. check_triplet_getter_input_domain maps the original input partition to the same allocation extent, offsets and view lengths. With remaining length L, positive chunk size s and legal index i, the complete chunk starts at i * s in the forward case and L - i * s - s in the reverse case. The native contract proof runs the original getter and checks its returned pointer and length, same allocation, containment and access obligations.

Exact triplet getter Consolidated local build Replay with both submitted fixes Satisfied replay covers
ChunksExact 59.78 s 63.51 s 19
ChunksExactMut 107.41 s 152.30 s 20
RChunksExact 80.70 s 142.18 s 19
RChunksExactMut 159.72 s 179.64 s 20

Combining equivalent input guards reduced the total solver time for these four harnesses from 857.36 s to 407.61 s in the same-build comparison. Every getter-owned cover passed in the replay. Each shared getter also reports one unreachable helper cover for a compile-time writable-input branch.

Local results and toolchain

Each ZST layout contributes 115 passing typed harnesses. Each of the five non-ZST layouts contributes 111. The matrix retains results from the compatible Kani baseline and the local tool-fix builds where the source and proof obligations match.

A fresh replay of both submitted fixes on Kani 0aac16ef used the original Std source, nightly-2026-10-23, CBMC 6.11.0 and each harness's declared solver. The replay adapts the compiler API and stub-pass registration to that baseline.

Replay group Passing
Exact ZST getter contracts previously failing pointer checks 8/8
CVC5 ChunksExactMut::nth_back previously stopped by CBMC status 6 6/6
Exact [u8; 3] getters 4/4
Matching size_hint contracts, triplet domain proof and subregion contract 8/8

All 26 replay harnesses completed within the per-harness timeout. The slowest took 326.66 s. The measured peak process-tree RSS was 2.33 GiB in the serial Linux run.

  • For a zero-sized pointee, arith_offset returns the original pointer. The fix evaluates both operands in order, including projected reads. Kani #5202
  • Native comparison and pattern assertion failures lower through Kani's GOTO panic model before reachability collects the diagnostic formatter graph. The fix preserves operand evaluation and honors enabled stubs. Kani #5203

The exact PR heads cb10fb8 and 55d33cc also build together on Kani main c25a57bc. That build produced the expected results for six positive and six expected-failure harnesses across eight tool regression files. It uses nightly-2026-11-18, which stopped the original Std source at core compilation on built-ins including pattern_type
and view_type. Hosted verification awaits a compatible Kani pin containing the fixes.

Limits

Area Scope of the evidence
Generic T The seven concrete Copy types exercise distinct layout and validity properties. A proof for arbitrary generic T remains outside this submission. Callback and accumulator proofs likewise use concrete models. Generic-type discussion #734
Const widths ArrayWindows executes its typed bodies at N = 1, 2, 4. A separate arithmetic proof checks the bounds for arbitrary positive widths.
Initialization and value validity Inputs are initialized by the slice model. The bool observation checks the modeled representation at an arbitrary selected element. The dedicated uninit-checks and valid-value-checks passes are disabled.
Reference permissions The proofs check spatial access, explicit write frames and selected retained-reference and disjointness properties. Full Rust borrow permissions, immutable-byte guarantees and arbitrary unchecked access histories remain outside the model. UB modeling discussion #733
Panic paths and functional behavior The local checks use checked arithmetic and panic-abort. Modular hint summaries can admit additional checked panics. The proof records those properties separately and checks the modeled memory-safety obligations. Dynamic diagnostic formatting is outside Kani's modeled panic path.

Resolves #282

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

@v3risec
v3risec requested a review from a team as a code owner November 3, 2026 08:24
@feliperodri feliperodri added the Challenge Used to tag a challenge label Nov 3, 2026
@v3risec v3risec changed the title Challenge 18: Verify Slice Iter safety with Kani Challenge 18: Unbounded verification for Slice Iter safety with Kani Nov 19, 2026
@v3risec

v3risec commented Nov 19, 2026 •

Copy link
Copy Markdown
Author

Verification update

The audited local matrix covers 785/785 typed harnesses and 14/14 auxiliary proofs, including all 63 typed nth_back cases and the four [u8; 3] exact getters. It covers all 82 distinct required implementations present in this Std snapshot. The evidence uses symbolic lengths and keeps unwinding checks enabled without an explicit unwind bound.

  • Each required target executes its real implementation. The four triplet exact getters keep their native getter contracts. An arithmetic input-domain proof preserves their allocation and range coordinates, and a separate subregion proof establishes access to the selected chunk.
  • The runtime body audit is clean. Every explicit assume or any_where is followed by a cover. The mutable nth_back and selected triplet proofs use verified summaries only for independently checked callees.

Toolchain follow-up

The submitted fixes cover ZST pointer identity and early lowering of native assertion failures. The exact PR heads build together on Kani main c25a57bc, and all eight targeted tool regression files gave their expected results. With nightly-2026-11-18, the original nightly-2026-10-23 Std source stops at core compilation before verification.

Replaying both fixes on the compatible Kani pin 0aac16ef passed the 14 previously blocked harnesses, the four optimized triplet getters, and eight matching contract or model proofs. The same source, declared solvers and unwind settings were used. The six ChunksExactMut::nth_back runs retained their audited checked-panic properties, and the memory-safety checks passed.

Both fixes are open upstream. Hosted checks need a compatible pin that contains them. The verification notes record the type, const-width, allocation and UB-model boundaries for review. Kani #5202, Kani #5203

@v3risec

v3risec commented Nov 19, 2026

Copy link
Copy Markdown
Author

Restored the three original // SAFETY comments in Windows, Chunks and ArrayWindows.

Preserved the upstream harness coverage with 44 retained regressions and 28 symbolic replacements. All 44 retained regressions passed on the clean project pin c5e65fdf.

@v3risec

v3risec commented Nov 19, 2026

Copy link
Copy Markdown
Author

I updated ffi::c_str::verify::check_invariant to find the first NUL with a reverse byte scan. The previous check used Iter::position. Its new loop invariant tracks the cursor and element validity, so the abstraction can skip a matching byte and return None for [1, 0]. The revised harness preserves both original assertions and both covers, and passes on the current CI toolchain.

The earlier main CI already passed -Z loop-contracts. Kani applies the loop-contract pass when the compiled model for a harness contains a loop contract. The new annotations on the shared slice iterator methods activated that pass for these five existing harnesses. All five passed on the same toolchain in the upstream baseline run.

The remaining four failures are CBMC 6.11.0 assigns false positives in check_from_ptr_contract, check_from_bytes_with_nul, check_from_bytes_until_nul, and check_u64_fmt. With loop contracts enabled, CBMC checks writes to function-local counters inside unannotated loops against the wrong write set. All five harnesses passed locally with the revised CStr check and a goto-instrument build containing the upstream fix. The four remaining failures are blocked until hosted CI picks up that fix, which is already merged in CBMC’s development branch. CBMC rust-lang#9164

@v3risec

v3risec commented Nov 22, 2026

Copy link
Copy Markdown
Author

@feliperodri I've completed Challenge 18 and updated the PR description with the verification results and remaining limitations. Could you please take a look when you have a chance? I'd appreciate your feedback. Thanks!

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 18: Verify the safety of slice iter functions - part 1

2 participants