Skip to content

Verifying str and String: model UTF-8 as a type invariant with contracts for validation and iteration #5187

Open

Description

@feliperodri

Verifying code that uses str and String has long been a bottleneck for Kani (see the related issues below). This issue collects what we found while investigating #5162 and proposes a direction: model UTF-8 as a type invariant, with contracts for validation and iteration, instead of letting CBMC unroll the standard library's UTF-8 loops.

What Rust says about strings

  • Layout. str is [u8]; &str is a pointer and a length; String wraps a Vec<u8>. len(), indexing and slicing are all in bytes. Chars exist only when you decode.
  • UTF-8 is a library (safety) invariant, not a validity invariant. The Reference (Behavior considered undefined): "A str value is treated like [u8], i.e. it must be initialized." The str docs: "Constructing a non-UTF-8 string slice is not immediate undefined behavior, but any function called on a string slice may assume that it is valid UTF-8." By contrast, a char that is a surrogate or above char::MAX is an invalid value (immediate UB). So -Z valid-value-checks covers char but can never cover str: UTF-8 is a type invariant that library code relies on.
  • Where the invariant is established and where it is used. Established by str::from_utf8 / String::from_utf8 (checked), from_utf8_unchecked (safety precondition: "The bytes passed in must be valid UTF-8"), and as_bytes_mut (the caller must restore it). Relied on by decoding (Chars, CharIndices, the str::pattern searchers, count), which reads lead and continuation bytes without re-checking them.
  • UTF-8 validity is local. Per the Unicode table of well-formed byte sequences (what utf8_char_width and run_utf8_validation implement): the lead byte fixes the width (1–4); continuation bytes are 0x80..=0xBF; four lead bytes restrict the second byte (E0: A0..BF, ED: 80..9F, F0: 90..BF, F4: 80..8F); C0, C1 and F5..FF never appear. So "is valid UTF-8" is a conjunction of constraints on windows of at most 4 bytes, expressible as a quantified predicate or built in by generating whole chars.
  • Char boundaries are cheap; loops are not. is_char_boundary and the check behind &s[a..b] are a one-byte test. Decoding one char (next_code_point) is straight-line code. The cost is in loops whose trip count is symbolic because each step advances by a variable width: validation (run_utf8_validation and its word-at-a-time ASCII fast path) and iteration (Chars, count, searchers). CBMC unrolls them to the unwinding bound even when the string is tiny.

Measurements

On Linux with CBMC 6.11.0, for a string of at most 4 bytes, each row is one harness:

harness --default-unwind 20 --default-unwind 6
generate with kani::any_str_ref (nondeterministic bytes, longest valid prefix) 331K variables, 21s 28K, 1.7s
generate valid by construction (up to 4 kani::any::<char>(), each encode_utf8) 94K, 1.5s 94K, 1.5s
CharSliceSearcher over it, advanced up to 4 steps from each end (any_char_slice_searcher) 1.39M, 78s 570K, 22s
s.chars().count() once did not finish in 20 min 1.63M, 211s

In the autoharness test cargo_autoharness_multichareq_searcher, the CharSliceSearcher harnesses go from 1.40–1.66M variables at unwind 20 to 580–716K at unwind 6, with every cover still satisfied and all unwinding assertions passing (#5162; #5157 now runs that test with --default-unwind 6).

Takeaways:

  1. Decoding and iteration are the bottleneck, not generation. One chars().count() on 4 bytes costs about 60× more than generating the string.
  2. Generating by construction removes the sensitivity to the unwinding bound (94K at any bound), while today's generator ranges from 28K to 331K depending on it.
  3. The unwinding bound matters as much as the model. With --bounded-arguments, autoharness uses a fixed default of 20 (LOOP_UNWIND_DEFAULT); deriving it from the bounds is a cheap, sound improvement (tracked in Flaky CI: cargo_autoharness_multichareq_searcher times out on macos-15-intel and fails the merge queue #5162).

Proposal

Treat a string as a byte buffer plus the predicate utf8(bytes), which is established at a few entry points, assumed by every decoder, and preserved by the safe API:

Rust concept Kani mechanism effect
str's UTF-8 invariant a type invariant: assumed for inputs, asserted where it is established no validation loop when a harness receives a &str
from_utf8 / from_utf8_unchecked function contracts: from_utf8(v).is_ok() == utf8(v) (plus valid_up_to); precondition utf8(v) validation replaced by the predicate via stub_verified
iteration (Chars, CharIndices, count, searchers) loop contracts / stubs: the unread rest is valid UTF-8 and starts at a char boundary no unrolling to the bound
generating strings (any_str_ref, String::bounded_any, autoharness) build from whole chars valid by construction, no validation loop

Suggested phases:

  1. By-construction generators, and a bound-derived default unwind for --bounded-arguments (Flaky CI: cargo_autoharness_multichareq_searcher times out on macos-15-intel and fails the merge queue #5162). No new trust assumptions.
  2. A utf8 predicate in Kani (quantified, or local over byte windows), contracts for from_utf8 / from_utf8_unchecked, and opt-in verified stubs for validation and the main iteration paths, each proved by a bounded proof_for_contract in Kani's CI.
  3. Replace Kani's own stubs with real function contracts, loop contracts and type invariants from verify-rust-std as they land.

Any stub that is not yet proved is an assumption and must be listed in docs/src/soundness.md, as we do for the derive(Debug) models.

Related issues

Activity

  1. added
    [E] Performance
    [C] Feature / Enhancement
    on Nov 17, 2026
  2. self-assigned this
    on Nov 17, 2026
  3. added
    T-TrackingIssue
    Z-Contracts
    on Nov 17, 2026
  4. added this to the Contracts milestone on Nov 17, 2026
  5. added theissue type on Nov 17, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

T-TrackingIssueZ-Contracts[C] Feature / Enhancement[E] Performance

Type

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions