Skip to content

perf(publish): bound the resolution signal and pageStatuses to a 192 KiB budget (repo#2658) - #641

Merged
nc9 merged 6 commits into
mainfrom
perf/resolution-signal-budget-2658
Oct 11, 2026
Merged

nc9 merged 6 commits into
mainfrom
perf/resolution-signal-budget-2658

Conversation

@nc9

@nc9 nc9 commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Billing: this changes how coverage.auditedPages is derived (the count billing reads). With a complete crawled list nothing changes: it is still the payload's pages plus the signal's pages, less removed ones. With a clipped list (crawledComplete: false) it is max(payload-evidenced pages, crawledCount - removedCount). The claimed counts can only raise it, never lower it. They are used only as non-negative integers, clamped to the 10,000-page crawl ceiling (REPORT_LIMITS.maxPages). The private API PR clamps them to the plan's page limit.

Part of squirrelscan/repo#2658 (epic repo#2655). The resolution signal (crawled URLs plus failing-page hashes per check) and pageStatuses were the only publish fields that grew with pages after per-class capping: about 0.3 KB a page, over 1 MiB from about 2,800 pages. This puts both in a fixed 192 KiB budget. It also wires that budget into #640's capper, so the whole capped body fits 1 MiB whatever the crawl size.

  • Compact signal (resolutionSignalCompact, types in core-contracts resolution.ts): base64 of raw-deflated JSON. Crawled URLs sorted, failing / not-evaluated / removed sets as gap-coded indexes into them. It hashes exact URLs, so the crawled set has no 32-bit collision risk.

  • Decoder (decodeResolutionSignal, @squirrelscan/rules/resolution-decode, the API's side) turns it back into the legacy ResolutionSignal the merge reads. It refuses data past 192 KiB. It inflates with node:zlib inflateRawSync(..., { maxOutputLength: 4 MiB }), under Workers nodejs_compat. Before JSON.parse it counts containers, nesting and separators outside strings, against what a valid payload can hold. Then it validates every field.

  • Builder (buildPublishResolution, rules resolution.ts): fits pageStatuses (clipped to 32 KiB, 404/410 first) plus the signal into RESOLUTION_PUBLISH_LIMITS.maxBytes, keys included. REPORT_CAPS.signalMaxBytes / pageStatusesMaxBytes now alias it, so there is one number. Over budget it either drops the costliest keys (listed in truncated) or clips the crawled list (crawledComplete: false, crawledCount, removedCount), whichever keeps more page × key decisions. Failing sets are in URL order, so clipping does not depend on check order.

  • Capper (audit-engine publish-cap.ts):

    • step 1 calls buildPublishResolution with rules, check names and pages in sorted order;
    • the raw signal build, buildPageStatuses and canonicalSignal are gone;
    • any resolutionSignal / resolutionSignalCompact on the input is stripped, never published;
    • the transport's exact bytes (named key constants) are reserved in full, and its share scales with maxBytes;
    • every body is measured whole and over the ceiling throws PublishedReportTooLargeError (part: "body");
    • a report without pages publishes no signal;
    • duplicate status rows keep a 404/410, read from the same source as removedPageUrls.

    The "needs repo#2658" caveats and the TODO(repo#2658, repo#2657) gate are gone. The CLI slimForPublish TODO now says the capper's preconditions have landed.

  • Merge (audit-engine merge-core.ts, merge-promise.ts):

    • When a signal was sent but lost its say (the key is truncated, or the page is off a clipped list), a prior resolves only on positive payload evidence. That means a pass for that page and check with no failing row beside it, no sampled failing aggregate and no dropped classes; or the rule's noindex verdict; or a complete item list. Otherwise it carries.
    • Removed pages named by the signal are staled even when pageStatuses clipped them.
    • Capped rescore (feat(engine): score a capped report from its check tallies (repo#2657) #642) under a clipped list: notCrawledThisRun credits no carried page, and notEvaluatedThisRun keeps carries on unlisted pages.
  • CLI slimForPublish sends the compact shape. The legacy buildResolutionSignal stays as the reference.

  • Docs: reports.mdx "Size cap on large sites" covers the budget, what degrades, and where full detail lives (squirrel report --format json|llm).

  • TODO(repo#2669) Sentry hook points, as comments only: the oversize error, hard-cap detail stamps, and the signal's over-budget path.

Pairs with a private PR, after this merges:

  • bump the gitlink;
  • the API schema accepts resolutionSignalCompact, decodes it before the merge, deletes it before storage, keeps accepting the legacy shape, and clamps claimed counts to the plan page limit;
  • worker-agent switches to buildPublishResolution;
  • the private capper tests read the whole body.

Deploy order: API first, then the CLI release. Until then, an old API strips the unknown field and merges without a signal (pre-#1185 behaviour).

Measurements

Signal plus pageStatuses, real-shape fixture (anonymized 50-page surface report, 257 page check classes) extended to N pages. "slug" and "entropy" swap in realistic or random URLs of the fixture's 63-byte mean length.

URLs pages legacy compact all pages listed
fixture 2,800 / 10,000 1,488 / 2,862 KiB 23 / 62 KiB yes / yes
slug 2,800 / 10,000 1,486 / 2,848 KiB 69 / 190 KiB yes / yes (8 of 154 keys dropped)
entropy 2,800 / 10,000 1,477 / 2,817 KiB 118 / 192 KiB yes / 4,518 listed

On the real fixture's per-page rows at 50 to 10,000 pages, the decoded compact signal equals the legacy signal as sets, truncated included. The 12 and 27 keys truncated at 5,000 and 10,000 pages come from the existing RESOLUTION_SIGNAL_LIMITS count caps. Build time: 50 to 150 ms at 2,800 pages, 2.4 s for the over-budget search at 10,000 slug pages on a quiet box.

Decoder memory under workerd (the API runtime)

Bun tests cannot show this: Bun inflates a DecompressionStream lazily, workerd does not. Measured on local workerd 1.20261006.1 at the API's compatibility_date (2024-12-30), with wrangler dev --local and RSS of that workerd process:

hostile body previous decoder (DecompressionStream + read cap) this decoder
258 KB of deflated zeros +276 MiB, refused after 45 ms +11 MiB, refused in 3 ms
1.36 MB of deflated zeros +564 MiB, refused after 278 ms +19 MiB, refused in 5 ms
20 KB deflated {}, x 1.3M under an unknown key parsed (+118 MiB) +7 MiB, refused in 5 ms (shape)
a real 3,000-URL signal decoded in 2 ms decoded in 4-6 ms

The API schema also caps data at 192 KiB, so the 1.36 MB body never reaches the decoder in production.

Known residuals (only when the byte budget clips the crawled list)

  • Capped rescore only. It needs checkTallies, which no producer sends until the capper is wired (repo#2667). Off a clipped list a carried finding can duplicate a tally entry. A warning gains half credit that way, so a rule at pass ratio r gains about k(0.5 - r)/(N + k). In the opposite direction, crediting no carried page with synthetic passes deflates the score. The fix is to ship hashes of every crawled page (a few bytes each), filed as a sub-issue of repo#2655 that gates repo#2667.
  • With a clipped list, a 404 page the payload still names counts as audited, the same as today's shape. The billing floor wins.
  • Past 10,000 distinct failing URLs for one check (beyond the crawl ceiling), the per-check collection still stops in input order.

Verification

  • tsgo --noEmit in core-contracts, rules, audit-engine, apps/cli: clean.

  • bun test (explicit files, sequential), all pass:

    • rules: resolution-compact, resolution, fold (112);
    • audit-engine: publish-cap, capped-rescore, compact-resolution-merge, site-pages-contract-coverage, cloud-merge, item-locator-resolve, scan-truncated-carry, sampled-audited-pages, carried-provenance-merge, rate-limited-coverage, complete-store-parity, bounded-carried-merge, merge-session-pages, fingerprint-parity, merge-scoring (289);
    • report: mixed-provenance-capped-2657, rule-catalog-2656 (10);
    • apps/cli: publish-size-bound, publish-slim, publish-degrade (19).
  • New tests:

    • publish-cap.test.ts: the worst case asserts the whole body <= PUBLISHED_REPORT_MAX_BYTES - envelopeBytes; the 10,000-page light shape too; transport is the compact signal; no raw or input signal rides along; the transport share scales with a smaller ceiling; a report without pages publishes no signal; a page listed twice keeps its removal whatever the row order.
    • capped-rescore.test.ts: off a clipped list, no carried page is credited with passes the tallies hold; a carry on a page the payload names stays scored. The capped score is never above the uncapped one in either.
    • compact-resolution-merge.test.ts: billing floor and clamp, plus the carry-safety cases.

    Each guard was mutation-checked: reverting it fails its test.

  • oxfmt --check / oxlint on touched apps/cli files: clean. [email protected] check --strict in docs: passed.

  • Codex review: earlier rounds on the signal and merge, plus two on the capper wiring. Every finding is fixed except the residuals above.

Acceptance criteria (repo#2658):

  • 10,000-page fixture within budget: yes.
  • Same resolves and carries as today's signal at 50 and 500 pages: parity tests.
  • Clipped keys listed in truncated and never resolved: tests.
  • API accepts today's shape: private PR.

squirrelscan agent skill: no change needed. The skill reads local --format llm output, not the publish body.

Checklist

  • I added or updated tests for behavioral changes.
  • I did not include secrets, customer data, or incompatible third-party material.
  • Every commit includes a DCO Signed-off-by line (git commit -s).

@nc9
nc9 force-pushed the perf/resolution-signal-budget-2658 branch from 20f5bfe to 1a482a3 Compare October 11, 2026 07:14
nc9 added 2 commits October 11, 2026 18:23
…the whole body (repo#2658) [skip ci]

Signed-off-by: Nik Cubrilovic <[email protected]>
@nc9
nc9 force-pushed the perf/resolution-signal-budget-2658 branch from a29e2eb to 3186bac Compare October 11, 2026 07:24
…e statuses, needs pages; failing sets in URL order (repo#2658)

Signed-off-by: Nik Cubrilovic <[email protected]>
@nc9
nc9 force-pushed the perf/resolution-signal-budget-2658 branch from 3186bac to 8b39fd6 Compare October 11, 2026 07:24
@nc9
nc9 marked this pull request as ready for review October 11, 2026 07:24
@claude

claude Bot commented Oct 11, 2026

Copy link
Copy Markdown

Review of #641 (compact resolution signal, fixed byte budget). I read the full diff but did not run the tests. CI was still pending when I looked.

  • (medium) apps/cli/src/controllers/report/publish.ts: slimForPublish no longer sends resolutionSignal at all (the new test asserts "resolutionSignal" in slim is false). An API that predates resolutionSignalCompact will either drop the signal or reject the body, depending on how strict its schema is. Without the signal, smart-audits would go back to resolving findings on pages that fell outside the sample, which the signal exists to prevent. Please confirm the server change deploys before or with this release, or keep sending the old field behind a version gate.
  • (medium) packages/audit-engine/src/merge-promise.ts: crawledCount and removedCount are publisher-controlled and can raise auditedPages, which feeds billing. The cap at REPORT_LIMITS.maxPages and the rule that the claim can only raise the evidenced count are good. Still, any client can inflate its audited count up to 10k when crawledComplete === false. Consider limiting the raise to what the byte-budget clipping could plausibly explain, or at least add a test for the abuse case.
  • (low) merge-core.ts and merge-promise.ts: the new carry-versus-resolve logic has several interacting sets (passedCheckPages, notApplicablePages, incompleteItemChecks, truncatedChecks, crawledComplete). compact-resolution-merge.test.ts covers the main paths. I'd still add cases for a truncated key combined with a clipped page list, and for rulesWithDroppedChecks. A wrong branch here carries stale findings forever or resolves them wrongly.
  • (low) publish.ts: the TODO(repo#2656) comment says the preconditions have landed. If so, a tracking issue or a follow-up to drop precomputed would stop it lingering.
  • (nit) publish-size-bound.test.ts: the timeout went from 20s to 30s on a CPU-heavy test. That may be flaky on slow CI runners, so it's worth watching.
  • (nit) docs/reports.mdx: the "192 KB" and "4,000 to 5,000 pages" figures are hard-coded. They will drift if RESOLUTION_PUBLISH_LIMITS changes.

I found no security issues beyond the billing-claim point above. The docs addition is clear.

…re-parse shape check (repo#2658)

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

claude Bot commented Oct 11, 2026

Copy link
Copy Markdown

Review of #641. I read the CLI publish changes, the merge-core and merge-promise changes, the publish-cap changes and the tests. I did not read the new rules/resolution encoder or decoder, and CI was still pending when I looked.

  • (medium) apps/cli/src/controllers/report/publish.ts: slimForPublish now sends only resolutionSignalCompact and never the old resolutionSignal. A server that predates the compact reader will get no signal, so findings on pages outside the sample may carry forever. Please confirm the API deploy is ordered before the CLI release, or that the server falls back safely when only the compact field is present.
  • (low) merge-promise.ts: crawledCount and removedCount are publisher claims. Clamping them to maxPages and only letting them raise the count is sensible. A tampered CLI can still inflate auditedPages by up to 10,000 pages, and billing reads that number. Consider a test for this case, or a note saying the exposure is accepted.
  • (low) merge-core.ts: the new carry-unless-positive-evidence path (passedCheckPages, notApplicablePages, incompleteItemChecks) is a lot of subtle branching. I saw no merge-core tests in the diff I read. Please add cases for a truncated key, a clipped crawledUrls list, and an incomplete item list with no signal.
  • (nit) publish-size-bound.test.ts raises its timeout from 20s to 30s. That could be flaky on slow CI; the adversarial fixture is the likely cause.

…re it is parsed (repo#2658)

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

claude Bot commented Oct 11, 2026

Copy link
Copy Markdown

Reviewed the decoder (resolution-decode.ts) and the merge-core changes. I did not read the builder, the capper or the tests in depth, and I did not run the test suite.

  • (low) packages/rules/src/resolution-decode.ts decodeMap: out[key] = set on a plain {} with an attacker-controlled key. A key of "__proto__" sets the prototype instead of creating an entry, so that entry is silently dropped. This is harmless for the merge, since a dropped entry only means a carry. Still, Object.create(null) or a Map would make the decoder behave the same for every key.
  • (nit) resolution-decode.ts: const limits and the MAX_* constants are declared below the functions that use them. It works, because they are only read at call time. Moving them to the top would be easier to follow.
  • (nit) inflateCapped: Buffer.from(base64, "base64") ignores invalid characters instead of throwing. Bad input then fails later as an inflate error, so the behaviour is safe, but the error message will be unhelpful.
  • (low) Test coverage: I did not confirm tests for the new merge branches (resolution && !signal with passedCheckPages, notApplicablePages and completeItemChecks, and incompleteItemChecks). Please confirm each path has a case. A case where a clipped list leaves a prior finding on an off-list page should carry, not resolve.

Positives:

  • The inflate cap, the pre-parse shape bounds and the strict validation are thorough.
  • The billing change can only raise the count, and it is clamped to maxPages.
  • Failing safe by carrying findings is the right default.

No high or critical issues found.

@claude

claude Bot commented Oct 11, 2026

Copy link
Copy Markdown

Review of #641 (compact resolution signal and the 192 KiB budget). I read the CLI changes, the new resolution-decode.ts, and the PR description. I did not trace the full merge-core.ts, merge-promise.ts or buildPublishResolution logic or run the tests. CI was still pending when I looked.

The design is sound. The decoder is carefully bounded: the inflate has an output cap, there is a shape pre-scan before JSON.parse, and everything is validated. Failing closed (drop the signal, so findings carry) is the right default.

Findings:

  • (medium) packages/rules/src/resolution-decode.ts, decodeMap: out[key] = set on a plain {} with an attacker-controlled key. A payload key of "__proto__" sets the object's prototype instead of creating an own property. That silently drops the entry from Object.keys and Object.entries, and the merge then treats that check as having no failing pages. It can't pollute the global prototype, and the effect is bounded by "findings carry" or a lost failing set. Still, a missing failing set could resolve findings that should carry. Use Object.create(null), a Map, or reject __proto__ keys. The same applies to removedByStatus.
  • (low) resolution-decode.ts, decodeMap: the three maps are not checked for duplicate or overlapping indexes across keys. Gap coding with gap >= 0 can't repeat an index within a key, so this is fine. But removed is only bounded by urls.length, and notEvaluated only reuses hashAt. That seems intended. I'd add a test that states it.
  • (low) resolution-decode.ts, assertParseBounded: the limits const is declared after the exported function that uses it. This works because the function runs after module init, but it is fragile if anyone adds a top-level call. Move the constants above the function.
  • (low) resolution-decode.ts, inflateCapped: Buffer.from(base64, 'base64') ignores invalid characters, and data.length is capped by characters, not decoded bytes. The inflate cap makes this safe. A stricter base64 check would reject malformed input earlier and make failures easier to diagnose.
  • (medium) Billing: coverage.auditedPages becomes max(payload-evidenced pages, crawledCount - removedCount) when the list is clipped, and crawledCount is client-claimed. The PR says the private API clamps it to the plan page limit. That clamp is the only guard against a client inflating billed pages, and it lives outside this repo. Please confirm it lands in the same deploy window, since the compact shape is accepted here first. The REPORT_LIMITS.maxPages clamp (10,000) is also only a ceiling, not a plan limit.
  • (low) Rollout: this depends on the API deploying first. An old API strips the unknown field and merges without a signal. Say in the release notes that CLI-before-API silently loses resolutions, so findings stay open until the API catches up.
  • (low) Performance: the over-budget search takes 2.4 s at 10,000 slug pages, and publish.ts builds it once on the publish path. That is acceptable. I'd still log or time it, because the Sentry hook is currently comments only (TODO(repo#2669)).
  • (nit) The PR is about 2.8k added lines across the CLI, rules, audit-engine and core-contracts. The core-contracts changes, decoder, builder and merge changes would be easier to review and bisect as separate PRs. This is not a blocker.
  • (nit) .secrets.baseline changes only a line number and a timestamp. That is expected from the package.json edit.

I have no critical or high findings. The medium __proto__ item is worth a small fix and a test before merge.

@nc9
nc9 merged commit bf538db into main Oct 11, 2026
15 checks passed
@nc9
nc9 deleted the perf/resolution-signal-budget-2658 branch October 11, 2026 08:29
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