Repository navigation
Description
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.
stris[u8];&stris a pointer and a length;Stringwraps aVec<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
strvalue is treated like[u8], i.e. it must be initialized." Thestrdocs: "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, acharthat is a surrogate or abovechar::MAXis an invalid value (immediate UB). So-Z valid-value-checkscoverscharbut can never coverstr: 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"), andas_bytes_mut(the caller must restore it). Relied on by decoding (Chars,CharIndices, thestr::patternsearchers,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_widthandrun_utf8_validationimplement): the lead byte fixes the width (1–4); continuation bytes are0x80..=0xBF; four lead bytes restrict the second byte (E0:A0..BF,ED:80..9F,F0:90..BF,F4:80..8F);C0,C1andF5..FFnever 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_boundaryand 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_validationand 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:
- Decoding and iteration are the bottleneck, not generation. One
chars().count()on 4 bytes costs about 60× more than generating the string. - 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.
- 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:
- 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. - A
utf8predicate in Kani (quantified, or local over byte windows), contracts forfrom_utf8/from_utf8_unchecked, and opt-in verified stubs for validation and the main iteration paths, each proved by a boundedproof_for_contractin Kani's CI. - 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
- Performance: Memory blows up on a simple program that uses String find #2001 (String
find), Poor performance scaling for a simple program involving String push/pop #2015 (String push/pop), Memory blows up on a small program involving String split #2302 (Stringsplit), Poor performance scaling for string comparison function #2309 (string comparison), Performance drastically differs across two string indexing operations #3328 (string indexing, closed), Call to format! causes an infinite loop #4507 (format!),<[u8]>::containsdoes not converge even on fully concrete data (memchr specialization);iter().anyverifies in 0.2s #4779 (<[u8]>::contains/ memchr), Performance: common std constructs (padded integer formatting,str::parse, recursive drop,Backtrace::capture) time out #5127 (padded formatting,str::parse), Toolchain upgrade to nightly-2026-10-24 failed #5061 (derive(Debug)name search through memchr, fixed by Upgrade the Rust toolchain to nightly-2026-11-11 #5157), Flaky CI: cargo_autoharness_multichareq_searcher times out on macos-15-intel and fails the merge queue #5162 (the autoharness searcher test). - Correctness of string generation: Autoharness: &str arguments can be invalid UTF-8 under verify-std, causing spurious failures #5030 (
&strarguments can be invalid UTF-8 under verify-std). - Contracts on string code: Function Contracts: Modifies for str #3349 (
modifiesforstr), Loop contracts:forloops over iterators without aKaniIntoIterimpl (e.g.char::DecodeUtf16) cannot carry a contract #4907 (loop contracts over iterators such aschar::DecodeUtf16). - Autoharness: Autoharness: types that should be supported (no Arbitrary, trait objects, fn pointers, HashMap, Option<&T>, Pin, tuples with &str) #5137 (tuples with
&strand other unsupported types).
Activity