Skip to content

fix(crawler): bound the crawl preamble with one phase budget - #194

Merged
nc9 merged 10 commits into
mainfrom
fix/1733-crawl-preamble-budget
Sep 2, 2026
Merged

nc9 merged 10 commits into
mainfrom
fix/1733-crawl-preamble-budget

Conversation

@nc9

@nc9 nc9 commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

Fixes squirrelscan/repo#1733 (private tracker).

The bug

PR #187 (for #1699) gave every root probe a deadline that survives its body read. It left the sum untouched: seven sequential stages carrying fixed 15-30s deadlines, so an origin answering 200 on every root path and then stalling the body burned 150.3s across 28 requests before page 1 - the entire 120s crawl phase a quick cloud audit gets, on a site that crawls fine once the preamble is past.

Two bounds, because the two halves fail differently

The central design decision, and it changed during review: the preamble is not one homogeneous thing.

Root probes (redirect resolution, robots, llms, markdown, well-known, agent-access, RSL) share one wall-clock budget.

budget = min(45_000ms, timeoutMs x 3)

Each request takes min(its own deadline, what the budget has left); once spent, the rest are skipped without a request and store the same unreachable shape a network failure gives them. Cutting these short costs AX metadata, and their rules degrade to unknown.

The sitemap walk is NOT on that budget. It runs on a progress window: it stops when it stops completing fetches, not when a clock expires. Cutting the walk short costs pages, and a site with 60 legitimate sitemaps (~48s of honest work) is slow without being stalled. A stalled origin completes nothing, so the window expires after ~one chunk; a healthy one keeps earning a fresh window and walks every sitemap.

That asymmetry is the fix for the review's MED 2 (silent page loss on a healthy origin) without reopening the hole the issue is about.

An unconfirmed probe is unknown, never a confirmed absence

The first round of this PR degraded budget exhaustion into confident negatives. exists: false and discovered: [] each conflate "the origin answered 404" with "we never got an answer", and the rules turned the second into definite, high-weight findings.

Both cases predate this PR - a robots.txt that timed out or 5xx'd has always reported "No robots.txt found" (weight 8). The budget made them far more reachable, so they are fixed here:

probe before now
robots.txt "No robots.txt found" (fail, w8) "robots.txt could not be checked" (info) when a reason was recorded; a clean 404 records none and still fails
sitemap "No XML sitemap found" (fail, w10) "discovery did not complete" (info) when the walk was truncated
RSL "broken" warn, leaking the internal reason unknown only when the doc was never attempted

The RSL fix is deliberately narrow. A URL we actually tried and could not fetch stays a broken reference - that is the defect the rule exists to surface, and an existing test pins it. Both are status: 0, so PROBE_NOT_ATTEMPTED_ERROR (now in core-contracts) is the discriminator.

Carrying the signal needed RobotsTxtRecord.error (schema 23, one additive ALTER, local sqlite only, not a prod migration) and SitemapDiscovery.truncated (persisted via crawl stats, no migration). Both optional, so older rows and other storage backends read as the confirmed case. The new column is on the reconciler's self-heal list and the drift guard, because the migration-renumbering gap has already bitten pages and sitemaps in turn.

Tests

packages/crawler/tests/preamble-budget.test.ts and packages/rules/tests/unconfirmed-probe-not-missing.test.ts.

Every test was verified to fail with its fix reverted: the stalled-origin tests time out at 30s (they would take ~180s), the truncation test reports 63 not-reached records instead of 0, and each rules test flips back to the missing-finding. The healthy-origin tests use deliberately slow responses - instant ones pass under any budget however brutal, and falsify nothing.

Two guards were dropped rather than kept untested: the sitemap recursion's entry guard (the chunk-loop guard already covers it, and no test could tell them apart) and the redundant crawler-tests CI job - cli-tests runs bare bun test from the repo root, which already covered packages/crawler.

Where the signal has to live

truncated first went only into report-stream.ts, which assembles the report after rules have scored. It was inert - crawl/sitemap-exists still saw undefined and still failed. Rules read the SitemapDiscovery built in adapter.ts (three literals), so it goes there. The first test missed this by asserting on the finished report and passed with the fix deleted; it now drives runRulesOnStorage and asserts on the check the rule produced.

Bounding the walk

The progress window alone is gameable: an origin answering ONE request per chunk instantly and stalling the other four spends a full window per chunk and re-arms it every time, so the walk runs as long as the origin likes. There is now a hard stop (SITEMAP_WALK_TOTAL_MS, 60s) the re-arm cannot reach past. Truncating there is safe only because truncation is honest - we say we did not finish rather than claiming the site has no sitemap. A configured hard stop shorter than the window is honored rather than silently widened to it.

What counts as progress is a settled fetch, not a successful one. Keying the re-arm off success punished a real shape: one quick 404 alongside four stalled bodies is a responsive origin the walk is getting through, but the chunk finds no sitemap, so the window died after one round and 5 of 68 candidates were ever visited. Failure results now carry settled - the origin answered and the request finished, whether that was a 404, a 500, or an empty body - and only a chunk where nothing came back at all burns the window.

Worst case before page 1 is therefore 45s (root probes) + 60s (walk hard stop) = 105s, against the 120s a quick cloud crawl gets. Those two maxima do not co-occur naturally: an origin that stalls the root probes completes nothing during the walk either, so its walk dies at the first 20s window. Reaching 105s takes an origin that stalls the probes and drips settled responses through the walk. The lever if you want a tighter guarantee is SITEMAP_WALK_TOTAL_MS, at the cost of truncating honest slow walks sooner - which is now an explicit, reported gap rather than silent page loss.

Truncation deep in the recursion was also being lost: it was computed only from unvisited top-level entry points, so an index whose children were abandoned reported truncated: false. The walk now records it wherever it gives up, including the depth cap and the URL budget.

Deliberately not in scope

The same unknown-vs-absent conflation exists in the llms.txt / markdown / well-known probes and in crawl/sitemap-coverage + integrity/orphan-page (which infer from a possibly-partial sitemap corpus). All pre-existing, all mostly informational rather than scored, and each needs its own probe contract plus rule change. Filed as squirrelscan/repo#1760 rather than bundled here. The plumbing this PR adds - PROBE_NOT_ATTEMPTED_ERROR, SITEMAP_NOT_CHECKED_ERROR, SitemapDiscovery.truncated - is what that work builds on.

Verification

whole-tree bun test 4903 pass / 4 skip / 0 fail; audit-engine goldens 63 pass with byte-identical numbers (98221 findings, healthScore 48); typecheck clean across 16 workspaces; lint, format:check and detect-secrets clean; all 13 CI checks green.

nc9 added 5 commits September 2, 2026 12:56
…lscan/repo#1733)

#1699 gave each root probe a deadline that survives its body read; it left
their SUM unbounded. The preamble is seven sequential stages carrying fixed
15-30s deadlines, so an origin answering 200 on every root path and then
stalling the body burned 150.3s across 28 requests before page 1 - the whole
120s crawl phase a quick cloud audit gets, on a site that crawls fine once
the preamble is past.

Add a PhaseBudget shared by seed redirect resolution, robots, the
llms/markdown/well-known/agent-access/RSL probes, and sitemap discovery. Each
request takes min(its own deadline, what the budget has left); once spent, the
remaining probes are skipped and store the same "unreachable" shape a network
failure gives them, so no probe row goes missing.

Budget = min(45s, timeoutMs x 3). The 45s ceiling leaves 75s of a 120s quick
phase for pages; the x3 clamp mirrors detectRedirects' REDIRECT_BUDGET_HOPS so
a config asking for snappy requests gets a snappy preamble.

Also run packages/crawler's suite in CI - `bun test` runs from apps/cli, so
the crawler guards had never executed there.

Signed-off-by: Nik Cubrilovic <[email protected]>
…uirrelscan/repo#1733)

Review follow-up. The recursion's budget guard only ran on the way INTO a
level. A sitemap index is attacker-sized - one robots.txt can declare
thousands of Sitemap: lines - so a budget expiring partway through a level
left the chunk loop walking every remaining URL, awaiting a skip result for
each. Break the loop instead, mirroring the URL-count guard beside it.

Test asserts the property that actually differs: `fetchSitemap` short-circuits
a spent budget in ~0ms, so request COUNT is bounded either way; what separates
the two is whether `failed` fills with a budget-exhausted record per remaining
entry point (63 without the guard, 0 with it).

Also record why the budget is scoped to start() rather than shared with a
caller's own seed pre-resolution: the caller's work between the two would sit
inside the window, so a slow local lookup could reach the preamble with the
budget already spent. The duplicate resolution itself is #1727.

Signed-off-by: Nik Cubrilovic <[email protected]>
…relscan/repo#1733)

Measured 1.04x locally (1559ms against a 1500ms budget), so 6x was slack that
asserted almost nothing. 3x keeps headroom for a busy CI box while making the
bound the test actually claims to check.

Signed-off-by: Nik Cubrilovic <[email protected]>
squirrelscan/repo#1733)

Acceptance review on #194. The budget degraded to confident NEGATIVES: a probe
that never got an answer produced the same shape as one that answered 404, and
the rules turned that into definite missing-file findings. Same principle as
the content-encoding probes in public #9 - a failed confirmation must degrade
to unknown.

Both HIGH findings were real, and both predate this PR: a robots.txt that timed
out or 5xx'd has always reported "No robots.txt found" (weight 8). The budget
made them far more reachable, so they are fixed here.

- robots: RobotsTxtRecord now carries the fetch error (schema 23, one additive
  ALTER, local sqlite only), buildRobotsData surfaces it, and crawl/robots-txt
  reports "could not be checked" instead of "No robots.txt found". A clean 404
  records no error and still fails, which is the discriminator.
- sitemaps: discoverSitemaps reports `truncated` and emits a not-reached record
  per unvisited entry point; persisted via crawl stats, so crawl/sitemap-exists
  no longer claims "No XML sitemap found" for a walk that never looked.
- rsl: only a NOT-ATTEMPTED document degrades to unknown. A URL we actually
  tried and could not fetch stays a broken reference - that is the defect the
  rule exists to surface, and an existing test pins it. Both are status 0, so
  PROBE_NOT_ATTEMPTED_ERROR (now in core-contracts) is the discriminator.

MED 2: the sitemap walk is off the shared budget entirely and runs on a
progress window - it stops when it stops COMPLETING fetches, not when a clock
expires. A stalled origin ends after ~one chunk; a site with 60 legitimate
sitemaps walks all of them. Truncating the walk costs pages, not metadata,
which is why it does not share the AX probes' ceiling.

Also: removed the redundant crawler-tests CI job. The cli-tests job runs bare
`bun test` from the repo root (4890 tests across 382 files), which already
included packages/crawler - my comment claiming otherwise was wrong.

Dropped the sitemap recursion's entry guard: the chunk-loop guard already
covers it, and it could not be falsified by any test.

Tests: rules-level coverage that unconfirmed robots/sitemap/rsl probes produce
no missing-findings while genuine absences still fail (each verified to fail
with the rule fix reverted); healthy-origin tests now use slow responses, since
instant ones pass under any budget and falsify nothing.

Signed-off-by: Nik Cubrilovic <[email protected]>
nc9 added 5 commits September 2, 2026 14:23
…/repo#1733)

The migration-renumbering gap has now bitten `pages` (#921) and `sitemaps` in
turn: a DB stamped past migration N by a build that numbered its own migration
N skips it forever, and the next write throws "no column named X". Migration 23
adds robots_txt.error, so it goes on the reconciler's self-heal list at the same
time, and the source-parsing drift guard grows a third case so the next
ALTER-added robots_txt column cannot forget.

Signed-off-by: Nik Cubrilovic <[email protected]>
squirrelscan/repo#1733)

Codex pass on the acceptance fixes. Three real defects, one of them mine
undoing my own fix.

1. The truncation flag was INERT. I set it in report-stream, which assembles
   the report AFTER rules have scored; rules read the SitemapDiscovery the
   adapter builds. So crawl/sitemap-exists still saw undefined and still
   emitted "No XML sitemap found" for a walk that never looked. Wired into all
   three adapter literals. My first test missed this by asserting on the
   finished report - it passed with the fix deleted - so it now drives
   runRulesOnStorage and asserts on the check the rule produced.

2. The progress window alone is gameable: an origin answering ONE request per
   chunk instantly and stalling the other four spends a full window per chunk
   and re-arms it every time, so the walk runs as long as the origin likes.
   Added a hard stop (SITEMAP_WALK_TOTAL_MS) the re-arm cannot reach past.
   Truncating there is safe only because truncation is now honest: we say we
   did not finish rather than claiming the site has no sitemap.

3. Truncation deep in the recursion was lost - it was computed only from
   unvisited TOP-LEVEL entry points, so an index whose children were abandoned
   reported truncated: false. The walk now records it wherever it gives up,
   including the depth cap and the URL budget.

Also: crawl/sitemap-valid no longer counts a never-requested sitemap as a
"failed to fetch" defect (the marker moved to core-contracts so both sides
share one string); the CLI report path carries both signals instead of
hard-coding errors: [] and dropping a zero-result truncated walk entirely; and
crawl/robots-txt reports the consequence rather than pasting the internal
"crawl phase budget exhausted" marker into user-facing copy.

Verified: whole-tree 4898 pass / 4 skip / 0 fail; engine goldens byte-identical
(98221 findings, healthScore 48); typecheck and lint clean. Each new guard was
checked by reverting its fix - the slow-drip test runs unbounded and times out,
the adapter test flips to "fail"/"No XML sitemap found".

Signed-off-by: Nik Cubrilovic <[email protected]>
…top (squirrelscan/repo#1733)

Round-2 verification findings.

MED 2 — the progress window re-armed only on `success`, which punished a real
shape: one quick 404 alongside four stalled bodies is a RESPONSIVE origin the
walk is getting through, but the chunk found no sitemap, so the window died
after one round and 5 of 68 candidates were ever visited. Failure results now
carry `settled` (the origin answered and the request finished — a 404, a 500,
an empty body) and any settled fetch re-arms. Only a chunk where nothing came
back at all burns the window. The regression reproduces the 5-of-68 number
exactly when reverted.

MED 1 — `sitemap-valid` filtered `failed`, and every adapter literal hard-codes
`failed: []`, so the not-reached guard was inert on the engine path and a
truncated walk got a generic "No sitemap to validate" — which reads as a
finished check that found nothing. It now reads `truncated`, the signal that
actually reaches rules, and says the check did not complete. The regression
enables sitemap-valid alongside sitemap-exists.

LOW — `Math.max(windowMs, totalMs)` silently widened a configured hard stop
shorter than the window (walkTotalMs 200 with a 2s window ran ~2s). Dropped:
`walkRemainingMs` already takes whichever bound is nearer, so the cap is honest.

NIT — refreshed two comments still describing the removed entry guard.

Also filled the new robots `error` field in the synthetic-site fixture writer
so fixtures keep matching the shape a real crawl writes.

Each guard verified by reverting it: the fast-404 walk stops at 5 requests,
sitemap-valid falls back to "skipped", the short hard stop runs to 2022ms.
Whole-tree 4903 pass / 4 skip / 0 fail; goldens byte-identical; typecheck,
lint, format:check clean.

Signed-off-by: Nik Cubrilovic <[email protected]>
@nc9
nc9 merged commit 00f6a8e into main Sep 2, 2026
13 checks passed
@nc9
nc9 deleted the fix/1733-crawl-preamble-budget branch September 2, 2026 05:32
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