Skip to content

feat(engine): one report capper and a 1 MiB published-report constant (repo#2656) - #640

Merged
nc9 merged 4 commits into
mainfrom
feat/report-capper-2656
Oct 11, 2026
Merged

nc9 merged 4 commits into
mainfrom
feat/report-capper-2656

Conversation

@nc9

@nc9 nc9 commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Part of squirrelscan/repo#2656 (epic squirrelscan/repo#2655): every published report gets capped at the source, to one 1 MiB constant, by one function that the CLI and the cloud container will both call. The caps follow the tuning on 187 real published reports in the cap-tuning comment on repo#2656.

  • PUBLISHED_REPORT_MAX_BYTES (1 MiB) and REPORT_CAPS in @squirrelscan/core-contracts/limits. Every number is a named, tunable constant: 10 pages / 5 items / 1 source page per issue class, 25 classes per rule, site checks 10/10, resourceSizes 20 rows x 3 source pages, 50 robots directives, sitemaps 25 entries x 10 children, entity map 128 KiB, 192 KiB kept back for the scoring transport, 16 KiB for the envelope (so the report itself gets at least 816 KiB).
  • capReportForPublish in @squirrelscan/audit-engine (Worker-clean ./publish-cap entry, also on the main barrel):
    • one aggregate per (rule, check name, status, provenance, foldKey) class with its true counts (details.pagesTruncated, details.additional, details.occurrences). The fold runs once per class (no stacked (+N more pages)), members go in page order, and a class of one per-page check stays that page's check;
    • the page sample leads with the page the class hits hardest (most items), then URL order; items are ranked by how many pages they are on, and a kept item whose sourcePages sample is shorter than its spread carries pageCount. An items array over the 1,000-item clamp is ranked before the clamp;
    • per-page pass rows dropped. Their counts go in checkTallies, the contract repo#2657 reads: per rule and check name, the scorer's own IssueTally fields over this run's fresh checks, unfolded, carried and unrendered left out. A test shows calculateHealthScoreFromTallies over them equals calculateHealthScore over every row;
    • top-level siteChecks entries that repeat a site check ruleResults already publishes are left out (9,137 of 9,138 entries on the tuning corpus; the only readers are schema bounds, the publish breadcrumb count and the payload scanner). Anything no rule carries stays;
    • rule description / solution left out of the body (description stays as "" because the publish schema requires the field);
    • a breadth-first byte fitter: every class at 10/5 if the body fits; else every class gets a counts row, then a 3/1 sample, then 10/5, in priority order (robots and sitemap penalty checks, then fail, warn, info, by size) while the budget lasts; if the counts rows alone do not fit, the display sections go to their minimum and the entity map is dropped and the fill runs again; last, counts rows are admitted by byte budget. That last step fits by construction. Only a skeleton (score, rule meta, tallies, enrichment sections) over budget throws PublishedReportTooLargeError;
    • a detail: { capped, tier, caps, classesReduced?, classesDropped?, entityMapDropped?, fullDetail? } stamp for the viewers (repo#2661). tier is how far the fitter went (0 full sample, 1 breadth-first fill, 2 minimal sections, 3 admission);
    • deterministic: top-level keys, rules, the resolution signal and pageStatuses come out in a fixed order, and source pages are sampled in URL order. Never mutates its input.
  • withCatalogRuleText / ruleCatalogLookup in @squirrelscan/report (plus ./rule-catalog and ./affected-pages entries): whoever renders a report joins the rule text back from the catalog, and the catalog wins whenever it knows the rule.
  • CheckItem.pageCount (optional) in core-contracts.

Nothing calls the capper yet, so this PR changes no behaviour. Wiring it into slimForPublish (CLI) and truncateReportForPublish (container) has to wait until the API reads checkTallies for the rescore (repo#2657) and joins rule text at render. Until then, a capped body would move the server score and blank rule descriptions.

Known limits

  • resolutionSignal and pageStatuses still grow with pages crawled (raw URLs). The fitter measures them first and fits everything else into what they leave, never less than the budget minus its 192 KiB reserve. When the signal is over its reserve (2,000+ pages, or hundreds of classes failing on 100+ pages, as in the engine worst-case test) the whole body is over 1 MiB until repo#2658 bounds it. The breadth-first fill uses the room it is given, so this shows up more readily than with the old ladder's slack.
  • A rule the producer already folded (over 500 checks) reaches the capper with its first 1,000 items and at most 100 source pages each, so ranking and pageCount are over what that fold kept (pageCount is a floor there). Passing unfolded classes to the capper is a wiring-time choice.

Measured (real-shape fixture from the private repo, not checked in here)

pages body body without signal tier
50 385KB 352KB 0
100 414KB 354KB 0
500 608KB 337KB 0
2,000 1,401KB 339KB 0

Every page-scope class failing on every page, 10 of the heaviest real items each (352 B): 1,008KB, tier 1. 206 of 220 aggregates keep the full 10/5 sample, 30 classes get a smaller one, none is left out (the old ladder put every class at 5/3). 10,000 pages was not re-run on the fixture (memory on the lane box); the engine test covers flatness to 10,000 pages on a lighter shape.

Verification

  • bun test packages/audit-engine/tests/publish-cap.test.ts: 33 pass. Covers the size bound at 50 / 500 / 2,000 / 10,000 pages, the every-class-fails worst case filled breadth first with every class kept, max-length strings (tier 2, every class kept), fail-before-warn priority just under the full-sample size, admission past the fill, the typed error, sample caps and true totals, ranking (per-page fold and site check), ranking past the 1,000-item clamp, worst-page pin (folded here and folded elsewhere), siteChecks dedupe (including key order and an upstream-clamped copy), score parity from tallies, suffix stacking, provenance split, 25-class cap, determinism across rule, check and page order, no input mutation. Mutation-checked: removing the ranking, the pre-clamp ranking, the pin, the zero-weight pages in the pin, the dedupe, the sorted-key dedupe, the clamped-form dedupe key, or reversing the fill priority each fails a test.
  • Private repo: apps/worker-agent/src/publish-cap-2656.test.ts (real-shape fixture) 3 pass, apps/api/tests/schemas/capped-report-2656.test.ts 6 pass.
  • tsgo --noEmit in packages/core-contracts, packages/report, packages/audit-engine and apps/cli: clean.
  • bun build --target=browser src/publish-cap.ts: no node: imports or linkedom in the import closure (only bun's inlined node:net polyfill via utils, as before).
  • Codex review passes on both commits. Findings fixed on the second: ranking before the items clamp, worst page against every listed page, prior pageCount kept across a fold, source pages sampled in URL order. Rebutted: dedupe compares the clamped form on purpose, since the producer's top-level copy is clamped (capMixedRuleChecksForPublish) and never equals the raw rule check.

Docs: none in this PR, since nothing user-facing changes yet. The CLI wiring PR adds the docs note on the capped published report and where full detail lives.

squirrelscan agent skill: no change. The audit-website skill reads the local --format llm output, never the published report.

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 marked this pull request as ready for review October 10, 2026 23:00
… (repo#2656)

PUBLISHED_REPORT_MAX_BYTES (1 MiB) and REPORT_CAPS in core-contracts, and
capReportForPublish in audit-engine (Worker-clean, ./publish-cap entry): one
aggregate per issue class with a 10-page / 5-item sample and its true counts,
per-page pass rows dropped with their counts kept in checkTallies, rule text
left out of the body, and a byte fitter (10/5, 5/3, 3/1, counts only, no
entity map, then classes admitted by byte budget). Deterministic, never
mutates its input.

withCatalogRuleText in @squirrelscan/report joins rule description and
solution back from the rule catalog at render time.

Not wired into either publish producer yet: the server rescore reads the
tallies first (repo#2657).

Signed-off-by: Nik Cubrilovic <[email protected]>
@nc9
nc9 force-pushed the feat/report-capper-2656 branch from d85d2bb to be074d8 Compare October 10, 2026 23:12
… page first (repo#2656)

Aligns the capper with the caps tuned on 187 real published reports:

- fitter fills breadth first: every class a counts row, then 3/1, then
  10/5, in priority order while the budget lasts; then minimal display
  sections without the entity map; then byte admission. Replaces the
  global 10/5 -> 5/3 -> 3/1 -> counts ladder, so a tight budget cuts the
  least important classes instead of every class.
- items ranked by page spread, with a per-item pageCount when the sample
  lists fewer source pages; ranked before the 1,000-item clamp.
- each class's page sample leads with the page it hits hardest.
- top-level siteChecks entries that repeat a published rule check are
  left out (no reader besides schema bounds and publish counts).
- envelope reserve 16 KiB (report >= 816 KiB of 1 MiB), sitemaps 25
  entries / 10 children; detail.classesReduced counts reduced classes.

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

claude Bot commented Oct 11, 2026

Copy link
Copy Markdown

Review of #640 (one report capper, 1 MiB published-report constant). I read the diff through the sampling and fixed-section code. I did not read the byte fitter, buildPageStatuses, the tests, or the report and core-contracts changes line by line. The CI checks were still pending when I looked.

  • (medium) publish-cap.ts: the "never over 1 MiB" guarantee does not hold yet. The PR body says resolutionSignal and pageStatuses grow with pages crawled, so at roughly 2,000+ pages the body is over budget. The measured table shows 1,401KB at 2,000 pages. The header comment and the PUBLISHED_REPORT_MAX_BYTES docs say the body fits whatever the crawl size. Please say in those comments that this depends on repo#2658, and add an explicit gate or TODO so the wiring PR can't land before it.
  • (medium) publish-cap.ts (sampleCheck, clampMessage): sizes are compared by .length (UTF-16 units) against messageChars, while the budget is in bytes. CJK or emoji-heavy messages can be 3-4x larger in bytes than the cap suggests. The fitter measures real bytes, so this affects the tier chosen and not correctness. Still, the tests only use ASCII "max-length strings", so add a multi-byte case.
  • (low) slimEntityMap: the bare catch {} drops the entity map silently. The comment explains why that is intended. Even so, the detail stamp's entityMapDropped flag can't tell a projection failure from a budget drop. Consider a distinct signal or a debug log.
  • (low) foldRule / foldClass: CLASS_FOLD_LIMITS sets item and page limits to MAX_SAFE_INTEGER, so memory scales with the input. That is bounded by the input, as the comment says. For the 10,000-page case, the engine test uses a "lighter shape" and the fixture run hit memory limits. Consider a test or a note on peak memory, since this will run inside a Worker-like environment.
  • (low) capSummary: it slices lists one level deep inside entries, so deeper nested arrays are uncapped. This is fine if the summary schema is that shallow. A short comment confirming it would help.
  • (nit) publish-cap.ts is about 1,240 lines. Splitting the fixed-section cappers (capSitemaps, capRobotsTxt, capResourceSizes, capSummary) from the class folding and fitting would make it easier to review and maintain.
  • (nit) Nothing calls the capper yet, so there is no behaviour change and the risk is low. The PR description is clear about this and about the wiring order (repo#2657).

Overall the design is sound: it is deterministic, doesn't mutate its input, and has good test coverage. I found nothing blocking.

…ty map failure stamp (repo#2656)

- docs no longer claim the whole body fits whatever the crawl size: it
  needs repo#2658 to bound resolutionSignal/pageStatuses. A TODO gate in
  publish-cap.ts and at the CLI's slimForPublish says not to wire the
  capper before repo#2658 and repo#2657.
- messageChars documented as UTF-16 units (the schema's unit), not bytes;
  a CJK + emoji test pins the byte bound, the unit clamp and no split
  surrogate pair.
- detail.entityMapFailed marks an entity map that could not be projected,
  apart from a budget drop (entityMapDropped).
- notes: measured heap cost of the full-limit class fold at 10,000 pages,
  and the summary's two-level depth that capSummary relies on.

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

nc9 commented Oct 11, 2026

Copy link
Copy Markdown
Contributor Author

Review triage, all in 20f5e97:

  • (medium) "never over 1 MiB" overclaim: fixed. The publish-cap.ts header and the PUBLISHED_REPORT_MAX_BYTES docs now say the whole body fits only once repo#2658 bounds resolutionSignal / pageStatuses (1,401KB at 2,000 pages today). Gate: a TODO(repo#2658, repo#2657) in publish-cap.ts and at the CLI's slimForPublish says not to wire the capper before both land. The repo#2658 branch (pub#641) is rebasing onto this PR to wire the bounded transport into the capper's first step, and it tightens the worst-case test from "rest of the body" to the whole body at or under PUBLISHED_REPORT_MAX_BYTES - envelopeBytes. That test is the hard gate.
  • (medium) .length vs bytes: fixed (docs + test). messageChars is documented as UTF-16 code units, the unit the publish schema's string caps count, so it stays a unit cap by design. The byte fitter measures real UTF-8 bytes, so it shapes how much text a level keeps, never the size bound. New test: CJK (3 bytes a unit) and emoji messages, ids and labels, with the emoji cut on odd boundaries. It asserts the whole body is within budget in bytes, messages are within the unit cap, bytes exceed units (so the case is real), and no lone surrogate anywhere. Swapping the clamp for a plain slice fails it.
  • (low) slimEntityMap bare catch: fixed. A map that cannot be projected now stamps detail.entityMapFailed. A budget drop still stamps entityMapDropped, and the two are never set for the same cause. Tested, and mutation-checked.
  • (low) full-limit class fold memory: noted. Measured on a synthetic 10,000 pages x 24 checks (240k checks): 0.8 s, heap +141 MB right after the call, against +94 MB with the fold's default limits. The note is on CLASS_FOLD_LIMITS. Not gated by a test: a heap-peak assertion at this shape flaps with GC timing. The producers run the capper on a report already in memory, and the API, if it runs it, only over a publish body.
  • (low) capSummary depth: comment added. The summary schema is two levels deep (lists, or entries holding one list such as urlIssues[].issues and redirectChains[].hops).
  • (nit) split the file: not now. Two lanes are stacking on this branch (repo#2657 scoring, repo#2658 transport), and a move would turn their rebases into conflicts. Moving the fixed-section cappers out is a follow-up once those land.
  • (nit) no behaviour change: agreed. The comment-only TODO in the CLI is the only file outside the engine and contracts.

Checks: bun test packages/audit-engine/tests/publish-cap.test.ts 35 pass. tsgo --noEmit clean in core-contracts, audit-engine and apps/cli. CLI format:check and lint clean.

@claude

claude Bot commented Oct 11, 2026

Copy link
Copy Markdown

I read the diff, with most attention on the capReportForPublish entry point. I did not trace every helper in the 1,264-line publish-cap.ts, and I did not run the tests. CI was still pending when I checked.

No blocking issues found. Comments:

  • (medium) publish-cap.ts (capReportForPublish): the budget only reserves Math.min(transportBytes, REPORT_CAPS.signalMaxBytes) for resolutionSignal and pageStatuses. Once the transport grows past 192 KiB (large crawls), the whole body can exceed PUBLISHED_REPORT_MAX_BYTES and nothing throws. The header comment and the TODO document this, and the function is not wired into either producer yet, so it is not a regression. Still, please make sure repo#2658 lands first, and consider a final whole-body assertion or typed error in the wiring PR so an oversize body is never silently published.
  • (low) CLASS_FOLD_LIMITS sets the item, page and source-page limits to Number.MAX_SAFE_INTEGER. Your own measurement shows +141 MB heap at 10k pages x 24 checks. That is fine in the producers. If the API later runs this on client-supplied bodies, the route's body limit is the only bound, so state that as a requirement where the API call site is wired.
  • (low) slimForPublish in apps/cli/src/controllers/report/publish.ts and capReportForPublish now coexist, with only a TODO in publish.ts pointing at the replacement. Please link a tracking issue so the old path is not forgotten.
  • (nit) transportBytes adds the magic constants + 24 and + 20. Name them or explain them in a comment.
  • (nit) buildCheckTallies skips info-only classes. The doc comment says so, but checkTallies consumers (repo#2657) should be told that a missing entry means 0 scored, not 'unknown'.

Test coverage looks good. There are dedicated tests for size, determinism, and for tallies matching the scorer, plus a rule-catalog test. I would add a test for the case where transportBytes is over signalMaxBytes and the output is over budget, so that behavior is pinned down intentionally.

@nc9

nc9 commented Oct 11, 2026

Copy link
Copy Markdown
Contributor Author

Second review, triage (no new commit, to save a CI run; each point lands with the PR that owns it):

  • (medium) whole-body assertion or typed error at wiring: agreed, owned by repo#2658. pub#641 rebases onto this PR. It replaces the min(transport, signalMaxBytes) reserve with the bounded compact transport, which is already within its budget, and tightens the worst-case test to the whole body at or under PUBLISHED_REPORT_MAX_BYTES - envelopeBytes. The wiring will not land before that (TODO gate in publish-cap.ts).
  • (low) API call site must rely on the body limit: agreed. That is a requirement for whichever PR calls the capper in the API (repo#2659 makes that limit 1 MiB on every publish route). The CLASS_FOLD_LIMITS note already states it.
  • (low) tracking issue for the slimForPublish TODO: the TODO cites repo#2656, whose first acceptance criterion is exactly this replacement (CLI and container bodies built by the same engine function). The issue stays open until the wiring lands.
  • (nit) + 24 / + 20 in transportBytes: these are the JSON key, separator and a few bytes of margin for "resolutionSignal": and "pageStatuses":. That whole measurement is rewritten by the repo#2658 rebase (compact signal plus keys), so I'm leaving it to that commit rather than renaming twice.
  • (nit) a missing checkTallies entry means 0 scored: agreed. I've passed it to the repo#2657 consumer lane so the rescore treats absence as zero, not unknown.
  • test for transport over its reserve: pinned already. "every class failing on every page fills breadth first..." asserts the rest of the body is within budget - signalMaxBytes and the signal is over signalMaxBytes. repo#2658 flips it to the whole-body bound.

@claude

claude Bot commented Oct 11, 2026

Copy link
Copy Markdown

Reviewed the diff (new publish-cap.ts plus its test file, a ./publish-cap export, and a TODO in publish.ts). I read the helpers and folding logic in detail. I skimmed the budget-fill section and did not read the tests line by line. I did not run the tests. CI was still pending when I looked.

  • (low) publish-cap.ts: CLASS_FOLD_LIMITS removes the fold's item and page caps (Number.MAX_SAFE_INTEGER). Your measurement of +141 MB of heap at 10k pages is fine for the producers. The header notes the API may also run this on an untrusted publish body, so it is worth confirming that the route's body-size limit bounds the input before that wiring lands. Otherwise the function is an amplification point.
  • (low) publish-cap.ts: PublishedReportTooLargeError is thrown when the skeleton alone is over budget. Once wired in, each producer needs an explicit handler for it. A publish that fails outright is worse than a degraded one.
  • (nit) The headers in publish-cap.ts and publish.ts gate the wiring on repo#2656, #2657 and #2658, which are not public in this repo. Please link them or summarise the gate in the PR description so external contributors can follow it.

The module is not wired into any producer, so runtime risk is limited to the new export. Determinism, no input mutation, and the scorer-unit tallies look carefully designed. I found no blocking issues.

@nc9

nc9 commented Oct 11, 2026

Copy link
Copy Markdown
Contributor Author

Review triage (integrator, head f519e60, an update-branch merge of main with no change to this PR's diff):

  • (low) CLASS_FOLD_LIMITS uncapped fold as an amplification point on an untrusted body: deliberate, already answered in the triage of the second round. Nothing calls the capper yet; whichever change wires it into a server route must rely on that route's body-size limit, and the CLASS_FOLD_LIMITS note states the requirement.
  • (low) a handler for PublishedReportTooLargeError in each producer: deliberate, it belongs to the wiring change, which this PR's TODO gate keeps from landing first.
  • (nit) gate references in the headers: left as is.

@nc9
nc9 merged commit c974661 into main Oct 11, 2026
15 checks passed
@nc9
nc9 deleted the feat/report-capper-2656 branch October 11, 2026 06:21
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