Repository navigation
Conversation
- Created a new Cargo.toml for the async-deadlock benchmark, specifying dependencies on `tokio` and `parking_lot`. - Implemented the main logic in src/main.rs, featuring two asynchronous tasks that demonstrate deadlock potential using mutexes. - Utilized Arc and Mutex from the parking_lot crate to manage shared state across tasks.
- Added `async_spawn` and `async_join` fields to `PnConfig` for better async control. - Updated `ThreadControlKind` enum to include `AsyncSpawn` and `AsyncJoin`. - Enhanced thread control classification to recognize async spawn and join patterns. - Modified `BodyToPetriNet` to handle async thread control, improving the analysis of async tasks.
- Renamed the original async task to `task1` and created a new async task `task2` to demonstrate different locking patterns. - Updated the main function to spawn the new task names, maintaining the benchmark's focus on async deadlock scenarios.
- Removed the pn.toml.example configuration file as it is no longer needed. - Updated LockGuardId to include an optional field index for guards stored in coroutine/struct states. - Refactored BlockingCollector to utilize the new lockguard_id_for_dest method, improving the handling of lock-call destinations and ensuring accurate tracking of guard projections. - Enhanced alias ID generation to incorporate the field index from LockGuardId, improving alias analysis accuracy.
- Reorganized imports for better structure and readability. - Enhanced the `proj_kinds` function to improve formatting and clarity. - Updated the handling of closure and coroutine aggregates in `process_closure_aggregate`, ensuring accurate upvar type collection. - Improved the formatting of constraint additions for better readability. - Streamlined the handling of environment paths for closures and coroutines, enhancing maintainability.
ScreenshotReduced Petri net for ReproductionBench source ( async fn task1(a: Arc<Mutex<i32>>, b: Arc<Mutex<i32>>) {
let _ga = a.lock();
tokio::time::sleep(Duration::from_millis(10)).await;
let _gb = b.lock();
}
async fn task2(a: Arc<Mutex<i32>>, b: Arc<Mutex<i32>>) {
let _ga = a.lock();
tokio::time::sleep(Duration::from_millis(10)).await;
let _gb = b.lock();
}
#[tokio::main]
async fn main() {
let l1 = Arc::new(Mutex::new(0));
let l2 = Arc::new(Mutex::new(0));
let h1 = tokio::spawn(task1(l1.clone(), l2.clone()));
let h2 = tokio::spawn(task2(l2.clone(), l1.clone()));
let _ = h1.await;
let _ = h2.await;
}Run: ./detect.sh bench/deadlock/async-deadlock/ -m deadlock --pn-analysis-dir=tmp/async-verify --viz-petrinet --viz-stategraphWhat fires (classification)
Lock grouping (the open gap)Both guards per task are now collected (incl. the one held across Every cross-instance alias query returns Result |
|
|
||
| if let ty::FnDef(def_id, substs) = *func_ty.kind() { | ||
| let fn_path = self.tcx.def_path_str(def_id); | ||
| if let Some(control_kind) = |
There was a problem hiding this comment.
Async spawn misses coroutine callees
High Severity
AsyncSpawn is classified, but operand_closure_instance still only matches Closure/FnDef, not Coroutine/CoroutineClosure. tokio::spawn of an async fn future therefore never records spawn_calls or a spawn ThreadControl edge to the task body, so alias-based join matching cannot recover the spawned task.
Additional Locations (1)
Reviewed by Cursor Bugbot for commit 96ea40a. Configure here.
| } | ||
|
|
||
| let lockguard_id = LockGuardId::new(self.instance_id, destination.local); | ||
| let lockguard_id = Self::lockguard_id_for_dest(self.instance_id, destination); |
There was a problem hiding this comment.
Drop call ignores projected guards
Medium Severity
Lock acquire and Drop terminators identify coroutine-state guards with lockguard_id_for_dest (field-sensitive), but the ::drop call path still builds LockGuardId::new without a field. Projected guards unlocked via an explicit drop call are missed, so the lock token is never returned.
Additional Locations (2)
Reviewed by Cursor Bugbot for commit 96ea40a. Configure here.
| .and_then(|a| a.node.place()) | ||
| .map(|p| format!("{:?}", p.ty(self.body, self.tcx).ty)) | ||
| .unwrap_or_default(); | ||
| log::warn!("[async] spawn: failed to resolve future from arg (ty={})", first_ty); |
There was a problem hiding this comment.
Join skips Pin handle locals
Medium Severity
AsyncJoin on Future::poll passes a Pin<&mut JoinHandle> local into handle_join, which only looks up that local in spawn_handle_end. Refs are tracked in local_ref_source, but join never follows them (or Pin construction), so handle-identity join fails and falls back to spawn order.
Reviewed by Cursor Bugbot for commit 96ea40a. Configure here.
Progress: aliasing fix landedResult: 4 locks → 2 real locks (AB–BA structure correct)
This is exactly the expected cross-task lock identity. Reduced net now has Root cause of the fix
Genuine AB–BA deadlock now detectedState Remaining (separate from aliasing): bug count 16 ≠ 1The count is inflated because the model treats the coroutine suspend-return ( |
Status: aliasing problem fixed ✓The original problem — four guards collapsing to the wrong four lock resources — is fixed by What the fix changed
Remaining (documented, not part of the aliasing fix)Bug count is 16, not 1. The deadlock detector flags every terminal state without Branch commits (vs
|
Final: bug count = 1 ✓ (genuine AB–BA deadlock)
The single incident is the genuine AB–BA: both tasks blocked at What got fixed (3 issues driving the count from 16 → 1)
Regression checkSync benchmarks ( Branch |
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 2 potential issues.
There are 5 total unresolved issues (including 3 from previous reviews).
❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.
Reviewed by Cursor Bugbot for commit d2d0747. Configure here.
| } | ||
| } | ||
| false | ||
| } |
There was a problem hiding this comment.
Fragile Pending suspend detection
Medium Severity
block_sets_poll_pending decides whether a coroutine return is a suspend by checking whether {:?} of the _0 assignment contains the substring Pending. Rustc often lowers Poll::Pending as an Aggregate/Adt with a numeric VariantIdx, so that Debug string may never include Pending, and suspends keep being treated as real completions (lock leak / wrong terminals).
Reviewed by Cursor Bugbot for commit d2d0747. Configure here.
| self.handle_fallthrough(bb_idx, &cont, name, "suspend"); | ||
| } | ||
| return; | ||
| } |
There was a problem hiding this comment.
Missing suspend continuation dead-ends
Medium Severity
When a coroutine return is classified as Poll::Pending but find_suspend_continuation returns None, handle_return exits without adding any outgoing arc. The suspend block becomes a sink; tokens stuck there look like deadlocks even though the task should resume or complete.
Additional Locations (1)
Reviewed by Cursor Bugbot for commit d2d0747. Configure here.





Summary
Models Rust
async/tokiocontrol flow in the MIR→Petri-net pipeline: task spawn,JoinHandle.await, and lock guards held across.awaitsuspend points. Adds anasync-deadlockbench and documents the one remaining PTA gap.Changes
Async spawn/join classification (
config.rs,structure.rs,callgraph.rs)async_spawn/async_joinconfig regexes (tokio::spawn, etc.).ThreadControlKind::AsyncSpawn/AsyncJoin.classify_async_join_by_ty:.awaiton aJoinHandlelowers tocore::futureblanket impls (into_future/Pin<&mut _>::poll) whose def-paths never mentionJoinHandle, so the join site is recognized by inspecting the awaited future's type.Coroutine future resolution (
closure.rs,thread_control.rs)resolve_closure_def_idnow resolvesTyKind::Coroutine/CoroutineClosure, sotokio::spawn(task(...))'s future resolves to its(start, end)places andhandle_joincan link the spawned task'sendinto the.awaitjoin transition.Coroutine-state guard recognition (
blocking.rs,pointsto.rs,calls.rs,drop_unsafe.rs)LockGuardIdgains afieldso a guard stored in coroutine state ((*_state as variant#N).k) is keyed by its field.BlockingCollector::register_projected_guardcollects guards whoselock()destination is a projection and records the resolved receiver;handle_lock_call/handle_droplook up guards field-sensitively.PTA groundwork (
builder.rs)Rvalue::AggregatehandlesAggregateKind::Coroutine/CoroutineClosurelike closures (records construction site + env heap). Foundation for coroutine-layout modeling.Bench + docs
bench/deadlock/async-deadlock/— two tokio tasks, AB–BA lock order across.await.docs/async-modeling.md— design, the type-check rationale, and the open PTA gap.Known remaining gap
Cross-instance
Arc<Mutex>aliasing through coroutine state is still unsound: coroutines read upvars via_1.0 → State → Downcast(variant#N) → field, which the closure-style_1.field_ienv binding doesn't match, so the four guards in the bench split into four lock resources instead of two. Fix requirestcx.coroutine_layoutmodeling (documented indocs/async-modeling.md).Note
Medium Risk
Touches core PTA env binding, lock-guard identity, and Petri-net control flow for coroutines. Heuristic string checks (
Poll::Pending,JoinHandlein types) can mis-classify unrelated futures or inflate/miss deadlocks.Overview
Enables deadlock detection on
async/tokiotasks:tokio::spawnandJoinHandle.awaitare wired like thread spawn/join, and mutex guards stored in coroutine state across.awaitare tracked as real lock resources.Spawn/join. New
AsyncSpawn/AsyncJoinkinds plus config regexes. Because.awaitlowers tocore::futureblanketpoll/into_future, join is recognized by type (JoinHandlein the awaited ty) and only on::pollso the task end token is not consumed twice.PTA + guards. Coroutine aggregates reuse closure upvar heaps. Env binding for coroutines points
_1.0(Pin<&mut State>) at that heap soArc<Mutex>captures alias across tasks.LockGuardIdis field-sensitive; projectedlock()destinations in state variants are registered with their receiver.Control flow.
Poll::Pendingreturns resume to the continuation instead of completing the task (which leaked held locks). Coroutinebb0dispatch only takes the entry discriminant so resume states are not explored from the initial poll.The new
bench/deadlock/async-deadlock(AB–BA acrosssleep().await) is documented as reporting exactly one deadlock.Reviewed by Cursor Bugbot for commit d2d0747. Bugbot is set up for automated code reviews on this repo. Configure here.