Skip to content

perf(audit-engine): detach the external-link occurrences from the pages they were read off - #240

Merged
nc9 merged 4 commits into
mainfrom
perf/detach-external-link-occurrences-1860
Sep 7, 2026
Merged

nc9 merged 4 commits into
mainfrom
perf/detach-external-link-occurrences-1860

Conversation

@nc9

@nc9 nc9 commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

For squirrelscan/repo#1860 (epic #1866), after #234 / #237 / #236.

The page loop those PRs fixed is now bounded. The pre-rules walk that runs before it is not.

What is still holding the pages

absorbExternalLinkOccurrences accumulates every external-link appearance across the whole crawl. It has to run with each batch's DOMs live, because link position (nav/header/footer/body) is not in stored parsedData. So href and text are read straight off the live document, which makes both of them slices of that page's html, and JSC keeps a slice attached to the buffer it came from. The map outlives every batch, so one retained anchor text holds a whole 959 KB page as UTF-16 until the walk ends.

The map key pins a page exactly as well as a value does, which is easy to miss: detaching only the occurrence record leaves the retention in place on any site whose outbound links differ per page.

Measured

scripts/prerules-retention.ts, over real 959 KB drscholls pages with per-page-distinct external links, batch 50, against a control that absorbs nothing. String backing store held above that control:

50 pages 100 pages 150 pages
before 0 MB 94 MB 187 MB
after 3 MB 0 MB -1 MB

1.87 MB per page, which is one 959 KB page as UTF-16, against roughly 200 KB of actual link data across the whole run. Flat after.

It reads as zero at 50 pages because that is one batch: a pinned page only costs anything once the walk has moved past it. Projected at the sizes #1866 is aimed at, the old path holds about 9 GB at 5,000 pages.

This is invisible to every obvious measure, in the same way #234 was. heapUsed barely moves — a string's backing store is not on the JS heap — and RSS shows nothing because the arena absorbs it. It appears in external, and in the count of live page-sized strings in a heap snapshot, which the script reports because it is the unambiguous one: 51 live (one batch, the floor) after the fix, against 1 before, where the pinned buffers had been merged away from any single node.

The fix

One structuredClone of the whole batch's additions, not one per link, then merged into target in absorption order. Order is what parity rests on: the map ends up with the same entries, the same per-href occurrence order and the same key insertion order the attached version produced, and string map keys compare by value, so a detached href still finds an entry an earlier batch stored.

What I did NOT change, and why

The two other collectors on the same walk were measured, not assumed:

  • asset collector — css/script keys do come off the DOM, but they are resolved through new URL().toString(), so they are already fresh. Measured 3 MB above control at 150 pages.
  • cloud prefetch collector — 17 MB at 150 pages, which is its documented bounded metadata sample (SERVICE_LIMITS.metadataMaxPages entries) rather than a per-page term.

The rest of the page loop, for the record

scripts/page-loop-census.ts and scripts/universe-field-census.ts measure what the loop still retains per page, by dropping one accumulator at a time inside a single process. A between-process comparison of two variants carries the run's own variance, which on this fixture is ±50 MB and swamps the signal.

KB/page
universe links 16
universe images 10
page check maps (pageResults + pageRuleResults + ruleResultsMap) 21
collected fingerprint 9
collected scriptSrcs 6
universe schema 5
tallies 0

Identical at 50, 100 and 150 pages. That is about 80 KB per page in total, all of it values the site pass reads, and live page HTML through the loop stays batch-bounded (49 live strings at the end of every batch, never growing). So the page loop is not where the remaining growth was.

Test fix worth calling out

detach-from-page.test.ts's memory harness sampled heapUsed alone. The attached control therefore measured 0 KB/item, the test took its INCONCLUSIVE branch on every run, and it has been green while asserting nothing. It samples heapUsed + external now and its assertion actually runs.

Gates

Byte identity unchanged: the v1-vs-v2 canonical, streaming, pre-rules, collector, page-rules, scoring and report-stream goldens, the five site-query goldens, the 518-page baseline and the complete-store parity all pass. streaming-pre-rules-golden.test.ts already pins batched-vs-resident collection for this exact function; detach-production-boundaries.test.ts adds detached-vs-attached, asserts the clone took the real path with no fallback, and measures on page-sized inputs with both arms warmed first (whichever arm ran first was paying for the parser's one-time structures and looking like the leaker).

Review

Four codex rounds (gpt-6-astra). The production change was approved in round 1 and is byte-identical through all of them — same packages/audit-engine/src tree hash on every commit. Round 1 also mutation-tested it: with the detach call site removed both new tests fail, and with it restored both pass five consecutive runs without the INCONCLUSIVE guard firing.

Every subsequent finding was in the measurement scripts, which is where a wrong number does the damage — someone sizes a container off it.

  • Round 1. The slope was fitted to heartbeat samples, which land mid-batch while the batch's documents are progressively released: a draining working set mixed with filling accumulators, which can report negative retention for a growing loop. And the field census treated per-field drops as independent when h1.texts IS headings.h1Texts and schema's fields are schemas'.
  • Round 2. The boundary hook runs while that batch's PageRecords are still in scope, so a short final batch holds less html than a full one and sits below the trend by itself. Measured at batch 40 over 150 pages: 309 / 374 / 381, then 329 for the 30-page tail. Also, author.socialProfiles IS the schema's sameAs array and the identity survives the clone, so author had to join the schema group, and the three visible* fields were in no group at all while the residual row claimed to be object shells.
  • Round 3. The full-batch test read pagesDone, which counts only pages the loop SCORES, so a full 50-row batch holding one non-HTML page looked short and was discarded. Fullness comes from the fetched rows now. The same round took apart batch-floor.ts, a script I had added to separate the batch working set from allocator residency, and it could not do either: heap-snapshot node sizes already include backing stores, so adding external double-counted them (a 32 MiB ArrayBuffer moves the sum by 64); RSS - LIVE also contains live native allocations, SQLite's caches and resident JIT code; per-boundary snapshots perturb the RSS being measured; and it pinned a batch size, so it never exercised the byte budget it was supposed to be evidence about. It is deleted rather than patched. That question needs an OS-recorded high-water and allocator accounting.
  • Round 4. Clean.

@nc9
nc9 force-pushed the perf/detach-external-link-occurrences-1860 branch from fa39502 to 26706c1 Compare September 7, 2026 15:37
nc9 added 4 commits September 8, 2026 02:07
…es they were read off

The pre-rules walk's external-link map outlives every batch, and its `href` and
`text` are read off the live DOM, so both are slices of that page's html. JSC
keeps a slice attached to the buffer it came from, so one retained anchor text
holds a whole 959 KB page as UTF-16 until the walk ends — including the map KEY,
which pins a page just as effectively as a value does.

Measured over real 959 KB pages with per-page-distinct external links, batch 50,
against a control that absorbs nothing. String backing store held above control:

           50 pages   100 pages   150 pages
  before      0 MB       94 MB      187 MB
  after       3 MB        0 MB       -1 MB

1.87 MB per page against ~200 KB of actual link data. It reads as zero at 50
pages because that is one batch: the retention only shows once a pinned page is
one the walk has already moved past.

The batch is detached in one structuredClone rather than one per link, and
merged in absorption order so `target` ends up with exactly the entries and
per-href order the attached version produced.

Also fixes the memory harness in detach-from-page.test.ts, which sampled
heapUsed alone. A string's backing store is not on the JS heap and a slice pins
the buffer, so the attached control measured 0 KB/item and the test took its
INCONCLUSIVE branch on every run — green, asserting nothing.

Refs squirrelscan/repo#1860, #1866.

Signed-off-by: Nik Cubrilovic <[email protected]>
Both are in the diagnostics, not the production path.

page-loop-growth.ts fitted its slope to heartbeat samples, which land mid-batch
while the batch's documents are part-released. That mixes a draining working set
with filling accumulators, and a single-batch crawl could report a negative
per-page retention for a loop that was growing. It fits batch boundaries now,
drops the first (the only one whose preceding state is "no batch ever read", so
it carries the walk's warm-up), and says outright that it is a diagnostic whose
slope moves by a factor of two between runs — the per-structure attribution
comes from the two censuses, which repeat exactly at 50/100/150.

universe-field-census.ts claimed its per-field drops were independent. Two pairs
alias on a fresh parse: `h1.texts` IS `headings.h1Texts`, and `schema`'s four
fields ARE `schemas`'. Deleting one half first attributed the shared data to the
other, which read as "the deprecated `schema` field costs 5 KB/page and
`schemas` costs 1". Aliased fields are dropped as one group now.

Refs squirrelscan/repo#1860.

Signed-off-by: Nik Cubrilovic <[email protected]>
Scripts only; the production change is byte-identical to the reviewed commit.

page-loop-growth.ts: the batch-boundary hook runs while that batch's PageRecords
are still in scope, so a SHORT final batch is holding less html than a full one
and its sample sits below the trend on its own. Measured on a 150-page crawl at
batch 40: boundaries read 309 / 374 / 381 and then 329 for the 30-page tail.
Partial batches are printed and excluded from the fit now. The slope is labelled
a TAIL slope, since excluding the startup boundary moves that allocation into
the intercept rather than making it go away, and the heartbeat maximum is
labelled a post-collect high-water rather than a container peak — `retained()`
collects before it samples, so it cannot see an RSS spike between heartbeats.

universe-field-census.ts: `author` aliases the schema group. `author.socialProfiles`
IS the Person/Organization schema's `sameAs` array and the identity survives
detachParsedPage, so deleting `author` second billed the shared array to it.
`visibleAuthor` / `visibleDatePublished` / `visibleDateModified` were in no
group at all and fell into the residual row, which claimed to be object shells.

Adds batch-floor.ts, which answers the question the other two cannot: how much
of the loop's RSS is the batch working set and how much is the allocator not
returning freed pages. It samples live heap from a snapshot (the only measure
that cannot include unswept blocks) against RSS at each boundary, and takes the
peak WITHOUT a collect, because the high-water is what the container is charged.

Refs squirrelscan/repo#1860.

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

Scripts only; production is byte-identical to the reviewed commit.

The full/partial test read `pagesDone`, which advances only for pages the loop
actually SCORES. A full 50-row batch holding one non-HTML or WAF page therefore
looked short and was thrown out of the fit. The loop reads by OFFSET over the
same rows `getPageCount` counts, so fullness is now `BATCH * batchIndex <=
pageCount`, which is right whatever the batch holds.

batch-floor.ts is removed rather than fixed. It claimed to separate the batch
working set from allocator residency, and it could not do either:

- `LIVE` added `external` to the heap snapshot's node sizes, but those sizes
  ALREADY include backing stores. A 32 MiB ArrayBuffer moves the snapshot by
  32 MiB, `external` by 32 MiB, and that sum by 64.
- `RSS - LIVE` is not freed-but-unreturned memory. It also contains live native
  allocations, SQLite's caches, resident JIT code and thread stacks, none of
  which a collect makes unused.
- Taking a snapshot per boundary perturbs the RSS it is measuring, by about
  4 MiB per snapshot, and changes the instrumentation rate with the batch size.
- The peak sampler runs on heartbeats inside sync CPU, so it cannot see a spike
  between two of them, and the script pinned an explicit batch size, so it never
  exercised the byte budget it was meant to be evidence about.

Separating those terms needs an OS-recorded high-water and allocator-specific
accounting, not a heap snapshot. The peak line in page-loop-growth.ts now says
what it is: a sampled floor on the peak, not the container's high-water.

Refs squirrelscan/repo#1860.

Signed-off-by: Nik Cubrilovic <[email protected]>
@nc9
nc9 force-pushed the perf/detach-external-link-occurrences-1860 branch from 3fb1828 to 8cd691a Compare September 7, 2026 16:07
@nc9
nc9 merged commit fdf28c2 into main Sep 7, 2026
13 checks passed
@nc9
nc9 deleted the perf/detach-external-link-occurrences-1860 branch September 7, 2026 16:14
nc9 pushed a commit that referenced this pull request Sep 7, 2026
…#1913

The CLI audit was still the resident pipeline: one buildSiteContext over every
crawled page, a parsed page plus its DOM held through the whole rules phase, and
a second whole-crawl getPages in the report. End-of-run retained heap grew about
1.5 MB per crawled page while max RSS read flat, because the macOS compressor
absorbed it.

Every post-crawl phase now walks the pages table in byte-budgeted batches and
drops each batch's DOMs before reading the next, using the same engine functions
the hosted runtime has run since #1860 rather than a second implementation:

- runStreamingPreRules replaces buildSiteContext + checkExternalLinksOnStorage +
  fetchResourceAssets. Two seams were added to it for the CLI: onBatchContext,
  for a caller's own page-time collectors, and resolveBulkChecker, so the paid
  dead-links spend confirm still lands before the phase rather than inside its
  progress output.
- runStreamingRules replaces runRulesOnStorage.
- reconstructReport's page pass is batched.
- The cloud-prefetch payloads, the tech-detect page sample, the dead-links link
  count and the smart-audits page list are collected during the pre-rules walk.
  Payload strings are detached from the page they were sliced off (#240): a
  6 KB text excerpt pins a whole page, which the resident path never had to
  care about and a streamed walk does.

Batch size comes from SQUIRREL_STREAM_BATCH_BYTES (48 MB of raw html by
default), the same dial and default the container reads, with
SQUIRREL_STREAM_BATCH_PAGES to pin a page count. A value that is not a plain
integer is refused and named rather than silently partially parsed, because
"48mb" through parseInt is 48 BYTES and clamps to a 1 MB batch.

Measured on a 6-template synthetic estate (mean 128 KB/page, 10% a real 982 KB
product page), interleaved cold runs, heapUsed sampled after Bun.gc(true):

  pages   wall            end heapUsed
    400   47s  ->  47s    685 MB ->   265 MB
  1,000  194s  -> 128s  1,662 MB ->   565 MB
  2,500  502s  -> 177s  3,902 MB ->   996 MB

Wall time improves rather than regressing: the resident path's own 1.6-3.9 GB
costs more in collector and compressor work than the streamed walk's extra parse
per page. Reports are identical at all three sizes, and at 2,500 pages the only
difference between the two runs is perf/ttfb, which grades the server's response
time and saw a machine under 3.9 GB of pressure.

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

* perf(cli): run the audit's post-crawl phases on the streaming pipeline #1913

The CLI audit was still the resident pipeline: one buildSiteContext over every
crawled page, a parsed page plus its DOM held through the whole rules phase, and
a second whole-crawl getPages in the report. End-of-run retained heap grew about
1.5 MB per crawled page while max RSS read flat, because the macOS compressor
absorbed it.

Every post-crawl phase now walks the pages table in byte-budgeted batches and
drops each batch's DOMs before reading the next, using the same engine functions
the hosted runtime has run since #1860 rather than a second implementation:

- runStreamingPreRules replaces buildSiteContext + checkExternalLinksOnStorage +
  fetchResourceAssets. Two seams were added to it for the CLI: onBatchContext,
  for a caller's own page-time collectors, and resolveBulkChecker, so the paid
  dead-links spend confirm still lands before the phase rather than inside its
  progress output.
- runStreamingRules replaces runRulesOnStorage.
- reconstructReport's page pass is batched.
- The cloud-prefetch payloads, the tech-detect page sample, the dead-links link
  count and the smart-audits page list are collected during the pre-rules walk.
  Payload strings are detached from the page they were sliced off (#240): a
  6 KB text excerpt pins a whole page, which the resident path never had to
  care about and a streamed walk does.

Batch size comes from SQUIRREL_STREAM_BATCH_BYTES (48 MB of raw html by
default), the same dial and default the container reads, with
SQUIRREL_STREAM_BATCH_PAGES to pin a page count. A value that is not a plain
integer is refused and named rather than silently partially parsed, because
"48mb" through parseInt is 48 BYTES and clamps to a 1 MB batch.

Measured on a 6-template synthetic estate (mean 128 KB/page, 10% a real 982 KB
product page), interleaved cold runs, heapUsed sampled after Bun.gc(true):

  pages   wall            end heapUsed
    400   47s  ->  47s    685 MB ->   265 MB
  1,000  194s  -> 128s  1,662 MB ->   565 MB
  2,500  502s  -> 177s  3,902 MB ->   996 MB

Wall time improves rather than regressing: the resident path's own 1.6-3.9 GB
costs more in collector and compressor work than the streamed walk's extra parse
per page. Reports are identical at all three sizes, and at 2,500 pages the only
difference between the two runs is perf/ttfb, which grades the server's response
time and saw a machine under 3.9 GB of pressure.

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

* fix(cli): close three gaps the streamed audit port opened #1913

Found by an adversarial review of the port, all three verified in code:

- The external-link phase lost the global dead-link cache. The resident entry
  point (checkExternalLinksOnStorage) reached for getGlobalLinkCache() itself;
  the collected-links entry point takes it as an argument and reads an absent
  one as "no caching". Every re-audit would have re-checked every external link
  and resubmitted already-known urls to the PAID bulk checker.

- The report's per-page fields were still pinning whole pages. meta, og,
  twitter, schema and the h1 texts are slices of the page's html, and in JSC a
  retained slice holds the buffer it was cut from. The resident path was holding
  the page anyway; here the batch is dropped right after, so each kept title held
  its megabyte. Measured on ~1 MB pages: 77.5 MB retained across 80 pages
  attached, 2.1 MB detached. One copy per page of five small objects.

- Sitemap status checks silently stopped at 2,000 urls. The engine's asset pass
  capped the orphan list at REPORT_LIMITS.maxPages before the configured
  resource limit was applied, so on a 3,000-page crawl with more than 2,000
  uncrawled sitemap urls a 404 at position 2,001 was never fetched and
  crawl/sitemap-4xx reported a pass. The candidates are now bounded by the
  resource limit alone; the arrays that travel on the report stay capped. The
  cloud is unaffected, it passes resourceCheckMaxItems = 100.

Reports stay identical to the resident path at 400 and 1,000 pages, and end
heapUsed is unchanged at 266 MB and 563 MB.

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

* docs(cli): document the streamed audit's memory behaviour and its two dials #1913

The batch dials are user-facing and had no page. Added to the debug guide,
next to tracing, because that is where someone lands when an audit is slow or
large: what the batching does, the two env vars with the container's names and
default, why turning the budget down usually makes peak memory worse, and the
opt-in per-sub-phase heap line. Says to read heapUsed rather than rss, since
macOS compression makes the resident figure stop tracking what is held.

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