Skip to content

Challenge 26: Verify the safety of Rc and Weak in alloc::rc - #661

Open
kasimte wants to merge 3 commits into
model-checking:mainfrom
kasimte:challenge-26
Open

kasimte wants to merge 3 commits into
model-checking:mainfrom
kasimte:challenge-26

Conversation

@kasimte

@kasimte kasimte commented Aug 27, 2026 •

Copy link
Copy Markdown

Towards #382. Solves Challenge 26: Safety of Rc.

Verifies the safety of Rc and Weak in alloc::rc with Kani. The change is additive: one new mod verify in library/alloc/src/rc.rs, with no change to any std runtime body. All 12 required pub unsafe functions and all 54 listed safe functions carry Kani harnesses. Inputs are symbolic, and every input-bearing harness carries a kani::cover witness, so no harness passes vacuously. There are no cfg(kani) body swaps, so the code Kani verifies is the code that runs. All harnesses pass through scripts/run-kani.sh.

Scope follows the challenge. Generic T is limited to primitives, and allocator coverage is Global, both explicit and default. System lives in std and is not nameable from alloc. To keep CI cost down, harnesses run over a fixed set of primitive types: i8, i128, u8, u128, bool, unit, [u8; 4], and [u8] / [u128] slices.

Unsafe functions (12/12)

Each function is verified by #[kani::proof_for_contract] against a safety::requires precondition. Eleven also carry a safety::ensures postcondition. The four strong-count mutators assert the strong count changes by exactly ±1 and carry kani::modifies frame conditions.

Function Harness coverage
Rc<MaybeUninit<T>, A>::assume_init rc_check_assume_init
Rc<[MaybeUninit<T>], A>::assume_init rc_check_assume_init_slice
Rc<T>::from_raw rc_check_from_raw_{sized,unsized}
Rc<T>::increment_strong_count sized and unsized
Rc<T>::decrement_strong_count sized and unsized
Rc<T, A>::from_raw_in sized and unsized
Rc<T, A>::increment_strong_count_in sized and unsized
Rc<T, A>::decrement_strong_count_in sized and unsized
Rc<T, A>::get_mut_unchecked sized and unsized
Rc<dyn Any, A>::downcast_unchecked primitive subset and Vec payloads
Weak<T>::from_raw sized and unsized
Weak<T, A>::from_raw_in sized and unsized

Safe functions (54/54)

Every function in the challenge table has a rc_check_* harness, by API area:

  • Constructors and slice constructors. Lengths are symbolic under layout-validity assumptions, and pin / pin_in use a !Unpin sentinel.
  • Accessors and conversions. get_mut, make_mut, try_unwrap, and downcast are each exercised across their documented states.
  • From / FromIterator / TryFrom, including both TryFrom<Rc<[T]>> match arms.
  • Ownership and drop across unique / shared / weak_present, and the Weak methods across live / dangling / strong-zero.
  • RcInnerPtr refcount ops and the UniqueRc / UniqueRcUninit family.

The two RcFromSlice paths are both reached directly: the T: Copy specialization (today's TrivialClone impl) by primitives, and the T: Clone default through a manual-Clone wrapper, since no primitive reaches the Clone default.

Contracts

  • Preconditions and postconditions use safety::{requires, ensures}. The four modifies clauses use cfg_attr(kani, kani::modifies(...)), because the safety crate exposes no modifies wrapper.
  • Every pointer-validity precondition is a provenance check. It rebuilds the inner pointer from the data pointer, compares them with ptr::addr_eq, checks size and alignment with kani::mem::checked_size_of_raw and checked_align_of_raw, and requires strong >= 1. No contract constructs or consumes an Rc.

Soundness

  • Each harness body carries one kani::cover witness (141 total), placed after the last assumption and before the operation under test (before the panicking operation in should_panic harnesses). Every harness reports N of N cover properties satisfied, so every kani::assume has a reachability witness downstream of it.
  • Branch-state families construct each state explicitly and assert its documented outcome: Some / None, Ok / Err, strong and weak count relations, pointer identity, post-drop upgrade() behavior, and make_mut's clone-on-write and weak-disassociation effects. Constructor harnesses assert value preservation.
  • Both reachable abort guards, the inc_strong and inc_weak refcount overflows, have #[kani::should_panic] harnesses. A sweep of the remaining assert! / panic! / unwrap sites found no other reachable guard under the documented preconditions: the Layout::array().unwrap() sites are unreachable under the layout-validity assumptions, and the TrustedLen capacity-overflow panic needs an iterator longer than usize::MAX.

Loop verification

from_iter_exact's element-writing loop is verified against the unmodified upstream for-loop by bounded unrolling, with #[kani::unwind(5)] over length-3 inputs and a justification in-code. A loop-contract formulation cannot carry the element-value postconditions these harnesses assert: under invariant havoc, no invariant relates an opaque impl Iterator's yielded prefix to the memory the harness checks.

Bounds

  • The shared nondeterministic-vector helper bounds the symbolic length at sz <= 100, a CI tractability measure, not a safety precondition. Three sampled harnesses re-verify locally with the bound removed: clone_rc_vec_u8 (22.4s), from_raw_vec_u8 (40.5s), and get_mut_vec_u8_shared_none (35.2s), all with covers satisfied.
  • The assume_init_slice harnesses carry the same len <= 100 bound for runner memory on wide element types. The unbounded form verifies on the Linux CI runners, but the widest variants exceed macOS runner memory.
  • Fixed harness lengths (len 3, and N = 100 in into_array) carry in-code justifications.

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

@kasimte
kasimte requested a review from a team as a code owner August 27, 2026 18:56
@feliperodri feliperodri added the Challenge Used to tag a challenge label Sep 12, 2026

@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.

Thanks @kasimte, and apologies — this was also missed in the Challenge 26 round (created after our triage snapshot). Reviewed now.

This is excellent and essentially equal on verification merit to the solution we approved: 12/12 unsafe fns with genuine safety::{requires,ensures} + matching #[kani::proof_for_contract] (21 macro sites, sized + unsized/slice; real provenance/validity preconditions and checkable postconditions, satisfied by construction not assume) and ~54/54 safe abstractions (≥75%). Clean on T1/T2/T7, symbolic inputs, kani::cover non-vacuity witnesses, should_panic refcount-overflow twins.

Requesting changes for two reasons:

  1. One runtime-code edit. Weak::drop is reformatted from upstream's one-liner (let inner = if let Some(inner) = self.inner() { inner } else { return };) to a 5-line block. Semantically identical, but per CLAUDE.md this repo must not change std runtime logic / must stay in upstream sync, and it will diverge from upstream rustfmt (risk of check_rustc.sh format mismatch). Please revert that line.
  2. Prioritization: we reviewed both open Ch26 solutions and approved #582 (v3risec) — same 12/12 real proof_for_contract + ~54/54 coverage, but with no runtime-source edit and a leaner harness count (yours expands to ~1,293 harnesses = higher CI cost). We're keeping this as the strong alternative.

Minor: 5 loop-bearing safe fns use #[kani::unwind(5)] (bounded, len-3 inputs) — fine and challenge-permitted, but a weaker guarantee than an inductive proof. Superb work; revert the Weak::drop reflow and it's a clean equal to #582.

@kasimte

kasimte commented Sep 13, 2026

Copy link
Copy Markdown
Author

Thanks @feliperodri — appreciate you circling back. Addressed both points:

  • Reverted Weak::drop to upstream's one-liner — the diff is now purely additive (+3,459/−0, one file), with no runtime-source change.
  • Trimmed the primitive instantiations (961 → 593 harness invocations) to lower CI cost, while keeping all 12 unsafe fns and the full safe-fn set covered.

I've re-requested review — thanks again for the careful read.

Rc::into_array now returns Result<Rc<[T; N]>, Rc<[T]>> instead of
Option; adapt the harness binding and assertion accordingly.
feliperodri pushed a commit to srivatsansamraj/kani that referenced this pull request Oct 22, 2026
The gotoc backend handles `abort` but not `abort_immediate`. 

As of nightly-2026-10-11, `core::intrinsics` no longer declares `abort`.
`abort_immediate` is its renamed successor, and the standard library
calls it directly (e.g. in `Rc`'s reference-count overflow guards).
Harnesses reaching it fail with `Unsupported intrinsic abort_immediate`.

This handles `abort_immediate` exactly like `abort`: reaching it is a
failed assertion.

Manual testing: against verify-rust-std at its nightly-2026-10-11 pin,
the two `Rc` overflow `should_panic` harnesses in
[model-checking/verify-rust-std#661](model-checking/verify-rust-std#661)
fail with the unsupported-intrinsic error before this change and verify
successfully with it.

Resolves model-checking#5036

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

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.

2 participants