Skip to content

refactor(domain): charge remaining fixed allowances through Budget - #11319

Merged
morluto merged 3 commits into
mainfrom
refactor/budget-slice2
Nov 15, 2026
Merged

morluto merged 3 commits into
mainfrom
refactor/budget-slice2

Conversation

@morluto

@morluto morluto commented Nov 15, 2026 •

Copy link
Copy Markdown
Owner

Summary

Second Budget slice (W6 step 5). Eight more hand-written allowances charge through Budget (src/domain/budget.ts, #11293), so the safe-integer check, refused-charge-changes-nothing rule and refund floor live in one place. The budget-arithmetic baseline drops from 30 to 17 entries, and to 4 with the collapsed #11383 (below); two more allowances whose field names escaped the guard pattern (NativeAOT parser budget, CDP request retention) are migrated too.

Refs #11293

Problem and expected behavior

Each site repeated the arithmetic, with drift between copies:

  • JavaScriptSemanticWorkMeter.charge, ContractInventory.reserve (API contracts) and the CDP runtime retention counters charged first and checked afterwards, so a refused charge still moved the counter.
  • javascriptSymbolicBindings kept #remainingEvaluations with four inline copies of "over the allowance: zero it and record wrapper_visits" and three --x < 0 checks that drove the counter negative.
  • InterfaceBuilderDecodeBudget, NativeAotParserBudget, ManagedDecodeBudget, UnityFsArtifactReader and DesktopContentStore each reimplemented the safe-integer/fits check.

Expected: one owner does the arithmetic; each owner keeps its own limit failure and reported facts. Reported limit values are unchanged.

Change and scope

  • InterfaceBuilderDecodeBudget, NativeAotParserBudget: wrap Budget (NativeAOT has separate work and working-memory budgets; remainingWorkingMemoryBytes replaces limits.workingMemoryBytes - workingMemoryBytes at its one caller).
  • ManagedDecodeBudget: reserved and transient bytes charge one Budget; releaseTransient refunds the transient part. Same admission as before (bytes > remaining - transient).
  • UnityFsArtifactReader: cumulative block decoding is a Budget created when the bundle opens; the member-read reservation still precedes the decode charge.
  • DesktopContentStore.retainBytes: reserves before writing and refunds when the write fails (previously checked, wrote, then subtracted). File publication moved to #publish unchanged.
  • javascriptSymbolicBindings: one #spendWrapperVisits(cost) replaces the copies; on exhaustion it spends the rest, as the old zeroing did, so later visits keep failing.
  • CDP runtime: new RuntimeRetention (in CdpRuntimeRetention.ts) owns cumulative metadata/source/request retention; retained_bytes still reports the total the refused charge would reach. assertRuntimeRetention stays for the one-shot result-size check.
  • JavaScriptSemanticWorkMeter, API ContractInventory: Budget.charge / tryCharge.

Not included, with the reason for each (per-site decisions left open):

  • hexRecords.ts, uf2.ts #arenaUsed: a write cursor into a preallocated arena, not an allowance. A Budget would separate the cursor from the array it indexes; they may be better excluded from the guard or given an arena owner.
  • BunModuleGraphLayout, PlaywrightScenarioEvents: retained-cost counters with eviction (charge, then evict oldest until under the limit). Budget has no over-commit; these need an eviction-aware owner.
  • WebNetworkProjectionAccumulator: retained plus temporary bytes with checkpoints; temporaryCheckpoint can restore a higher temporary total than the current one, which a refund-only owner cannot express without a re-charge that may fail.
  • PythonPycParser nested retention, WebBundleAnalysisWorker, JavaScriptAnalysisWorker, EvidenceLedger: estimated or post-validation accounting tied to a shared admission helper (admitInvestigationRetention) or to worker result descriptors; each needs its own look.
  • CudaMetadataBudget, sqlite OutputBudget: their field names escape the guard pattern; left for a slice that also widens the pattern.

Contribution scope: not applicable (internal refactor within existing boundaries).

Folded in from #11383 (collapsed into this PR)

Budget additions:

  • chargeEvicting(amount, evict): evicts oldest entries until the charge fits; an amount above the maximum evicts nothing.
  • restore(mark): refunds everything charged since a used mark; never re-charges (a re-charge could fail).

Migrated:

  • CudaMetadataBudget (visits, section reads, temporary index) and the SQLite OutputBudget (fixed envelope charged up front; parts charged before they count; pre-decode and pre-projection checks read remaining).
  • Bun metadata range cache: LRU eviction through chargeEvicting; physical reads through a second Budget.
  • Playwright scenario events: re-pricing refunds the old cost and tryCharges the new one; admission charges with tryCharge. (There is no eviction here, so plain refund/charge fits.)
  • WebNetworkProjectionAccumulator: one shared allowance plus retained and temporary shares; checkpoints restore by refunding. The old temporary checkpoint could raise the temporary share without admission; leases end LIFO and releaseTemporary never runs inside one (checked in all three subclasses), so restoring only ever lowers.
  • EvidenceLedger: commits its admitted delta (charge, or refund when a replacement shrinks); clear() restores to 0.
  • WebBundleAnalysisWorker: charges an admitted result; on the completed-snapshot recovery path it now retains facts only when they still fit.
  • PythonPycParser nested code walk: steps and retained references.

Guard: inside a hand-written …Budget class, a field adjusted by hand and compared with </> is counted whatever its name. Unchecked tallies (Protobuf's yield counter, ManagedDecode's transient ledger) stay uncounted. Widening by name alone (…Bytes, …Visits) would have added about 50 matches, many of them observation tallies (#stdoutObservedBytes, bytesRead, #notMainFlashBytes) that are not allowances, so it was not done. Firmware arena cursors are write offsets, not allowances: renamed #arenaWriteOffset, out of the guard's scope.

budget-arithmetic: 17 → 4.

Not included: JavaScriptAnalysisWorker (4). Its retained estimate deliberately over-commits past two live-heap-dependent ceilings and records parentCapacityExhaustion instead of refusing; Budget cannot express that without a behaviour change, so it needs a separate decision. Pyc's other tallies (#reportedStringBytes, #reportedConsts, #keySteps, #keyBytes) are not counted by the guard and are left for a later slice.

Contract and boundary impact

  • Semantic owner and earliest changed stage: Budget (src/domain/budget.ts) owns the arithmetic; each provider owner keeps its failure. New RuntimeRetention owns CDP cumulative retention for CdpRuntimeSources and CdpRuntimeRequests.
  • Contribution scope fit and linked maintainer decision: not applicable.
  • CLI and MCP/tool-catalog contract: none.
  • Provider, bridge, target-format, or platform compatibility: none.
  • Evidence, artifact, provenance, or reconstruction contract: none; limit failures and their reported values are unchanged.
  • Target selection, authority, upstream behavior, and cleanup details: none.
  • Generated metadata, package, or installation impact: none.

Evidence and regression coverage

  • Tests added or updated: src/browser/execution/CdpRuntimeRetention.test.ts (new owner: admits to the limit, reports the would-be total, separate source-text limit); DesktopContentStore.test.ts "charges nothing for a write that fails" (the reservation is refunded).
  • Base reproduction or other evidence: source-derived; this is a behaviour-preserving refactor. The desktop test also passes on the base (the old code charged only after a successful write); it guards the new refund path.
  • Remaining proof gaps: none known beyond the sites listed above.

Evidence from #11383

  • Tests added or updated: src/domain/budget.test.ts (evicting charge, refused evicting charge, restore never re-charges); tests/evaluation/budgetArithmeticGuard.test.ts (named allowances, hand-checked fields in a …Budget class, unchecked tallies ignored).
  • Base reproduction or other evidence: the new guard counts the pre-migration CudaInfo.ts as 3 and SqliteDatabaseInspection.ts as 2 (Protobuf and ManagedDecode budgets as 0); probed against the files from refactor(domain): charge remaining fixed allowances through Budget #11319's head.
  • User-visible CLI/MCP output (if applicable): none.
  • Remaining proof gaps: no real browser run for the Playwright change; covered by the unit suites below.

Validation performed

  • npm run check:fast — passed (typecheck, lint, architecture guards).
  • node scripts/verify/architecture-guards.mjs --shrink-baselines — lowered budget-arithmetic 30 → 17 entries.
  • npm run test:local -- the 16 touched owners' test files (Interface Builder budget/NIB, UnityFs reader and boundaries, CDP runtime requests, desktop content store, API contract parser, semantic work allowance and phase, symbolic bindings, NativeAOT budget/discovery accounting/hydration/main, managed decode budget) — 16 files, 297 tests passed.
  • npm run test:local -- src/desktop/DesktopContentStore.test.ts src/browser/execution/CdpRuntimeRetention.test.ts — passed.

Validation from #11383

  • node scripts/verify/architecture-guards.mjs --shrink-baselines — passed; budget-arithmetic 17 → 4.
  • npm run test:local -- tests/evaluation/budgetArithmeticGuard.test.ts src/gpu/CudaInfo.test.ts src/gpu/GpuInventory.test.ts src/sqlite/SqliteDatabaseSnapshotLimits.test.ts src/domain/firmware/hexRecords.test.ts src/domain/firmware/uf2.test.ts — 6 files, 81 tests passed.
  • npm run test:focused -- tests/boundary/sqlite/sqliteDatabaseInspection.test.ts tests/boundary/sqlite/sqliteDatabaseFailures.test.ts tests/boundary/sqlite/sqliteDatabaseProvider.test.ts tests/boundary/gpu/codeObjects.test.ts — 4 files, 213 passed, 1 skipped.
  • npm run test:local -- src/domain/budget.test.ts src/artifacts/bun/BunModuleGraph.test.ts src/artifacts/bun/BunStandaloneArtifactReader.test.ts src/browser/PlaywrightScenarioEvents.sharedContext.test.ts src/browser/PlaywrightScenarioEvents.test.ts src/domain/analysisView/WebNetworkProjectionAccumulator.test.ts src/domain/analysisView/WebNetworkApiSurfaceAccumulator.test.ts src/domain/analysisView/EnvironmentManifestAccumulator.test.ts src/domain/analysisView/environmentStateView.test.ts src/domain/analysisView/environmentManifestView.test.ts src/domain/analysisView/environmentStateGate.test.ts src/domain/analysisView/environmentStatePaging.test.ts — 12 files, 243 tests passed.
  • npm run test:focused -- tests/boundary/filesystem/bunMetadataReadBudget.test.ts tests/boundary/filesystem/bunStandaloneIntegration.test.ts — 2 files, 7 tests passed.
  • npm run test:local -- src/application/investigation/EvidenceLedger.residualUnknown.test.ts src/application/investigation/EvidenceLedger.test.ts src/application/investigation/InvestigationRetention.test.ts src/python/PythonPycParser.test.ts src/python/PythonPycBytecodeEquality.test.ts — 5 files, 101 tests passed.
  • npm run test:focused -- src/browser/WebBundleAnalysisWorker.test.ts src/browser/WebBundleAnalysisWorkerCapacity.test.ts src/browser/WebBundleAnalysisWorkerReadCompletion.test.ts — 3 files, 41 tests passed.
  • npm run check:fast — passed (also ran as the pre-push hook).

Compatibility, safety, and release

  • Breaking changes or migration steps: none.
  • Real Hopper/Ghidra, browser, or OS coverage: not applicable.
  • Package or release metadata impact: none.
  • Security, privacy, process, or containment review: no new authority.

Author readiness

Human owner:

  • I reviewed the final diff and relevant existing code, understand the change and its edge cases, and take responsibility for the complete PR, including AI-assisted work.
  • I checked the evidence above, confirmed it supports the current change, and recorded meaningful validation gaps.
  • I declare this PR ready for initial maintainer review.

Before merge

  • This PR addresses a concrete problem or an agreed enhancement.
  • Material scope and authority questions are resolved, and any required maintainer scope decision covers the final diff.
  • The PR has one focused outcome and the title follows type(scope): outcome.
  • Related issue is linked, or the reason for not linking one is stated above.
  • Tests cover changed observable behavior and meaningful failure paths.
  • Owning docs, contracts, and generated metadata are updated where needed.
  • User-visible CLI/MCP changes include representative output.
  • I checked the final diff for secrets, unrelated cleanup, and unsupported claims.

@chatgpt-codex-connector

Copy link
Copy Markdown
Codex Review Summary: ❌ Failed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ❌ Failed 2026-11-15T16:13:53.779960Z
We couldn’t complete this review. Comment @codex review to try again.
3170fd0 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@greptile-apps

greptile-apps Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 5/5 Tier: plus

[Medium impact] The reviewed changes appear safe to merge; no new actionable issue was established.

Summary

The latest commit moves more fixed allowances onto Budget, adds cache eviction and checkpoint refunds, and widens the arithmetic guard.

  • Resource allowances now share one owner for charges, refunds, and checkpoints.
  • Parser and artifact limits use the same allowance rules.
  • JavaScript analysis spends symbolic visits through one shared counter.
  • Browser runtime captures use one owner for retained-byte limits.
  • Retained caches and browser data use shared allowance accounting.
  • Desktop file copies reserve space before publishing.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  Owner["Resource owner"] --> Charge["Budget charge"]
  Charge --> Fits{"Fits remaining allowance?"}
  Fits -->|Yes| Keep["Keep resource"]
  Fits -->|No| Failure["Owner reports its limit failure"]
  Cache["Cache needs room"] --> Evict["Remove oldest entries and refund"]
  Evict --> Charge
  Keep --> Release["Discard reservation or end checkpoint"]
  Release --> Refund["Refund released amount"]
Loading

Reviews (3) · Last reviewed commit: "refactor(domain): charge the remaining f..." · Reviewed by Greptile

@morluto
morluto force-pushed the refactor/budget-slice2 branch from 3170fd0 to 129ab25 Compare November 15, 2026 16:24
#11383)

* refactor(domain): charge CUDA metadata and SQLite reply budgets through Budget

CudaMetadataBudget (visits, section reads, temporary index) and the SQLite
OutputBudget kept hand-written allowances whose field names escaped the
budget-arithmetic guard; the SQLite reply budget also charged each part
before checking it. Both now charge Budget, which refuses an oversized
charge without changing the remainder.

The guard now also counts, inside any hand-written ...Budget class, a field
that is adjusted by hand and compared with < or >, whatever its name.
Unchecked tallies (a yield counter, a reservation ledger) stay uncounted.
Firmware arena cursors are write offsets, not allowances: they are renamed
#arenaWriteOffset and leave the guard's scope. Baseline 17 -> 15.

* refactor(domain): move cache, re-priced, checkpointed and ledger retention onto Budget

Budget gains chargeEvicting (evict the oldest cache entries until a charge
fits) and restore (refund everything charged since a used mark, never
re-charging). With them:

- the Bun metadata range cache evicts through chargeEvicting and charges
  physical reads through a second Budget;
- Playwright scenario events refund an event's old cost and try-charge its
  re-priced cost, and admission charges with tryCharge;
- WebNetworkProjectionAccumulator keeps one shared allowance plus retained
  and temporary shares whose checkpoints restore by refunding;
- EvidenceLedger commits its admitted delta (charge, or refund when a
  replacement shrinks) and clears with restore(0);
- the web bundle worker charges an admitted result, and on the completed-
  snapshot path retains facts only when they still fit;
- the Pyc nested code walk charges steps and retained references.

budget-arithmetic 15 -> 4 (JavaScriptAnalysisWorker only).

* build(verify): declare the budget-arithmetic guard's counter for typed tests
@morluto morluto changed the title refactor(domain): charge eight more allowances through the Budget owner refactor(domain): charge remaining fixed allowances through Budget Nov 15, 2026
@morluto

morluto commented Nov 15, 2026

Copy link
Copy Markdown
Owner Author

@greptileai please review the latest commit (f38f9dd). #11383 was collapsed into this PR: it adds Budget.chargeEvicting and Budget.restore, moves CUDA, SQLite, Bun, Playwright, WebNetworkProjectionAccumulator, EvidenceLedger, the web bundle worker and the Pyc nested walk onto Budget, and widens the budget-arithmetic guard to hand-written ...Budget classes (17 -> 4).

@morluto
morluto merged commit 64c119d into main Nov 15, 2026
7 of 9 checks passed
@morluto
morluto deleted the refactor/budget-slice2 branch November 15, 2026 19:08
mertkayacs added a commit to mertkayacs/rea that referenced this pull request Nov 16, 2026
morluto#11319 replaced the wrapper-visit counter with a Budget, so the loader proof charge no longer compiled on current main. Spend it through the shared helper, which records the same limit.
morluto added a commit that referenced this pull request Nov 19, 2026
… reach Electron (#4915)

* test(javascript): cover the isolated-world probe outside Electron identity

* fix(javascript): expand Electron call paths only with an Electron reference

* test(javascript): cover Electron reach through resolved names, aliases and worker URLs

* fix(javascript): attribute call-path unknowns only where the walk can reach Electron

* test(javascript): cover a hoisted read that precedes a loader alias

* fix(javascript): keep call-path unknowns for late-initialized loader aliases

* test(javascript): drop a duplicate loader-alias case

* test(javascript): cover loader aliases reached through bindings and calls

* fix(javascript): prove a late initializer loader-free before dropping its unknown

* test(javascript): cover loaders behind default parameters, wrappers and long alias chains

* fix(javascript): resolve identifiers inside late initializers and bound the loader proof

* fix(javascript): bound late loader proofs and preserve input uncertainty

* fix(javascript): fail closed for receiver and mutated loaders

* fix(javascript): close loader-free proof gaps

* fix(javascript): retain uncertain loader sources

* test(javascript): cover remaining loader proof gaps

* fix(javascript): bound alias writes and preserve loader uncertainty

* test(javascript): cover demand-driven loader mutation facts

* perf(javascript): index loader mutation facts on demand

* style(javascript): apply oxfmt to the loader proof changes

* test(javascript): cover inherited loaders and rebound alias writes

* fix(javascript): preserve inherited loaders and rebound aliases

* test(evaluation): update scoped feature coverage oracle

* test(javascript): cover inherited loader proof gaps

* fix(javascript): preserve projected and inherited loaders

* fix(javascript): prove safe parameter member reads

* test(javascript): cover loader proof review gaps

* fix(javascript): close remaining loader proof gaps

* fix(javascript): preserve qualified global replacements

* fix(javascript): preserve spread rest uncertainty

* fix(javascript): retain retried handler uncertainty

* fix(javascript): retain import.meta loader uncertainty

* fix(javascript): detach fresh constructed aliases

* fix(javascript): check inherited members of ambient loaders

* test(javascript): parse call-path gate fixtures as established CommonJS

* fix(javascript): prove projected locals inside late initializers

A function-local binding was accepted by scope alone, so a destructuring
projection such as `const { r } = {}` inside a late initializer never met
the inherited-member check that a top-level projection goes through. Route
projected locals through the binding proof; locals with inline initializers
keep the scope shortcut, since the walk already visits their expressions.

* fix(javascript): keep late results with changed prototypes or import.meta uncertain

The loader-free proof inspected member expressions inside a late function
but not what its caller does with the result. With `Object.prototype.load =
require`, `var load = () => ({})` and `load().load("electron")` reach the
loader through a member selected after the call, and a bare `import.meta`
returned after `import.meta.load = ...` does the same. Check each result
expression: a literal fails when its prototype chain gained members, a bare
`import.meta` when any of its members changed, and a result of unknown shape
when either happened. Promise and generator results inherit from
Object.prototype as well. `SemanticPropertyPathCoverage.touches` answers
whether any retained write or escape sits below a prefix.

* fix(javascript): detach replacements held by fresh bindings

`alias = replacement` with `const replacement = {}` selected an identifier
initializer, so the later `alias.other = 1` stayed a shared write on the
original alias group and the resolver treated `base` as overwritten,
dropping its bridge call path. Resolve the identifier to its binding and
accept it when that binding only ever received one fresh allocation.
Bindings that can hold the original object keep the shared write.

* fix(javascript): charge loader proofs through the wrapper-visit budget

#11319 replaced the wrapper-visit counter with a Budget, so the loader proof charge no longer compiled on current main. Spend it through the shared helper, which records the same limit.

* test(javascript): keep the alias bound off the quadratic write index

The 8,000 by 8,000 alias bound spent its time in the ambient write index, which walks every store to an object for each member write. That cost is the same on main and is not what the bound covers. Reach the same 64 million alias and write pairs with 32,000 aliases and 2,000 writes, which runs in about 2.5 seconds instead of 8.5 on the same host.

Drop the 30 second overrides on both alias bounds too. They halved the hosted CI deadline the source project gives them, and the testing guide asks tests to leave deadlines to the project.

* refactor(javascript): ask the effect log for loader proof effects

Main now guards reads of the effect indexes outside javascriptSemanticEffectLog.ts. The loader proof read them directly in 15 places. Route those reads through the log: the existing ambientPathMayHaveChanged and bindingHasMemberWrites queries, plus three timeless queries for a path or any member below it, an ambient binding write, and an escape at a site other than the call being proved. The answers are unchanged.

* fix(javascript): retain uncertainty for changed ambient values

---------

Co-authored-by: morluto <[email protected]>
@morluto morluto added the area: domain Domain logic, errors, and pure functions label Nov 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area: domain Domain logic, errors, and pure functions

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant