diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml new file mode 100644 index 0000000..96b6ab6 --- /dev/null +++ b/.github/workflows/smoke.yml @@ -0,0 +1,23 @@ +name: Smoke + +on: + push: + branches: [ "main" ] + pull_request: + branches: [ "main" ] + +env: + CARGO_TERM_COLOR: always + +jobs: + smoke: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v4 + # rust-toolchain.toml pins the nightly toolchain + rustc-dev components; + # rustup installs them on first use. + - name: Build pn + run: cargo build --bin pn --verbose + - name: Run pipeline smoke tests (async + sync regression baselines) + run: ./scripts/smoke.sh diff --git a/.gitignore b/.gitignore index 4201a14..24dfce1 100644 --- a/.gitignore +++ b/.gitignore @@ -8,3 +8,4 @@ bench/** .vscode .DS_Store +tmp/ diff --git a/README.md b/README.md index 85e18ab..077acde 100644 --- a/README.md +++ b/README.md @@ -121,6 +121,15 @@ Default flags when none are given: -m deadlock --pn-analysis-dir=/tmp ``` +### Run smoke tests + +`./scripts/smoke.sh` builds `pn`, analyzes the benchmark crates, and asserts each deadlock report's `Bug count` (and the lock-group count for async cases). It guards the async modeling (`bench/deadlock/async-deadlock` expects 1 bug / 2 lock groups; `bench/deadlock/async-no-deadlock` expects 0 bugs / 1 lock group) and the sync regression baselines. The same script runs in CI (`.github/workflows/smoke.yml`). + +```bash +./scripts/smoke.sh # builds pn, runs all cases +PN_BIN=target/debug/pn ./scripts/smoke.sh # reuse an existing binary +``` + ## Common flags | Flag | Meaning | diff --git a/bench/deadlock/async-no-deadlock/Cargo.toml b/bench/deadlock/async-no-deadlock/Cargo.toml new file mode 100644 index 0000000..c425931 --- /dev/null +++ b/bench/deadlock/async-no-deadlock/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "async-no-deadlock" +version = "0.1.0" +edition = "2021" + +[workspace] + +[dependencies] +tokio = { version = "1", features = ["rt-multi-thread", "macros", "sync", "time"] } +parking_lot = { version = "0.12", features = ["send_guard"] } diff --git a/bench/deadlock/async-no-deadlock/src/main.rs b/bench/deadlock/async-no-deadlock/src/main.rs new file mode 100644 index 0000000..89b5d15 --- /dev/null +++ b/bench/deadlock/async-no-deadlock/src/main.rs @@ -0,0 +1,30 @@ +// Async false-positive guard: two spawned tasks share a single mutex and hold +// it across an `.await` suspend point. There is no lock-order cycle (only one +// lock exists), so every interleaving can make progress and the analyzer must +// report zero deadlocks. Exercises suspend/resume semantics (C-007/T-003), +// cross-instance `Arc` alias merging (C-006), and spawn/join wiring +// (C-001..C-004) without a bug to find. +use std::sync::Arc; + +use parking_lot::Mutex; + +async fn task1(m: Arc>) { + let mut _guard = m.lock(); + tokio::time::sleep(std::time::Duration::from_millis(10)).await; + *_guard += 1; +} + +async fn task2(m: Arc>) { + let mut _guard = m.lock(); + tokio::time::sleep(std::time::Duration::from_millis(10)).await; + *_guard += 2; +} + +#[tokio::main] +async fn main() { + let m = Arc::new(Mutex::new(0)); + let h1 = tokio::spawn(task1(m.clone())); + let h2 = tokio::spawn(task2(m.clone())); + let _ = h1.await; + let _ = h2.await; +} diff --git a/scripts/smoke.sh b/scripts/smoke.sh new file mode 100755 index 0000000..0a7b21b --- /dev/null +++ b/scripts/smoke.sh @@ -0,0 +1,110 @@ +#!/usr/bin/env bash +# +# Petri-net pipeline smoke tests (todolist T-001). +# +# Builds `pn` (unless PN_BIN is set), analyzes the benchmark crates listed +# below, and asserts the deadlock report's `Bug count` — and, for the async +# cases, the number of lock groups discovered (`[lockgroup-detail]` log lines). +# These assertions guard the async modeling (C-001..C-012, T-003) and the +# sync regression baseline promised in the todolist "engineering constraints". +# +# Usage: +# ./scripts/smoke.sh # build pn + run all cases +# PN_BIN=target/debug/pn ./scripts/smoke.sh # reuse an existing binary +# +# Environment: +# PN_BIN pn binary to use (default: build target/debug/pn) +# PN_SMOKE_DIR scratch directory for reports/logs (default: /tmp/smoke) +# PN_LOG log level for pn (default: warn; lock-group lines need warn) + +set -euo pipefail + +DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" + +PN_BIN="${PN_BIN:-}" +if [[ -z "$PN_BIN" ]]; then + echo "==> building pn" + cargo build --manifest-path "$DIR/Cargo.toml" --bin pn + PN_BIN="$DIR/target/debug/pn" +fi +[[ -x "$PN_BIN" ]] || { echo "pn binary not found/executable: $PN_BIN" >&2; exit 1; } + +# pn links dynamically against the active toolchain's librustc_driver. +RUSTC_SYSROOT="$(rustc --print sysroot)" +export LD_LIBRARY_PATH="${RUSTC_SYSROOT}/lib${LD_LIBRARY_PATH:+:${LD_LIBRARY_PATH}}" +export PN_LOG="${PN_LOG:-warn}" + +TMP="${PN_SMOKE_DIR:-$DIR/tmp/smoke}" +rm -rf "$TMP" +mkdir -p "$TMP" + +failures=0 + +# run_case [expected-lock-groups|-] +run_case() { + local bench="$1" crate="$2" expect_bugs="$3" expect_groups="${4:--}" + local log="$TMP/$crate.log" + local out="$TMP/$crate" + + local label="bugs=$expect_bugs" + if [[ "$expect_groups" != "-" ]]; then + label="$label groups=$expect_groups" + fi + echo "==> $bench (expect $label)" + if ! RUSTC_WRAPPER="$PN_BIN" \ + PN_FLAGS="-m deadlock -p $crate --pn-analysis-dir=$out" \ + CARGO_TARGET_DIR="$TMP/target" \ + cargo build --manifest-path "$DIR/bench/$bench/Cargo.toml" >"$log" 2>&1; then + echo "FAIL: $crate: build/analysis failed (see $log)" + tail -n 5 "$log" + failures=$((failures + 1)) + return + fi + + local report="$out/$crate/deadlock_report.txt" + if [[ ! -f "$report" ]]; then + echo "FAIL: $crate: missing report $report" + failures=$((failures + 1)) + return + fi + + local bugs groups ok=1 + bugs="$(sed -nE 's/^Bug count *: *([0-9]+).*/\1/p' "$report")" + if [[ "$bugs" != "$expect_bugs" ]]; then + echo "FAIL: $crate: bug count '$bugs' != expected '$expect_bugs'" + ok=0 + fi + + if [[ "$expect_groups" != "-" ]]; then + groups="$(grep -c '\[lockgroup-detail\] group' "$log" || true)" + if [[ "$groups" != "$expect_groups" ]]; then + echo "FAIL: $crate: lock groups '$groups' != expected '$expect_groups'" + ok=0 + fi + fi + + if ((ok)); then + echo "PASS: $crate (bugs=$bugs)" + else + failures=$((failures + 1)) + fi +} + +# --- async corpus (T-001): suspend/resume, spawn/join, lock-group merging --- +run_case deadlock/async-deadlock async_deadlock 1 2 +run_case deadlock/async-no-deadlock async_no_deadlock 0 1 + +# --- sync regression baseline (todolist "engineering constraints") --- +run_case deadlock/intra intra 4 +run_case deadlock/inter inter 4 +run_case deadlock/conflict-inter conflict_inter 1 +run_case deadlock/lock-closure lock_closure 1 +run_case deadlock/static-ref static_ref 1 +run_case deadlock/condvar-closure condvar_closure 6 + +echo +if ((failures > 0)); then + echo "smoke: $failures case(s) FAILED" + exit 1 +fi +echo "smoke: all cases passed" diff --git a/src/memory/pta/builder.rs b/src/memory/pta/builder.rs index b9f213a..a29b2c6 100644 --- a/src/memory/pta/builder.rs +++ b/src/memory/pta/builder.rs @@ -591,12 +591,12 @@ impl<'a, 'tcx> ConstraintBuilder<'a, 'tcx> { ) { let empty = self.arena.empty_path(); - // 为闭包/协程环境创建一个 heap + // Create a heap for the closure/coroutine environment self.call_counter += 1; let clo_heap = self.arena.heap( AllocSite { func: self.func, - bb: 0, // 闭包定义不是 call site,用 0 + bb: 0, // A closure definition is not a call site; use 0 idx: self.call_counter, }, empty, @@ -607,7 +607,7 @@ impl<'a, 'tcx> ConstraintBuilder<'a, 'tcx> { // be constructed at several sites; all recorded heaps are unioned. self.closure_envs.entry(def_id).or_default().push(clo_heap); - // 字段级 Copy: clo_heap.field_i ⊇ upvar_value_i + // Field-level Copy: clo_heap.field_i ⊇ upvar_value_i for (i, op) in fields.iter_enumerated() { let Some(value) = self.operand_value(op) else { continue; @@ -655,7 +655,7 @@ impl<'a, 'tcx> ConstraintBuilder<'a, 'tcx> { } } } - // 如果 upvar 是引用类型,还需要 AddressOf + // If the upvar is a reference type, also add an AddressOf constraint let upvar_ty = upvar_tys.get(i.as_usize()); if let Some(upvar_ty) = upvar_ty { if upvar_ty.is_ref() { @@ -674,7 +674,7 @@ impl<'a, 'tcx> ConstraintBuilder<'a, 'tcx> { } } - // 将 dst_local (闭包变量) 指向这个 heap + // Point dst_local (the closure variable) at this heap let dst_slot = self .arena .var_ctx(self.ctx.clone(), self.func, dst_local, empty); @@ -757,7 +757,7 @@ impl<'a, 'tcx> ConstraintBuilder<'a, 'tcx> { self.arena .var_ctx(self.ctx.clone(), self.func, u32::MAX - i as u32, empty); - // 字段级 Copy: clo_heap.field_j ⊇ upvar_value_j + // Field-level Copy: clo_heap.field_j ⊇ upvar_value_j for (j, upvar_loc) in arg_nodes.iter().enumerate() { if let Some(upvar_loc) = upvar_loc { let field_path = self.arena.extend_path(empty, ProjElem::Field(j as u32)); diff --git a/src/translate/mir_to_pn/terminator.rs b/src/translate/mir_to_pn/terminator.rs index 6f9106f..cfc2427 100644 --- a/src/translate/mir_to_pn/terminator.rs +++ b/src/translate/mir_to_pn/terminator.rs @@ -151,6 +151,11 @@ impl<'translate, 'analysis, 'tcx> BodyToPetriNet<'translate, 'analysis, 'tcx> { // (the poll-switch's other target). if self.tcx.is_coroutine(self.instance.def_id()) && self.block_sets_poll_pending(bb_idx) { if let Some(cont) = self.find_suspend_continuation(bb_idx) { + log::debug!( + "[async] structured suspend detection matched bb{} -> continuation bb{}", + bb_idx.index(), + cont.index() + ); self.handle_fallthrough(bb_idx, &cont, name, "suspend"); } return; @@ -229,16 +234,96 @@ impl<'translate, 'analysis, 'tcx> BodyToPetriNet<'translate, 'analysis, 'tcx> { /// Whether the return block sets `_0` to `Poll::Pending` (a coroutine /// suspend) rather than `Poll::Ready` (completion). + /// + /// Structured detection (no debug-string rendering): the `Pending` variant + /// of the body's `Poll`-shaped return type is located by variant name, and + /// every `_0`-writing statement is matched against it — + /// `SetDiscriminant { _0, v }`, `_0 = Aggregate(Adt(.., v, ..))`, or + /// `_0 = const` (variant `DefId` for unevaluated consts, discriminant bits + /// for evaluated ones). The last recognized `_0` write in the block decides. fn block_sets_poll_pending(&self, bb_idx: BasicBlock) -> bool { + use rustc_middle::mir::{AggregateKind, Operand, RETURN_PLACE, Rvalue, StatementKind}; + + let Some(pending_idx) = self.poll_pending_variant() else { + return false; + }; + let bb = &self.body.basic_blocks[bb_idx]; + let mut sets_pending = false; for stmt in &bb.statements { - if let rustc_middle::mir::StatementKind::Assign(box (place, _)) = &stmt.kind { - if place.local.index() == 0 { - return format!("{:?}", stmt.kind).contains("Pending"); + match &stmt.kind { + StatementKind::SetDiscriminant { + place, + variant_index, + } if place.local == RETURN_PLACE && place.projection.is_empty() => { + sets_pending = *variant_index == pending_idx; + } + StatementKind::Assign(box (place, rvalue)) + if place.local == RETURN_PLACE && place.projection.is_empty() => + { + let variant = match rvalue { + Rvalue::Use(Operand::Constant(constant), _) => { + self.const_poll_variant(constant.const_) + } + Rvalue::Aggregate(box AggregateKind::Adt(_, variant_index, _, _, _), _) => { + Some(*variant_index) + } + _ => None, + }; + if let Some(variant) = variant { + sets_pending = variant == pending_idx; + } } + _ => {} + } + } + sets_pending + } + + /// The `Pending` variant of the body's return type when it is a + /// `Poll`-shaped enum (has both `Ready` and `Pending` variants). + fn poll_pending_variant(&self) -> Option { + let adt_def = self.body.return_ty().ty_adt_def()?; + if !adt_def.is_enum() { + return None; + } + let mut pending = None; + let mut has_ready = false; + for (idx, variant) in adt_def.variants().iter_enumerated() { + match variant.name.as_str() { + "Pending" => pending = Some(idx), + "Ready" => has_ready = true, + _ => {} + } + } + has_ready.then_some(pending).flatten() + } + + /// Resolve a constant `Poll` value to its enum variant without rendering: + /// fieldless variants may stay unevaluated and reference the variant's + /// `DefId`; evaluated consts carry the discriminant bits, matched against + /// the ADT's discriminant table. + fn const_poll_variant( + &self, + constant: rustc_middle::mir::Const<'tcx>, + ) -> Option { + use rustc_middle::mir::Const; + + let adt_def = self.body.return_ty().ty_adt_def()?; + match constant { + Const::Unevaluated(unevaluated, _) => adt_def + .variants() + .iter_enumerated() + .find(|(_, variant)| variant.def_id == unevaluated.def) + .map(|(idx, _)| idx), + evaluated => { + let scalar = evaluated.try_to_scalar_int()?; + let bits = scalar.to_bits(scalar.size()); + adt_def + .discriminants(self.tcx) + .find_map(|(idx, discr)| (discr.val == bits).then_some(idx)) } } - false } /// Find the block a coroutine suspend resumes to: the poll switch that diff --git a/todolist.md b/todolist.md index 251a852..7121e53 100644 --- a/todolist.md +++ b/todolist.md @@ -1,68 +1,73 @@ -# Async 建模 —— 覆盖范围与待办清单 +# Async modeling — coverage and roadmap -> 本文档记录 MIR → Petri 网管线中异步(`async`/`tokio`)建模的**当前覆盖范围**与**后续演进方向**,按工程优先级排列。回归测试统一后置(见 `T-001`)。 +> This document records the **current coverage** and the **planned evolution** of async (`async`/`tokio`) modeling in the MIR → Petri net pipeline, ordered by engineering priority. Regression testing is now in place via `scripts/smoke.sh` + CI (see `T-001`). -## 当前覆盖范围(已实现并验证) +## Current coverage (implemented and verified) -| ID | 能力 | 机制 | 状态 | +| ID | Capability | Mechanism | Status | | --- | ---- | ---- | ---- | -| C-001 | `tokio::spawn` 分类 | `classify_thread_control` 扩展 `AsyncSpawn`,正则命中 `tokio…::spawn` | ✅ | -| C-002 | `JoinHandle.await` 识别 | 类型判定 `classify_async_join_by_ty`(被 await future 类型含 `JoinHandle`),不依赖 def-path(blanket impl 路径不含 `JoinHandle`) | ✅ | -| C-003 | 协程 future 解析 | `resolve_closure_def_id` 支持 `TyKind::Coroutine`/`CoroutineClosure`,spawn 实参解析到协程 `(start, end)` | ✅ | -| C-004 | spawn/join 接线 | 复用 `handle_spawn`/`handle_join`:spawn 输出弧到协程 `start`,join 从任务 `end` 汇合 | ✅ | -| C-005 | 跨 await 锁 guard 识别 | `LockGuardId.field` + `register_projected_guard`,协程状态投影 `(*_state as variant#N).k` 中的 guard 按其字段索引注册并解析 receiver | ✅ | -| C-006 | 协程 upvar 数据流 | PTA env 阶段按 `tcx.is_coroutine` 分支:`_1.0 → state-heap`(状态指针),修正闭包式 `_1.field_i` 不匹配协程访问形状的问题;跨实例 `Arc` 别名归并到同一锁资源 | ✅ | -| C-007 | 挂起/完成语义 | `handle_return` 区分 `Poll::Pending`(挂起,续接到 continuation)与 `Poll::Ready`(完成,接函数 end) | ✅ | -| C-008 | 状态分发约束 | 协程 `bb0` 判别式 switch 仅接入口态(discriminant 0),resume 路径由挂起续接,避免"未挂起即重 poll"假路径 | ✅ | -| C-009 | Join 去重 | `.await` 降级中的 `into_future` 包装不作为 join,仅 `poll` 调用接 join,避免任务结束 token 被二次消费 | ✅ | -| C-010 | 基准验证 | `bench/deadlock/async-deadlock`:双任务 AB-BA 死锁,锁分组收敛为 2 个真实锁,`Bug count == 1` | ✅ | - -覆盖效果:异步死锁(持锁跨 `.await`、任务间互等)经可达性分析可检出;spawn/join 同步边与线程模型同构。 - -## 待办(Roadmap) - -### T-001 回归测试自动化 -- **现状**:无自动化测试守护 async 建模;C-005~C-009 任一回归都无法被 CI 捕获。 -- **目标**:新增 CI smoke test,对 `bench/deadlock/async-deadlock` 断言 `Bug count == 1` 且锁分组 == 2;并扩充 async bench 语料(`select!`、`tokio::sync::Mutex`、超时变体)。 -- **状态**:待办(用户明确统一后置)。 - -### T-002 future 组合子覆盖(`select!` / `join!` / `tokio::join!`) -- **现状**:仅覆盖 `JoinHandle.await`(`poll` 调用形态)。`join!`/`select!` 宏展开为 `poll_fn` + 多 future 轮询,无单一 `poll` 调用锚点,当前分类无法命中。 -- **目标**:在 `CallSiteCollector::visit_local_decl` 层识别 `futures_util::future::join::Join` / `select::Select` / `JoinAll` 组合子类型,建模"全分支汇合"(join)与"先到先得 + 取消落选分支"(select)。select 需处理落选分支的 `CoroutineDrop`(释放其持有的锁),否则误报死锁。 -- **优先级**:高(`select!` 是 tokio 核心模式,目前为已知盲区)。 - -### T-003 挂起检测的版本鲁棒性 -- **现状**:C-007 用 `_0 = Poll::Pending` 的 debug-string 启发式判定挂起,绑定当前 rustc(nightly-2026-05-29)的 MIR 形态(`SetDiscriminant` 渲染)。 -- **目标**:改用结构化判定(`Rvalue::SetDiscriminant` 的 variant 与 `Poll` ADT 判别式对照,或 `Body::coroutine_kind`/`tcx.coroutine_kind`),消除对 debug 输出的依赖;对工具链升级做兼容测试。 - -### T-004 协程布局建模(`tcx.coroutine_layout`) -- **现状**:C-006 用状态指针 + upvar 槽位近似,未显式建模 `State.variant#N.k` 布局;对多挂起点、复杂 upvar 场景的精度依赖近似。 -- **目标**:以 `tcx.coroutine_layout(def_id)` 映射 upvar 到具体 variant 字段,替代启发式投影;为 T-002/T-008 提供结构化基础。 - -### T-005 跨域(线程 + 任务)共享锁健全性 -- **现状**:`LockGuardId.field` 使协程状态槽 guard 与普通 local guard 身份区分;`std::sync::Mutex` 在线程与任务间共享时的 receiver 别名依赖 points-to 归并,未做专项验证。 -- **目标**:补充"线程持锁、异步任务阻塞"跨域用例,验证不因 sync/async 上下文判别而拆分共享锁(避免假阴性);必要时为 receiver 别名建立专项断言。 - -### T-006 异步同步原语扩展 -- **现状**:`LockGuardTy` 显式排除 `tokio`/`async_std`/`futures`/`loom` 的 guard;`tokio::sync::Mutex` 等异步原语未建模。 -- **目标**:按需纳入 `tokio::sync::Mutex`/`RwLock`/`Semaphore`/`mpsc` 通道,映射为对应资源 place;评估其与 std 原语在挂起场景下的语义差异(取消安全性、取消时释放)。 - -### T-007 执行器/计时语义 -- **现状**:`sleep().await` 的 Pending/Ready 分支按非确定性探索,未建模 timer 推进与超时释放。 -- **目标**:为时间相关 future 引入抽象的调度 token(或显式"可恢复挂起"模型),消除"挂起即终态"的过度近似;评估对状态空间规模的影响。 - -### T-008 检测器扩展(async 场景) -- **现状**:死锁检测器可用;数据竞争/原子性检测对 async 场景未验证。 -- **目标**:将 `.await` 挂起点作为抢占点接入原子性检测精度;验证跨任务 `UnsafeRead`/`UnsafeWrite` 的 happens-before(join 边)语义。 - -## 已知限制(当前不建模,作为声明) - -- 执行器调度与任务优先级:任务交错由 Petri 网非确定性枚举,不区分调度策略。 -- timer/超时/IO 就绪:不建模时间推进,挂起分支按非确定处理。 -- `select!` 取消语义:落选分支的资源释放未建模(见 T-002)。 -- 挂起检测绑定工具链版本(见 T-003)。 - -## 工程约束 - -- 所有 C-005~C-009 的翻译层改动以 `tcx.is_coroutine` / join 类型判定门控,**不影响同步代码路径**(回归已验证 `conflict-inter`/`lock-closure`/`inter`/`intra`/`static-ref`/`condvar-closure` 计数不变)。 -- `LockGuardId.field` 是唯一触及共享代码的改动:sync guard 的 `field` 恒为 `None`,行为退化为原有 `(instance, local)` 语义。 \ No newline at end of file +| C-001 | `tokio::spawn` classification | `classify_thread_control` extended with `AsyncSpawn`; the regex matches `tokio…::spawn` | ✅ | +| C-002 | `JoinHandle.await` recognition | Type-based check `classify_async_join_by_ty` (the awaited future's type contains `JoinHandle`); does not rely on the def-path (blanket impl paths never mention `JoinHandle`) | ✅ | +| C-003 | Coroutine future resolution | `resolve_closure_def_id` supports `TyKind::Coroutine`/`CoroutineClosure`; spawn arguments resolve to the coroutine's `(start, end)` places | ✅ | +| C-004 | spawn/join wiring | Reuses `handle_spawn`/`handle_join`: spawn adds an output arc to the coroutine `start`; join converges from the task `end` | ✅ | +| C-005 | Lock guards held across `.await` | `LockGuardId.field` + `register_projected_guard`: guards stored in coroutine state projections `(*_state as variant#N).k` are registered by field index and resolved to their receiver | ✅ | +| C-006 | Coroutine upvar dataflow | The PTA env phase branches on `tcx.is_coroutine`: `_1.0 → state-heap` (the state pointer), fixing the mismatch between closure-style `_1.field_i` and coroutine access shapes; `Arc` aliases across instances merge into one lock resource | ✅ | +| C-007 | Suspend/completion semantics | `handle_return` distinguishes `Poll::Pending` (suspend, routed to the continuation) from `Poll::Ready` (completion, routed to the function end) | ✅ | +| C-008 | State dispatch constraint | The coroutine `bb0` discriminant switch only wires the entry state (discriminant 0); resume paths come from suspend continuations, avoiding bogus "re-poll without suspend" paths | ✅ | +| C-009 | Join deduplication | The `into_future` wrapper in `.await` lowering is not treated as a join; only the `poll` call wires the join, so the task-completion token is not consumed twice | ✅ | +| C-010 | Benchmark validation | `bench/deadlock/async-deadlock`: two-task AB-BA deadlock; lock groups converge to the 2 real locks; `Bug count == 1` | ✅ | +| C-011 | Structured suspend detection (T-003) | `block_sets_poll_pending` is now a structured check: the `Pending` variant of the `Poll`-shaped return type is located by variant name and matched against `SetDiscriminant` / `Aggregate(Adt)` / constants (unevaluated consts by variant `DefId`, evaluated consts by discriminant bit pattern); no dependency on debug-string rendering | ✅ | +| C-012 | CI smoke regression (T-001) | `scripts/smoke.sh` + `.github/workflows/smoke.yml`: async corpus asserts bug counts and lock-group counts; sync benchmarks guard the regression baselines | ✅ | + +Coverage result: async deadlocks (locks held across `.await`, mutual waits between tasks) are detected by reachability analysis; spawn/join synchronization edges are isomorphic to the thread model. + +## Roadmap + +### T-001 Regression test automation ✅ (done) +- **Implementation**: `scripts/smoke.sh` builds `pn`, analyzes each benchmark crate, and asserts the `Bug count` in `deadlock_report.txt` plus the `[lockgroup-detail]` lock-group count; `.github/workflows/smoke.yml` runs it on push / pull_request (`main`). +- **Completed**: + - `bench/deadlock/async-deadlock` asserts `Bug count == 1` and lock groups `== 2`; + - new async corpus entry `bench/deadlock/async-no-deadlock` (two tasks sharing one mutex, held across `.await`) asserts `Bug count == 0` and lock groups `== 1`, guarding against **false positives** in suspend semantics and alias merging; + - sync regression baselines (`intra`/`inter`/`conflict-inter`/`lock-closure`/`static-ref`/`condvar-closure`) are covered by the same script, aligned with the "counts unchanged" promise in the engineering constraints. +- **Remaining (depends on T-002/T-006)**: `select!`, `tokio::sync::Mutex`, and timeout-variant corpus entries are not included yet — those paths are not modeled, so asserting on them would give a false green signal; add them together with the corresponding features. + +### T-002 Future combinator coverage (`select!` / `join!` / `tokio::join!`) +- **Current state**: only `JoinHandle.await` (the `poll` call shape) is covered. `join!`/`select!` macros expand to `poll_fn` + polling of multiple futures, with no single `poll` call anchor, so the current classification cannot match them. +- **Goal**: recognize `futures_util::future::join::Join` / `select::Select` / `JoinAll` combinator types at the `CallSiteCollector::visit_local_decl` layer; model "all branches converge" (join) and "first one wins + cancel the losing branches" (select). For select, the losing branch's `CoroutineDrop` must be handled (releasing the locks it holds), otherwise deadlocks are falsely reported. +- **Priority**: high (`select!` is a core tokio pattern and currently a known blind spot). + +### T-003 Version robustness of suspend detection ✅ (done) +- **Implementation**: `block_sets_poll_pending` is now a structured check. It first locates the `VariantIdx` of `Pending` from the body's return type (a `Poll`-shaped enum, identified by having both `Ready` and `Pending` variants by name), then structurally matches every `_0`-writing statement in the block: `SetDiscriminant { _0, v }`, `_0 = Aggregate(Adt(.., v, ..))`, `_0 = const` (`Const::Unevaluated` matched by variant `DefId`; evaluated consts matched by discriminant bit pattern against `adt_def.discriminants`). The last recognized `_0` write decides; the debug-string heuristic has been removed. +- **Verification**: `async-deadlock` still reports `Bug count == 1` with `2` lock groups (the suspend path is hit via the structured check); sync baseline counts are unchanged (the check is gated by `tcx.is_coroutine`, so sync paths are unaffected). The async assertions in `smoke.sh` serve as the compatibility test for toolchain upgrades. + +### T-004 Coroutine layout modeling (`tcx.coroutine_layout`) +- **Current state**: C-006 approximates with the state pointer + upvar slots and does not explicitly model the `State.variant#N.k` layout; precision for multiple suspend points and complex upvar scenarios relies on the approximation. +- **Goal**: use `tcx.coroutine_layout(def_id)` to map upvars to concrete variant fields, replacing the heuristic projections; provide the structural foundation for T-002/T-008. + +### T-005 Cross-domain (thread + task) shared-lock soundness +- **Current state**: `LockGuardId.field` distinguishes guards in coroutine state slots from plain local guards; receiver aliasing when a `std::sync::Mutex` is shared between threads and tasks relies on points-to merging and has not been specifically validated. +- **Goal**: add "thread holds the lock, async task blocks on it" cross-domain cases and verify that shared locks are not split by sync/async context discrimination (avoiding false negatives); add dedicated assertions for receiver aliasing if needed. + +### T-006 Async synchronization primitive extension +- **Current state**: `LockGuardTy` explicitly excludes `tokio`/`async_std`/`futures`/`loom` guards; async primitives such as `tokio::sync::Mutex` are not modeled. +- **Goal**: model `tokio::sync::Mutex`/`RwLock`/`Semaphore`/`mpsc` channels on demand, mapping them to the corresponding resource places; evaluate their semantic differences from std primitives in suspend scenarios (cancellation safety, release on cancel). + +### T-007 Executor/timer semantics +- **Current state**: the Pending/Ready branches of `sleep().await` are explored nondeterministically; timer advancement and timeout release are not modeled. +- **Goal**: introduce an abstract scheduling token (or an explicit "resumable suspend" model) for time-related futures, eliminating the "suspend is terminal" over-approximation; evaluate the impact on state-space size. + +### T-008 Detector extensions (async scenarios) +- **Current state**: the deadlock detector works; data-race/atomicity detection has not been validated for async scenarios. +- **Goal**: feed `.await` suspend points into atomicity detection as preemption points; validate the happens-before (join edge) semantics of cross-task `UnsafeRead`/`UnsafeWrite`. + +## Known limitations (currently not modeled, stated explicitly) + +- Executor scheduling and task priorities: task interleavings are enumerated nondeterministically by the Petri net; scheduling policies are not distinguished. +- timer/timeout/IO readiness: time advancement is not modeled; suspend branches are treated nondeterministically. +- `select!` cancellation semantics: resource release of losing branches is not modeled (see T-002). +- Suspend detection only recognizes direct writes to `_0` within the block (`SetDiscriminant` / constant / `Aggregate(Adt)`); an indirect `Poll::Pending` write routed through a temporary is not covered (see T-003 for what is done). + +## Engineering constraints + +- All translation-layer changes in C-005~C-009 are gated by `tcx.is_coroutine` / join type checks and **do not affect sync code paths** (regressions verified: `conflict-inter`/`lock-closure`/`inter`/`intra`/`static-ref`/`condvar-closure` counts unchanged). +- `LockGuardId.field` is the only change touching shared code: for sync guards `field` is always `None`, degrading to the original `(instance, local)` semantics.