Skip to content

feat(cli): keep the last 3 audits of a project and retire the rest (#1912) - #285

Merged
nc9 merged 7 commits into
mainfrom
lane-retention-auto
Sep 8, 2026
Merged

nc9 merged 7 commits into
mainfrom
lane-retention-auto

Conversation

@nc9

@nc9 nc9 commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor

The automatic half of squirrelscan/repo#1912, on top of #259. Nik's decision on the issue: retention on by default, keep the last 3, count in squirrel.toml, one line the first time it takes something.

What it does

After a successful audit, the audits outside [storage] keep_audits are retired through #259's retireCrawls. They stay listed and refuse to open, exactly as a self disk --prune retirement does.

[storage]
keep_audits = 3      # default
keep_audits = 0      # off (also: false)
Retired 1 older audit and freed 95.2 MB inside project.db for the next audit; keep more with [storage] keep_audits (now 3)

stderr only, so -f json cannot be polluted, and the hint appears only the first time a project retires anything (read off the audits, not off a settings file).

Measured

Five audits of a 40-page site into one project, both arms after PRAGMA wal_checkpoint(TRUNCATE):

after 5 audits keep_audits = false keep_audits = 3
project.db family 14.71 MB 11.85 MB
free inside the file 0 2.82 MB (23.9%)
pages rows 200 120
rule_results rows 40,445 24,267
audits listed 5 5 (2 retired)
pages fetched by audit 5 0 of 40 0 of 40

A sixth audit left it at 11.86 MB, which is what a ceiling looks like. The last row is the one that matters and it is measured on the audits that ran after data was retired: retiring never takes the newest page record per url, so a re-audit still answers every page from its conditional GET. The first audit fetched 40 of 40; every one after it fetched 0.

The pass costs 0.35 ms when there is nothing to retire and 59 ms when one audit goes, at 1,000 pages an audit.

Why the space stays inside the file

At a window of three, an audit retires one audit's worth of rows every time, and that is about a quarter of the file. A share-based VACUUM threshold alone would therefore rewrite the whole database after every audit, forever, which is the cost this feature exists to avoid. Left alone those pages are reused by the next audit and the file plateaus. The rewrite is reserved for more than one audit going at once, which means retention switched on over a backlog or a window lowered.

That made self disk --prune find nothing to do while the file stayed large, so it now offers the rebuild on its own:

acme-docs  412 MB  rebuilding to return 96.4 MB

Nothing left to retire: 96.4 MB across 1 project(s) is already free inside the files and only a rebuild returns it.

Rebuild? [y/N]

Verified end to end on a real project: 11.9 MB to 8.7 MB, and the audit after it still fetched 0 of 40.

Only a real audit retires, and only a real audit counts

A run can finish with a report whose own status is failed or blocked — a site that is down, or answers 403 to everything — and the command exits nonzero on it. Gating the pass on that is half the job. crawls.status reads analyzed for those runs too, so counting crawl rows meant three good audits, two days of downtime and one recovery run would keep the two blocked runs and delete all three audits from before the outage.

Migration 27 records what the report actually said on the crawl. The same column carries a building sentinel between the analyzed transition and the report being reconstructed, which closes the window where a second audit of the same project could retire a crawl its own process is still reading and turn a run that was going to succeed into "Audit data was reclaimed".

Bounded per criterion 5, which took three plan fixes

pages is keyed (crawl_id, normalized_url), so nothing could serve a lookup by url alone — and the predicate deciding which page rows a retirement may delete is exactly that, correlated, once per candidate row. Retiring one crawl of four, ~8 KB of html per row:

pages rows SCAN newer idx_pages_url_recency
4,000 80 ms 9.5 ms
10,000 493 ms 29 ms
40,000 11,779 ms 61 ms

getCachedPage runs the same lookup once per url on every incremental re-audit and was scanning too. Two more, both invisible in row counts:

  • The recency test a > b OR (a = b AND c > d) seeks to the url and then walks every version of it. As the row value (newer.fetched_at, newer.rowid) > (p.fetched_at, p.rowid) it range-seeks. Equivalence to the old spelling is asserted over a tie fixture rather than argued.
  • The sweep that collects page rows an earlier retirement kept reads every row in pages when written as a join, and costs one probe per audit ever retired when driven by a list of retired crawl ids. Driven by the urls the current crawl just wrote it is bounded by the audit — and that is also exactly the set that can have changed, since a row only becomes superseded by an audit crawling its url again.

Every gate for these is an EXPLAIN QUERY PLAN assertion. An index that exists proves nothing if the planner does not choose it, and a timing on a loaded box proves nothing at all.

pages is the hottest write table in a crawl, so the index has to pay for itself there too. 2,000 page inserts of 8 KB of html each, one statement per page, median of three alternating runs: 329.4 ms without, 325.6 ms with (noise, in the wrong direction), and the file 0.9% larger. A real 100 MB project.db at version 24 opened at version 27 in 69 ms, both columns added and all three indexes built, every row intact and its page cache still reading back.

idx_crawls_retired and idx_crawls_retention are partial indexes from opposite sides of retired_at, and they are created after the migrations rather than in the SCHEMA string: SCHEMA is exec'd first, so an index naming a migration-added column throws at open on a pre-25 database, before the migration that would add it can run. There is a test that opens such a database.

Review

Two adversarial codex rounds, thirteen findings. Eleven fixed, including every P1. Two left deliberately, both filed rather than buried:

  1. A crashed audit leaks — An audit interrupted while building its report leaves a crawl retention never counts or retires #288. A process killed between the analyzed stamp and its report leaves report_status = 'building', and that crawl is then never counted and never retired. Same class as the failed crawls feat(cli): squirrel self disk --prune, to reclaim what old audits are holding #259 already leaves alone, and self disk --prune still reaches it.
  2. Rows superseded before this shipped are not swept eagerly — Page rows superseded before automatic retention shipped are never collected #289. They are collected the next time their url is crawled. The only pre-existing retirement is feat(cli): squirrel self disk --prune, to reclaim what old audits are holding #259's prune, merged the day before, so the backlog is at most one dead row per re-crawled url, and eager collection would cost the history-shaped scan this spent three attempts removing.

Tests

  • Policy: keeps exactly N renderable; disabled at 0 and at false; never the crawl that just ran; a running crawl is neither retired nor counted; a failed or blocked report is neither retired nor counted; a building crawl is untouched; a NULL report_status is an ordinary audit; ties on started_at break by insert order, not by the query plan.
  • What it must not take: the conditional-GET cache survives with the right etag; a url only the retired audit saw keeps its row; a row an earlier retirement kept is collected once a later audit supersedes it, and the url still resolves to the newest record.
  • The VACUUM guard from both sides: one retirement does not rewrite the file even with the free share past the threshold (asserted, not assumed), and a backlog does, with the file itself smaller afterwards.
  • Plans: the superseded predicate seeks on url and on recency; the sweep reads no table whole; getCachedPage seeks; the index does not change which row a tie resolves to.
  • Migrations through writes: a pre-25 database opens and its retired_at survives a write; a pre-26 database gains the index, with the precondition that it really was a scan before.
  • Prune: an already-retired project can still be rebuilt; audits an earlier pass retired are not planned again; the kept count is audits you can open; an audit with nothing deletable in it is still a retirement.

Every new guard was mutation-checked: the test fails with the guard removed, and passes with it back.

Docs: a new [storage] page, plus the audit, report and self disk pages. Benchmarks row added.

nc9 added 7 commits September 8, 2026 19:11
…1912)

Re-auditing a project wrote a whole new crawl and retired nothing, so
project.db grew by about one audit every time: 95 MB per audit of a
1,000-page site, unbounded, with nothing saying so. #259 shipped the
manual reclaim; this is the automatic half Nik signed off on.

After a SUCCESSFUL audit, retire the audits outside `[storage]
keep_audits` (default 3, `0` or `false` disables) through the existing
retireCrawls path. Retired audits stay listed and refuse to open, as
#259 made them. One line on stderr when something goes, never stdout,
so `-f json` cannot be polluted.

Only a successful audit retires, and a failed one does not hold a place
in the window either. `crawls.status` reads `analyzed` for a run whose
report came out `failed` or `blocked`, so without migration 27 recording
what the report actually said, three good audits plus two days of a site
being down plus one recovery run would keep the two blocked runs and
delete all three audits from before the outage. That column also carries
a `building` sentinel between the analyzed transition and the report
being reconstructed, so a second audit of the same project cannot retire
a crawl whose own process is still reading it.

The freed space stays inside the file on purpose. At a window of three
an audit retires one audit's worth of rows every time, about a quarter
of the file, so a share-based VACUUM threshold would rewrite the whole
database after every audit forever. Left alone those pages are reused
and the file plateaus; the rewrite is reserved for more than one audit
going at once, which means a backlog or a lowered window.

Bounded per criterion 5, which needed three plan fixes:

- `pages` is keyed (crawl_id, normalized_url), so the superseded-pages
  predicate had no index for its lookup by url and re-read the whole
  table per candidate row: 11,779 ms at 40,000 rows, 61 ms with
  migration 26's idx_pages_url_recency. getCachedPage was scanning the
  same way on every incremental re-audit.
- The recency test `a > b OR (a = b AND c > d)` seeks to the url then
  walks every version of it; as a row-value comparison it range-seeks.
  Equivalence to the old spelling is asserted, ties included.
- The sweep of page rows an earlier retirement kept reads every row in
  `pages` when written as a join, and costs a probe per audit ever
  retired when driven by a list of retired crawl ids. Driven by the urls
  this crawl just wrote it is bounded by the audit, which is also the
  only set that can have changed. Two partial indexes on `crawls` keep
  the candidate query and the retired lookup off a table that only
  grows; both are created after the migrations rather than in SCHEMA,
  which runs first and would throw on a pre-25 database.

Measured, 40-page site, five audits, after a WAL checkpoint: 14.71 MB
unbounded against 11.85 MB at keep 3, with a sixth audit leaving it at
11.86. Every audit after the first fetched 0 of 40 pages, including the
ones that ran after data was retired, so retiring never costs a cold
re-crawl. The pass itself is 0.35 ms when there is nothing to retire
and 59 ms when one audit goes, at 1,000 pages an audit.

`self disk --prune` also had to change: with retention on it found
nothing to retire and would have left the file large, so it now offers
the rebuild on its own, counts kept audits as ones that can still be
opened, and asks "Retire them?" on the number of audits going rather
than the number of rows.

Two adversarial review rounds, thirteen findings, eleven fixed. The two
left are recorded in the PR.

Signed-off-by: Nik Cubrilovic <[email protected]>
…crawl

A swallowed setReportStatus leaves the crawl reading `building`, which
retention treats as neither retirable nor countable, so it holds its
rows until someone prunes. Not worth failing a finished audit over, but
worth a line.

Signed-off-by: Nik Cubrilovic <[email protected]>
Under [Unreleased], not a new v0.0.92 heading: the release workflow
extracts the section matching the version being cut, so a v0.0.92
section holding only this line would ship as the whole release notes
and drop everything already sitting under [Unreleased].

Signed-off-by: Nik Cubrilovic <[email protected]>
@nc9
nc9 force-pushed the lane-retention-auto branch from 675e7be to 593f588 Compare September 8, 2026 09:11
@nc9
nc9 merged commit e5a9737 into main Sep 8, 2026
13 checks passed
@nc9
nc9 deleted the lane-retention-auto branch September 8, 2026 09:19
nc9 pushed a commit that referenced this pull request Sep 8, 2026
…1990

Five audits of a 40-page project after rebasing onto automatic retention (#285):
two crawls retired, cache rows under exactly the three that remain, and every
audit after the first still replays every page. The carry-forward is what makes
retiring the crawl an entry came from harmless.

Signed-off-by: Nik Cubrilovic <[email protected]>
nc9 added a commit that referenced this pull request Sep 9, 2026
…f re-running them (#1990) (#295)

* perf(audit-engine): replay an unchanged page's rule results instead of re-running them #1990

A second audit of an unchanged site already fetched nothing and was not faster:
parse, page rules, the page-time collectors and report reconstruction re-ran in
full on every page whether or not that page changed. Crawl reuse is a bandwidth
feature; this is the one that makes a re-audit cheap.

A page now replays its stored rule results when every input its rules read is
unchanged. It is never parsed and its rules never run. Site rules always run.

At 2,500 pages, both arms on this build with SQUIRREL_RULE_CACHE=0 as the only
difference: the warm rules phase falls from 131 s to 12 s and the warm run from
171 s to 44 s, with the report byte-identical to its cold counterpart across all
3,044,401 bytes. The cold cost is below what the box can resolve.

The key covers the page's EXACT html bytes via a new pages.html_hash, not
content_hash, which is whitespace-normalized so the incremental crawler can call
a reformatted page unchanged; the rest of the page record the rules and
extractPageFeatures read, including the three timings performance/ttfb reads; and
a run context of the build version, the enabled page rules with their resolved
options, and the SiteData entry fields page rules read. A run with threat intel
enabled does not replay at all: IntelContext is two functions over feeds that
refresh daily, and its configuration identity is not an identity of its verdicts.

Template fan-out composes by abstention: a replayed page neither takes a cluster
verdict nor becomes a representative.

Signed-off-by: Nik Cubrilovic <[email protected]>

* fix(audit-engine): close seven review findings on the rule-result cache #1990

P1, and the interesting one: a replayed page has to RECORD into the template
fan-out, not abstain from it. Abstention makes which page runs a template-scoped
rule depend on what happens to be cached — on the audit after one page changes,
the changed page is the only fresh one and keeps its own verdict, where a fresh
audit would have the cluster's first page fan its verdict onto it. The next
fully-replayed audit then disagrees with a fresh audit of identical content and
persists the disagreement. A replayed page now records, keyed on the
page_features.template_fp its own run stored, which reproduces the fresh audit's
election exactly. Stored checks drop their own pageUrl stamp so what the fan-out
caches stays page-identity-free, and the replay re-stamps as the fresh path does.
Gated by a test that adds a viewport meta to one page of a cluster; the gate was
mutation-checked and fails without the fix.

P1: rules.ignore_applicability changes a gated rule from a skipped check to its
real verdict without touching the rule list or any rule's options, so it is now
part of the run context.

P2, five: the current UTC year is in the run context, because
content/stale-copyright reads it at execution and is the only page rule that
reads a clock; pages.content_hash and pages.parsed_data joined the page key, the
first because extractPageFeatures copies it verbatim and the second because
buildSiteContext prefers it over the HTML; the codec keeps Dates and own
__proto__ keys, both of which a plain-object walk drops; canonicalJson no longer
merges NaN/Infinity/-Infinity or [] with new Array(1); and the warm lookup picks
one row per key in SQL instead of decompressing every retained audit's copy,
which was work that grew with history rather than with the crawl.

Benchmarks re-measured on the fixed code, quiet box: the warm rules phase falls
from 106 s to 13 s at 2,500 pages and the report is byte-identical to its cold
counterpart.

Signed-off-by: Nik Cubrilovic <[email protected]>

* fix(audit-engine): make the rule cache and template fan-out mutually exclusive #1990

The second review round showed the fan-out fix closed only one direction. A
fanned verdict belongs to the page's CLUSTER, so no per-page key can capture what
it depends on: cache two pages of one cluster, change the FIRST one, and the
second replays the verdict it inherited from the representative's previous run
while a fresh audit gives it the new one. Nothing about the second page changed,
so nothing about its key can notice.

Enabling the cache therefore turns fan-out off for that run. Cost, measured: the
cold rules phase goes from 116 s to 124 s at 2,500 pages, 6.9%, and cold wall time
is unchanged; every audit after the first takes the 89% the cache buys. It also
makes the report the one every rule actually computed rather than one where some
verdicts were inherited, which is #275's open question made visible.

With nothing inheriting a verdict, the pageUrl stripping and record-on-replay the
previous commit added are gone: a stored check is what its own page produced.

Also from the second round: an invalid Date no longer decodes to the epoch, array
holes and -0 no longer canonicalize onto their neighbours, and the year-boundary
straddle is documented as bounded (the run stores under the old year's key, and
the next audit misses every one of those rows rather than serving one).

Gates: the composition test now compares like configurations, and a new one pins
the exclusivity directly - with a cache supplied the fan-out does zero work, which
an output diff cannot be relied on to show.

Signed-off-by: Nik Cubrilovic <[email protected]>

* fix(audit-engine): key the rule cache on the time zone, and stop replaying across a year rollover #1990

Third review pass, both reproduced. content/date-agreement resolves a bare schema
date through Date.parse, which reads it in LOCAL time, so the same page yields a
different year under UTC and under Australia/Sydney: the runtime time zone is now
part of the run context. And a long audit can cross UTC New Year while it runs,
where content/stale-copyright reads the clock itself and a page replayed after
midnight would serve last year's verdict; rather than freeze a year the rule
cannot be told about, replay stops for the rest of such a run and those pages are
audited normally.

Also drops a header comment still describing the fan-out composition design that
was rejected two commits ago.

Signed-off-by: Nik Cubrilovic <[email protected]>

* docs(benchmarks): record the rule cache against the retention window #1990

Five audits of a 40-page project after rebasing onto automatic retention (#285):
two crawls retired, cache rows under exactly the three that remain, and every
audit after the first still replays every page. The carry-forward is what makes
retiring the crawl an entry came from harmless.

Signed-off-by: Nik Cubrilovic <[email protected]>

* test(audit-engine): mark the published SHA-256 vectors as not secrets #1990

The entropy detector cannot tell a digest from a credential, and the vectors for
"" and "abc" are neither secret nor ours. The documented mitigation is the inline
pragma; detect-secrets-hook passes locally with it.

Signed-off-by: Nik Cubrilovic <[email protected]>

---------

Signed-off-by: Nik Cubrilovic <[email protected]>
Co-authored-by: Nik Cubrilovic <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant