Skip to content

fix(audit-engine): keep paid cloud prefetch results when the phase is abandoned - #582

Merged
nc9 merged 5 commits into
mainfrom
claude/cloud-prefetch-abandon-qf3efx
Oct 8, 2026
Merged

nc9 merged 5 commits into
mainfrom
claude/cloud-prefetch-abandon-qf3efx

Conversation

@nc9

@nc9 nc9 commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

Refs #280

Hold list (credits): a human merges this.

Summary

The cloud prefetch built its CloudPrefetchResult only when the whole phase finished. A caller that bounds the phase with a deadline was left with a rejected promise on expiry, and everything already charged server-side (results, site metadata, spend lines) was discarded.

How paid results are now preserved and reused

  • Caller-owned accumulator. CloudPrefetchAccumulator is passed in as input.accumulator. The prefetch writes into it as each call returns. Stage 0 (site metadata) and the site-unit services land their envelope and spend line when their call resolves. Each page-unit batch records its outcome the moment it returns.
  • abandon() turns the accumulator into a normal CloudPrefetchResult at any moment:
    • Results that returned are kept in the store, so they reach cloudScope and the rules use them. The page-unit merge is the same batch-order merge the completed path does.
    • Every key that had not returned reads skipped / service-unavailable. This only fills gaps, so nothing that returned is overwritten. A failures record with detail prefetch deadline reached marks the lost coverage.
    • The result carries abandoned: true. When it has a balance figure, it also carries balanceAfterApproximate: true.
  • No new calls after abandon. Once abandoned, the prefetch dispatches no further service or batch, and render polling stops.
  • Deadline helpers. prefetchCloudDataWithDeadline(input, ms) and a deadlineMs option on runContainerCloudPrefetch / runContainerCloudPrefetchFromPayloads race the prefetch against the deadline. When the deadline wins they resolve with abandon() instead of rejecting. A caller that enforces its own deadline can pass accumulator and call abandon() itself.

Charging semantics

  • Spend lists exactly the calls known to be charged, each once. A call that returned contributes the same line it would on a completed run. A render batch is charged when it is submitted, so a batch whose submit was acknowledged counts as spent even if its job had not finished. Its pages read service-unavailable, the same treatment a render poll timeout gets today.
  • What is not reported. A call still in flight at the deadline, such as keyword-gaps, is not counted. Its response has not arrived, so the container cannot know whether the server will charge it. Because it may yet be charged, balanceAfter on an abandoned result is flagged balanceAfterApproximate: true. The server ledger and the account balance stay authoritative, as before. No new call is dispatched after the deadline, so this window is limited to calls already on the wire.
  • No double reporting. abandon() is idempotent and memoized, and its result is built from copies. Calls that land after it never reach a result the caller already holds. If the prefetch finished first, abandon() returns that completed result object unchanged.
  • Completed runs are unchanged. Without an accumulator, the prefetch creates its own and returns the same result as before. With a deadline that does not fire, the result is deep-equal and serializes identically, with no abandoned or balanceAfterApproximate key.

Rollout note

This PR adds the engine capability. Nothing in this repo passes deadlineMs or an accumulator yet: the CLI never bounds the prefetch, so CLI audits are unchanged, and the hosted runner will adopt the option separately. The changelog entry and docs/cloud/credits.mdx describe the capability, not shipped hosted behaviour.

Agent skill

The squirrelscan agent skill needs no change. Nothing changes in CLI flags, output shape or rule ids, and service-unavailable was already a documented skip reason.

Acceptance criteria

  • When the prefetch is abandoned at its deadline, results that already returned are used by the rules rather than discarded. Evidence: packages/audit-engine/tests/cloud-prefetch-abandon.test.ts, "a deadline with some services returned keeps their results...". After the deadline, site-metadata, keyword-gaps and the returned render page p0 are ok in the store, and the other pages read service-unavailable. "container path: deadlineMs keeps what returned instead of rejecting" covers the same path through runContainerCloudPrefetchFromPayloads with the default rule set.
  • The spend for an abandoned prefetch covers exactly the calls that were charged, with no line reported twice and none omitted. Evidence: the same test asserts spend = keyword-gaps 25 + render 2 units / 4 credits. Those are p0, which returned, and p1, whose submit was acknowledged. p2 to p4 (no submit acknowledged) and p5 (never sent) are excluded. The test also checks totalSpent 29, balanceAfter 971 with balanceAfterApproximate: true, and the failure record. "an abandoned run dispatches nothing more, and late results never reach the result" releases a hung submit after abandon. It asserts that no new batch is sent, that abandon() returns the same object, and that spend and store are unchanged.
  • A prefetch that completes normally behaves exactly as it does today, byte for byte. Evidence: "a prefetch that finishes in time returns exactly what an unbounded one does" checks toEqual and identical serialization. It also checks there is no abandoned or balanceAfterApproximate key, and that abandon() after completion returns the completed result. The existing tests/cloud-prefetch.test.ts (50 tests) and the CLI parity tests pass unchanged.
  • A test drives the deadline with some services already returned and asserts both the kept results and the reported spend. Evidence: the first test in the new file runs prefetchCloudDataWithDeadline(..., 50) over a client where some calls resolve, one render job hangs after an acknowledged submit, and others never answer.

Verification

Run on head 49cfecd, after merging main:

  • bun test tests/cloud-prefetch-abandon.test.ts tests/cloud-prefetch.test.ts in packages/audit-engine: 55 pass, 0 fail.
  • bun test tests/audit/cloud-prefetch-parity.test.ts tests/audit/cloud-prefetch-non-public-base.test.ts in apps/cli: 23 pass, 0 fail.
  • bun run typecheck in packages/audit-engine and apps/cli: clean.
  • bun run format:check (root): pass. oxlint on the touched files: no new warnings.
  • make validate in docs: all checks passed.
  • bun run test:release: 19 pass.
  • detect-secrets-hook --baseline .secrets.baseline on the changed files: clean.

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).

… abandoned

The cloud prefetch built its result only when the whole phase finished, so a
caller that bounded it with a deadline had nothing to recover on expiry: every
result already charged server-side was discarded with the store, the site
metadata and the spend lines.

Add a caller-owned CloudPrefetchAccumulator that the prefetch fills as each
call returns. abandon() turns it into a CloudPrefetchResult at any moment:
returned results are kept for the rules, unreturned keys read
service-unavailable, and spend covers exactly the calls known to be charged
(including a render batch acknowledged on submit), each once. After abandon no
new call is dispatched. prefetchCloudDataWithDeadline and a deadlineMs option
on the container entry points wrap this so a deadline resolves with the
partial result instead of rejecting. A prefetch that completes is unchanged.

Refs #280

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

claude Bot commented Oct 8, 2026

Copy link
Copy Markdown

Review of #582 (partial-result handling for a cloud prefetch that hits its deadline). I read the full diff but did not run the tests.

  • (medium) CHANGELOG.md:21, docs/cloud/credits.mdx:117 The changelog and docs say a cloud audit now keeps its results when the analysis step times out. In this repo nothing sets deadlineMs or passes an accumulator: a grep finds only the new plumbing in cloud-prefetch-run.ts. So the open-source code path behaves as before unless an out-of-tree caller (the container or cloud worker) wires it up. Either say so in the PR description, or make the user-facing claim conditional on that caller landing.
  • (medium) cloud-prefetch.ts (abandon() docs and the credits doc) "Lists exactly the calls that were charged, each once" is stronger than what the code does. A site-unit call (such as keyword-gaps) or a Stage 0 call that is in flight at abandon time is not reported. The server may still charge for it after its response is lost, so spend can be under-reported. The code comment admits this, but the changelog and docs do not. Soften the wording, or say that only render submits are counted.
  • (low) cloud-prefetch.ts abandon() For the in-flight render service, the charged amount is recomputed with computeCost(feature, batch.length). The completed path may charge per page by a different rule, such as the perPage cap logic. A test that compares the two for a partially capped batch would guard against drift.
  • (low) cloud-prefetch.ts fetchPageBatch After abandon, a render poll stops after its next attempt, and a batch already awaiting render() or client.* still runs to completion in the background. The same is true of in-flight site calls. That is fine, but a late-landing call can still be charged without ever appearing in the result. This is the same under-reporting as above.
  • (nit) cloud-prefetch.ts ABANDONED_STOP and the stop ?? (acc.abandoned ? ...) line are a bit hard to follow. A short comment saying that outcomes from these batches are never read would help.
  • (nit) The test file covers the main abandon scenarios well. A test for abandon() called twice (idempotent) and for abandon after settle would document the two promised guarantees, if they are not already covered further down in that file.

No critical or high-severity issues found.

…e charged

A call still in flight when the prefetch deadline fires is not reported, so
the docs and changelog no longer claim the spend is exact. Clarify the
ABANDONED_STOP comment.

Refs #280

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

nc9 commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor Author

Round 1 (d22615c):

  • (medium) user-facing claim needs a caller to wire it up: rebutted. The PR description's "Rollout note" already says the hosted runner that enforces the deadline lives outside this repo and gets this behavior once it passes deadlineMs (or its own accumulator plus abandon()). The issue scoped the fix to the prefetch exposing its partial state, and that is what lands here. The changelog describes the shipped end state, the same way earlier hosted-side entries do.
  • (medium) "exactly the calls that were charged" overclaims: fixed. docs/cloud/credits.mdx and CHANGELOG.md now say the spend lists each call the audit knows was charged: every call that came back, plus any render batch the cloud had accepted. They also say that a call still running at the limit is not listed, and that the balance is the authoritative figure. This matches the abandon() doc comment.
  • (low) render cost recomputed in abandon(): no change needed. The completed path charges a returned batch as computeCost(plan.feature, batch.length) (cloud-prefetch.ts, in fetchBatchOutcome). abandon() uses the same expression for a charged batch that has not returned. perPage is only the per-envelope creditsSpent, not the line total, so the two paths cannot drift.
  • (low) late in-flight calls can be charged without being reported: same point as the second medium, now covered by the docs wording.
  • (nit) ABANDONED_STOP: comment expanded in this push.
  • (nit) idempotence and abandon after settle: already covered. "an abandoned run dispatches nothing more..." asserts accumulator.abandon() returns the same object twice. "a prefetch that finishes in time..." asserts abandon() after completion returns the completed result and abandoned stays false.

Checks on this push: make validate (docs) pass, root format:check pass, audit-engine typecheck clean, 55/55 prefetch tests pass, secret scan clean.

@claude

claude Bot commented Oct 8, 2026

Copy link
Copy Markdown

Review of #582 (keep paid cloud prefetch results when the phase is abandoned). I read the full source diff and the docs and changelog changes. I did not read the new test file line by line, and I did not run the tests.

No blocking problems. The design holds up: a caller-owned accumulator, an idempotent and memoized abandon() that works on copies, and no dispatch after abandon.

  • (low) CHANGELOG.md and docs/cloud/credits.mdx: the text says that after the limit "nothing more is charged for the audit's enrichment". Calls already on the wire at the deadline can still be charged. That covers single-call services such as ai-parse and keyword-gaps, and any batch past the stop check. The PR body admits this, and the same docs paragraph says the balance is authoritative. I'd soften the sentence to "no new call is started".
  • (low) packages/audit-engine/src/cloud-prefetch.ts, abandon(): if it fires before acc.planned is set, for example during the early preflight, planned is null. In that case nothing is stamped service-unavailable and the store comes back empty. That works only if the rules treat a missing key as skipped. A short test or comment for this early-deadline case would help.
  • (low) packages/audit-engine/src/cloud-prefetch.ts: nothing in this repo passes deadlineMs or accumulator, because the hosted runner lives elsewhere. Until that runner changes, the fix does nothing for hosted audits, and the changelog describes the end state as already shipped. Consider noting that in the release notes, or confirming the runner change lands alongside.
  • (nit) cloud-prefetch.ts: ABANDONED_STOP is applied after the abandon snapshot, so its outcome is never read. The comment explains this well. A one-line assertion in the tests that these batches never reach fetchPageBatch would pin it, if the late-result test doesn't already do that.
  • (nit) abandon() allocates copies of the whole store. That is fine for a one-time deadline path, so no action is needed.

nc9 commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor Author

Round 2: no critical, high or medium findings, so no push this round. Replies to the low findings and nits:

  • (low) "nothing more is charged for the audit's enrichment": fair. The same paragraph already says a call still running at the limit is not listed and that the balance is authoritative. I'll leave the sentence for the maintainer to tweak at merge ("no new cloud call is started after the limit"), or it can ride the next push if this PR gets another one.
  • (low) abandon() before acc.planned is set: this cannot happen with an empty store. planned is assigned synchronously before the first await (the getBalance() preflight). Every earlier return happens before that first await and settles the result itself, so an abandon taken at any await point sees planned populated. Test "abandoned before preflight returns: every planned key skips, no spend, no balance" hangs getBalance and asserts every render page and the keyword-gaps site key read service-unavailable.
  • (low) hosted runner not wired here: see the PR's "Rollout note" and the round 1 reply.
  • (nit) batches after abandon never reach fetchPageBatch: already pinned. "an abandoned run dispatches nothing more..." releases a hung submit after abandon, which frees a slot, and asserts the render submit list is still p0 to p4, so p5 is never sent.
  • (nit) store copy in abandon(): agreed, it runs once per deadline.

…-abandon-qf3efx

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

# Conflicts:
#	CHANGELOG.md
@claude

claude Bot commented Oct 8, 2026

Copy link
Copy Markdown

Review of #582 (partial results when the cloud prefetch hits its deadline)

  • (high) packages/audit-engine/src/cloud-prefetch-run.ts, apps/cli/src/audit/cloud.ts:441,654: nothing in the repo passes deadlineMs or an accumulator. The only non-test callers of prefetchCloudData (apps/cli/src/audit/cloud.ts) are unchanged, and runContainerCloudPrefetch has no caller that sets either field. As far as I can see, the deadline path is never reached, so users get no behaviour change. The CHANGELOG and docs/cloud/credits.mdx both say a cloud audit now keeps partial results at its time limit. If the container or API caller lives in a private repo, say so in the PR. Otherwise wire it up, or reword the docs so they don't claim shipped behaviour.
  • (medium) cloud-prefetch.ts, abandon(): a site-unit call (keyword-gaps and similar) still in flight at the deadline is reported as unspent and service-unavailable. The server may still charge it, so the spend can under-report. The docs do disclose this and point to the balance as authoritative. Even so, balanceAfter is computed as preflight.total - totalSpent, so it will be optimistic in that case. Consider flagging it as approximate when abandoned is set.
  • (low) fetchPageBatch / runBatch: after an abandon, in-flight requests keep running and are never cancelled (no AbortSignal). Render polling now stops, but other hung calls leak until they settle. Passing a signal would be cleaner.
  • (low) abandon() builds planned from specs after the Stage-1 gating. If an abandon happens before planned is set (during gating or preflight), planned is null and the result has an empty store, so no rule gets service-unavailable entries. This is probably fine because rules default to skipped, but a test would confirm it.
  • (nit) ABANDONED_STOP and the reassigned s capture comment in fetchBatchOutcome are slightly awkward. A short note that outcomes are discarded after an abandon is enough.

Test coverage is good: the new cloud-prefetch-abandon.test.ts covers partial render batches, idempotency and spend. It has no test of a real caller enforcing a deadline end to end. CI was still pending when I looked.

nc9 commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor Author

Round 3: rebuttals, no code change.

  • (high) nothing in the repo passes deadlineMs or accumulator: this is the same point as round 1, and the PR already says it under "Rollout note". The deadline that abandons the prefetch is enforced by the hosted runner, which lives outside this repo. Issue Cloud prefetch discards results it has already paid for when the phase is abandoned #280 scopes the fix to the prefetch exposing what it has accumulated, so that the bounding caller can keep it. The CLI callers at apps/cli/src/audit/cloud.ts:441,654 need no wiring: the CLI never bounds or abandons the prefetch (no deadline, timeout or Promise.race around it). It always gets the completed result, and that path is unchanged byte for byte. The end-to-end deadline coverage in this repo is "container path: deadlineMs keeps what returned instead of rejecting", which goes through runContainerCloudPrefetchFromPayloads with the default rule set.
  • (medium) balanceAfter is optimistic when a site-unit call is in flight at abandon: balanceAfter is already documented as an estimate that does not reflect concurrent usage (CloudPrefetchResult.balanceAfter: "render with a ~ qualifier"), and the CLI renders it as balance ~N (apps/cli/src/cli/commands/audit.ts:533). An abandoned result also carries abandoned: true, so a consumer can tell the two apart. The user-facing docs now say that a call still running at the limit is not listed and that the balance is authoritative. Nulling the estimate would throw away a figure that is correct in the common case (no site call in flight).
  • (low) no AbortSignal for in-flight calls: cancelling a request that has already been sent does not undo a charge the server makes for it, so a signal saves sockets but not credits. The credit-relevant part is that nothing new is dispatched after abandon, and that is in this PR. Leaving the signal out to keep the diff to the issue's scope.
  • (low) planned null before preflight or gating: planned is assigned before the first await (the getBalance() preflight), not after Stage-1 gating, so an abandon at any await point sees it populated. Test "abandoned before preflight returns: every planned key skips, no spend, no balance" hangs getBalance and asserts that every planned key reads service-unavailable.
  • (nit) ABANDONED_STOP: the round 1 push expanded its doc comment to say exactly that its outcome is never read.

This was the third and final bot-review round, so I'll stop iterating and leave further calls to the maintainer.

nc9 commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor Author

Status: ready for a human merge (hold list, credits).

  • CI is green on the head commit 71312dc: all 15 checks, including CLI tests, audit engine golden tests, docs, secret scan, CodeQL and sign-offs. There is no merge conflict, since main is merged in.
  • Three bot-review rounds are done. Round 1 fixed a medium finding (the docs and changelog now say spend lists only the calls known to be charged). The other medium and high findings were rebutted with evidence above. No open finding is left for this PR to act on.
  • One follow-up is needed outside this repo for hosted audits to benefit: the hosted runner has to pass deadlineMs (or its own accumulator plus abandon()). See "Rollout note" in the description.
  • The acceptance criteria are listed in the description with their tests, for the maintainer to tick after merge.

nc9 added 2 commits October 8, 2026 20:01
…refetch

A call still in flight when the prefetch is abandoned is not in the spend
but may yet be charged, so an abandoned result now carries
balanceAfterApproximate whenever it has a balance figure. Completed results
are unchanged and never carry the key.

Reword the changelog entry and the credits docs to describe the engine
capability (keeping paid results when a caller bounds the prefetch with a
deadline) rather than shipped hosted behaviour: nothing in this repo passes
deadlineMs yet.

Refs #280

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

claude Bot commented Oct 8, 2026

Copy link
Copy Markdown

Reviewed the diff for cloud-prefetch.ts, cloud-prefetch-run.ts, the docs and the new test file. I did not run the tests or the type-check.

No blocking problems found. The accumulator design holds up. abandon() copies the store, spend and failures, so calls that land after it can't change a result the caller already holds. It is idempotent, and settle() makes a late abandon return the completed result unchanged. Promise.race also keeps a late rejection from the losing branch from becoming an unhandled rejection.

  • (low) cloud-prefetch.ts prefetchCloudDataWithDeadline: Math.max(0, NaN) is NaN, and setTimeout treats that as about 1ms. A bad deadlineMs would then abandon almost immediately instead of failing fast. Consider guarding with Number.isFinite.
  • (low) cloud-prefetch.ts abandon(): failure is assigned inside the forEach closure. TypeScript can narrow it to never at the ...(failure ?? ...) spread. A for loop would avoid that. Please make sure tsc is green.
  • (low) cloud-prefetch.ts abandon(): a site-unit call that is still in flight when abandon runs goes into failures with attemptedUnits equal to missed, and it is not in spend. That matches the balanceAfterApproximate doc. Check that consumers of failures don't treat these as refunded or definitely uncharged.
  • (nit) runPrefetch writes acc.planned and acc.pages directly, although the class marks them @internal and public. A small init() method would make single-use ownership clearer. A second run on the same accumulator is only prevented by the doc comment.
  • (nit) The ABANDONED_STOP comment says the outcome is never read. That is true, but inFlight.outcomes[i] is still written after abandon. Harmless.

Test coverage looks good: the new file covers render charged-on-submit, hung providers and the container path.

nc9 commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor Author

Review on 49cfecd: no critical, high or medium findings, so no push. This head was the single push requested for the maintainer's changes.

  • (low) deadlineMs NaN: valid but unreachable today. The only callers are the tests and the container option, which a caller sets to a computed budget. It can ride a follow-up if the hosted runner's adoption wants a guard.
  • (low) failure narrowed to never in the forEach: typecheck is green, both locally (tsgo --noEmit in packages/audit-engine and apps/cli) and in CI ("Format, lint, and typecheck" passed on this head).
  • (low) in-flight site-unit call in failures: intended. These entries are coverage loss with reason service-unavailable, not refunds. That is also why balanceAfterApproximate is set on such a result. No consumer reads failures as a refund signal: the CLI renders them as a partial-coverage warning.
  • (nit) single-use accumulator and (nit) outcomes[i] written after abandon: agreed that both are harmless. Leaving them as documented.

@nc9
nc9 merged commit ed26818 into main Oct 8, 2026
15 checks passed
@nc9
nc9 deleted the claude/cloud-prefetch-abandon-qf3efx branch October 8, 2026 20:58
nc9 pushed a commit that referenced this pull request Oct 9, 2026
* origin/main:
  feat(core-contracts): audit levels definition (quick, surface, full) (#602)
  test(rules): restore the real fetch when a graphql test stubs twice (#599)
  chore(release): v0.0.107 (#595)
  docs(changelog): release notes for v0.0.107 (#594)
  feat(rules): add GraphQL introspection and GET mutation probing rules (#593)
  fix(audit-engine): keep paid cloud prefetch results when the phase is abandoned (#582)
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