Skip to main content

diff_risk_core/detectors/
async_boundary.rs

1//! Async-boundary detector (Risk Matrix category B).
2//!
3//! Flags the most common ways an LLM silently introduces a deadlock or
4//! an executor-starvation bug in async Rust:
5//!
6//! * **`.await` inside a loop** — still the #1 "AI shipped a quadratic
7//!   roundtrip" pattern. Detected with a per-hunk indentation walk over
8//!   the added lines; false positives are possible when diff context is
9//!   missing but the precision/recall trade-off is acceptable for a
10//!   warning signal.
11//! * **`block_on` / `block_in_place`** — synchronously blocking the
12//!   executor.
13//! * **`std::thread::sleep`** — almost always wrong in async code.
14//! * **`async fn` signature changes** — adding or removing `async` from
15//!   a function changes every caller's await-point topology.
16//!
17//! Future (AST-level) work will catch `impl Future for …`, `Poll::Ready`
18//! hand-rolls, and `tokio::spawn` misuse.
19
20use regex::Regex;
21use std::sync::OnceLock;
22
23use crate::detectors::Detector;
24use crate::diff::{AddedLine, Diff};
25use crate::report::{Finding, RiskCategory, Severity};
26
27/// Keyword + indentation-tracking async-boundary detector.
28#[derive(Debug, Default, Clone, Copy)]
29pub struct AsyncBoundaryDetector;
30
31impl AsyncBoundaryDetector {
32    /// Construct a new detector.
33    #[must_use]
34    pub fn new() -> Self {
35        Self
36    }
37}
38
39fn loop_header_re() -> &'static Regex {
40    static RE: OnceLock<Regex> = OnceLock::new();
41    // Matches a loop header anchored to the line's first non-whitespace token.
42    // We intentionally do *not* match bare `loop` inside an expression because
43    // that's far rarer than the statement-level pattern we care about.
44    RE.get_or_init(|| Regex::new(r"^\s*(for\s+|while\s+|loop\s*\{)").expect("loop header regex"))
45}
46
47fn block_on_re() -> &'static Regex {
48    static RE: OnceLock<Regex> = OnceLock::new();
49    RE.get_or_init(|| Regex::new(r"\b(block_on|block_in_place)\s*\(").expect("block_on regex"))
50}
51
52fn thread_sleep_re() -> &'static Regex {
53    static RE: OnceLock<Regex> = OnceLock::new();
54    // `std::thread::sleep`, `thread::sleep`, or bare `sleep(` (from a `use` import).
55    // The bare form is too ambiguous without AST, so we require `thread::sleep` here.
56    RE.get_or_init(|| Regex::new(r"\bthread::sleep\b").expect("thread::sleep regex"))
57}
58
59fn async_fn_re() -> &'static Regex {
60    static RE: OnceLock<Regex> = OnceLock::new();
61    RE.get_or_init(|| Regex::new(r"\basync\s+fn\b").expect("async fn regex"))
62}
63
64impl Detector for AsyncBoundaryDetector {
65    fn name(&self) -> &'static str {
66        "async-boundary"
67    }
68
69    fn detect(&self, diff: &Diff) -> Vec<Finding> {
70        let mut findings = Vec::new();
71
72        for hunk in &diff.hunks {
73            findings.extend(await_in_loop(&hunk.path, &hunk.added));
74
75            for added in &hunk.added {
76                findings.extend(scan_added_line(&hunk.path, added));
77            }
78
79            for removed in &hunk.removed {
80                if async_fn_re().is_match(removed) {
81                    findings.push(Finding {
82                        category: RiskCategory::AsyncBoundary,
83                        severity: Severity::Medium,
84                        file: hunk.path.clone(),
85                        line: None,
86                        message: format!(
87                            "async fn removed or converted to sync: {}",
88                            truncate(removed, 120)
89                        ),
90                    });
91                }
92            }
93        }
94
95        findings
96    }
97}
98
99fn scan_added_line(path: &str, added: &AddedLine) -> Vec<Finding> {
100    let mut out = Vec::new();
101    let text = &added.text;
102
103    if block_on_re().is_match(text) {
104        out.push(Finding {
105            category: RiskCategory::AsyncBoundary,
106            severity: Severity::High,
107            file: path.to_string(),
108            line: Some(added.line),
109            message: format!("executor-blocking call introduced: {}", truncate(text, 120)),
110        });
111    }
112
113    if thread_sleep_re().is_match(text) {
114        out.push(Finding {
115            category: RiskCategory::AsyncBoundary,
116            severity: Severity::High,
117            file: path.to_string(),
118            line: Some(added.line),
119            message: format!(
120                "`thread::sleep` added — blocks the executor if called from an async task: {}",
121                truncate(text, 120)
122            ),
123        });
124    }
125
126    if async_fn_re().is_match(text) {
127        out.push(Finding {
128            category: RiskCategory::AsyncBoundary,
129            severity: Severity::Medium,
130            file: path.to_string(),
131            line: Some(added.line),
132            message: format!(
133                "async fn signature added or changed: {}",
134                truncate(text, 120)
135            ),
136        });
137    }
138
139    out
140}
141
142/// Indentation-tracking walk over a hunk's added lines that flags any
143/// `.await` appearing inside a still-open loop introduced earlier in the
144/// same added block.
145fn await_in_loop(path: &str, added: &[AddedLine]) -> Vec<Finding> {
146    let mut stack: Vec<usize> = Vec::new();
147    let mut findings = Vec::new();
148
149    for line in added {
150        let indent = leading_ws(&line.text);
151
152        // Pop any loops we've de-indented out of.
153        while let Some(&top) = stack.last() {
154            if indent <= top {
155                stack.pop();
156            } else {
157                break;
158            }
159        }
160
161        let is_loop = loop_header_re().is_match(&line.text);
162        let has_await = line.text.contains(".await");
163
164        // If `.await` lands while at least one loop header is still open above us,
165        // that's the canonical "await inside a loop" smell.
166        if has_await && !stack.is_empty() && !is_loop {
167            findings.push(Finding {
168                category: RiskCategory::AsyncBoundary,
169                severity: Severity::High,
170                file: path.to_string(),
171                line: Some(line.line),
172                message: format!(
173                    "`.await` inside a loop — risks serialised round-trips: {}",
174                    truncate(&line.text, 120)
175                ),
176            });
177        }
178
179        if is_loop {
180            stack.push(indent);
181        }
182    }
183
184    findings
185}
186
187fn leading_ws(s: &str) -> usize {
188    s.chars().take_while(|c| c.is_whitespace()).count()
189}
190
191fn truncate(s: &str, max: usize) -> String {
192    let trimmed = s.trim();
193    if trimmed.chars().count() <= max {
194        trimmed.to_string()
195    } else {
196        let cut: String = trimmed.chars().take(max).collect();
197        format!("{cut}…")
198    }
199}
200
201#[cfg(test)]
202mod tests {
203    use super::*;
204    use crate::diff::parse_unified_diff;
205
206    fn run(diff_text: &str) -> Vec<Finding> {
207        let diff = parse_unified_diff(diff_text).expect("valid diff");
208        AsyncBoundaryDetector::new().detect(&diff)
209    }
210
211    #[test]
212    fn await_inside_for_loop_is_high() {
213        let diff = "\
214--- a/src/work.rs
215+++ b/src/work.rs
216@@ -1,3 +1,6 @@
217 pub async fn go(items: Vec<Id>) {
218+    for id in items {
219+        fetch(id).await;
220+    }
221 }
222";
223        let findings = run(diff);
224        assert!(
225            findings.iter().any(
226                |f| f.severity == Severity::High && f.message.contains(".await` inside a loop")
227            ),
228            "expected await-in-loop hit, got {findings:?}"
229        );
230    }
231
232    #[test]
233    fn await_outside_loop_is_not_flagged() {
234        let diff = "\
235--- a/src/work.rs
236+++ b/src/work.rs
237@@ -1,2 +1,3 @@
238 pub async fn go() {
239+    fetch().await;
240 }
241";
242        let findings = run(diff);
243        assert!(
244            !findings.iter().any(|f| f.message.contains("inside a loop")),
245            "plain .await must not trigger the loop rule, got {findings:?}"
246        );
247    }
248
249    #[test]
250    fn block_on_added_is_high() {
251        let diff = "\
252--- a/src/runner.rs
253+++ b/src/runner.rs
254@@ -3,3 +3,4 @@ pub fn run(rt: &Runtime) {
255     let task = build();
256+    rt.block_on(task);
257 }
258";
259        let findings = run(diff);
260        assert!(
261            findings
262                .iter()
263                .any(|f| f.severity == Severity::High && f.message.contains("executor-blocking")),
264            "block_on must fire High, got {findings:?}"
265        );
266    }
267
268    #[test]
269    fn thread_sleep_added_is_high() {
270        let diff = "\
271--- a/src/net.rs
272+++ b/src/net.rs
273@@ -1,2 +1,3 @@
274 pub async fn poll_once() {
275+    std::thread::sleep(std::time::Duration::from_millis(50));
276 }
277";
278        let findings = run(diff);
279        assert!(
280            findings
281                .iter()
282                .any(|f| f.severity == Severity::High && f.message.contains("thread::sleep")),
283            "thread::sleep must fire High, got {findings:?}"
284        );
285    }
286
287    #[test]
288    fn new_async_fn_is_medium() {
289        let diff = "\
290--- a/src/api.rs
291+++ b/src/api.rs
292@@ -1,1 +1,2 @@
293 pub mod handlers;
294+pub async fn refresh() {}
295";
296        let findings = run(diff);
297        assert!(
298            findings
299                .iter()
300                .any(|f| f.severity == Severity::Medium
301                    && f.message.contains("async fn signature")),
302            "async fn added should fire Medium, got {findings:?}"
303        );
304    }
305
306    #[test]
307    fn async_converted_to_sync_is_medium() {
308        let diff = "\
309--- a/src/api.rs
310+++ b/src/api.rs
311@@ -1,3 +1,3 @@
312-pub async fn refresh() {}
313+pub fn refresh() {}
314";
315        let findings = run(diff);
316        assert!(
317            findings
318                .iter()
319                .any(|f| f.severity == Severity::Medium
320                    && f.message.contains("removed or converted")),
321            "async→sync must fire Medium, got {findings:?}"
322        );
323    }
324
325    #[test]
326    fn non_async_diff_is_silent() {
327        let diff = "\
328--- a/src/math.rs
329+++ b/src/math.rs
330@@ -1,1 +1,2 @@
331 pub fn add(a: i32, b: i32) -> i32 {
332+    a + b
333 }
334";
335        assert!(run(diff).is_empty());
336    }
337}