Repository navigation
refactor(domain): charge remaining fixed allowances through Budget - #11319
Conversation
Codex Review Summary: ❌ FailedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
[Medium impact] The reviewed changes appear safe to merge; no new actionable issue was established. SummaryThe latest commit moves more fixed allowances onto
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"]
Reviews (3) · Last reviewed commit: "refactor(domain): charge the remaining f..." · Reviewed by Greptile |
…d runtime budgets through Budget
3170fd0 to
129ab25
Compare
#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
|
@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#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.
… 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]>
Summary
Second
Budgetslice (W6 step 5). Eight more hand-written allowances charge throughBudget(src/domain/budget.ts, #11293), so the safe-integer check, refused-charge-changes-nothing rule and refund floor live in one place. Thebudget-arithmeticbaseline 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.javascriptSymbolicBindingskept#remainingEvaluationswith four inline copies of "over the allowance: zero it and recordwrapper_visits" and three--x < 0checks that drove the counter negative.InterfaceBuilderDecodeBudget,NativeAotParserBudget,ManagedDecodeBudget,UnityFsArtifactReaderandDesktopContentStoreeach 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: wrapBudget(NativeAOT has separate work and working-memory budgets;remainingWorkingMemoryBytesreplaceslimits.workingMemoryBytes - workingMemoryBytesat its one caller).ManagedDecodeBudget: reserved and transient bytes charge oneBudget;releaseTransientrefunds the transient part. Same admission as before (bytes > remaining - transient).UnityFsArtifactReader: cumulative block decoding is aBudgetcreated 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#publishunchanged.javascriptSymbolicBindings: one#spendWrapperVisits(cost)replaces the copies; on exhaustion it spends the rest, as the old zeroing did, so later visits keep failing.RuntimeRetention(inCdpRuntimeRetention.ts) owns cumulative metadata/source/request retention;retained_bytesstill reports the total the refused charge would reach.assertRuntimeRetentionstays for the one-shot result-size check.JavaScriptSemanticWorkMeter, APIContractInventory: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. ABudgetwould 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).Budgethas no over-commit; these need an eviction-aware owner.WebNetworkProjectionAccumulator: retained plus temporary bytes with checkpoints;temporaryCheckpointcan restore a higher temporary total than the current one, which a refund-only owner cannot express without a re-charge that may fail.PythonPycParsernested 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, sqliteOutputBudget: 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)
Budgetadditions:chargeEvicting(amount, evict): evicts oldest entries until the charge fits; an amount above the maximum evicts nothing.restore(mark): refunds everything charged since ausedmark; never re-charges (a re-charge could fail).Migrated:
CudaMetadataBudget(visits, section reads, temporary index) and the SQLiteOutputBudget(fixed envelope charged up front; parts charged before they count; pre-decode and pre-projection checks readremaining).chargeEvicting; physical reads through a secondBudget.tryCharges the new one; admission charges withtryCharge. (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 andreleaseTemporarynever 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.PythonPycParsernested code walk: steps and retained references.Guard: inside a hand-written
…Budgetclass, 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 recordsparentCapacityExhaustioninstead of refusing;Budgetcannot 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
Budget(src/domain/budget.ts) owns the arithmetic; each provider owner keeps its failure. NewRuntimeRetentionowns CDP cumulative retention forCdpRuntimeSourcesandCdpRuntimeRequests.Evidence and regression coverage
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).Evidence from #11383
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…Budgetclass, unchecked tallies ignored).CudaInfo.tsas 3 andSqliteDatabaseInspection.tsas 2 (Protobuf and ManagedDecode budgets as 0); probed against the files from refactor(domain): charge remaining fixed allowances through Budget #11319's head.Validation performed
npm run check:fast— passed (typecheck, lint, architecture guards).node scripts/verify/architecture-guards.mjs --shrink-baselines— loweredbudget-arithmetic30 → 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-arithmetic17 → 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
Author readiness
Human owner:
Before merge
type(scope): outcome.