Skip to content

fix: Prevent QuickJS disposal aborts in safe mode - #8924

Merged
vijayh-bruno merged 25 commits into
usebruno:mainfrom
prateek-bruno:bugfix/BRU-4035-fix-quickjs-dispose-behaviour
Aug 18, 2026
Merged

vijayh-bruno merged 25 commits into
usebruno:mainfrom
prateek-bruno:bugfix/BRU-4035-fix-quickjs-dispose-behaviour

Conversation

@prateek-bruno

@prateek-bruno prateek-bruno commented Aug 10, 2026 •

Copy link
Copy Markdown
Collaborator

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:

  • The engine damages itself under large payloads. Runs pulling distinct ~130KB+ strings into scripts request after request abort on teardown (Jira Ticket), as does a multi-MB body grown into an uncatchable out-of-memory (Github Issue). Both strand engine-internal objects no host code can free (a debug engine build shows bundled-library objects whose refcounts never reach zero). An engine defect, already reported upstream (Reproducible list_empty assertion failure justjake/quickjs-emscripten#235); it can only be contained, not fixed here.
  • Cleanup ran while script work was still alive. Vars and assert expressions run synchronously and cannot wait, so async work they start is still pending when the context is destroyed: a one-line post-response var (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.RuntimeError during 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

Running a request with Multi-MB response body with some tests
Before After
Screenshot 2026-08-10 at 7 13 45 PM Screenshot 2026-08-10 at 7 12 49 PM
Running a request with promise inside a variable expression
Before After
image Screenshot 2026-08-13 at 8 53 03 PM

Contribution Checklist:

  • I've used AI significantly to create this pull request
  • The pull request only addresses one issue or adds one feature.
  • The pull request does not introduce any breaking changes
  • I have added screenshots or gifs to help explain the change if applicable.
  • I have read the contribution guidelines.
  • Create an issue and link to the pull request.
  • I've run the claude code review skill locally.

Summary by CodeRabbit

  • Bug Fixes

    • Improved sandbox reliability when scripts encounter memory limits or runtime shutdown errors.
    • Ensured synchronous and asynchronous executions settle cleanly without masking the original script error.
    • Improved cleanup of pending work and allocated resources during sandbox teardown.
    • Preserved subsequent sandbox execution after recoverable runtime failures.
    • Prevented background cleanup errors from causing unhandled failures.
    • Improved recovery when replacing a failed runtime module.
  • Tests

    • Added comprehensive coverage for teardown, pending jobs, deferred work, memory traps, module recovery, and error handling.

@coderabbitai

coderabbitai Bot commented Aug 10, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: cf2b6e1d-0d1d-4be9-8fad-989282d6ff89

📥 Commits

Reviewing files that changed from the base of the PR and between fa1e196 and ae0061e.

📒 Files selected for processing (3)
  • packages/bruno-js/tests/quickjs-sandbox.helpers.js
  • packages/bruno-js/tests/quickjs-teardown.spec.js
  • packages/bruno-js/tests/quickjs-trap-containment.spec.js
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/bruno-js/tests/quickjs-teardown.spec.js
  • packages/bruno-js/tests/quickjs-trap-containment.spec.js

Walkthrough

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

Changes

QuickJS lifecycle handling

Layer / File(s) Summary
Deferred resource disposal
packages/bruno-js/src/sandbox/quickjs/utils/index.js
Deferred handles are tracked and explicitly disposed. Teardown drains jobs before deferreds, tracked handles, and the VM.
WASM module recovery
packages/bruno-js/src/sandbox/quickjs/index.js
The WASM loader supports explicit reloads, tracks module generations, and recycles modules after runtime traps. Synchronous and asynchronous execution bind contexts to the active module and preserve script errors during cleanup.
Lifecycle and trap validation
packages/bruno-js/tests/quickjs-sandbox.helpers.js, packages/bruno-js/tests/quickjs-teardown.spec.js, packages/bruno-js/tests/quickjs-trap-containment.spec.js
Tests capture allocations and validate cleanup across pending jobs, background requests, chained work, runtime traps, module replacement, and ordinary teardown errors.

Estimated code review effort: 4 (Complex) | ~45 minutes

Suggested reviewers: vijayh-bruno

Poem

Deferred jobs wait, then clear,
QuickJS traps no longer steer.
Modules renew, contexts rest,
Script errors stay with the test.
Handles fade when cleanup is done.

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
Loading
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The changes address issue #8744 by preventing QuickJS runtime aborts through safer teardown, deferred cleanup, module recovery, and targeted tests.
Out of Scope Changes check ✅ Passed The implementation and tests remain focused on QuickJS Safe Mode teardown, resource cleanup, runtime recovery, and related failure scenarios.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly identifies the main change: preventing QuickJS disposal aborts in Safe Mode.
✨ Finishing Touches 💡 1
🛠️ Fix failing CI checks 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@prateek-bruno prateek-bruno changed the title fix: quickjs dispose behaviour fix: Prevent QuickJS disposal aborts and unbounded teardown waits in safe mode Aug 10, 2026
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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

📥 Commits

Reviewing files that changed from the base of the PR and between 23aa48d and d827451.

📒 Files selected for processing (5)
  • packages/bruno-js/src/sandbox/quickjs/index.js
  • packages/bruno-js/src/sandbox/quickjs/utils/index.js
  • packages/bruno-js/tests/quickjs-sandbox.helpers.js
  • packages/bruno-js/tests/quickjs-teardown.spec.js
  • packages/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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

📥 Commits

Reviewing files that changed from the base of the PR and between d827451 and d236941.

📒 Files selected for processing (3)
  • packages/bruno-js/src/sandbox/quickjs/index.js
  • packages/bruno-js/tests/quickjs-sandbox.helpers.js
  • packages/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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

📥 Commits

Reviewing files that changed from the base of the PR and between d236941 and e698d7f.

📒 Files selected for processing (4)
  • packages/bruno-js/src/sandbox/quickjs/index.js
  • packages/bruno-js/tests/quickjs-sandbox.helpers.js
  • packages/bruno-js/tests/quickjs-teardown.spec.js
  • packages/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
@prateek-bruno
prateek-bruno force-pushed the bugfix/BRU-4035-fix-quickjs-dispose-behaviour branch from ed668e8 to ae0061e Compare August 12, 2026 07:38
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

@sid-bruno sid-bruno left a comment •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor edge cases and tests that you can validate if they are necessary

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)
@prateek-bruno prateek-bruno changed the title fix: Prevent QuickJS disposal aborts and unbounded teardown waits in safe mode fix: Prevent QuickJS disposal aborts in safe mode Aug 13, 2026
@sanish-bruno

Copy link
Copy Markdown
Collaborator

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.
@prateek-bruno

Copy link
Copy Markdown
Collaborator Author

@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.
@prateek-bruno
prateek-bruno force-pushed the bugfix/BRU-4035-fix-quickjs-dispose-behaviour branch from 13f1d46 to 934a158 Compare August 14, 2026 10:06
…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.
@prateek-bruno
prateek-bruno force-pushed the bugfix/BRU-4035-fix-quickjs-dispose-behaviour branch from 934a158 to 9895c21 Compare August 14, 2026 10:50
sanish-bruno
sanish-bruno previously approved these changes Aug 14, 2026
@vijayh-bruno
vijayh-bruno merged commit d8447ed into usebruno:main Aug 18, 2026
13 of 15 checks passed
@prateek-bruno
prateek-bruno deleted the bugfix/BRU-4035-fix-quickjs-dispose-behaviour branch August 18, 2026 14:24
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Bruno Safe mode first-run crash with large response body assertions (QuickJS JS_FreeRuntime assertion)

5 participants