Repository navigation
Generate nondeterministic reference-count state for Rc/Arc Arbitrary - #4788
Closed
rbeauchamp wants to merge 2 commits into
Closed
rbeauchamp wants to merge 2 commits into
rbeauchamp wants to merge 2 commits into
Conversation
…4752) Count observers (strong_count, weak_count, get_mut, try_unwrap, make_mut) branch only on uniqueness, so the Arbitrary impls and the AnyRc/AnyArc autoharness models now leak one representative per behavioral equivalence class: strong_count in {1, 2}, weak_count in {0, 1}. Previously every generated value had strong_count == 1, so functions observing count state were 'verified' for states real callers can violate.
Contributor
There was a problem hiding this comment.
🟡 Changes recommended
Restricting exact observable counts to {1,2} × {0,1} leaves an unsound input-space under-approximation while reporting generation as unbounded.
Get a fresh assessment by requesting another Copilot review.
Pull request overview
Expands nondeterministic Rc/Arc generation to include shared and weak-reference states.
Changes:
- Generates four representative reference-count states.
- Adds direct and autoharness regression tests.
- Updates expected autoharness failures.
File summaries
| File | Description |
|---|---|
library/kani/src/arbitrary.rs |
Adds nondeterministic leaked strong/weak references. |
tests/kani/RefCount/nondet_rc_arc.rs |
Tests reference-count behavior and pointee coverage. |
tests/script-based-pre/cargo_autoharness_smart_pointers/src/lib.rs |
Adds an AnyArc count test. |
tests/script-based-pre/cargo_autoharness_smart_pointers/smart-pointers.expected |
Records the additional expected failure. |
Review details
Suppressed comments (3)
library/kani/src/arbitrary.rs:52
- This also caps
Arcat strong count 2 and weak count 1, although both count APIs reveal larger valid values exactly. A function that checks an incomingArchasstrong_count <= 2orweak_count <= 1can therefore be incorrectly verified; this needs full count modeling or explicit bounded semantics.
if bool::any() {
std::mem::forget(arc.clone());
}
if bool::any() {
std::mem::forget(std::sync::Arc::downgrade(&arc));
library/kani/src/arbitrary.rs:82
- The
AnyRcmodel has the same finite refcount cap, while autoharness still classifies smart-pointer models as unboundedArgSupport::Arbitrary(kani-compiler/src/kani_middle/mod.rs:1169-1172, 1230-1236). Consequently, successful proofs about exact counts above 2/1 receive no bounded-result caveat. Either model every valid count or route this model through bounded-argument classification.
if crate::any() {
std::mem::forget(rc.clone());
}
if crate::any() {
std::mem::forget(std::rc::Rc::downgrade(&rc));
library/kani/src/arbitrary.rs:96
- The
AnyArcmodel is likewise finite but is reported by autoharness as unbounded. Exact count checks such asArc::strong_count(&a) <= 2can therefore produce an unsound successful result without requiring--bounded-arguments; please generate the full state space or classify this path as bounded.
if crate::any() {
std::mem::forget(arc.clone());
}
if crate::any() {
std::mem::forget(std::sync::Arc::downgrade(&arc));
- Files reviewed: 4/4 changed files
- Comments generated: 2
- Review effort level: Balanced
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
Comment on lines
+32
to
+36
| if bool::any() { | ||
| std::mem::forget(rc.clone()); | ||
| } | ||
| if bool::any() { | ||
| std::mem::forget(std::rc::Rc::downgrade(&rc)); |
Comment on lines
+27
to
+29
| // --- Reachability: shared ownership and weak references are both generated. | ||
| // Each `should_panic` harness asserts the old (incomplete) behavior; it must FAIL, proving | ||
| // the newly covered class is reachable. |
acearyanarun
added a commit
to acearyanarun/kani
that referenced
this pull request
Nov 17, 2026
Kani models the reference counts of generated Rc/Arc values with only finitely many states (model-checking#4752), yet autoharness reported such harnesses as checked "against all possible inputs" with no caveat, since Rc/Arc arguments are unbounded in the pointee and need no --bounded-arguments. Add an independent, non-gating caveat, mirroring is_ctor_based: - HarnessMetadata::is_refcount_bounded, set when some generated value contains an Rc/Arc, found by walking the argument types (references, raw pointers, arrays, slices, tuples, pattern types, ADT fields and generic arguments; PhantomData skipped; over-approximating, so a missed caveat is not possible). Formatting-trait harnesses use the impl's self type. - A "(refcount)" marker in the summary table (it fits the Kind column, so other rows do not shift), a note after the table, and a qualified "all possible inputs" message. - is_refcount_bounded in the --export-json document, with the schema, fixtures, checker and RFC 0015 updated. ArgSupport::Bounded is deliberately not reused: it is gated behind --bounded-arguments, which would disable Rc/Arc support by default. The Rc/Arc generators are unchanged (see model-checking#4788). Tests: a json-handler test asserting the export field, marker, note and message per function (direct, AnyRc/AnyArc model paths, nested field, tuple, reference, Box; negative controls incl. PhantomData), with covers that must be SATISFIED for the generated unique state; updated smart-pointer expectations; driver unit tests. Docs: limitations of the finite model in the autoharness reference. Part of model-checking#4752.
acearyanarun
added a commit
to acearyanarun/kani
that referenced
this pull request
Nov 17, 2026
…aveat The relocated bullets described a model with shared representatives (from the closed model-checking#4788) and the overflow trade-off of that design. Generated Rc/Arc values are always uniquely owned, so say that only the counts 1 and 0 are checked and that no other holder exists.
feliperodri
added a commit
to Tiramisu-Cake/kani
that referenced
this pull request
Nov 19, 2026
…king#5070) > **Draft — Local validation complete; CI and maintainer review pending.** The pinned nightly toolchain was installed successfully on macOS. The compiler build, unit tests, regression tests, formatting, and Clippy checks all passed locally. This PR contains only the independent reporting change. Shared-state tests requiring model-checking#4788 remain separate. ## Summary AutoHarness-generated `Rc`/`Arc` values have finitely modeled reference counts, but current AutoHarness output describes these harnesses as verifying "all possible inputs" without identifying that limitation. This PR makes the limitation visible without disabling default `Rc`/`Arc` support. - Adds an independent `HarnessMetadata::is_refcount_bounded` caveat. - Marks affected harnesses `(refcount)` in the AutoHarness summary, adds an explanatory note, and qualifies the per-function progress message. - Exposes `is_refcount_bounded` in `--export-json`, including schema, fixtures, and RFC documentation updates. - Adds tests for the marker, metadata compatibility, JSON reporting, type nesting, and non-vacuous uniquely owned states. - Documents the finite-model limitation and remaining caveats. **This PR does not change any `Rc`/`Arc` generator.** ## Why this matters Today, generated `Rc`/`Arc` values are uniquely owned (`strong_count == 1`, `weak_count == 0`). PR model-checking#4788 proposes additional shared-ownership states (`strong_count` in `{1, 2}` and `weak_count` in `{0, 1}`). Neither model covers all exact count values a caller may supply, so a successful verification result needs to communicate that limitation. A function checking, for example, `Rc::strong_count(&x) > 2` can still depend on unmodeled states. The existing `(bounded)` marker is gated by `--bounded-arguments`; reusing it would prevent default generation of `Rc`/`Arc` arguments. The new `(refcount)` caveat is separate and non-gating. ## Implementation - The compiler inspects generated argument types, following references, arrays, tuples, ADT fields and generic arguments, while skipping `PhantomData`. It deliberately errs toward warning on uncertain nesting rather than silently omitting a caveat. - The metadata field defaults to `false` when absent in older serialized metadata. - The driver adds a summary marker and note, plus an explicit qualification when printing individual verification progress. - JSON export includes the field, and the schema and fixtures are updated. - Regression tests check direct and nested types, the `AnyRc`/`AnyArc` reporting paths, negative controls, and coverage expectations for uniquely owned states. The type-based detection may flag types whose generation cannot actually produce an `Rc`/`Arc`. The warning does not claim complete modeling. It also does not cover manual harnesses using `kani::any()`. ## Difference from model-checking#4788 | | model-checking#4788 | This PR | |---|---|---| | Focus | Generate additional `Rc`/`Arc` ownership states | Report the finite modeling limitation | | Code | `Rc`/`Arc` arbitrary-value generators | Compiler metadata, driver output, JSON export, docs | | Dependency | Core generator change | Independent of model-checking#4788 | Shared-state regression cases that *depend* on model-checking#4788 are intentionally excluded from this PR; they can be contributed when the generator change lands. ## Testing **Passed locally on macOS using nightly-2026-10-23:** - `cargo build-dev` — passed, including `kani-compiler`. - `cargo test -p kani-driver -p kani_metadata` — 214 driver tests and 4 metadata tests passed; 2 documentation tests passed, 1 ignored. - `cargo run -p compiletest -- --suite json-handler --mode exec autoharness-refcount` — 1 passed, 0 failed. - `cargo run -p compiletest -- --suite script-based-pre --mode exec --force-rerun cargo_autoharness_smart_pointers` — 1 passed, 0 failed. - `cargo run -p compiletest -- --suite script-based-pre --mode exec --force-rerun autoharness` — 42 passed, 0 failed. - `./scripts/kani-fmt.sh --check` — passed. - `cargo clippy --workspace --tests -- -D warnings` — passed. - `RUSTFLAGS="--cfg=kani_sysroot" cargo clippy --workspace -- -D warnings` — passed. The broader AutoHarness suite includes the smart-pointer test, so these counts overlap. **Pending:** GitHub CI and maintainer review. The shared-ownership regression tests depending on model-checking#4788 are intentionally excluded. ## Related work Part of model-checking#4752. Related: model-checking#4788 (generator), model-checking#4958 (aliasing metadata), and model-checking#4991 (AutoHarness documentation restructure; may require rebase/conflict resolution). By submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0 and MIT licenses. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01WddFow1MppHhSFwg9HdZCz --------- Co-authored-by: Felipe R. Monteiro <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Description
kani::any::<Rc<T>>()/kani::any::<Arc<T>>()(and theAnyRc/AnyArcautoharness models) always produced a fresh allocation:strong_count == 1andweak_count == 0on every generated value. A function observing reference-count state could be verified for states a real caller can violate — e.g.assert_eq!(Arc::strong_count(&a), 1)passed even thoughlet _y = a.clone(); f(a)trips it at runtime. This is an input-space under-approximation (false-negative hazard) affectingstrong_count,weak_count,get_mut,try_unwrap,make_mut, etc.Design
Every documented count-dependent behavior of
Rc/Arcbranches only on uniqueness:strong_count == 1, and forget_mut/try_unwrapadditionallyweak_count == 0. The behavioral equivalence classes of real reference-count states are therefore exactly four —strong ∈ {1, ≥2} × weak ∈ {0, ≥1}— and the generator now covers all four with one representative each (strong_count ∈ {1, 2},weak_count ∈ {0, 1}) by nondeterministically leaking aclone()and/or adowngrade(). A leaked reference is observationally identical to one held by a caller for the duration of the function under verification. Generation stays loop-free, so it needs no unwinding bound, and the pointee remains fully nondeterministic.Note: this intentionally makes previously-"verified" uniqueness assertions fail — that is the soundness fix taking effect, not a regression.
Context
Surfaced in #4752 (during review of #4698). The issue offered two directions — model nondeterministic refcount state, or document the limitation; this PR implements the former, and the equivalence-class argument means the {1, 2} × {0, 1} representatives are behaviorally complete for the documented API surface rather than a lossy bound.
Manual testing
tests/kani/RefCount/nondet_rc_arc.rs(12 harnesses): count validity (strong_count >= 1), reachability of shared/weak states (#[kani::should_panic]on the old always-unique assertions — each now fails on exactly the count assertion), bothget_mutoutcomes,get_mutsucceeds underassume(unique && no weak), and extreme pointee values (kani::cover!(*rc == 255)SATISFIED) under sharing.tests/script-based-pre/cargo_autoharness_smart_pointers/witharc_count, which fails through theAnyArcmodel path onassertion failed: Arc::strong_count(&a) == 1(verifying the models carry the same semantics);.expectedupdated.FunctionContracts/receiver_contracts,SizeAndAlignOfDst,UnsizedCoercion,AsyncAwait,Drop): 28/28 pass.Resolves #4752
By submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0 and MIT licenses.