Repository navigation
fix: Prevent QuickJS disposal aborts in safe mode - #8924
vijayh-bruno merged 25 commits into
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (3)
🚧 Files skipped from review as they are similar to previous changes (2)
WalkthroughQuickJS sandbox cleanup now drains pending jobs, disposes deferred resources, preserves script errors, and recycles WASM modules after runtime traps. New tests cover synchronous, asynchronous, background, chained, and out-of-memory execution. ChangesQuickJS lifecycle handling
Estimated code review effort: 4 (Complex) | ~45 minutes Suggested reviewers: Poem
Sequence Diagram(s)sequenceDiagram
participant Script
participant QuickJSSandbox
participant Teardown
participant WASMModule
Script->>WASMModule: Load or reload module
Script->>QuickJSSandbox: Execute with module generation
QuickJSSandbox->>Teardown: Return result and pending deferred state
Teardown->>QuickJSSandbox: Drain jobs and dispose deferred handles
Teardown->>QuickJSSandbox: Dispose tracked handles and VM
Teardown-->>Script: Preserve script error or return cleanup result
Teardown->>WASMModule: Recycle module after WebAssembly.RuntimeError
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches 💡 1🛠️ Fix failing CI checks 💡
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
10 scenarios across two specs with a shared harness; red on this commit, green with the fix
Drain jobs before the handle flush and dispose unsettled deferreds so JS_FreeRuntime never sees leftover GC objects; contain engine traps by recycling the failing module generation; background fire-and-forget work instead of blocking the run on it, restoring pre-3.5.0 script semantics
77a4bda to
d827451
Compare
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@packages/bruno-js/src/sandbox/quickjs/index.js`:
- Around line 98-100: Update the synchronous executor around executeQuickJsVm
and createManagedQuickJsContext to handle QuickJSModule being null during the
module-reload window deterministically: either await module readiness through an
asynchronous contract or throw a clear reload-specific error instead of passing
null and returning undefined. Add a trap-recovery test that calls
executeQuickJsVm immediately after recycleQuickJSModuleOnAbort.
In `@packages/bruno-js/tests/quickjs-sandbox.helpers.js`:
- Line 23: Define a shared test collection path using path.join(os.tmpdir(),
...) and reuse it across
packages/bruno-js/tests/quickjs-sandbox.helpers.js:23-23 and :83-83, and
packages/bruno-js/tests/quickjs-trap-containment.spec.js:57-57, :69-69, and
:88-88 for Bru, runInSandbox, and trap-containment calls; remove the
Unix-specific '/' and '/tmp/collection' values.
🪄 Autofix
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro Plus
Run ID: 34c3caed-9af0-4611-a6ba-430c73c4dbc4
📒 Files selected for processing (5)
packages/bruno-js/src/sandbox/quickjs/index.jspackages/bruno-js/src/sandbox/quickjs/utils/index.jspackages/bruno-js/tests/quickjs-sandbox.helpers.jspackages/bruno-js/tests/quickjs-teardown.spec.jspackages/bruno-js/tests/quickjs-trap-containment.spec.js
Red before the swap: the rebuilt module cannot resolve before a synchronous call, so null-then-load fails this deterministically. Also share one os.tmpdir based collection path across the specs
A trapped instance still evaluates correctly, so it keeps serving the synchronous executor (assertions, vars) until the replacement resolves; nulling first left a window where those calls failed on a missing engine. The reload lives in loader() with an in-flight guard so concurrent traps cannot start duplicate builds
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@packages/bruno-js/src/sandbox/quickjs/index.js`:
- Around line 27-36: The loader currently overwrites the working
quickJSModulePromise before a reload succeeds, leaving normal calls and the
rejection handler unusable after failure. Update the loader flow around
newQuickJSWASMModule and loader so failed replacements preserve the prior
resolved promise/module, while successful replacements still update
QuickJSModule; ensure the replacement rejection is explicitly handled and add
coverage for a failed reload followed by a normal load.
In `@packages/bruno-js/tests/quickjs-trap-containment.spec.js`:
- Around line 78-93: Update the test around executeQuickJsVmAsync and the
trapped-module replacement flow to control the replacement-loading promise
rather than suppressing all failures with catch. Assert that recycling has
started, invoke executeQuickJsVm while replacement loading remains pending, then
resolve the replacement and await completion so the test specifically verifies
synchronous evaluation during the reload window.
🪄 Autofix
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro Plus
Run ID: a058d1b3-5e23-493f-8247-1b1ed1f0c402
📒 Files selected for processing (3)
packages/bruno-js/src/sandbox/quickjs/index.jspackages/bruno-js/tests/quickjs-sandbox.helpers.jspackages/bruno-js/tests/quickjs-trap-containment.spec.js
🚧 Files skipped from review as they are similar to previous changes (1)
- packages/bruno-js/tests/quickjs-sandbox.helpers.js
Red before the loader hardening: the rejected replacement build escaped as an unhandled rejection and poisoned the memo, failing later runs. Also assert dispose synchronously and name both specs in the harness header
Log and contain build rejections in loader itself: a failed reload falls back to the old, still-functional module for callers already awaiting and restores its memo, while a failed initial load clears the memo for retry and surfaces the real error. Count recycles in the log so frequent reloads are diagnosable, and make disposeContext call sites self-describing
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@packages/bruno-js/tests/quickjs-trap-containment.spec.js`:
- Around line 125-133: Update the quickjs execution test around
executeQuickJsVmAsync to assert that the replacement build actually started:
after the reload completes, verify builds equals 2 before or alongside checking
wasmModule. Do not rely on the empty catch or the cached module identity alone,
since those can pass without exercising the failed replacement path.
🪄 Autofix
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro Plus
Run ID: 493f1ab6-b6c2-438d-af2a-ae4c21a4a616
📒 Files selected for processing (4)
packages/bruno-js/src/sandbox/quickjs/index.jspackages/bruno-js/tests/quickjs-sandbox.helpers.jspackages/bruno-js/tests/quickjs-teardown.spec.jspackages/bruno-js/tests/quickjs-trap-containment.spec.js
🚧 Files skipped from review as they are similar to previous changes (3)
- packages/bruno-js/tests/quickjs-teardown.spec.js
- packages/bruno-js/src/sandbox/quickjs/index.js
- packages/bruno-js/tests/quickjs-sandbox.helpers.js
Guards the failed-reload spec against a vacuous pass: if the OOM ever stops trapping, the build counter fails loudly instead of the cached module satisfying the identity assertion; the second check pins that recovery does not kick extra rebuilds
Inline the spec timing values at their use sites; move the OOM fixtures behind a runOomScript helper and rejection capture behind collectUnhandledRejections; pin that the sync eval runs on the trapped module and that the failed replacement build really started
ed668e8 to
ae0061e
Compare
A never-settled deferred pins the flush more sharply than the old guarded timer, whose late settle was never asserted; also explain the lateWorkKinds table
The rollback assignment already computes what awaiters can still get, so test it instead of re-deriving the condition
Retain the 3.5.x contract: a run finishes only when all of its async work has finished, awaited or not; the wait is unbounded and cancelling the request is the way out. Teardown runs after the wait instead of racing it. Re-pin the run lifecycle tests to this contract and pin that async test() callbacks complete before results are read (usebruno#4678)
|
Good to have: Check if we can add an E2E or integration test test that can decisively assert the problem. @prateek-bruno |
The engine prints its gc_obj_list assertion to stderr before the trap is caught, so a handled trap read as a crash in CLI output. The module now builds through a variant whose printErr drops exactly that line, CLI only; the app keeps it for diagnostics. The recycle warn is reworded for users and shows the session count only on repeats, and the redundant dispose error log is skipped when the trap was contained. Also removes the unconsumed hasPendingDeferreds helper.
Pins for the host split (abort line printed in electron, swallowed on the cli), exact-marker pass-through of all other engine stderr, the repeat-only session count, waitForPendingDeferreds surviving a rejecting settle promise, and the async test() pin now verbatim to the reported script (VM Promise + setTimeout instead of the bru.sleep paraphrase).
CLI (bruno-cli integration): a run fetching 60 distinct large payloads trips the engine trap; asserts the run passes, the containment warn is present, and the raw abort line is absent from output. GUI (playwright): a six-request safe-mode collection covering the fire-and-forget wait, the contained trap, sync vars async expressions and async test() callbacks; asserts two full runner passes and that the abort line stays visible in the app process output.
|
@sanish-bruno I have added the e2e test cases. Also on cli it will now only throw a clean warning when recycling the QuickJS module instead of an Aborted Error, on electron app it will still log Aborted Error. This is so cli output remains clean and readable. We'll still print a QuickJS was recycled warning text in both cli and electron when we do. |
The first contained trap keeps the full self-explanatory sentence; repeats compress to 'QuickJS engine replaced again (N this session)' so heavy-payload runs do not print a wall of identical lines while keeping one line per trap. Adds a triple-phase fixture to the e2e collection where the pre-request, post-response and test contexts each trap and are contained independently within one request.
Adds a /api/large-payload route to bruno-tests and points the safe-mode fixtures at it and the existing /api/wait-for, dropping the spec's own http server. Also drops the preferences the playwright defaults supply.
13f1d46 to
934a158
Compare
…helper The trap-containment collection was seven heredocs inside the spec. It now lives under tests/integration/fixtures, copied into a temp dir by createCollectionFixture, which substitutes the address the spec's server bound to at runtime.
934a158 to
9895c21
Compare
Description
Ref: BRU-4035, BRU-4010, BRU-4320
Fixes #8744
Fixes the Safe Mode crashes where a run aborts during QuickJS context cleanup even though every request and test passed.
Problem
The engine requires cleanup to be complete: destroying a context while anything it created is still alive kills the whole process with
Aborted(Assertion failed: list_empty(&rt->gc_obj_list)). Two things left work alive at that moment:Promise.resolve().then(() => bru.sleep(5))) reproducibly kills the process. Wrong cleanup order made it worse: handles were freed before the engine's queued jobs ran.Fix
Engine traps are contained by replacing the module
A
WebAssembly.RuntimeErrorduring dispose retires that module instance: the run still reports its true result and the next run gets a fresh heap. The trapped instance keeps serving until the replacement is ready, a failed replacement build falls back to the old working module, and ordinary dispose errors surface as the run's error instead.Teardown frees everything, in the right order
Runs dispose only after the existing wait for pending async work, never racing it. Disposal drains queued jobs first, frees deferreds that never settled, then releases every tracked handle. The synchronous vars/assert path relies on this entirely, since it can never wait.
Every behavior above is pinned by a dedicated test, including one for async
test()callbacks completing before results are read (the existing #4678, safe mode).Screenshots
Contribution Checklist:
Summary by CodeRabbit
Bug Fixes
Tests