Skip to main content

vector_core/
spawn_audit.rs

1//! The policy check behind [`crate::db::spawn_bound`], shared by every crate
2//! that spawns per-account work.
3//!
4//! A bare `tokio::spawn` leaves its task resolving whoever is logged in when it
5//! finally asks, which is how account A's work lands in account B's storage.
6//! That mistake is invisible in review, so it is caught mechanically instead:
7//! walk a source tree and fail on an unbound spawn.
8//!
9//! A task that genuinely owns no account state — a process-lifetime listener, a
10//! socket drain, CPU work on bytes already in hand — is exempted per site with a
11//! `// spawn-detached: <why>` marker on the line or just above it. Per site, not
12//! per file: files hold both kinds, and exempting one wholesale hides the other.
13
14use std::path::Path;
15
16/// Every unbound `tokio::spawn` under `src_root`, as `path:line` relative to
17/// `crate_root`. Empty means the tree is clean.
18pub fn unbound_spawns(crate_root: &Path, src_root: &Path) -> Vec<String> {
19    let mut offenders = Vec::new();
20    let mut stack = vec![src_root.to_path_buf()];
21    while let Some(dir) = stack.pop() {
22        let Ok(entries) = std::fs::read_dir(&dir) else { continue };
23        for entry in entries.flatten() {
24            let path = entry.path();
25            if path.is_dir() {
26                stack.push(path);
27                continue;
28            }
29            if path.extension().and_then(|e| e.to_str()) != Some("rs") {
30                continue;
31            }
32            let rel = path
33                .strip_prefix(crate_root)
34                .unwrap_or(&path)
35                .to_string_lossy()
36                .replace('\\', "/");
37            let Ok(src) = std::fs::read_to_string(&path) else { continue };
38            for (line, n) in unbound_lines_in(&rel, &src) {
39                let _ = line;
40                offenders.push(format!("{rel}:{n}"));
41            }
42        }
43    }
44    offenders.sort();
45    offenders
46}
47
48/// Whether one file's shipping code still spawns unbound. Used by the ratchet.
49pub fn has_unbound_spawn(src: &str) -> bool {
50    unbound_lines(src).next().is_some()
51}
52
53/// [`has_unbound_spawn`] for a file at `rel` (relative to its crate root), with the stricter
54/// rule for the transport directories.
55pub fn has_unbound_spawn_at(rel: &str, src: &str) -> bool {
56    unbound_lines_in(rel, src).next().is_some()
57}
58
59/// The unbound spawn lines in one file's shipping code, as `(line, 1-based no)`.
60///
61/// Tests spawn freely — only shipping code is bound — so everything from the
62/// test MODULE onward is ignored. The cut is the first `#[cfg(test)]` that
63/// introduces a `mod`, not the first `#[cfg(test)]` anywhere: a test-only hook
64/// function early in a file would otherwise hide every line after it.
65// Assembled at compile time so this file never contains the text it searches for.
66const NEEDLE: &str = concat!("tokio::", "spawn(");
67const RT_NEEDLE: &str = concat!("rt::", "spawn(");
68const ON_NEEDLE: &str = concat!("spawn_", "on(");
69const METHOD_NEEDLE: &str = concat!(".", "spawn(");
70
71/// Directories whose tasks run on the transport runtime: there any `.spawn(` (a `JoinSet`, a
72/// runtime handle) starts a task too, so it needs the marker as well.
73const TRANSPORT_DIRS: &[&str] = &["src/transport/", "src/i2p/"];
74
75fn unbound_lines(src: &str) -> impl Iterator<Item = (&str, usize)> {
76    unbound_lines_in("", src)
77}
78
79/// [`unbound_lines`] for the file at `rel`. A file that opens with `#![cfg(test)]` is a test
80/// module in its own right and spawns freely.
81fn unbound_lines_in<'a>(rel: &str, src: &'a str) -> impl Iterator<Item = (&'a str, usize)> {
82    let strict = TRANSPORT_DIRS.iter().any(|d| rel.contains(d));
83    let test_file = src
84        .lines()
85        .map(str::trim)
86        .find(|l| !l.is_empty() && !l.starts_with("//"))
87        .is_some_and(|l| l == "#![cfg(test)]");
88    let all: Vec<&str> = if test_file { Vec::new() } else { src.lines().collect() };
89    let cut = all
90        .windows(2)
91        .position(|w| {
92            w[0].trim() == "#[cfg(test)]"
93                && matches!(w[1].trim_start(), l if l.starts_with("mod ") || l.starts_with("pub mod ") || l.starts_with("pub(crate) mod "))
94        })
95        .unwrap_or(all.len());
96    let lines: Vec<&str> = all[..cut].to_vec();
97    let owned: Vec<(&str, usize)> = lines
98        .iter()
99        .enumerate()
100        .filter(|(i, line)| {
101            (line.contains(NEEDLE)
102                || line.contains(RT_NEEDLE)
103                || line.contains(ON_NEEDLE)
104                || (strict && line.contains(METHOD_NEEDLE)))
105                && !line.trim_start().starts_with("//")
106                && !line.contains("spawn-detached:")
107                && !lines[..*i].iter().rev().take(4).any(|p| p.contains("spawn-detached:"))
108        })
109        .map(|(i, line)| (*line, i + 1))
110        .collect();
111    owned.into_iter()
112}
113
114/// Account access from a thread that does not carry the account.
115///
116/// A tokio task-local rides the task, not the thread. `spawn_blocking` and
117/// `std::thread::spawn` run outside it, so `db::` and `STATE` there resolve
118/// whoever is live rather than the caller's account — the one way left to write
119/// one account's data into another's storage. Nothing in the tree does this;
120/// this is what keeps it that way.
121pub fn account_access_off_task(crate_root: &Path, src_root: &Path) -> Vec<String> {
122    let mut offenders = Vec::new();
123    let mut stack = vec![src_root.to_path_buf()];
124    while let Some(dir) = stack.pop() {
125        let Ok(entries) = std::fs::read_dir(&dir) else { continue };
126        for entry in entries.flatten() {
127            let path = entry.path();
128            if path.is_dir() {
129                stack.push(path);
130                continue;
131            }
132            if path.extension().and_then(|e| e.to_str()) != Some("rs") {
133                continue;
134            }
135            let rel = path.strip_prefix(crate_root).unwrap_or(&path).to_string_lossy().replace('\\', "/");
136            let Ok(src) = std::fs::read_to_string(&path) else { continue };
137            let prod = src.split("#[cfg(test)]").next().unwrap_or("");
138            let lines: Vec<&str> = prod.lines().collect();
139            for (i, line) in lines.iter().enumerate() {
140                if !line.contains("spawn_blocking") && !line.contains("std::thread::spawn") {
141                    continue;
142                }
143                if line.trim_start().starts_with("//") {
144                    continue;
145                }
146                let window = lines[i..(i + 14).min(lines.len())].join("\n");
147                let body = spawned_call(&window);
148                if body.contains("db::") || body.contains("STATE.") {
149                    offenders.push(format!("{rel}:{}", i + 1));
150                }
151            }
152        }
153    }
154    offenders.sort();
155    offenders
156}
157
158/// The spawn call itself, from its name to its closing paren: what follows it runs back
159/// on the task.
160fn spawned_call(text: &str) -> &str {
161    let from = text.find("spawn_blocking").or_else(|| text.find("std::thread::spawn")).unwrap_or(0);
162    let mut depth = 0i32;
163    for (at, c) in text[from..].char_indices() {
164        match c {
165            '(' => depth += 1,
166            ')' => {
167                depth -= 1;
168                if depth == 0 {
169                    return &text[from..from + at + 1];
170                }
171            }
172            _ => {}
173        }
174    }
175    &text[from..]
176}
177
178/// The assertion both crates run. `pending` is a shrink-only worklist of files
179/// not yet converted; it is a ratchet, not an exemption, so a file that no
180/// longer spawns unbound must be deleted from it.
181pub fn assert_all_spawns_bound(crate_root: &Path, pending: &[&str]) {
182    let src_root = crate_root.join("src");
183    let offenders: Vec<String> = unbound_spawns(crate_root, &src_root)
184        .into_iter()
185        .filter(|o| !pending.iter().any(|p| o.starts_with(&format!("{p}:"))))
186        .collect();
187    assert!(
188        offenders.is_empty(),
189        "these tasks are not bound to an account — use vector_core::db::spawn_bound so their \
190         work follows the account they started under, or mark the site \
191         `// spawn-detached: <why it owns no account state>`:\n  {}",
192        offenders.join("\n  ")
193    );
194
195    let converted: Vec<&&str> = pending
196        .iter()
197        .filter(|file| {
198            std::fs::read_to_string(crate_root.join(file))
199                .map(|src| !has_unbound_spawn(&src))
200                .unwrap_or(false)
201        })
202        .collect();
203    assert!(
204        converted.is_empty(),
205        "these files are fully converted — delete them from the pending list so they stay \
206         converted:\n  {converted:?}"
207    );
208
209    let off_task = account_access_off_task(crate_root, &src_root);
210    assert!(
211        off_task.is_empty(),
212        "a blocking thread runs outside the task, so it does not carry the caller's account — \
213         these would read or write whoever is live instead. Do the work inline, or capture the \
214         session and re-enter it with db::with_session:\n  {}",
215        off_task.join("\n  ")
216    );
217}
218
219#[cfg(test)]
220mod tests {
221    use super::*;
222
223    #[test]
224    fn a_bare_spawn_is_caught_and_a_marked_one_is_not() {
225        assert!(has_unbound_spawn("fn f() { tokio::spawn(async {}); }"));
226        assert!(!has_unbound_spawn(
227            "fn f() { tokio::spawn(async {}); } // spawn-detached: pure CPU."
228        ));
229        assert!(!has_unbound_spawn(
230            "// spawn-detached: pure CPU.\ntokio::spawn(async {});"
231        ));
232        assert!(!has_unbound_spawn("fn f() { db::spawn_bound(async {}); }"));
233    }
234
235    #[test]
236    fn the_marker_does_not_reach_past_its_own_site() {
237        // Four lines of slack, so a marker above a multi-line setup still
238        // applies — but not so far that it silently covers the NEXT spawn.
239        let far = format!("// spawn-detached: nope.\n{}tokio::spawn(async {{}});", "\n".repeat(5));
240        assert!(has_unbound_spawn(&far));
241    }
242
243    #[test]
244    fn test_code_spawns_freely() {
245        assert!(!has_unbound_spawn("#[cfg(test)]\nmod t { fn f() { tokio::spawn(async {}); } }"));
246        assert!(!has_unbound_spawn("//! Tests.\n#![cfg(test)]\nfn f() { tokio::spawn(async {}); }"));
247    }
248
249    #[test]
250    fn spawn_audit_sees_spawn_on() {
251        let on = format!("fn f() {{ crate::transport::{}async {{}}); }}", concat!("spawn_", "on("));
252        assert!(has_unbound_spawn(&on), "an unannotated transport spawn is caught everywhere");
253        let marked = format!("// spawn-detached: process bridge.\n{on}");
254        assert!(!has_unbound_spawn(&marked));
255
256        let method = format!("fn f(set: &mut JoinSet<()>) {{ set{}async {{}}); }}", concat!(".", "spawn("));
257        assert!(has_unbound_spawn_at("src/transport/bridge.rs", &method), "a JoinSet spawn under transport/ is caught");
258        assert!(has_unbound_spawn_at("src/i2p/keeper.rs", &method));
259        assert!(!has_unbound_spawn_at("src/community/service.rs", &method), "other directories keep the old rule");
260        let marked = format!("// spawn-detached: the keeper.\n{method}");
261        assert!(!has_unbound_spawn_at("src/transport/bridge.rs", &marked));
262    }
263
264    #[test]
265    fn only_the_blocking_closure_counts_not_what_follows_it() {
266        let inside = "let x = spawn_blocking(move || {\n    db::get(1)\n}).await;";
267        let after = "let x = spawn_blocking(move || work(a, b)).await;\ndb::spawn_bound(async {});";
268        assert!(spawned_call(inside).contains("db::"));
269        assert!(!spawned_call(after).contains("db::"));
270    }
271}