Skip to content

Challenge 21: Unbounded verification for StrSearcher safety with Kani - #621

Open
v3risec wants to merge 18 commits into
model-checking:mainfrom
v3risec:challenge-21-string-searcher
Open

v3risec wants to merge 18 commits into
model-checking:mainfrom
v3risec:challenge-21-string-searcher

Conversation

@v3risec

@v3risec v3risec commented Aug 3, 2026 •

Copy link
Copy Markdown

Summary

This PR targets Challenge 21. It adds constructor and safety proofs for StrSearcher across Empty, Byte, short-period Two-Way, and long-period Two-Way needles. The proofs establish a type invariant C at construction and check that each of the six search methods preserves C and returns only ordered, in-bounds ranges on UTF-8 character boundaries.

Follow-up status. Verification of the revision described below on the official toolchain is pending the Kani fixes listed below and a pin update.

Proof approach

  • Inputs and induction. Haystack and needle lengths are independently symbolic within each applicable case. The 64-bit CI configuration with --object-bits 12 represents allocations up to 2^51 - 1 bytes. The Empty and Byte cases have their inherent needle lengths of zero and one byte. The required proofs use no kani::unwind annotations or fixed-size test inputs. The two #[kani::unwind(4)] annotations in pattern.rs belong to pre-existing upstream harnesses.
  • Invariant C. Forward and reverse cursors are independently in bounds and on UTF-8 boundaries. C also ties the Empty and Byte states to their needles, and records the preprocessing and cached-scan facts needed by the two Two-Way cases.
  • Production implementation. The Two-Way scans and the reject filters use the upstream control flow. The two Empty match arms enclose their existing loops in blocks to attach loop annotations. After accounting for those blocks and verification annotations, the production statements and original comments match upstream 1feeadd9379. The real str::ceil_char_boundary loop has its own inductive invariant and write set.
  • Compositional proofs. Constructor harnesses enter Pattern::into_searcher and use separate preprocessing lemmas for critical positions and periods. The search harnesses compose step contracts and checked summaries of the raw Two-Way and boundary-rounding code. Verified stubs have corresponding proof_for_contract harnesses. Explicit assumptions and assertions in the Challenge 21 module have reachability covers.
  • Challenge assumptions. Slice operations and UTF-8 decoding use the challenge's permitted assumptions. The proofs use local consequences of valid UTF-8 at the bytes being examined. They check the returned endpoints and the updated searcher state.

Required coverage

Function Proof obligation across the applicable cases
<&str as Pattern>::into_searcher Establish C, including the preprocessing facts for both Two-Way cases.
Searcher::next Check safety, Match and Reject ranges, and preservation of C for forward steps including Done.
Searcher::next_match Check returned match ranges and preservation of C, including the Empty filter loop.
Searcher::next_reject Check returned reject ranges and preservation of C across the forward filter loop.
ReverseSearcher::next_back Check safety, Match and Reject ranges, and preservation of C for reverse steps including Done.
ReverseSearcher::next_match_back Check returned match ranges and preservation of C, including the Empty reverse filter loop.
ReverseSearcher::next_reject_back Check returned reject ranges and preservation of C across the reverse filter loop. The challenge document calls it next_back_reject.

Kani dependencies and verification status

The current Kani pin is 9834c96ce90f with CBMC 6.11.0. It already includes Kani #5134 for match-arm attributes, #5135 for generic trait-method stubs and contracts, and #5136 for nested quantifier captures.

Open upstream work Affected proofs
Kani #4957 The real Short Two-Way loops can hit a compiler error when a local initializer branches. The upstream change lets the Short reverse case compile.
Kani #5071 or its storage-lifetime follow-up The real Byte next_reject and next_reject_back loops need Kani to account for the anonymous match temporary under their explicit loop_modifies.
Kani #5209 and the Short binding regression The outer Short loop needs to account for the i binding produced by its nested, contracted for loop. The remaining regression will determine whether the upstream nested-local or lifetime fix covers it. The regression must also reject omitted user writes under an explicit write set.

On local diagnostic runs, the proposed rust-lang#4957 and rust-lang#5071 changes let both Byte reject harnesses pass with CBMC 6.11.0. The Short reverse case still reported Check that i is assignable when the experimental destination rule was removed. The rule itself could incorrectly admit a user write, so results from that experimental compiler are diagnostic only. The previous successful CI at 89ed906e12a applies to the earlier proof revision.

Once the needed fixes reach the repository pin, I will rerun the two Byte rejection harnesses, the raw Short forward and reverse proofs and their public callers, both Empty match filters, and harness_ceil_char_boundary. I will report those results and the regular PR CI status against the updated pin.

Resolves #278

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 marked this pull request as ready for review August 6, 2026 13:57
@v3risec
v3risec requested a review from a team as a code owner August 6, 2026 13:57
@feliperodri

Copy link
Copy Markdown
Member

@v3risec is this a complement for #538?

@feliperodri feliperodri added the Challenge Used to tag a challenge label Aug 6, 2026
@v3risec

v3risec commented Aug 7, 2026

Copy link
Copy Markdown
Author

@feliperodri Not exactly. The main differences are:

  • Invariant: Verify safety of StrSearcher (Challenge 21) #538 mainly constrains the Two-Way cursors to be in bounds and on UTF-8 boundaries. This PR additionally constrains the period, critical positions, long/short-period states, and valid memory/memory_back states.
  • Two-Way verification: Verify safety of StrSearcher (Challenge 21) #538 replaces TwoWaySearcher::new, next, and next_back with nondeterministic abstractions satisfying output constraints. This PR preserves a representative iteration of the real control flow, indexing, arithmetic, and state updates, while summarizing the scans and remaining loop iterations.
  • Properties checked: In addition to valid UTF-8 result ranges and invariant preservation, this PR checks cursor progress, preprocessing-field preservation, memory transitions, and the relationship between returned ranges and the resulting state.
  • EmptyNeedle: The coverage mostly overlaps, although this PR keeps the finite filtering behavior more concrete instead of replacing it with a general nondeterministic result.

So I would describe this PR as an alternative and strengthening of the Challenge 21 portion of #538, rather than a direct complement.

@feliperodri

Copy link
Copy Markdown
Member

@v3risec can I review both PRs independently? If this one got approve, should I ignore #538?

@feliperodri feliperodri left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review: PR #621 — Challenge 21 (StrSearcher safety)

Verdict rationale

This PR is substantially and qualitatively different from the rejected #538. It does not repeat #538's fatal pattern, and it does real, careful verification work. However, it fails two required criteria that the author openly acknowledges in-code, so it cannot be approved as-is.

It is NOT the #538 body-swap / assume-the-conclusion failure (credit where due)

I classified all 12 #[cfg(not(kani))] blocks. None compile out TwoWaySearcher::new/next/next_back and replace them with pure nondeterministic stubs. Instead:

  • Boundary-repair loop swaps — forward Searcher::next (pattern.rs diff L96/L177 → kani at L115-145) and reverse next_back (L334/L362/L443): the real searcher.next::<RejectAndMatch>(...)/next_back::<...> call is preserved; only the while !is_char_boundary(b) { b += 1 } repair loop is summarized.
  • Candidate-loop swaps — continue 'search (L807, L1093) replaced by suffix summaries (kani_stub_after_failed_forward_candidate / ...reverse...).
  • Inner byte-scan for-loop swaps — (L820, L859, L1101, L1152) replaced by kani_scan_forward/kani_scan_reverse, which still index needle[index]/haystack[position+index] at a nondeterministic representative index over the complete scan interval (diff L590-598), so memory-safety of the real indexing is genuinely checked.
  • Empty-needle char decode (L68) — real .chars().next() retained in non-kani; kani models it as a nondet width 1..=4 bounded by remaining bytes plus a UTF-8 boundary assumption.

The real control flow, arithmetic (self.position += i - self.crit_pos + 1, self.position += self.period, etc.), and state transitions of the Two-Way algorithm are executed for one representative candidate. This is legitimate loop summarization, not a function-body swap.

Assume-the-conclusion check (FATAL in #538): PASS. The UTF-8 boundary facts on the Match path (assume_valid_utf8_two_way_match_boundaries, diff L1821-1855; assume_valid_utf8_two_way_reverse_match_start, L1857-1877) are gated behind assert!s that the relevant needle bytes were byte-equal to the haystack over the full final character, and the needle is valid UTF-8. Assuming the boundary then follows from "byte-equality with a valid-UTF-8 needle transfers the char boundary" — which is exactly a UTF-8 decoding fact Challenge 21 explicitly permits importing (assumptions 2 and 3). This is a defensible proof cut, not a raw assumption of the type-invariant conclusion.

Invariant is non-trivial: PASS. type_invariant_two_way_searcher (diff L2430-2482) constrains cursor bounds, char-boundaries of position/end, 1 <= period <= needle_len, crit_pos/crit_pos_back bounds, long/short-period sentinel consistency (memory/memory_back), and short-period boundary summaries. It is meaningful, not true.

Proof harnesses exist: 15 challenge #[kani::proof] harnesses (1 empty constructor + 6 empty methods + 6 Two-Way methods), plus the 2 retained small_slice_eq proofs. Absence of proof_for_contract is fine here since the challenge is invariant-based, not contract-based.

Blocking issue 1 — Verification is NOT unbounded (mandatory criterion FAILS)

The challenge states: "The verification must be unbounded—it must hold for inputs of arbitrary size." This PR hard-bounds inputs:

  • pattern.rs diff L1271: const MAX_UTF8_BYTES: usize = 16;
  • any_valid_utf8_str (L1273-1282) takes &[u8; MAX] and slices a 16-byte array; every harness builds haystack/needle from [u8; MAX_UTF8_BYTES] (e.g. L2752-2755).

So needle.len(), period, crit_pos, position, end are all bounded by 16. The author acknowledges this directly at diff L2748-2749 ("the concrete haystack and needle models remain bounded by MAX_UTF8_BYTES") and in the PR description ("the current harness models do not constitute an arbitrary-length input proof"). Summarizing the loops removes unwind bounds but does not make the input size unbounded. This is a clear failure of a mandatory requirement.

Blocking issue 2 — Creation does not establish C for TwoWay (success criterion 1 FAILS)

Criterion 1 requires proving that a searcher created from any valid UTF-8 haystack satisfies C. This is done for the empty needle via harness_str_searcher_empty_into_searcher (diff L2557-2565), which calls the real needle.into_searcher(haystack). But for the core Two-Way case there is no constructor harness: TwoWaySearcher::new is never invoked (grep: 0 references), and the invariant is only kani::assumed (e.g. L2772). The author explicitly disclaims this at diff L2745-2747: "Establishing it for the production preprocessing algorithm is a separate proof obligation and is not claimed by this module."

This is a real gap, not a formality: because the hand-written invariant is never cross-checked against what TwoWaySearcher::new actually produces, the preservation proofs (criterion 3) run over a hand-specified state set that is never tied to reachable states. If that set under-approximates reachable states, criterion 3 coverage is incomplete; the constructor harness is what closes this.

Non-blocking observations

  • The loop-state relations (valid_two_way_*_loop_state) are used as both assume (loop head) and assert (loop exit) but are not independently shown to be inductive; soundness of the suffix summaries rests on them. Worth a reviewer note even after the blockers are fixed.
  • kani::assume(false) is used to prune the continued-loop path (e.g. next_reject diff L271) after the per-iteration safety asserts fire — acceptable idiom, but each such site should be double-checked to confirm every concrete exit (Reject/Match/Done) is reachable via the symbolic prefix.

Direction to author

  1. Make inputs unbounded: drive the loop summaries/type_invariant off symbolic lengths rather than a fixed 16-byte array, or otherwise remove the input-size bound, so the proof holds for arbitrary-size haystack/needle.
  2. Add a Two-Way constructor harness that runs the real into_searcher/TwoWaySearcher::new on a valid UTF-8 (needle, haystack) and asserts type_invariant_two_way_searcher, closing criterion 1 for the core algorithm.

Once these two are addressed, the approach here (real algorithm + Challenge-21-permitted UTF-8 imports + non-trivial invariant) is a strong basis for approval.

@v3risec
v3risec requested a review from a team as a code owner August 25, 2026 08:50
@v3risec

v3risec commented Aug 25, 2026

Copy link
Copy Markdown
Author

@v3risec can I review both PRs independently? If this one got approve, should I ignore #538?

Yes, they can be reviewed independently. For Challenge 21, #621 and #538 are alternative implementations, not complementary ones.

@v3risec

v3risec commented Aug 25, 2026 •

Copy link
Copy Markdown
Author

@feliperodri Thank you for the detailed review. I checked the issues and non-blocking concerns as follows.

Blocking issue 2

This issue is addressed by harness_str_searcher_two_way_into_searcher. The harness executes the real production path:

Pattern::into_searcher
    -> StrSearcher::new
    -> TwoWaySearcher::new

It requires a non-empty needle, checks that the resulting implementation is StrSearcherImpl::TwoWay, and immediately asserts type_invariant_two_way_searcher after construction. It also checks the initial cursor state and covers both period branches. Therefore, within the documented bounded input domain, the production constructor is now machine-checked to establish C, and the preservation harnesses are no longer disconnected from the constructor.

Non-blocking observation 1

I manually checked the preservation obligations for the valid_two_way_*_loop_state summaries against the production branches. This review covered cursor monotonicity, short-period updates to memory and memory_back, preservation of the long-period sentinel, and the Reject/Match/Done exits in both the forward and reverse directions.

These summaries are therefore supported by a documented trusted argument, and their preservation obligations have been manually checked against the production control flow. This is an informal manual justification rather than a separate Kani harness proving inductiveness for every loop transition.

Non-blocking observation 2

I also checked the relevant kani::assume(false) sites. In next_reject and next_reject_back, they occur only after a representative iteration returns Match, indicating that the surrounding loop continues. Before pruning, the harness checks cursor progress and the corresponding loop-state relation. Concrete Reject and Done exits return directly, while paths with multiple preceding Match steps are represented by choosing the symbolic prefix at the final loop head.

The other assume(false) sites either terminate paths after a boundary assertion has already failed or filter invalid UTF-8 inputs. This is the intended symbolic-prefix loop-cut idiom.

Unbounded verification

I agree that the current verification is bounded rather than genuinely unbounded. I experimented with a symbolic Vec model to remove the fixed byte-array bound, but the verification took too long(over 500s) and was not acceptable under the current CBMC object-size and CI configuration. I therefore do not present it as an unbounded proof.

The remaining proof has an explicit bounded scope: the Two-Way constructor harness covers haystacks of up to 4 bytes and non-empty needles of up to 3 bytes. Within that domain, the constructive generator reaches every valid UTF-8 string and kani::cover covers both the short-period and long-period branches. The existing method harnesses retain their documented bounded models.

This is a justified bounded verification, but I am not claiming that it satisfies the challenge’s literal requirement for arbitrary-size inputs.

I would appreciate any further feedback on this scope or on ways to make the summaries and harnesses more precise. I would be happy to make further changes or optimizations based on your suggestions.

@feliperodri

Copy link
Copy Markdown
Member

Review — changes requested (Challenge 21)

Thanks for the submission. To set expectations up front: there are two Challenge 21 solutions (this PR and #538), and we give preference to #538 — it verifies the real TwoWaySearcher inductively with zero modification of the shipped code (+814/−0), whereas this PR modifies the verified code fairly heavily. That said, neither PR is currently acceptable, and this one is welcome to continue if the concerns below are addressed.

Concerns (local review, pinned Kani d4df833c + CBMC 6.8.0):

  1. Boundary safety is assumed, not proven. stub_utf8_forward_boundary_repair asserts representative_next <= haystack.len(), which is near-tautological (head < len ⟹ head+1 ≤ len). The boundary-repair loop's safety is effectively assumed under the challenge's UTF-8 allowance rather than established. The core property (returned indices lie on UTF-8 char boundaries) should be proven.
  2. Invasive edits to shipped code. The diff carries 12 cfg(not(kani)) body-swaps and −87 deletions of shipped lines. Even when gated, this alters the verified logic and is not plausibly upstreamable; the repo norm is to keep harnesses in a verify module over the real bodies.
  3. assume(false) dead-branch claims. There are 5+ kani::assume(false) sites. Please confirm at runtime that each branch is genuinely unreachable, so they aren't silently pruning live behavior (vacuity risk).
  4. Bounded (HAYSTACK=4 / NEEDLE=3). The challenge requires an unbounded proof.

Acceptance bar (same for both PRs): the solution can only be accepted if it presents an unbounded proof that completes within CI resource limits, verifying the real algorithm rather than assuming the safety property.

@feliperodri feliperodri left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Challenge 21 requires: "The verification must be unbounded---it must hold for inputs of arbitrary size." That requirement is final. A Kani solution will only be accepted if it is unbounded in the input size for every required function. This PR still verifies at least part of the challenge with bounded harnesses (kani::unwind bounds and/or fixed-size inputs), so I'm requesting changes until every required function is verified without a bound on the input size.

@v3risec

v3risec commented Nov 7, 2026

Copy link
Copy Markdown
Author

@feliperodri I have reworked the verification in response to your review.

The old small-array input model is replaced by independently symbolic haystack and needle lengths up to (1 << 51) - 1, matching the CI pointer-model limit. Maximum-length covers have been added.

The production algorithm statements are preserved. The old cfg(not(kani)) replacements and explicit assume(false) path cuts are removed. Search loops use nontrivial loop contracts.

Constructor harnesses cover Empty, Byte, Long and Short; the six interface proofs check safety, UTF-8 result boundaries and preservation of C. Contracts have corresponding proof_for_contract harnesses, and verification assumptions/assertions have reachability covers.

Following #740, I am keeping the std changes separate from the Kani fixes. The supporting fixes have now been submitted as 3 focused PRs:

Some results still use external GOTO/SMT profiles, so these 3 fixes alone have not yet been shown sufficient for normal CI. After the necessary fixes and integration work, I will update the Kani pin and rerun the full suite and CI.

I would appreciate feedback on the updated proof structure while those tool dependencies are addressed.

@v3risec

v3risec commented Nov 20, 2026

Copy link
Copy Markdown
Author

@feliperodri The latest local follow-up establishes C through the real constructor in all four cases and checks each of the six search methods over symbolic-length inputs. The length ceiling is the 64-bit CBMC allocation limit (2^51 - 1 bytes with --object-bits 12). The Empty match filters have an input-independent bound from Match/Reject alternation.

These results are for the local follow-up to f4554ffca1c, which is pending push. Repository CI still uses c5e65fdfc3e1. CI validation of the follow-up requires the updated proof revision and a Kani pin that includes the three fixes.

@v3risec

v3risec commented Nov 20, 2026

Copy link
Copy Markdown
Author

The eight Kani partitions and the goto-transcoder job on 0a0241d all used the repository pin c5e65fdfc3e1. They failed while compiling core because that revision could not resolve the generic Iterator::fold stub in harness_two_way_byteset_create. The error occurs before harness solving begins. Kani log · goto-transcoder log

Upstream Kani 0601bc57f, which I used for local verification, includes the fix for method-level generic resolution. CI verification is pending a pin update that includes the merged fixes. Kani #5135

@v3risec v3risec changed the title Challenge 21: Verify safety of StrSearcher with Kani Challenge 21: Unbounded verification for StrSearcher safety with Kani Nov 20, 2026
@v3risec

v3risec commented Nov 22, 2026

Copy link
Copy Markdown
Author

@feliperodri Thanks for the earlier feedback. All eight Kani partitions now pass on Ubuntu and macOS for b75c0c0 with the repository’s updated Kani pin 9834c96ce90f.

The final update splits the short-period forward proof cases and simplifies the range-agreement proof so they complete in CI. The real constructor establishes C in all four cases, and all six required search methods are verified over symbolic-length inputs with inductive search loops. This addresses the earlier review points on input bounds, constructor coverage, the real search implementations, and CI runtime.

@v3risec
v3risec requested a review from feliperodri November 22, 2026 11:38
@v3risec
v3risec marked this pull request as draft November 22, 2026 15:22
@v3risec
v3risec marked this pull request as ready for review November 23, 2026 03:22
@v3risec

v3risec commented Nov 23, 2026

Copy link
Copy Markdown
Author

@feliperodri The revised PR covers the constructor and all six StrSearcher methods required by Challenge 21. The harnesses exercise the production implementation. They check that construction establishes C and that every search method runs safely, returns in-bounds ranges on UTF-8 character boundaries, and preserves C.

The proof setup now meets the unbounded input-size requirement for every required function. Haystack and needle lengths are symbolic across all applicable searcher cases, up to the CI pointer model’s representable allocation size. The search loops use inductive contracts, including both Empty match filters. The Challenge 21 proofs use no #[kani::unwind] bounds and no fixed-size inputs. The two existing upstream unwind annotations belong to unrelated harnesses.

The current Kani pin 9834c96ce90f already includes model-checking/kani#5134, model-checking/kani#5135, and model-checking/kani#5136. Official CI validation of this revision still depends on the following upstream work.

  • Fix the compiler crash on branching initializers in the real Short Two-Way loops. Kani #4957
  • Handle the temporary in the Byte reject loops’ explicit write sets through the fix under review or its storage-lifetime follow-up. Kani #5071
  • Confirm that the nested-local fix also covers the generated i binding in the Short proof. Kani #5209

I’ll rerun the affected harnesses once the relevant fixes reach the repository pin. I’d be happy to help move the open Kani PRs forward by sharing reproducers or running regression tests if that would be useful.

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 21: Verify the safety of substring-related functions in str::pattern

2 participants