Skip to content

Commit ac7cf22

Browse files
voidstackloopclaude
andcommitted
Stop parsing every historical run to find the newest one
Same theme as the last two performance passes, one call site further: history::all_known_forms (behind `report`, `serve`'s /metrics and /api/forms, and `baseline --write`) picked each form's newest run by opening and fully parsing EVERY run file in that form's directory, just to keep whichever had the largest timestamp - discarding every other parsed run immediately after. save_run already encodes the timestamp in the filename itself ({ts}.json or {ts}-{suffix}.json, for same-second collisions), so the winner can be picked by comparing filenames alone - only that one file actually needs to be read and deserialized. A form directory with months of accumulated daily-monitor history now costs the same as one with a single run, for exactly the commands (report generation, the serve endpoints, baseline generation) that read across every known form at once. Side benefit this exposed: a single corrupted or truncated OLD run file used to fail all_known_forms outright (and therefore report/ serve/baseline for that whole form, via `?` propagation) even though the newest run was perfectly fine. It's now simply never read. Also fixed report::build's own copy of the "find the run immediately before this timestamp" snippet, missed when that was extracted into history::previous_run in the last commit (d6f510f) - report.rs still had its own copy-pasted .iter().rev().find(...). Verified with a real regression test, not just reasoning: saved two runs then corrupted the OLDER one's file in place and asserted all_known_forms still returns the correct newest run. Confirmed the test actually catches the regression it targets by temporarily reverting to the old "parse everything, keep the max" implementation - the test failed with a JSON parse error on the corrupted file, exactly as predicted - then restored the fix. cargo fmt/clippy -D warnings clean, full suite green (156 tests). Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
1 parent d6f510f commit ac7cf22

4 files changed

Lines changed: 73 additions & 16 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+
- **`all_known_forms` no longer parses every historical run to find the
28+
newest one.** `history::all_known_forms` — behind `formwatch report`,
29+
`serve`'s `/metrics`/`/api/forms`, and `baseline --write` — picked each
30+
form's newest run by fully parsing *every* run file in that form's
31+
directory and keeping the max timestamp, discarding everything else.
32+
Since `save_run` already encodes the timestamp in the filename
33+
(`{ts}.json` / `{ts}-{suffix}.json`), the winner can be picked by
34+
comparing filenames and only that one file needs to be read and
35+
parsed — a form directory with months of accumulated history now costs
36+
the same as one with a single run. Also fixed a latent robustness gap
37+
this exposed: a single corrupted/truncated old run file used to fail
38+
`all_known_forms` (and therefore `report`/`serve`/`baseline`) for that
39+
entire form; it's now simply never read. `report::build` also had its
40+
own copy of the `previous_run` find-predecessor snippet — missed in
41+
the fix below — now uses the shared helper too.
2742
- **History loaded once per invocation, not three times per form.**
2843
`print_run` (the CLI diff/flakiness display), `notify::regressions_from_history`
2944
(`--webhook-url`), and `issues::events_from_history`

‎README.md‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -216,7 +216,10 @@ share it across the CLI diff/flakiness display, `--webhook-url`, and
216216
`--github-issues-repo` — all three used to independently reload and
217217
re-parse the same form's entire history (screenshots included), so a
218218
long-lived deployment with a lot of accumulated history paid for that
219-
three times over on every run.
219+
three times over on every run. `formwatch report`, `serve`, and
220+
`baseline --write` list every form's newest run the same cheap way: by
221+
comparing filename timestamps, not by parsing every historical run just
222+
to find the most recent one.
220223

221224
## Custom checks
222225

‎src/history.rs‎

Lines changed: 53 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -122,28 +122,47 @@ pub fn load_runs(base: &Path, url: &str) -> Result<Vec<RunResult>> {
122122
Ok(runs.into_iter().map(|(_, run)| run).collect())
123123
}
124124

125+
/// Parses the leading `{timestamp}` out of a run filename (`{ts}.json` or
126+
/// `{ts}-{suffix}.json`, as [`save_run`] writes them) without opening or
127+
/// parsing the file itself — just enough to compare candidates by
128+
/// recency.
129+
fn timestamp_from_filename(path: &Path) -> Option<i64> {
130+
path.file_stem()?.to_str()?.split('-').next()?.parse().ok()
131+
}
132+
125133
/// Every URL formwatch has ever recorded a run for, newest run first.
134+
///
135+
/// Picks each form's newest run by filename timestamp rather than by
136+
/// parsing every run just to find the maximum — a form directory with a
137+
/// long-lived history stays cheap to summarize regardless of how many
138+
/// older runs it holds, since only the one winning file actually gets
139+
/// read and deserialized.
126140
pub fn all_known_forms(base: &Path) -> Result<Vec<RunResult>> {
127141
if !base.exists() {
128142
return Ok(vec![]);
129143
}
130144
let mut latest = vec![];
131145
for entry in fs::read_dir(base)? {
132-
let path = entry?.path();
133-
if !path.is_dir() {
146+
let dir = entry?.path();
147+
if !dir.is_dir() {
134148
continue;
135149
}
136-
let mut newest: Option<RunResult> = None;
137-
for f in fs::read_dir(&path)? {
138-
let f = f?.path();
139-
if f.extension().and_then(|e| e.to_str()) == Some("json") {
140-
let run: RunResult = serde_json::from_str(&fs::read_to_string(&f)?)?;
141-
if newest.as_ref().is_none_or(|n| run.timestamp > n.timestamp) {
142-
newest = Some(run);
143-
}
150+
let mut newest: Option<(i64, PathBuf)> = None;
151+
for f in fs::read_dir(&dir)? {
152+
let path = f?.path();
153+
if path.extension().and_then(|e| e.to_str()) != Some("json") {
154+
continue;
155+
}
156+
let Some(ts) = timestamp_from_filename(&path) else {
157+
continue;
158+
};
159+
if newest.as_ref().is_none_or(|(best, _)| ts > *best) {
160+
newest = Some((ts, path));
144161
}
145162
}
146-
if let Some(run) = newest {
163+
if let Some((_, path)) = newest {
164+
let run: RunResult = serde_json::from_str(&fs::read_to_string(&path)?)
165+
.with_context(|| format!("parsing {}", path.display()))?;
147166
latest.push(run);
148167
}
149168
}
@@ -589,6 +608,29 @@ mod tests {
589608
let _ = fs::remove_dir_all(&dir);
590609
}
591610

611+
#[test]
612+
fn all_known_forms_does_not_need_to_parse_non_newest_files() {
613+
// The newest run per form is picked by filename timestamp, not by
614+
// fully parsing every file to find the max — proven by corrupting
615+
// the OLDER run's file: the old "parse everything" implementation
616+
// would error on it, but picking the winner by filename alone
617+
// never touches it.
618+
let dir = std::env::temp_dir().join("formwatch-test-all-known-forms-corrupt");
619+
let _ = fs::remove_dir_all(&dir);
620+
let url = "https://city.gov/apply";
621+
save_run(&dir, &run_at(url, 100)).expect("save older");
622+
save_run(&dir, &run_at(url, 300)).expect("save newest");
623+
fs::write(dir_for(&dir, url).join("100.json"), "{not valid json")
624+
.expect("corrupt the older run's file");
625+
626+
let forms =
627+
all_known_forms(&dir).expect("the corrupted older file should never need parsing");
628+
assert_eq!(forms.len(), 1);
629+
assert_eq!(forms[0].timestamp, 300);
630+
631+
let _ = fs::remove_dir_all(&dir);
632+
}
633+
592634
fn run_at(url: &str, timestamp: i64) -> RunResult {
593635
RunResult {
594636
schema_version: SCHEMA_VERSION,

‎src/report.rs‎

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -123,10 +123,7 @@ pub fn build(history_dir: &Path) -> Result<ReportTemplate> {
123123
let mut forms = vec![];
124124
for run in history::all_known_forms(history_dir)? {
125125
let prior_runs = history::load_runs(history_dir, &run.url)?;
126-
let changes = prior_runs
127-
.iter()
128-
.rev()
129-
.find(|r| r.timestamp < run.timestamp)
126+
let changes = history::previous_run(&prior_runs, run.timestamp)
130127
.map(|prev| history::diff(prev, &run))
131128
.unwrap_or_default();
132129
let flaky = history::flakiness(&prior_runs);

0 commit comments

Comments
 (0)