Repository navigation
fix(crawler): keep the fetch deadline armed through the body read - #187
Merged
Merged
Conversation
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
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]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
The bug
A crawl of a slow origin could park forever before it emitted its
startedevent, 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
AbortControllerdeadline and cleared it in.finally()on the fetch promise — which settles the moment the response headers arrive. The body was read afterwards byreadBodyCapped, which caps bytes, not seconds, and holds no live abort signal. An origin that answers200promptly and then trickles or stalls its body hung there indefinitely.The pre-
startedinstance is the seed'sdetectRedirectsprobe, the only network call ahead of thestartedevent. 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):startedemitted at 10.17s, crawl proceedsstartedevent at all;start()still hung when the harness gave up at 45sRow one proves the deadline works for headers; row two proves it is already disarmed by the time the body is read.
The fix
packages/crawler/src/deadline.ts:withRequestDeadlineholds the timer across the body read, andsafeFetchWithDeadlineis that oversafeRedirectFetchfor 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 inpackages/fetchersalready used the correcttry/finallyshape and is untouched.)detectRedirectsgains a whole-chain wall-clock budget, so ten individually bounded hops cannot accumulate past the crawl-phase setup slack, and honors the crawl's configuredtimeoutMswhen it is tighter than the 10s ceiling (the 30s default leaves prod behavior unchanged).detectRedirectsnow 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.Tests
packages/crawler/tests/deadline.test.tscovers the helper directly.packages/crawler/tests/slow-origin-crawl.test.tsdrives 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/cli1889 pass,audit-enginegolden 63 pass;tsgo --noEmitclean 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 ofMAX_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.