Skip to content

fix(crawler): keep the fetch deadline armed through the body read - #187

Merged
nc9 merged 4 commits into
mainfrom
fix/1699-slow-site-crawl-wedge
Sep 1, 2026
Merged

nc9 merged 4 commits into
mainfrom
fix/1699-slow-site-crawl-wedge

Conversation

@nc9

@nc9 nc9 commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

The bug

A crawl of a slow origin could park forever before it emitted its started event, so the caller saw a crawl that never began rather than one that ran out of time.

Every fetch in the crawl preamble armed an AbortController deadline and cleared it in .finally() on the fetch promise — which settles the moment the response headers arrive. The body was read afterwards by readBodyCapped, which caps bytes, not seconds, and holds no live abort signal. An origin that answers 200 promptly and then trickles or stalls its body hung there indefinitely.

The pre-started instance is the seed's detectRedirects probe, the only network call ahead of the started event. That is the discriminator: a hang anywhere later finalizes with whatever pages exist, while a hang here looks like a crawl that never started.

Isolated against a synthetic Bun origin (idleTimeout: 0, so the client is what has to give up):

root stalls result
before it sends headers deadline fires, started emitted at 10.17s, crawl proceeds
after it sends headers (the body) no started event at all; start() still hung when the harness gave up at 45s

Row one proves the deadline works for headers; row two proves it is already disarmed by the time the body is read.

The fix

  • New packages/crawler/src/deadline.ts: withRequestDeadline holds the timer across the body read, and safeFetchWithDeadline is that over safeRedirectFetch for the root probes. All eight sites that had the broken shape now route through it — core/crawler.ts, robots.ts, llms.ts, markdown.ts, well-known.ts, agent-access.ts, rsl.ts, sitemaps.ts. (The page fetcher in packages/fetchers already used the correct try/finally shape and is untouched.)
  • detectRedirects gains a whole-chain wall-clock budget, so ten individually bounded hops cannot accumulate past the crawl-phase setup slack, and honors the crawl's configured timeoutMs when it is tighter than the 10s ceiling (the 30s default leaves prod behavior unchanged).
  • detectRedirects now falls back to the last URL that actually served a response, banked as soon as its headers land, instead of to an unfetched client-redirect target. A meta-refresh can no longer reroute the seed on the strength of a later timeout.
  • Paths that inspect only the headers now cancel the body instead of leaving the response half-consumed.

Tests

packages/crawler/tests/deadline.test.ts covers the helper directly. packages/crawler/tests/slow-origin-crawl.test.ts drives a Bun origin whose root answers 200 and then stalls (and a second that trickles a byte every 50ms forever, which no byte cap can end), plus an origin that is slow on every single response, plus the served-URL semantics above.

Verified the regression tests fail against the pre-fix crawler: both stalled-body tests time out at 25s on origin/main, and the served-URL test returns the pre-redirect seed. Suites: crawler 264 pass, apps/cli 1889 pass, audit-engine golden 63 pass; tsgo --noEmit clean for crawler, audit-engine and cli.

Fixes the crawl wedge tracked in https://github.com/squirrelscan/repo/issues/1699 (root-cause write-up posted there).

Also covered: a client-redirect target that never serves headers (the case that distinguishes the settled-URL fallback from returning currentUrl), and a redirect chain the whole-chain budget must stop short of MAX_REDIRECTS. Every new assertion was mutation-checked — reverting the behavior it covers makes it fail.

Scope note

The crawl preamble still has no budget as a whole: its stages are sequential with fixed per-probe deadlines, so an origin whose root-probe paths answer 200 and then stall their bodies burns 150.3s measured before the first page, against a 120s crawl-phase floor plus 30s grace. That is tracked separately in https://github.com/squirrelscan/repo/issues/1733 (P2) rather than fixed here: a shared budget trades AX data completeness on slow-but-healthy origins for phase bounding, which is a product call, and the structurally correct version (stop() aborting in-flight preamble requests) means threading an AbortSignal through all seven probe modules. The per-request deadlines in this PR are the precondition for either.

nc9 added 4 commits September 2, 2026 07:45
Every fetch in the crawl preamble cleared its abort timer in `.finally()`
on the fetch promise, i.e. the moment the response HEADERS arrived, and
only then read the body. `readBodyCapped` caps bytes, not seconds, so an
origin that answered 200 and then stalled or trickled its body parked the
crawl there forever.

The pre-`started` instance is the seed's `detectRedirects` probe. That is
why the failure surfaced as a crawl that never began rather than one that
ran out of time: the "wedged before any pages were collected" backstop
fires only when no `started` event ever arrives, and `detectRedirects` is
the sole network call ahead of it.

Route all eight sites through one `withRequestDeadline` helper that holds
the timer across the body read; give `detectRedirects` a whole-chain
budget so ten bounded hops cannot outlast the crawl-phase setup slack;
and have it fall back to the last URL that actually served rather than to
an unfetched client-redirect target.

Regression tests drive a Bun origin that answers 200 and then stalls (and
one that trickles) its root body; both hang the pre-fix crawler.

Signed-off-by: Nik Cubrilovic <[email protected]>
Review follow-ups on the deadline fix.

`detectRedirects` recorded the resolved URL only after the body read
finished, so the one case the fix is about — headers arrive, body stalls
— discarded the hop that had demonstrably served and handed the crawl
back the pre-redirect seed. Record it as soon as the headers land.

`withRequestDeadline` requires its callback to read or cancel the body;
the robots 404 / non-2xx paths and the llms 404 / oversize paths returned
without doing either, leaving an error body and its connection alive.

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

Acceptance-review follow-ups.

A rejected sitemap body read reported the raw runtime exception once the read
moved inside the deadline, where it used to classify as "Empty response". That
text reaches persisted sitemap-failure records, so restore it; changing what
users see there is a separate call, not a side effect of this fix.

The chain budget was `hopTimeoutMs * MAX_REDIRECTS` capped at 30s, which is
indistinguishable from ten independent hop budgets whenever the cap is not the
binding term — and untestable without a 100s crawl. Express it as three full
request timeouts instead: identical 30s in production (10s hops), and small
enough elsewhere that a test can pin it.

Tests: assert the deadline fires NEAR its expiry rather than merely eventually,
and that it is actually disarmed after a normal read (waiting past the deadline
and checking the signal — omitting the clearTimeout previously passed). Add a
client-redirect target that never serves headers, which is the case that
distinguishes the settled-URL fallback from returning `currentUrl`, and a
redirect chain that the whole-chain budget must stop short of MAX_REDIRECTS.

Each new assertion was mutation-checked: reverting the behavior it covers makes
it fail.

Signed-off-by: Nik Cubrilovic <[email protected]>
@nc9
nc9 merged commit fb9fe3f into main Sep 1, 2026
13 checks passed
@nc9
nc9 deleted the fix/1699-slow-site-crawl-wedge branch September 1, 2026 22:41
nc9 added a commit that referenced this pull request Sep 2, 2026
Five fetchers cleared their AbortController timer where the fetch resolved,
i.e. when the response HEADERS landed, leaving the body read with no time
bound. readBodyCapped and response.text() cap BYTES, not seconds, so an
origin that answers 200 and then trickles or stalls its body parked the
caller forever. Same class as #187 fixed in the
crawler; these are the stragglers.

clearTimeout moves into a finally that wraps the body read. The script
fetchers split their retry loop out of the attempt so each retry arms a
fresh deadline instead of inheriting a spent one.

The CLI forks are the live path for the `squirrel` binary (apps/cli imports
its own crawler/, not the engine package), so fixing only the package would
have left users hanging.

Sites fixed:
- packages/audit-engine/src/script-fetcher.ts (body read)
- packages/audit-engine/src/external-checker.ts (WAF 403 body read)
- apps/cli/src/crawler/script-fetcher.ts (fork)
- apps/cli/src/crawler/external-checker.ts (fork)
- apps/cli/src/crawl/sitemaps.ts (text read ran after the timer cleared)

Scripts and external links are fetched during rules enrichment, after the
crawl, so the failure mode was a post-crawl hang: an audit with all its
pages that never finishes. The sitemap read hangs the crawl preamble.

Regression tests serve headers then hold the body stream open forever; all
five hang without the fix and time out at the deadline with it. The engine
tests are added to test:golden so CI actually runs them.

Refs squirrelscan/repo#1729

Signed-off-by: Nik Cubrilovic <[email protected]>
nc9 added a commit that referenced this pull request Sep 2, 2026
#191)

* fix(audit-engine): keep the fetch deadline armed through the body read

Five fetchers cleared their AbortController timer where the fetch resolved,
i.e. when the response HEADERS landed, leaving the body read with no time
bound. readBodyCapped and response.text() cap BYTES, not seconds, so an
origin that answers 200 and then trickles or stalls its body parked the
caller forever. Same class as #187 fixed in the
crawler; these are the stragglers.

clearTimeout moves into a finally that wraps the body read. The script
fetchers split their retry loop out of the attempt so each retry arms a
fresh deadline instead of inheriting a spent one.

The CLI forks are the live path for the `squirrel` binary (apps/cli imports
its own crawler/, not the engine package), so fixing only the package would
have left users hanging.

Sites fixed:
- packages/audit-engine/src/script-fetcher.ts (body read)
- packages/audit-engine/src/external-checker.ts (WAF 403 body read)
- apps/cli/src/crawler/script-fetcher.ts (fork)
- apps/cli/src/crawler/external-checker.ts (fork)
- apps/cli/src/crawl/sitemaps.ts (text read ran after the timer cleared)

Scripts and external links are fetched during rules enrichment, after the
crawl, so the failure mode was a post-crawl hang: an audit with all its
pages that never finishes. The sitemap read hangs the crawl preamble.

Regression tests serve headers then hold the body stream open forever; all
five hang without the fix and time out at the deadline with it. The engine
tests are added to test:golden so CI actually runs them.

Refs squirrelscan/repo#1729

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

* fix(cli): await and catch the discarded sitemap body cancel

A bare `void body.cancel()` leaves a rejected cancel unhandled — an
already-errored stream rejects, and an unhandled rejection is a worse
outcome than an undrained socket.

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

* fix(crawler): hold the fetch deadline through fetchPageStandard's body read

Acceptance-review follow-ups on the #1729 deadline sweep.

packages/crawler/src/fetcher.ts had the same clear-at-headers bug wearing a
try/finally that looks correct: requestWithTiming cleared its timer in a
finally that closes at the fetch, then returned the Response for
fetchPageStandard to read much later. The same finally also removed the
fiber-interrupt bridge, so the watchdog's abort never reached the reader --
readBodyCapped stayed parked on reader.read() for the life of the process,
holding the socket and its buffered chunks.

Not an unbounded hang: crawler.ts's per-URL watchdog (>=120s) is the
backstop. But a stalled page burned the whole watchdog instead of timeoutMs.

requestWithTiming now returns a TimedResponse whose deadline stays armed;
the caller owns it across the redirect loop and the body read, drops
superseded hops (which the loop never did, leaking their sockets), and
Effect.ensuring releases whatever is still held on every exit -- a
try/finally inside Effect.gen would not run on failure. The body read's
interrupt bridge now aborts the request rather than only losing a race, and
a deadline that fires mid-body reports a timeout, not a parse error.
fetchPageStandard is split behind Effect.suspend so the held-response state
is per RUN: callers retry this same Effect value.

External checker (both copies): a 403 whose body could not be read no
longer abandons WAF detection. Detection runs on the response headers,
which are evidence in their own right -- most WAFs are identifiable from
cf-ray / x-sucuri-id / a provider server value alone. Giving up there
reported live, bot-guarded links as broken, and the deadline now makes that
read fail more often.

Sitemaps: the terminal catchAll carries the failure reason instead of
collapsing every non-HTTP failure to "Unexpected error", so a body-read
timeout, a connect failure and an HTTP error are distinguishable. Its
error-channel value no longer mimics the success shape.

Tests: each new case was verified against origin/main -- 4 of 5 engine and
6 of 8 CLI cases fail there, and both crawler stall cases fail, one by
hanging and one by observing that the server never saw the client abort.
The retry tests now stall attempt 2's body, so they pin that the retry's
deadline is fresh AND covers its body; the earlier form passed unfixed.

Refs squirrelscan/repo#1729

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

* fix(crawler): cancel a held response released without a body read

Round-2 review findings, both reproduced with an instrumented probe before
being fixed and re-probed after.

release() only disarmed the timer. Every path that releases WITHOUT a body
read therefore left the stalled body and its socket parked for the life of
the process -- the exact leak class this change exists to kill. Two such
paths: a terminal 403/429/5xx that fails applyStatusGuards before any read,
and a redirect hop still held when the NEXT request fails (the loop drops a
superseded hop only once a newer response arrives). Probe on both:
`server saw cancel: false`. release() now aborts as well. That is safe
unconditionally because release runs only as the effect leaves: on the
success path the stream is already drained and the abort is a no-op.

The 503 challenge read swallowed every failure via orElseSucceed, including
the timeout this PR newly maps, so a stalled 503 body came back as the
generic `network: Server error: 503` -- blaming the origin for our own
deadline. It now re-fails on a timeout and still degrades every other read
failure to "no body", so the guard can classify the 503 from headers alone.

Three tests added, each verified to fail against the previous commit: two
use a server-side `req.signal` observer to prove the connection is actually
cancelled (terminal status, failed hop), and one asserts the stalled-503
classification is `timeout`.

Rebased onto main after #193 merged.

Refs squirrelscan/repo#1729

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

---------

Signed-off-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