Skip to content

Commit d6f510f

Browse files
voidstackloopclaude
andcommitted
Load each form's history once per invocation, not three times
Another performance pass, same shape as the LLM client reuse fix: found genuine duplicated I/O by tracing what happens after one test/monitor run completes, rather than guessing at a bottleneck. print_run (the CLI diff/flakiness display), notify::regressions_from_history (--webhook-url), and issues::events_from_history (--github-issues-repo) each independently called history::load_runs for the exact same URL - a full directory scan plus parsing every historical run's full JSON, base64 screenshots included. With both integrations enabled (which the README documents as the full CI setup), a single monitor run over N forms did 3N full history reloads instead of N, and it gets worse the longer a deployment has been accumulating history - exactly the growth pattern retention/prune exists to bound, but doesn't eliminate. Fix: main::load_prior_by_url loads each URL's history exactly once per invocation (deduplicating repeated URLs too, in case a monitor config lists one twice) and the three consumers take that pre-loaded map instead of hitting disk themselves. notify::regressions_from_runs and issues::events_from_runs are renamed from *_from_history since they no longer do any I/O or return Result - the caller now owns loading, they just diff what they're given. Also noticed the "find the run immediately before this timestamp" snippet (prior.iter().rev().find(|r| r.timestamp < run.timestamp)) was copy-pasted identically in all three places already being touched - collapsed into one history::previous_run helper rather than threading three copies through the refactor. Verified with two mutation tests: forced load_prior_by_url's dedup to build a fresh test (confirmed one entry per distinct URL, not one per call); flipped previous_run's `<` to `<=` and confirmed the new previous_run test failed (it would otherwise diff a run against itself), then restored it. cargo fmt/clippy -D warnings clean, full suite green (155 tests). Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
1 parent 3a8530f commit d6f510f

6 files changed

Lines changed: 174 additions & 53 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,21 @@ project doesn't have a release yet, so everything below is grouped under
2424

2525
### Performance
2626

27+
- **History loaded once per invocation, not three times per form.**
28+
`print_run` (the CLI diff/flakiness display), `notify::regressions_from_history`
29+
(`--webhook-url`), and `issues::events_from_history`
30+
(`--github-issues-repo`) each independently called `history::load_runs`
31+
for the same URL — a full directory scan plus a parse of every
32+
historical run, screenshots included. With both integrations enabled
33+
(the README's own documented full CI setup), that was 3 full history
34+
reloads per form, growing with however much history has accumulated.
35+
`main::load_prior_by_url` now loads each URL's history once per
36+
invocation and shares it; `notify::regressions_from_runs` and
37+
`issues::events_from_runs` (renamed, since they no longer touch disk
38+
themselves) take that pre-loaded map instead. Also collapsed the
39+
`prior.iter().rev().find(|r| r.timestamp < run.timestamp)`
40+
"find the predecessor" snippet — copy-pasted identically in all three
41+
places — into one `history::previous_run` helper.
2742
- **LLM client reuse across a whole `monitor` run.** `--llm` semantic
2843
checks used to build a brand-new HTTP client (`LlmClient::new`) for
2944
every single form, discarding its connection pool immediately after —

‎README.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -211,6 +211,13 @@ flip-flopped rather than settling — a `[FLAKY]` note in plain text, a
211211
is a genuine regression or fix, not flakiness; only a check that's
212212
genuinely unstable across several runs gets flagged.
213213

214+
`test`/`monitor` load each form's history exactly once per invocation and
215+
share it across the CLI diff/flakiness display, `--webhook-url`, and
216+
`--github-issues-repo` — all three used to independently reload and
217+
re-parse the same form's entire history (screenshots included), so a
218+
long-lived deployment with a lot of accumulated history paid for that
219+
three times over on every run.
220+
214221
## Custom checks
215222

216223
Anything specific to your forms that the built-in checks don't cover — a

‎src/history.rs‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -166,6 +166,19 @@ pub struct CheckChange {
166166
pub to: Status,
167167
}
168168

169+
/// The most recent of `runs` with a timestamp strictly before
170+
/// `before_timestamp` — "the previous run" that a fresh run is diffed
171+
/// against, whether for the CLI's own display, a webhook regression, or a
172+
/// GitHub Issues transition. Works regardless of `runs`' order (callers
173+
/// typically pass [`load_runs`]'s oldest-first output, which already
174+
/// includes the fresh run itself at the tail — this simply skips it and
175+
/// anything else not older).
176+
pub fn previous_run(runs: &[RunResult], before_timestamp: i64) -> Option<&RunResult> {
177+
runs.iter()
178+
.filter(|r| r.timestamp < before_timestamp)
179+
.max_by_key(|r| r.timestamp)
180+
}
181+
169182
/// Per-check status changes between two runs of the same form, keyed by
170183
/// check name so it survives checks being reordered or added/removed.
171184
pub fn diff(prev: &RunResult, curr: &RunResult) -> Vec<CheckChange> {
@@ -467,6 +480,23 @@ mod tests {
467480
assert_eq!(report[0].name, "Accessibility");
468481
}
469482

483+
#[test]
484+
fn previous_run_finds_the_newest_run_strictly_before_the_given_timestamp() {
485+
let runs = vec![
486+
run_at("https://city.gov/a", 10),
487+
run_at("https://city.gov/a", 20),
488+
run_at("https://city.gov/a", 30),
489+
];
490+
// The fresh run (ts=30) itself, and anything at/after it, must be
491+
// excluded — otherwise a run would be diffed against itself.
492+
assert_eq!(previous_run(&runs, 30).unwrap().timestamp, 20);
493+
assert_eq!(previous_run(&runs, 20).unwrap().timestamp, 10);
494+
assert!(previous_run(&runs, 10).is_none());
495+
// Order-independent.
496+
let shuffled = vec![runs[2].clone(), runs[0].clone(), runs[1].clone()];
497+
assert_eq!(previous_run(&shuffled, 30).unwrap().timestamp, 20);
498+
}
499+
470500
#[test]
471501
fn urls_differing_only_by_hyphen_vs_underscore_get_distinct_slugs() {
472502
// Regression test: collapsing every non-alphanumeric character to

‎src/issues.rs‎

Lines changed: 21 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020
use crate::checks::Status;
2121
use crate::error::{Error, Result};
2222
use crate::history::{self, RunResult};
23-
use std::path::Path;
23+
use std::collections::HashMap;
2424
use std::time::Duration;
2525

2626
/// One check's status transition for one form, exactly as recorded by
@@ -41,15 +41,22 @@ pub struct IssueEvent {
4141
pub to: Status,
4242
}
4343

44-
/// Every status transition across `runs`, each diffed against the most
45-
/// recent run recorded for its URL *before* `run.timestamp` — mirrors
46-
/// [`crate::notify::regressions_from_history`] exactly, except keeping
47-
/// every transition rather than filtering to `-> Fail` only.
48-
pub fn events_from_history(history_dir: &Path, runs: &[RunResult]) -> Result<Vec<IssueEvent>> {
44+
/// Every status transition across `runs`, each diffed against `prior`'s
45+
/// entry for its URL — mirrors [`crate::notify::regressions_from_runs`]
46+
/// exactly, except keeping every transition rather than filtering to
47+
/// `-> Fail` only. `prior` is loaded once per invocation by the caller and
48+
/// shared with anything else that needs the same history (see
49+
/// `main::load_prior_by_url`) instead of this re-reading it from disk.
50+
pub fn events_from_runs(
51+
runs: &[RunResult],
52+
prior: &HashMap<String, Vec<RunResult>>,
53+
) -> Vec<IssueEvent> {
4954
let mut events = Vec::new();
5055
for run in runs {
51-
let prior = history::load_runs(history_dir, &run.url)?;
52-
if let Some(prev) = prior.iter().rev().find(|r| r.timestamp < run.timestamp) {
56+
let Some(form_history) = prior.get(&run.url) else {
57+
continue;
58+
};
59+
if let Some(prev) = history::previous_run(form_history, run.timestamp) {
5360
events.extend(history::diff(prev, run).into_iter().map(|c| IssueEvent {
5461
form: run.name.clone(),
5562
url: run.url.clone(),
@@ -59,7 +66,7 @@ pub fn events_from_history(history_dir: &Path, runs: &[RunResult]) -> Result<Vec
5966
}));
6067
}
6168
}
62-
Ok(events)
69+
events
6370
}
6471

6572
/// A stable, greppable marker embedded (as an HTML comment, invisible in
@@ -477,7 +484,7 @@ mod tests {
477484
}
478485

479486
#[test]
480-
fn events_from_history_keeps_every_transition_not_just_fail() {
487+
fn events_from_runs_keeps_every_transition_not_just_fail() {
481488
let dir = std::env::temp_dir().join("formwatch-test-issues-events");
482489
let _ = std::fs::remove_dir_all(&dir);
483490
let url = "https://city.gov/apply";
@@ -486,8 +493,10 @@ mod tests {
486493
history::save_run(&dir, &run(url, 2, Status::Warn)).expect("save");
487494
history::save_run(&dir, &run(url, 3, Status::Fail)).expect("save");
488495

489-
let latest = history::load_runs(&dir, url).expect("load").pop().unwrap();
490-
let events = events_from_history(&dir, std::slice::from_ref(&latest)).expect("events");
496+
let loaded = history::load_runs(&dir, url).expect("load");
497+
let latest = loaded.last().unwrap().clone();
498+
let prior = HashMap::from([(url.to_string(), loaded)]);
499+
let events = events_from_runs(std::slice::from_ref(&latest), &prior);
491500

492501
// latest (ts=3, Fail) diffed against its predecessor (ts=2, Warn).
493502
assert_eq!(events.len(), 1);

‎src/main.rs‎

Lines changed: 84 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ use formwatch::{
1515
};
1616
use futures::stream::{self, StreamExt};
1717
use owo_colors::OwoColorize;
18+
use std::collections::HashMap;
1819
use std::net::SocketAddr;
1920
use std::path::{Path, PathBuf};
2021
use std::time::Duration;
@@ -574,6 +575,7 @@ async fn main() -> Result<()> {
574575
if let Some(path) = &settings.audit_log {
575576
audit::append(path, &run)?;
576577
}
578+
let prior_by_url = load_prior_by_url(&settings.history_dir, std::slice::from_ref(&run));
577579
if junit || sarif {
578580
emit_structured(
579581
std::slice::from_ref(&run),
@@ -585,15 +587,15 @@ async fn main() -> Result<()> {
585587
any_fail |= run_breaches(&run, settings.fail_on, settings.baseline.as_ref());
586588
} else {
587589
any_fail |= print_run(
588-
&settings.history_dir,
590+
prior_by_url.get(&run.url).map(Vec::as_slice).unwrap_or(&[]),
589591
&run,
590592
json,
591593
settings.fail_on,
592594
settings.baseline.as_ref(),
593595
)?;
594596
}
595-
notify_runs(&settings, std::slice::from_ref(&run)).await;
596-
github_issues_for_runs(&settings, std::slice::from_ref(&run)).await;
597+
notify_runs(&settings, std::slice::from_ref(&run), &prior_by_url).await;
598+
github_issues_for_runs(&settings, std::slice::from_ref(&run), &prior_by_url).await;
597599
}
598600
Command::Monitor {
599601
configs,
@@ -710,6 +712,7 @@ async fn main() -> Result<()> {
710712
}
711713
}
712714

715+
let prior_by_url = load_prior_by_url(history_dir, &runs);
713716
if junit || sarif {
714717
emit_structured(&runs, junit, sarif, out, settings.baseline.as_ref())?;
715718
any_fail |= runs
@@ -723,7 +726,7 @@ async fn main() -> Result<()> {
723726
} else {
724727
for run in &runs {
725728
any_fail |= print_run(
726-
history_dir,
729+
prior_by_url.get(&run.url).map(Vec::as_slice).unwrap_or(&[]),
727730
run,
728731
false,
729732
settings.fail_on,
@@ -732,8 +735,8 @@ async fn main() -> Result<()> {
732735
}
733736
}
734737

735-
notify_runs(&settings, &runs).await;
736-
github_issues_for_runs(&settings, &runs).await;
738+
notify_runs(&settings, &runs, &prior_by_url).await;
739+
github_issues_for_runs(&settings, &runs, &prior_by_url).await;
737740
}
738741
Command::Report {
739742
html,
@@ -1208,18 +1211,18 @@ async fn notify_test(config: &Config, webhook_url: Option<String>, json: bool) -
12081211

12091212
/// Sends a webhook notification for `runs` if one is configured and the
12101213
/// notify policy calls for it. Never fatal: a failed notification is a
1211-
/// warning, not a reason to lose a completed run's results.
1212-
async fn notify_runs(settings: &Settings, runs: &[history::RunResult]) {
1214+
/// warning, not a reason to lose a completed run's results. `prior` is
1215+
/// loaded once per invocation (see [`load_prior_by_url`]) and shared with
1216+
/// [`print_run`]/[`github_issues_for_runs`] rather than reloaded here.
1217+
async fn notify_runs(
1218+
settings: &Settings,
1219+
runs: &[history::RunResult],
1220+
prior: &HashMap<String, Vec<history::RunResult>>,
1221+
) {
12131222
let Some(url) = settings.webhook_url.as_deref() else {
12141223
return;
12151224
};
1216-
let mut regressions = match notify::regressions_from_history(&settings.history_dir, runs) {
1217-
Ok(r) => r,
1218-
Err(e) => {
1219-
tracing::warn!(error = format!("{e:#}"), "could not compute regressions");
1220-
return;
1221-
}
1222-
};
1225+
let mut regressions = notify::regressions_from_runs(runs, prior);
12231226
// A regression that the baseline already accepts isn't worth paging on.
12241227
if let Some(baseline) = &settings.baseline {
12251228
regressions.retain(|r| !baseline.is_accepted(&r.url, &r.check, r.to));
@@ -1241,21 +1244,18 @@ async fn notify_runs(settings: &Settings, runs: &[history::RunResult]) {
12411244
/// Creates/closes GitHub Issues for `runs`' regressions/recoveries if a
12421245
/// repo is configured. Never fatal, same as [`notify_runs`]: a dead
12431246
/// token or a rate limit is a warning, not a reason to lose a completed
1244-
/// run's results.
1245-
async fn github_issues_for_runs(settings: &Settings, runs: &[history::RunResult]) {
1247+
/// run's results. `prior` is loaded once per invocation (see
1248+
/// [`load_prior_by_url`]) and shared with [`print_run`]/[`notify_runs`]
1249+
/// rather than reloaded here.
1250+
async fn github_issues_for_runs(
1251+
settings: &Settings,
1252+
runs: &[history::RunResult],
1253+
prior: &HashMap<String, Vec<history::RunResult>>,
1254+
) {
12461255
let Some(gh) = &settings.github_issues else {
12471256
return;
12481257
};
1249-
let mut events = match issues::events_from_history(&settings.history_dir, runs) {
1250-
Ok(e) => e,
1251-
Err(e) => {
1252-
tracing::warn!(
1253-
error = format!("{e:#}"),
1254-
"could not compute GitHub issue events"
1255-
);
1256-
return;
1257-
}
1258-
};
1258+
let mut events = issues::events_from_runs(runs, prior);
12591259
// A baselined Fail is an accepted finding — it shouldn't spawn a
12601260
// tracking issue any more than it should page a webhook. A recovery
12611261
// (-> Pass) closes an issue regardless of baseline state.
@@ -1379,11 +1379,33 @@ fn emit_structured(
13791379
Ok(())
13801380
}
13811381

1382+
/// Loads each of `runs`' URLs' history exactly once per invocation
1383+
/// (deduplicating repeated URLs) and shares it across [`print_run`],
1384+
/// [`notify_runs`], and [`github_issues_for_runs`] — each of which
1385+
/// otherwise independently calls [`history::load_runs`] for the very same
1386+
/// URL, tripling history reads (each re-parsing every historical run,
1387+
/// screenshots included) for a single `test`/`monitor` invocation. A URL
1388+
/// that fails to load gets an empty history rather than aborting the run.
1389+
fn load_prior_by_url(
1390+
history_dir: &Path,
1391+
runs: &[history::RunResult],
1392+
) -> HashMap<String, Vec<history::RunResult>> {
1393+
let mut prior = HashMap::new();
1394+
for run in runs {
1395+
prior
1396+
.entry(run.url.clone())
1397+
.or_insert_with(|| history::load_runs(history_dir, &run.url).unwrap_or_default());
1398+
}
1399+
prior
1400+
}
1401+
13821402
/// Prints one run (JSON or colored text, plus the diff against its
13831403
/// previous run) and reports whether it breaches the `--fail-on` policy —
1384-
/// the caller aggregates that into the process exit code.
1404+
/// the caller aggregates that into the process exit code. `prior` is
1405+
/// `run`'s own history, loaded once per invocation by the caller (see
1406+
/// [`load_prior_by_url`]) rather than by this function.
13851407
fn print_run(
1386-
history_dir: &Path,
1408+
prior: &[history::RunResult],
13871409
run: &history::RunResult,
13881410
json: bool,
13891411
fail_on: FailOn,
@@ -1395,8 +1417,7 @@ fn print_run(
13951417
}
13961418

13971419
println!("\n{}", format!("== {} ({}) ==", run.name, run.url).bold());
1398-
let prior = history::load_runs(history_dir, &run.url)?;
1399-
let flaky = history::flakiness(&prior);
1420+
let flaky = history::flakiness(prior);
14001421
for check in &run.checks {
14011422
let baselined = check.status != checks::Status::Pass
14021423
&& baseline
@@ -1405,7 +1426,7 @@ fn print_run(
14051426
print_check(check, is_flaky(&flaky, check), baselined);
14061427
}
14071428

1408-
if let Some(prev) = prior.iter().rev().find(|r| r.timestamp < run.timestamp) {
1429+
if let Some(prev) = history::previous_run(prior, run.timestamp) {
14091430
print_changes(&history::diff(prev, run));
14101431
}
14111432
Ok(run_breaches(run, fail_on, baseline))
@@ -1517,6 +1538,37 @@ mod tests {
15171538
}
15181539
}
15191540

1541+
#[test]
1542+
fn load_prior_by_url_loads_each_url_once_even_with_repeated_urls() {
1543+
// notify_runs/github_issues_for_runs/print_run all used to call
1544+
// history::load_runs independently for the same URL; this map is
1545+
// what replaced that. A `monitor` config could in principle list
1546+
// the same URL twice, so this also checks the dedup itself, not
1547+
// just that the map has the right shape.
1548+
let dir = std::env::temp_dir().join("formwatch-test-load-prior-by-url");
1549+
let _ = std::fs::remove_dir_all(&dir);
1550+
let a = history::RunResult {
1551+
schema_version: history::SCHEMA_VERSION,
1552+
name: "A".into(),
1553+
url: "https://city.gov/a".into(),
1554+
timestamp: 1,
1555+
checks: vec![],
1556+
};
1557+
let b = history::RunResult {
1558+
url: "https://city.gov/b".into(),
1559+
..a.clone()
1560+
};
1561+
history::save_run(&dir, &a).expect("save a");
1562+
history::save_run(&dir, &b).expect("save b");
1563+
1564+
let prior = load_prior_by_url(&dir, &[a.clone(), a.clone(), b.clone()]);
1565+
assert_eq!(prior.len(), 2, "one entry per distinct URL");
1566+
assert_eq!(prior[&a.url].len(), 1);
1567+
assert_eq!(prior[&b.url].len(), 1);
1568+
1569+
let _ = std::fs::remove_dir_all(&dir);
1570+
}
1571+
15201572
#[test]
15211573
fn build_llm_client_is_none_when_disabled_and_some_when_enabled() {
15221574
// The client is built once per invocation (not once per form, see

0 commit comments

Comments
 (0)