Skip to content

Commit 66a9793

Browse files
voidstackloopclaude
andcommitted
Fix the concurrent-cold-cache Chrome download race
fetch_chrome() had a documented, real bug: two formwatch processes (or cargo test's own default parallelism) starting on a machine with no cached Chrome yet both downloaded and extracted straight into the same shared cache directory, corrupting each other's extraction ("corrupt deflate stream"). The fix was already prescribed in the ponytail comment this replaces: download into a private, unique temp directory, then atomically rename it into place. Design: each caller downloads into ~/.cache/formwatch/.chrome-download- <pid>-<nanos>, then calls fs::rename onto the shared cache_dir. Onto a non-existent or empty destination this succeeds outright; onto one a racing caller already populated it fails, and that failure is itself the race signal — the loser just discards its own copy. No lock file needed; a same-filesystem rename's atomicity is what makes both sides of the race safe. Whoever ends up owning cache_dir, a final BrowserFetcher::fetch() call against it resolves the executable path — verified by reading chromiumoxide_fetcher's source that this call is a local existence check with no network I/O once the revision folder is present, so re-resolving after the race costs nothing. The install-or-discard step is pure filesystem logic with no network dependency, so it's isolated into its own function and unit tested directly (no real Chrome download needed): one test proves a clean install moves tmp into place, the other proves a losing tmp is discarded while the winner's already-installed dest survives untouched. Verified both are meaningful by mutating install_or_discard two different wrong ways (never install; always overwrite the winner) and confirming each predicted the exact test that would catch it, before restoring the real implementation. Updates CONTRIBUTING.md's now-stale guidance (which described the bug and a cache-warming workaround) and CHANGELOG.md. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
1 parent b8a57ec commit 66a9793

3 files changed

Lines changed: 134 additions & 28 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,12 @@ the bug, not just reasoned about:
7676
- No timeout existed anywhere in the check engine; a hung page or
7777
custom check would block a run (and, with concurrency, a whole
7878
concurrency slot) forever.
79+
- Two formwatch processes downloading Chrome-for-Testing at the same
80+
time on a machine with a cold cache could corrupt each other's
81+
extraction ("corrupt deflate stream"). Each caller now downloads into
82+
its own private temp directory and atomically renames it into place;
83+
whichever caller loses that race discards its own copy instead of
84+
colliding with the winner's.
7985

8086
### Changed
8187

‎CONTRIBUTING.md‎

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -24,14 +24,13 @@ need Chrome. `tests/checks_test.rs` and `tests/runner_test.rs` launch a
2424
real headless Chrome and assert on the results — that's what `cargo test`
2525
running slower than instant is; it's exercising a browser, not hanging.
2626

27-
If you don't have system Chrome/Chromium installed, run something once to
28-
warm formwatch's own download cache (`cargo run -- test
29-
"file://$PWD/fixtures/test-form.html"`) *before* running `cargo test` —
30-
`cargo test`'s default parallelism means multiple tests can otherwise race
31-
to populate a cold cache at once and corrupt each other's download (see
32-
the `ponytail:` note on `fetch_chrome` in `browser.rs`). This doesn't
33-
affect real `formwatch` runs, which only ever launch the browser once per
34-
process.
27+
If you don't have system Chrome/Chromium installed, the first `cargo test`
28+
downloads Chrome-for-Testing into `~/.cache/formwatch/chrome` — `cargo
29+
test`'s default parallelism means several tests can hit a cold cache at
30+
the same time, but `fetch_chrome` in `browser.rs` downloads each into its
31+
own private temp directory and atomically renames it into place, so
32+
concurrent cold-cache downloads no longer corrupt each other. No warm-up
33+
step needed.
3534

3635
When you add or change a check, extend a fixture (or add a new one) with
3736
a case that would only pass/fail correctly if your change works, and

‎src/browser.rs‎

Lines changed: 121 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,46 +1,92 @@
11
use anyhow::{Context, Result};
22
use chromiumoxide::{Browser, BrowserConfig, BrowserFetcher, BrowserFetcherOptions, Page};
33
use futures::StreamExt;
4-
use std::path::PathBuf;
4+
use std::path::{Path, PathBuf};
5+
use std::time::{SystemTime, UNIX_EPOCH};
56
use tokio::task::JoinHandle;
67

78
/// Downloads a Chrome-for-Testing build into ~/.cache/formwatch/chrome. Only
89
/// runs when no system Chrome/Chromium can be auto-detected, so a plain
910
/// `cargo install formwatch` still works with no root/apt step.
1011
///
11-
/// ponytail: not safe for concurrent callers racing to populate a cold
12-
/// cache (two formwatch processes started at once on a machine with no
13-
/// Chrome yet, or — the way this was actually found — `cargo test`'s
14-
/// default test parallelism on a machine without system Chrome) can
15-
/// corrupt each other's extraction. Normal usage launches the browser
16-
/// once per process, so this doesn't bite real `formwatch test`/`monitor`
17-
/// runs; if it needs to be made safe, the fix is downloading into a
18-
/// per-process temp dir and atomically renaming into place. Contributors
19-
/// without system Chrome: run something that warms the cache once (e.g.
20-
/// `cargo run -- test file://...`) before `cargo test`.
12+
/// Safe for concurrent callers racing to populate a cold cache (two
13+
/// formwatch processes started at once on a machine with no Chrome yet, or
14+
/// `cargo test`'s default test parallelism on a machine without system
15+
/// Chrome): each downloads into its own private temp directory, then
16+
/// atomically renames it into place. Whichever caller's `fs::rename` lands
17+
/// first wins; every other caller's rename fails (the destination now
18+
/// exists and is non-empty), which is exactly the signal to discard its
19+
/// own copy and defer to the winner. No lock file needed — the
20+
/// atomicity of a same-filesystem rename provides the race-safety.
2121
async fn fetch_chrome() -> Result<PathBuf> {
2222
let home = std::env::var("HOME").context("HOME is not set")?;
2323
let cache_dir = PathBuf::from(home).join(".cache/formwatch/chrome");
24-
std::fs::create_dir_all(&cache_dir).context("creating chrome cache dir")?;
25-
let already_cached = cache_dir
26-
.read_dir()
27-
.map(|mut d| d.next().is_some())
28-
.unwrap_or(false);
29-
if !already_cached {
24+
25+
if !already_downloaded(&cache_dir) {
3026
eprintln!(
3127
"No Chrome/Chromium found — downloading one to {} (first run only)...",
3228
cache_dir.display()
3329
);
30+
download_into(&cache_dir).await?;
3431
}
32+
33+
// Whether we just won the race, lost it, or the cache was already warm,
34+
// BrowserFetcher::fetch() against the now-populated cache_dir is a
35+
// local-only existence check (no network) that resolves the final
36+
// executable path — see chromiumoxide_fetcher's BrowserFetcher::local().
37+
fetch_at(&cache_dir).await
38+
}
39+
40+
fn already_downloaded(cache_dir: &Path) -> bool {
41+
cache_dir
42+
.read_dir()
43+
.map(|mut d| d.next().is_some())
44+
.unwrap_or(false)
45+
}
46+
47+
async fn fetch_at(path: &Path) -> Result<PathBuf> {
3548
let opts = BrowserFetcherOptions::builder()
36-
.with_path(&cache_dir)
49+
.with_path(path)
3750
.build()
3851
.map_err(|e| anyhow::anyhow!(e))?;
39-
let fetcher = BrowserFetcher::new(opts);
40-
let info = fetcher.fetch().await.context("failed to download Chrome")?;
52+
let info = BrowserFetcher::new(opts)
53+
.fetch()
54+
.await
55+
.context("failed to download Chrome")?;
4156
Ok(info.executable_path)
4257
}
4358

59+
/// Downloads into a private, unique directory next to `cache_dir`, then
60+
/// hands it to [`install_or_discard`] to atomically become `cache_dir` —
61+
/// or to be thrown away if a racing caller already got there first.
62+
async fn download_into(cache_dir: &Path) -> Result<()> {
63+
let parent = cache_dir
64+
.parent()
65+
.context("chrome cache dir has no parent")?;
66+
std::fs::create_dir_all(parent).context("creating chrome cache dir's parent")?;
67+
68+
let nanos = SystemTime::now()
69+
.duration_since(UNIX_EPOCH)
70+
.map(|d| d.as_nanos())
71+
.unwrap_or(0);
72+
let tmp = parent.join(format!(".chrome-download-{}-{nanos}", std::process::id()));
73+
let _ = std::fs::remove_dir_all(&tmp); // stale leftover from a crashed prior run, if any
74+
75+
fetch_at(&tmp).await?;
76+
install_or_discard(&tmp, cache_dir);
77+
Ok(())
78+
}
79+
80+
/// Moves a completed download from `tmp` into `dest`. If `dest` already
81+
/// exists (a racing caller's download won first), the rename fails —
82+
/// that failure is the race signal, not a real error — so `tmp` is
83+
/// discarded instead, leaving the winner's `dest` untouched.
84+
fn install_or_discard(tmp: &Path, dest: &Path) {
85+
if std::fs::rename(tmp, dest).is_err() {
86+
let _ = std::fs::remove_dir_all(tmp);
87+
}
88+
}
89+
4490
async fn build_config(headful: bool) -> Result<BrowserConfig> {
4591
let mut builder = BrowserConfig::builder();
4692
if headful {
@@ -98,3 +144,58 @@ pub async fn open(browser: &Browser, url: &str) -> Result<Page> {
98144
}
99145
Ok(page)
100146
}
147+
148+
#[cfg(test)]
149+
mod tests {
150+
use super::*;
151+
152+
#[test]
153+
fn install_or_discard_moves_tmp_into_place_when_nothing_won_the_race() {
154+
let base = std::env::temp_dir().join("formwatch-test-install-or-discard-clean");
155+
let _ = std::fs::remove_dir_all(&base);
156+
let tmp = base.join("tmp");
157+
let dest = base.join("dest");
158+
std::fs::create_dir_all(&tmp).expect("create tmp");
159+
std::fs::write(tmp.join("chrome"), b"the download").expect("write marker file");
160+
161+
install_or_discard(&tmp, &dest);
162+
163+
assert!(!tmp.exists(), "tmp should have been moved, not left behind");
164+
assert_eq!(
165+
std::fs::read(dest.join("chrome")).expect("dest should contain the download"),
166+
b"the download"
167+
);
168+
169+
let _ = std::fs::remove_dir_all(&base);
170+
}
171+
172+
#[test]
173+
fn install_or_discard_defers_to_a_dest_that_already_won_the_race() {
174+
// Simulates losing the race: `dest` was already populated (by
175+
// another caller's `install_or_discard`) by the time this one
176+
// runs. The loser's `tmp` must be discarded, and the winner's
177+
// `dest` must survive untouched — not merged, not corrupted.
178+
let base = std::env::temp_dir().join("formwatch-test-install-or-discard-race");
179+
let _ = std::fs::remove_dir_all(&base);
180+
let tmp = base.join("tmp");
181+
let dest = base.join("dest");
182+
std::fs::create_dir_all(&tmp).expect("create tmp");
183+
std::fs::write(tmp.join("chrome"), b"the loser's download").expect("write marker file");
184+
std::fs::create_dir_all(&dest).expect("create dest");
185+
std::fs::write(dest.join("chrome"), b"the winner's download").expect("write marker file");
186+
187+
install_or_discard(&tmp, &dest);
188+
189+
assert!(
190+
!tmp.exists(),
191+
"the losing tmp dir should be discarded, not left behind"
192+
);
193+
assert_eq!(
194+
std::fs::read(dest.join("chrome")).expect("dest should be untouched"),
195+
b"the winner's download",
196+
"the winner's already-installed download must survive unchanged"
197+
);
198+
199+
let _ = std::fs::remove_dir_all(&base);
200+
}
201+
}

0 commit comments

Comments
 (0)