Skip to content

Challenge 7: Verify safety of Atomic types and Atomic Intrinsics with Kani - #683

Open
v3risec wants to merge 12 commits into
model-checking:mainfrom
v3risec:challenge-7-atomic
Open

v3risec wants to merge 12 commits into
model-checking:mainfrom
v3risec:challenge-7-atomic

Conversation

@v3risec

@v3risec v3risec commented Sep 8, 2026 •

Copy link
Copy Markdown

Summary

Resolves Challenge 7 (Safety of Methods for Atomic Types & Atomic Intrinsics) by combining Kani safety contracts/harnesses in library/core with a self-contained VeriFast concurrency and data-race companion proof in verifast-proofs/core/sync/atomic.rs/ and verifast-proofs/core/sync/atomic.rs-negative/.

Highlights

  • Zero production runtime modifications: library/core/src/sync/atomic.rs and library/core/src/intrinsics/mod.rs contain only Kani contract attributes and #[cfg(kani)] harnesses, with zero stub_verified, zero assume(false), and zero loop_invariant(true) added in Challenge 7 / this PR's changes. .github/workflows/ and shared scripts/run-kani.sh are left untouched.
  • Full Challenge 7 coverage (Parts 1–3 + T7):
    • Part 1 (all 12 from_ptr constructors): Verified across x86_64-unknown-linux-gnu (10 integer widths + AtomicBool + AtomicPtr<T>) and aarch64-unknown-linux-gnu (adding AtomicI128 / AtomicU128).
    • Part 2 (all 14 unsafe helpers + optional panics): Verified generic atomic_store, atomic_load, atomic_swap, atomic_add, atomic_sub, atomic_compare_exchange, atomic_compare_exchange_weak, atomic_and, atomic_nand, atomic_or, atomic_xor, atomic_max, atomic_umax, atomic_umin (plus atomic_min via Part 3), including continuing-unwind lifetime preservation on illegal orderings.
    • Part 3 (all 91 intrinsic/ordering entries): Verified against doc/src/challenges/0007-atomic-types.md via MIR route and edge checks: 810 integer permissions on x86_64, 972 on aarch64, and 25 pointer RMW edges (fetch_byte_{add,sub}, fetch_{and,or,xor} × 5 orderings, plus fetch_ptr_{add,sub} element scaling).
    • T7 (Kani contracts & harnesses): 176 targeted harnesses (174 non-panicking with verified post-call cover properties) on x86_64 (200 / 198 on aarch64), binding 186 (216 on aarch64) contracts in sync/atomic.rs and 41 in intrinsics/mod.rs to proof_for_contract harnesses; direct callsite ordering checks confirm 4/4 legal controls accepted and 8/8 illegal orderings rejected.
  • Data-race freedom & real multi-threaded POSIX clients:
    • Six layered VeriFast annotation profiles (access, rmw, pointer-access, pointer-rmw, u32, readonly) overlaid on untouched copies of library/core/src with Rust token-identity (source_tokens.rs), native MIR refinement, and compiled witness/production MIR bridge checks across both x86_64 and aarch64.
    • Supports both writable atomic borrows (frac == 1) and read-only fractional atomic borrows (0 < af < 1) split from full writable backing ownership [1](*p |-> val) (ruling out read-only .rodata / &'static fractional shares without writable backing), permitting concurrent ordinary non-atomic reads alongside atomic load and guaranteed-failing compare_exchange(_weak) on AtomicBool and AtomicU32, while rejecting potentially-writing CAS (including same-value current == new), store, RMWs, and concurrent ordinary writes.
    • Five two-worker POSIX clients (u32, boolean, pointer, width, readonly) are verified against witness-derived specifications, LLVM IR boundary-checked, linked against repository core, and executed on Linux x86_64.
  • Audited minimal VeriFast tool patch: verifast-core.patch (15 upstream files, 124 hunks, zero RustConstPtrType widening) is audited 1-to-1 against TRUSTED-BASE.md with positive and negative regressions across x86_64/aarch64 and normal/scoped export modes.
  • Upstream stdlib bug discovered (rust-lang/rust#166918): On EMULATE_ATOMIC_BOOL targets (riscv32/riscv64/loongarch32/loongarch64), failing AtomicBool::compare_exchange(_weak) performs an unconditional atomic RMW write (fetch_or(false) / swap), triggering Data Race UB with concurrent non-atomic reads under Miri (checks/upstream_bug_166918_miri.rs). Per General Rules, verification targets native 8-bit CAS platforms (x86_64-unknown-linux-gnu and aarch64-unknown-linux-gnu).

Verification Results

  • bash verifast-proofs/check-verifast-proofs.sh: PASS (all existing proofs + Challenge 7 all 6 profiles and witness/production MIR checks on x86_64 and aarch64, 5 two-worker POSIX clients verified, linked, and executed).
  • bash verifast-proofs/check-verifast-proofs-negative.sh: PASS (362 expected rejections across tool regressions, MIR/checker soundness controls, update rollback faults, fractional-only backing rejection, and single/two-thread negative controls).
  • Local Kani recipe (verifast-proofs/core/sync/atomic.rs/README.md) on pinned Kani 87c87010eda7797d7fa14033ca68bcbe17184a63 (Kani 0.68.0, CBMC 6.11.0) in both default and -Z uninit-checks modes: 176/176 harnesses PASS, 174/174 post-call covers satisfied, T7 metadata 186/41 complete, kani-negative-ordering.sh 4/4 legal accepted and 8/8 illegal rejected.
  • Not run locally: native AArch64 Kani (host is x86_64).

Known Limitations & Remaining Committee Scope Notes

  • Two conservative protocol boundaries remain outside this companion proof and are documented in README.md and TRUSTED-BASE.md: (1) operation-level overlapping mixed-width views (Gate 3-B), and (2) ordinary accesses after joining workers prior to ending the zero-runtime ghost borrow.
  • Neither Kani (ub_checks::can_dereference/can_write) nor VeriFast models OS page-table PROT_READ protections; VeriFast requires full [1] writable ownership before constructing either writable or read-only fractional atomic borrows, and OS page-permission details are documented in README.md and TRUSTED-BASE.md.

Resolves #83

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 requested a review from a team as a code owner September 8, 2026 16:10
@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.

Approving — leading solution for Challenge 7

Thanks @v3risec. Reviewed both open Challenge 7 solutions with our vacuity tooling and local Kani (pinned 0.67.0 / CBMC 6.8.0). This is complete and sound, and directly fixes the failure mode of the other solution (#578, whose contracts were decorative). Prioritizing it.

Coverage:

  • Part 1: 12/12 from_ptr with real #[requires] (align + valid-for-read + valid-for-write) / #[ensures(ptr::eq)] and matching #[kani::proof_for_contract] — including AtomicI128/U128 (the exact gap that sank #578; the harnesses exist in source and compile on targets with 128-bit atomic support). AtomicPtr covered over pointee sizes 0/1/2/3/4 as the doc requires.
  • Part 2: all 14 unsafe atomic ops (store/load/swap/add/sub/compare_exchange(_weak)/and/nand/or/xor/max/umax/umin + atomic_min) with requires + kani::modifies + ensures + proof_for_contract across every width + isize/usize + *mut u8, plus ordering #[requires] on the safe methods and 6 #[kani::should_panic] illegal-ordering proofs.
  • Part 3: intrinsic wrappers (const-generic intrinsics can't carry contracts directly — kani#3345) with proof_for_contract enumerating orderings/type matrix.

Soundness (all clean):

  • T1: no cfg body swaps — fn bodies unchanged, only attributes + use added.
  • T2: n/a (no loops/invariants).
  • T7: every contract has an explicit proof_for_contract; .github/workflows/kani.yml has no atomic autoharness entries, so — unlike #578 — the contracts are genuinely checked, not decorative.
  • Not assume-the-conclusion; genuinely symbolic (kani::any() values, any_ordering() families covering all legal variants, arbitrary pointer addresses).
  • No runtime std logic changed.

Local Kani (CBMC 6.8.0): 3/3 runnable-sample harnesses VERIFICATION SUCCESSFUL — harness_atomic_add_i32 (proof_for_contract), harness_safe_compare_exchange_panics_on_release (should_panic), harness_atomic_bool_from_ptr (proof_for_contract). harness_atomic_i128_from_ptr didn't register locally because 128-bit atomics are cfg-gated off on x86_64 — a target limitation, not an omission (the harness is present in source).

Note for the record: T-generic data-race / mixed-size overlapping-access UB is explicitly out of scope (Kani single-threaded model — consistent with the challenge, which points to concurrency being separate). Complete, sound, and the decisive improvement over #578.

@feliperodri
feliperodri requested a review from a team September 13, 2026 16:17
@feliperodri feliperodri added the Accepted Solution Tag used to mark the solution accepted for a given challenge label Sep 13, 2026
@v3risec

v3risec commented Sep 15, 2026

Copy link
Copy Markdown
Author

@feliperodri Thanks for the thorough review and approval! I really appreciate the detailed validation.

@v3risec

v3risec commented Sep 23, 2026

Copy link
Copy Markdown
Author

I added an explicit #[kani::unwind(2)] bound to the proof harnesses for Atomic*::update. update is implemented as a retry loop around compare_exchange_weak. Without an explicit unwind bound, Kani/CBMC does not infer a finite bound for this loop and keeps unwinding it during symbolic execution, which caused these harnesses to run indefinitely.

The explicit bound does not change the implementation being verified; it only controls loop unwinding in the proof harness. This is sound for these harnesses because Kani keeps unwinding assertions enabled: if two unwindings were insufficient to cover a feasible execution under the current model, the corresponding unwinding assertion would fail instead of silently truncating the proof.

With #[kani::unwind(2)], the unwinding assertions for the update loops pass, and all 14 update harnesses verify successfully.

This bound should be understood as a bound for these single-threaded verification harnesses under Kani's current atomic model, rather than as a general semantic bound on Atomic::update. In particular, Rust permits compare_exchange_weak to fail spuriously.

@feliperodri

Copy link
Copy Markdown
Member

@v3risec, a consistency note after re-reviewing #587 (Ch27, Arc).

Challenge 7's UB list requires the absence of data races, and this PR states that its harnesses are single-threaded and don't discharge that obligation. #587 is in the same position for Ch27. Both are approved as sound proofs toward their challenges, but neither solves its challenge on its own. Separately, CI doesn't pass -Z uninit-checks, so "reading from uninitialized memory" isn't checked automatically either.

You can address these in follow-up PRs. Whether solutions must cover data races, which Kani can't check, is being discussed in #733.

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

@v3risec, changing my review to request changes so this isn't merged as a solution to Challenge 7.

Challenge 7's UB list requires the absence of data races, and this PR states that its harnesses are single-threaded and don't discharge that obligation. Kani can't check data races, so this is a gap in the tool rather than in the proofs. #733 asks the committee how solutions should be judged on it. Until that's decided, a PR that leaves out a listed UB item doesn't complete the challenge.

The proofs themselves remain sound and useful. Separately, this has merge conflicts with main after the recent subtree syncs; could you rebase it?

@feliperodri feliperodri removed the Accepted Solution Tag used to mark the solution accepted for a given challenge label Nov 3, 2026
@v3risec

v3risec commented Nov 3, 2026

Copy link
Copy Markdown
Author

Thanks! I'm working on rebasing the PR.

@v3risec

v3risec commented Nov 3, 2026 •

Copy link
Copy Markdown
Author

@feliperodri I have synchronized this branch with current main and updated the verification code for the atomic API changes.

CI passed for commit 4bb26f7, including all eight Kani verification partitions across Ubuntu and macOS, and Rust Tests.

The changes are:

  • Updated the load/store proof targets, helper calls, and intrinsic wrappers to explicitly specify VOLATILE = false, resolving the const-generic compilation errors introduced by the upstream API changes. These proofs cover ordinary atomic accesses; the new volatile paths remain outside this PR's verification scope.
  • Updated contract proof targets to refer to the underlying Atomic<T> implementations, which Kani can resolve after the public atomic types became aliases. Also corrected the target configuration for the pointer update harness.
  • Changed the bool from_ptr harness to use symbolic byte storage, avoiding the unsupported arbitrary-bool-array layout under initialization checking. The contract preconditions retain valid bool representations, with assertions and cover checks confirming that both false and true are reachable.
  • Replaced the contracts on fetch_update, try_update, and update with ordinary proof harnesses. Their previous modifies(self) specification excluded legal callback writes to captured state. The harnesses now express the ordering preconditions explicitly with kani::assume, exercise callbacks that modify captured state, and check returned values and final atomic values. The optional-update harnesses cover both Some and None.
  • Fixed import formatting and added comments explaining the callback verification approach and its scope.

Regarding your note about -Z uninit-checks, I have now run all 338 Challenge 7 harnesses available on x86_64-unknown-linux-gnu with initialization checking enabled, using the unmodified Kani version pinned by this repository:

  • 14 from_ptr harnesses.
  • 135 unsafe-helper harnesses.
  • 91 atomic-intrinsic harnesses.
  • 98 safe-API harnesses, including 14 expected-panic harnesses.

All 338 passed, and all 374 cover properties were satisfied. The 128-bit cases were not registered on this target because of its atomic capability configuration. The CI configuration does not enable -Z uninit-checks, so the initialization-checking results above are additional local validation alongside the passing CI results.

No standard-library runtime function bodies were changed, and no Kani modifications were used for these verification results.

The verification remains single-threaded and does not discharge the data-race obligation discussed in #733.

v3risec and others added 4 commits November 25, 2026 14:23
Complete Challenge 7 (Atomic types and intrinsics) verification:
- Keep Kani contracts/harnesses in library/core with zero production body changes.
- Add zero-Python VeriFast companion proof and negative suite under
  verifast-proofs/core/sync/atomic.rs{,-negative} wired into the existing
  check-verifast-proofs{,-negative}.sh entrypoints (no workflow or shared Kani script edits).
- Cover all 12 Part 1 constructors, 14 Part 2 helpers + optional panics,
  91 Part 3 intrinsic/ordering entries (810 x86-64 / 972 AArch64 integer
  permissions, 25 pointer RMW edges), writable and read-only fractional
  atomic borrows, 5 linked/executed POSIX two-worker clients, and 362
  expected negative rejections.
- Document upstream EMULATE_ATOMIC_BOOL data-race bug rust-lang#166918
  with standalone Miri reproducer.
@v3risec

v3risec commented Dec 4, 2026

Copy link
Copy Markdown
Author

@feliperodri I have updated the Challenge 7 submission with a complete, self-contained VeriFast concurrency & data-race companion proof alongside the Kani contracts:

  1. VeriFast proof structure & repo conventions: Added verifast-proofs/core/sync/atomic.rs/ and verifast-proofs/core/sync/atomic.rs-negative/ wired into verifast-proofs/check-verifast-proofs.sh and verifast-proofs/check-verifast-proofs-negative.sh, with pure Bash + zero-dependency Rust MIR/inventory checker check_mir.rs and zero changes to .github/workflows/ or shared scripts/run-kani.sh.
  2. Full Part 1–3 + T7 coverage: Verified all 12 from_ptr constructors, all 14 Part 2 helpers + optional illegal-ordering panics, and all 91 Part 3 intrinsic/ordering entries (810 integer permissions on x86_64, 972 on aarch64, 25 pointer RMW edges), plus 176/176 Kani harnesses (174/174 post-call covers, T7 186/41 on x86_64, default & -Z uninit-checks) and 4/4 legal + 8/8 illegal Kani direct ordering contract checks.
  3. Writable & read-only concurrent protocols + 5 live POSIX worker clients: Both full writable borrows (frac == 1) and read-only fractional borrows (0 < af < 1, split from full writable backing ownership [1] to rule out .rodata/&'static shares, permitting concurrent ordinary non-atomic reads alongside atomic load and guaranteed-failing compare_exchange(_weak) on AtomicBool and AtomicU32) are verified across x86_64 and aarch64, with 5 two-worker POSIX clients linked and executed against repository core, and 362 expected rejections in negative CI.
  4. Minimal audited tool patch & upstream stdlib bug: verifast-core.patch stays minimal (15 files, 124 hunks, 1-to-1 audited in TRUSTED-BASE.md). During verification we also found and filed rust-lang/rust#166918 (Data Race UB in AtomicBool::compare_exchange(_weak) on EMULATE_ATOMIC_BOOL targets), so the companion scopes to native 8-bit CAS targets (x86_64 and aarch64) with a standalone Miri reproducer in checks/upstream_bug_166918_miri.rs.

Ready for another look whenever you have time!

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 7: Safety of Methods for Atomic Types & Atomic Intrinsics

2 participants