Skip to content

deepEquals: compare DOMException name, message and cause - #39308

Closed
robobun wants to merge 6 commits into
mainfrom
farm/69322043/deep-equals-domexception
Closed

robobun wants to merge 6 commits into
mainfrom
farm/69322043/deep-equals-domexception

Conversation

@robobun

@robobun robobun commented Aug 16, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

  • Bun.deepEquals(new DOMException("boom", "AbortError"), new DOMException("other", "NotFoundError")) returns true. Node's util.isDeepStrictEqual returns false.
  • The same comparison is shared by expect().toEqual() / toStrictEqual() (also inside expect.objectContaining / arrayContaining), assert.deepEqual, assert.deepStrictEqual and util.isDeepStrictEqual, so all of them treat any two DOMExceptions as equal, including ones with different cause values. assert.deepEqual(new DOMException("boom"), {}) passes as well.
  • Cause: a DOMException is a WebCore::JSDOMException wrapper (src/jsc/bindings/webcore/JSDOMException.h). Its name and message live in the wrapped WebCore::DOMException and are exposed as getters on the prototype, and the constructor stores cause as a non-enumerable own property (JSDOMException.cpp, construct()). The instance therefore has no enumerable own properties. specialObjectsDequal in src/jsc/bindings/bindings.cpp has no case for it (its ErrorInstanceType case only matches real JSC::ErrorInstances, and a DOMException wrapper is a plain ObjectType), so the comparison falls through to the generic own-property walk, which finds two empty objects.

Fix

  • domExceptionsDequal (new): if exactly one side is a DOMException the values are not equal; if both are, the wrapped names and messages must match and then cause is compared. On a match it returns nullopt so the existing own-property walk still compares any properties that were assigned onto the instances, exactly as the URL and Headers cases do.
  • It is called once per pair from Bun__deepEquals, after the two specialObjectsDequal passes and before the own-property walk, rather than from inside specialObjectsDequal: that function runs twice per pair (once per argument order), and since this comparison recurses into cause and then returns nullopt, placing it there compared every level of a cause chain twice, so a chain of n DOMExceptions cost 2^n comparisons (16 levels took about 6 s on a debug build; a getter inside a cause ran 4 times instead of 2). The helper starts with a JSType check, so pairs of ordinary objects (FinalObjectType) skip the class-chain walks.
  • errorCausesEqual (new) is the cause block lifted out of the ErrorInstanceType case unchanged and now used by both cases, so a DOMException's cause follows the same rules as an Error's (deep-compared in every mode; in strict modes a present cause: undefined also differs from an absent one).
  • Why this is the right comparison: node compares anything with Error.prototype in its chain (which includes DOMException) by name, message and cause, then own enumerable properties; Jest 30 does the same for instanceof Error values; Bun already applies these rules to Error via the ErrorInstanceType case. code is not compared separately because DOMException.cpp derives it from the name. Names and messages are compared with equalIgnoringNullity because both getters present a null and an empty WTF::String to JS as "".
  • The strings are read from the wrapped object rather than through [[Get]], mirroring the sanitizedNameString / sanitizedMessageString reads in the Error case: no user code runs for the name and message, and the result is the same for JS subclasses of DOMException, which share the wrapper class.
  • Verified with:
    • test/js/bun/bun-object/deep-equals.test.ts (new DOMException block, run in both Bun.deepEquals modes, including a getter-read count, a 64-deep cause chain and a cause cycle), test/js/bun/test/expect.test.js (new DOMException tests in the DOM types block, a getter-read count for toEqual / toStrictEqual, plus an Error cause test that pins the behaviour of the lifted block), test/js/node/assert/deep-equal.test.ts (DOMException rows in the deepStrictEqual / deepEqual / isDeepStrictEqual matrix, a skipPrototype case and a getter-read count, expectations checked against node v26). The DOMException tests fail on the unfixed binary and pass with the fix.
    • Existing deep-equals-temporal, deep-match, jest-extended, test-test, expect-extend, the test/js/node/assert suite and the upstream test-assert-deep-with-error.js / test-util-isDeepStrictEqual.js still pass.
    • The new tests also pass under BUN_JSC_validateExceptionChecks=1.
  • Out of scope, left as they were: assert.partialDeepStrictEqual has its own comparison in NodeUtilTypesModule.cpp with the same blind spot (reported separately); DOMExceptions created internally (for example AbortSignal.abort().reason) additionally carry enumerable own line / column / sourceURL properties, so two of those created on different lines still compare unequal, as before. DOMException: inherit from ErrorInstance for [[ErrorData]] and .stack #32898 re-parents JSDOMException onto JSC::ErrorInstance and changes its JSType; once it lands, DOMExceptions will take the ErrorInstanceType case instead, and this helper and its JSType check should be folded into that case.

Background

  • Bun__deepEquals (bindings.cpp) is one template behind all of Bun's deep-equality entry points; the template parameters select strict vs loose, Jest asymmetric matchers, and node's prototype check. Before the generic own-property walk it calls specialObjectsDequal(a, b) and then specialObjectsDequal(b, a); a case there returns true / false to decide the comparison or nullopt to let the own-property walk decide.
  • A DOM wrapper (JSDOMWrapper<T>) is the JS object for a native WebCore object; wrapped() returns the native object. WebIDL attributes such as DOMException.prototype.name are getters on the prototype that read from it, so wrapper instances normally have no own properties of their own.
  • JSC::ErrorInstance is the object class JSC uses for values created by the Error constructors; it is what specialObjectsDequal's ErrorInstanceType case compares. In Bun today a DOMException is not one, so it needs its own case.
  • JSType is the one-byte type tag in every JSC cell header. JSDOMException structures are created with the plain ObjectType; object literals and class instances are FinalObjectType, and most built-ins have their own tags, which is what specialObjectsDequal switches on.
Earlier shape of this PR (superseded)

The first revision called domExceptionsDequal from the ObjectType block of specialObjectsDequal, next to the Temporal handling. Review pointed out that because specialObjectsDequal runs once per argument order and the helper recurses into cause before returning nullopt, a chain of n DOMException causes took 2^n comparisons. 219e771 moved the single call into Bun__deepEquals and added the getter-count, chain and cycle tests; the comparison itself is unchanged.

Probe used to compare against node (node v26.3.0 vs bun 1.4.0 vs this branch)
case node bun 1.4.0 this branch
different name and message false true false
same name, different message false true false
same message, different name false true false
identical true true true
DOMException vs {} (loose) false true false
DOMException vs Error with the same message false false false
same name/message, different cause false true false
same name/message, equal object cause true true true
cause on one side only false true false
extra own property on one side false false false
same extra own property on both sides true true true
nested in an array / object, different names false true false

Remaining differences from node are pre-existing and not DOMException-specific: loose mode does not distinguish a present cause: undefined from an absent cause (same as for Error; recorded as a looseBug row in the matrix), and internally created DOMExceptions carry enumerable line / column own properties.

A DOMException wrapper keeps its name and message in the wrapped
WebCore::DOMException and exposes them as prototype getters, so it has no
own properties and the generic own-property walk in Bun__deepEquals
called any two DOMExceptions equal. This affected Bun.deepEquals,
expect().toEqual()/toStrictEqual(), assert.deepEqual/deepStrictEqual and
util.isDeepStrictEqual.

Compare the wrapped name and message plus the own non-enumerable cause
when both sides are DOMExceptions (a DOMException never equals anything
else), then fall through to the own-property walk for any properties
added to the instances. The cause comparison is shared with the
ErrorInstance case so the two stay in step.
@coderabbitai

coderabbitai Bot commented Aug 16, 2026 •

Copy link
Copy Markdown
Contributor

Warning

Review limit reached

@robobun, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 24 minutes

Limit details: You’ve used all 5 included reviews currently available under your plan.

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 4092b08e-49c7-4a9c-ae31-01bde47e02f9

📥 Commits

Reviewing files that changed from the base of the PR and between 83d65fa and 219e771.

📒 Files selected for processing (4)
  • src/jsc/bindings/bindings.cpp
  • test/js/bun/bun-object/deep-equals.test.ts
  • test/js/bun/test/expect.test.js
  • test/js/node/assert/deep-equal.test.ts

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

@robobun

robobun commented Aug 16, 2026 •

Copy link
Copy Markdown
Collaborator Author

Status: ready for review. Head is 219e771; CI build 99222 passed on it (179/179 jobs).

Reproduced on bun 1.4.0 with bun -e 'console.log(Bun.deepEquals(new DOMException("boom","AbortError"), new DOMException("other","NotFoundError")))' printing true (node prints false); the same pair also passes expect().toEqual(), assert.deepStrictEqual and util.isDeepStrictEqual. With this branch all four report the exceptions as different, and the new cases in test/js/bun/bun-object/deep-equals.test.ts, test/js/bun/test/expect.test.js and test/js/node/assert/deep-equal.test.ts fail on the unfixed binary and pass on the debug build.

Review so far: the mislabelled test row was dropped (48636e4); the comment-length findings were addressed (6e1a947, a952bcd); a test comment that misdescribed where cause lives was reworded (9a48d91); and the review finding that the DOMException comparison ran once per argument order, making cause chains exponential, was fixed by calling it once from Bun__deepEquals (219e771, with getter-count, 64-deep chain and cycle tests). The CodeRabbit comments above are its rate-limit notices, with no review content.

@claude claude 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.

Beyond the inline nit, I also checked: the errorCausesEqual extraction is a byte-faithful lift of the existing ErrorInstanceType cause block (same hasProperty/get/recursive-compare sequence, same RETURN_IF_EXCEPTION placement); domExceptionsDequal has exception checks after its only fallible call and the dynamicDowncast/wrapped()/equalIgnoringNullity reads cannot throw; the swapped specialObjectsDequal(c2, c1) call at bindings.cpp:865 covers the DOMException-on-right-only case; and the c1Type == ObjectType gate means plain object literals (FinalObjectType) skip the new downcast entirely.

Extended reasoning...

Verified the refactor and new handler against the surrounding code in bindings.cpp: the lifted cause helper preserves the original control flow and exception-check ordering, the new DOMException handler follows the same nullopt-then-fall-through contract as temporalObjectsDequal and the URL/Headers cases, and placement inside the ObjectType block keeps it off the plain-object hot path. Not approving because Bun__deepEquals backs every toEqual/deepStrictEqual in the test runner, so a human should confirm the C++ change.

Comment thread src/jsc/bindings/bindings.cpp Resolved
Comment thread src/jsc/bindings/bindings.cpp Resolved
Comment thread src/jsc/bindings/bindings.cpp Resolved
Comment thread src/jsc/bindings/bindings.cpp Resolved
Comment thread src/jsc/bindings/bindings.cpp Resolved
Comment thread src/jsc/bindings/bindings.cpp Resolved
Comment thread src/jsc/bindings/bindings.cpp Resolved
@robobun

robobun commented Aug 16, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 11:50 PM PT - Aug 15th, 2026

✅ @robobun, your commit 219e771d2f78a5444776d33de561526d3b300fb0 passed in Build #99222! 🎉


🧪   To try this PR locally:

bunx bun-pr 39308

That installs a local version of the PR into your bun-39308 executable, so you can run:

bun-39308 --bun

@robobun

robobun commented Aug 16, 2026

Copy link
Copy Markdown
Collaborator Author

Addressed the review round in 48636e4, 6e1a947 and a952bcd:

  • the mislabelled counterexample row in deep-equals.test.ts is gone; the remaining rows say what they hold
  • the comments flagged for length are down to one line each, and domExceptionsDequal now rejects a DOMException paired with a non-DOMException itself instead of documenting that the caller's swapped call covers it (same results, one fewer thing to explain)

No behaviour change beyond that; the three test files still fail on the unfixed binary and pass on the debug build.

Comment thread test/js/bun/test/expect.test.js Resolved
Comment thread src/jsc/bindings/bindings.cpp Resolved
…t order

specialObjectsDequal runs twice per pair (once with the arguments
swapped), and domExceptionsDequal returned nullopt after recursing into
the causes, so every level of a cause chain was compared twice and a
chain of n DOMExceptions took 2^n comparisons. Call it once from
Bun__deepEquals instead, after the special-object passes and before the
own-property walk.
@robobun

robobun commented Aug 16, 2026

Copy link
Copy Markdown
Collaborator Author

219e771 addresses the exponential cause-chain finding: domExceptionsDequal is now called once per pair from Bun__deepEquals (after the two specialObjectsDequal passes, before the own-property walk) instead of from inside specialObjectsDequal, which runs once per argument order. Measured on a debug build, a 16-level chain went from about 6 s to under 1 ms, and a getter inside a cause now runs twice (once per side) instead of four times. New tests cover the getter count in all three entry points, a 64-deep chain and a cause cycle; the PR description is updated to match.

@claude claude 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.

LGTM — the 2^n cause-chain issue from the previous round is resolved: domExceptionsDequal now runs once per Bun__deepEquals frame (outside specialObjectsDequal), and the new "reads each cause once per side" / "long chain of causes in linear time" / cycle tests pin that.

Checked: the errorCausesEqual extraction preserves the ErrorInstanceType path's behaviour (exception propagation via the caller's RETURN_IF_EXCEPTION, pinned by the new "deepEquals error causes" test); the ObjectType fast-path guard means plain FinalObjectType and array pairs skip the dynamicDowncast walks; mixed DOMException/Error and DOMException/plain-object pairs are rejected either by specialObjectsDequal's ErrorInstanceType case or by the new helper's own mixed-pair check; strict-mode subclass distinction still comes from calculatedClassName after the nullopt fall-through.

Extended reasoning...

Overview

Adds DOMException comparison to Bun__deepEquals in src/jsc/bindings/bindings.cpp: a new domExceptionsDequal helper compares the wrapped WebCore::DOMException name/message and the non-enumerable cause, then falls through to the existing own-property walk. The cause block from the ErrorInstanceType case is lifted into a shared errorCausesEqual helper. Tests are added across deep-equals.test.ts, expect.test.js, and the node deep-equal.test.ts matrix.

Since my previous review (the 🔴 2^n finding on the earlier revision), commit 219e771 moved the domExceptionsDequal call out of specialObjectsDequal into Bun__deepEquals directly, so it runs once per frame instead of once per argument order. Regression tests were added for read-count (2 per pair), a 64-deep cause chain, and a self-referential cause cycle.

Security risks

None identified. The comparison reads C++-owned WTF::String state via wrapped() without running user JS for name/message; cause is read via get() with proper RETURN_IF_EXCEPTION guards. No untrusted-size arithmetic, no allocation, no new GC-visible state.

Level of scrutiny

Moderate. Bun__deepEquals backs expect().toEqual(), assert.deepStrictEqual, and util.isDeepStrictEqual, so a regression would surface widely, but the change is additive (new special-object case) plus a mechanical extraction of existing code. I traced: the ObjectType-gate short-circuit keeps the hot path (two FinalObjectType objects, arrays) at two cheap type reads before returning nullopt; mixed pairs (DOMException vs Error, vs {}) are correctly rejected; the extracted errorCausesEqual preserves the original exception semantics because the caller re-checks RETURN_IF_EXCEPTION after the call; strict-mode subclass distinction is handled by the existing calculatedClassName check after fall-through.

Other factors

All earlier review threads (my mislabelled-test-row nit, the comment-cop length findings, my inaccurate-cause-comment nit, and the 🔴 2^n finding) have been addressed in 48636e4 / 6e1a947 / a952bcd / 9a48d91 / 219e771. The bug-hunting pass on the current head found nothing. Test coverage is thorough: both argument orders, both strict modes, subclass, structured clone, nested containers, asymmetric matchers, throwing cause getters, read-count, linear-time chain, and cycle termination — plus a Node-checked matrix and an Error-cause test that pins the lifted block. The PR description notes it was verified under BUN_JSC_validateExceptionChecks=1.

@github-actions

Copy link
Copy Markdown
Contributor

Closing this PR because it has been inactive for more than 90 days.

@github-actions github-actions Bot closed this Nov 15, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant