From 8aab3d744f9fd4e978fe0f2eda1400e8f82ed4e9 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 14 Aug 2026 14:53:05 +0000 Subject: [PATCH 1/5] assert.partialDeepStrictEqual: settle Set members and Map keys by lookup, pair off the rest in one pass setSubset compared every expected member against every actual member still unclaimed, and mapSubset rescanned its list of claimed identity keys with sameValue once per expected entry, so both were quadratic in the collection size whatever it held: a Set of 100k integers took several seconds and a Map of 10k string keys a quarter of a second. Port the shape of node's setEquiv/mapEquiv instead. Expected members actual holds by identity, and primitive Map keys, are settled by one hash lookup each; only the expected objects left over are queued, and actual is walked once, each entry claiming a queued one in node's probe order (front guess, back guess, then the rest) with swap-removal. Sets also get node's identity reservation: a member both sides hold is paired with itself rather than claimed by some structural subset of it. --- src/jsc/modules/NodeUtilTypesModule.cpp | 292 +++++++++++++----------- test/js/node/assert/deep-equal.test.ts | 229 +++++++++++++++++++ 2 files changed, 391 insertions(+), 130 deletions(-) diff --git a/src/jsc/modules/NodeUtilTypesModule.cpp b/src/jsc/modules/NodeUtilTypesModule.cpp index 46050f5ed8d1..889ad2b3133c 100644 --- a/src/jsc/modules/NodeUtilTypesModule.cpp +++ b/src/jsc/modules/NodeUtilTypesModule.cpp @@ -393,170 +393,202 @@ static bool arraySubsequence(JSC::JSGlobalObject* globalObject, JSC::MarkedArgum return nonIndexObjectSubset(globalObject, gcBuffer, cycles, scope, actual, expected); } -// Expected's entries as a subset of actual's: identity keys fast-path with -// index reservation so no actual entry is consumed twice; object keys match -// by partial deep equality. +enum class Pairing { Open, + Complete }; + +// The expected Set members / Map entries a hash lookup could not settle (copies; the caller +// rooted them in gcBuffer), claimed one by one while actual is walked once. +template +struct PendingExpected { + using Queue = WTF::Vector; + + Queue entries; + size_t first { 0 }; + size_t last; + // Front guesses keep hitting while actual arrives in expected's order, back guesses while + // it arrives reversed; only when both miss is the rest of the window scanned. + bool probeFront { true }; + + explicit PendingExpected(Queue&& queued) + : entries(std::move(queued)) + , last(entries.size() - 1) + { + ASSERT(!entries.isEmpty()); + } + + size_t openCount() const { return last - first + 1; } + + // One actual entry against the open window, in node's order (partialObjectSetEquiv / + // partialObjectMapEquiv, down to which entry is claimed when several would do): the front + // guess, the back guess, then the rest back to front. A claimed entry is swap-removed so it + // is never compared again; Complete means nothing is left to claim. `matches` may throw; + // callers RETURN_IF_EXCEPTION after this returns. + template + Pairing claimWith(JSC::ThrowScope& scope, const Matches& matches) + { + size_t scanFrom = first; + if (probeFront) { + bool hit = matches(entries[first]); + RETURN_IF_EXCEPTION(scope, Pairing::Open); + if (hit) { + if (first == last) + return Pairing::Complete; + first++; + return Pairing::Open; + } + if (first == last) + return Pairing::Open; + probeFront = false; + scanFrom++; + } + bool hit = matches(entries[last]); + RETURN_IF_EXCEPTION(scope, Pairing::Open); + if (!hit) { + probeFront = true; + size_t i = last; + while (!hit && i > scanFrom) { + i--; + hit = matches(entries[i]); + RETURN_IF_EXCEPTION(scope, Pairing::Open); + } + if (!hit) + return Pairing::Open; + entries[i] = entries[last]; + } + if (first == last) + return Pairing::Complete; + last--; + return Pairing::Open; + } +}; + +struct PendingMapEntry { + JSValue key; + JSValue value; +}; + +// Expected's entries as a subset of actual's (node's mapEquiv + partialObjectMapEquiv). A +// primitive key is settled by one lookup: actual must hold that key and the values must +// match, since no other entry can stand in for it. Object keys, identical ones included, are +// queued and matched structurally, key and value together, while actual is walked once. static bool mapSubset(JSC::JSGlobalObject* globalObject, JSC::MarkedArgumentBuffer& gcBuffer, CycleState& cycles, JSC::ThrowScope& scope, JSValue actual, JSValue expected) { auto& vm = globalObject->vm(); JSC::JSMap* actualMap = uncheckedDowncast(actual.asCell()); JSC::JSMap* expectedMap = uncheckedDowncast(expected.asCell()); - // Materialized lazily, rooted in gcBuffer (keys then values, pairwise). - bool materialized = false; - size_t entriesStart = 0; - size_t entryCount = 0; - WTF::Vector usedIndices; - JSC::MarkedArgumentBuffer usedIdentityKeys; - - auto materialize = [&]() -> bool { - if (materialized) - return true; - materialized = true; - entriesStart = gcBuffer.size(); - auto iter = JSC::JSMapIterator::create(vm, globalObject->mapIteratorStructure(), actualMap, JSC::IterationKind::Entries); - if (scope.exception()) [[unlikely]] - return false; - JSValue key, value; - while (iter->nextKeyValue(globalObject, key, value)) { - gcBuffer.append(key); - gcBuffer.append(value); - entryCount++; - } - usedIndices.fill(false, entryCount); - return true; - }; - - auto identityKeyUsed = [&](JSValue key) -> bool { - for (size_t i = 0; i < usedIdentityKeys.size(); i++) { - bool same = JSC::sameValue(globalObject, usedIdentityKeys.at(i), key); - // sameValue can resolve ropes and throw; plain check because the macro can't live - // inside a lambda — callers RETURN_IF_EXCEPTION right after this returns. - if (scope.exception()) [[unlikely]] - return false; - if (same) - return true; - } - return false; - }; - - auto expectedIter = JSC::JSMapIterator::create(vm, globalObject->mapIteratorStructure(), expectedMap, JSC::IterationKind::Entries); - RETURN_IF_EXCEPTION(scope, false); - JSValue expectedKey, expectedValue; - while (expectedIter->nextKeyValue(globalObject, expectedKey, expectedValue)) { - bool consumed = false; - bool identityPresent = actualMap->has(globalObject, expectedKey); - RETURN_IF_EXCEPTION(scope, false); - bool expectedKeyAlreadyUsed = identityKeyUsed(expectedKey); - // sameValue can resolve rope strings and throw; the lambda cannot - // hold the check macro, so check at every call site. + PendingExpected::Queue queued; + { + auto iter = JSC::JSMapIterator::create(vm, globalObject->mapIteratorStructure(), expectedMap, JSC::IterationKind::Entries); RETURN_IF_EXCEPTION(scope, false); - if (identityPresent && !expectedKeyAlreadyUsed) { - // Reserve the identity entry's index so the deep-matching loop - // below cannot consume it twice. - size_t identityIndex = SIZE_MAX; - if (materialized) { - for (size_t i = 0; i < entryCount; i++) { - bool same = JSC::sameValueZero(globalObject, gcBuffer.at(entriesStart + i * 2), expectedKey); - // Same rope-resolution hazard as identityKeyUsed: bail - // before the next VM-entering call, not after the loop. - RETURN_IF_EXCEPTION(scope, false); - if (same) { - identityIndex = i; - break; - } - } + JSValue expectedKey, expectedValue; + while (iter->nextKeyValue(globalObject, expectedKey, expectedValue)) { + if (expectedKey.isObject()) { + gcBuffer.append(expectedKey); + gcBuffer.append(expectedValue); + queued.append({ expectedKey, expectedValue }); + continue; } - if (identityIndex == SIZE_MAX || !usedIndices[identityIndex]) { - JSValue actualValue = actualMap->get(globalObject, expectedKey); - RETURN_IF_EXCEPTION(scope, false); - bool equal = compareBranch(globalObject, gcBuffer, cycles, scope, actualValue, expectedValue); + JSValue actualValue = actualMap->get(globalObject, expectedKey); + RETURN_IF_EXCEPTION(scope, false); + if (actualValue.isUndefined()) { + // get() answers undefined both for a missing key and for a key holding undefined. + bool held = actualMap->has(globalObject, expectedKey); RETURN_IF_EXCEPTION(scope, false); - if (equal) { - usedIdentityKeys.append(expectedKey); - if (identityIndex != SIZE_MAX) - usedIndices[identityIndex] = true; - consumed = true; - } + if (!held) + return false; } - } - if (consumed) - continue; - if (!expectedKey.isObject()) - return false; - if (!materialize()) - return false; - RETURN_IF_EXCEPTION(scope, false); - bool matched = false; - for (size_t i = 0; i < entryCount; i++) { - if (usedIndices[i]) - continue; - JSValue candidateKey = gcBuffer.at(entriesStart + i * 2); - bool candidateIsUsedIdentity = identityKeyUsed(candidateKey); - RETURN_IF_EXCEPTION(scope, false); - if (candidateIsUsedIdentity) - continue; - bool keyEqual = compareBranch(globalObject, gcBuffer, cycles, scope, candidateKey, expectedKey); + bool equal = compareBranch(globalObject, gcBuffer, cycles, scope, actualValue, expectedValue); RETURN_IF_EXCEPTION(scope, false); - if (!keyEqual) - continue; - bool valueEqual = compareBranch(globalObject, gcBuffer, cycles, scope, gcBuffer.at(entriesStart + i * 2 + 1), expectedValue); + if (!equal) + return false; + } + } + if (queued.isEmpty()) + return true; + + PendingExpected pending(std::move(queued)); + auto iter = JSC::JSMapIterator::create(vm, globalObject->mapIteratorStructure(), actualMap, JSC::IterationKind::Entries); + RETURN_IF_EXCEPTION(scope, false); + size_t visited = 0; + JSValue actualKey, actualValue; + while (iter->nextKeyValue(globalObject, actualKey, actualValue)) { + visited++; + if (actualKey.isObject()) { + Pairing pairing = pending.claimWith(scope, [&](const PendingMapEntry& entry) -> bool { + bool keyEqual = compareBranch(globalObject, gcBuffer, cycles, scope, actualKey, entry.key); + RETURN_IF_EXCEPTION(scope, false); + if (!keyEqual) + return false; + return compareBranch(globalObject, gcBuffer, cycles, scope, actualValue, entry.value); + }); RETURN_IF_EXCEPTION(scope, false); - if (valueEqual) { - usedIndices[i] = true; - matched = true; - break; - } + if (pairing == Pairing::Complete) + return true; } - if (!matched) + const size_t size = actualMap->size(); + const size_t unvisited = size > visited ? size - visited : 0; + if (unvisited < pending.openCount()) return false; } - return true; + return false; } -// Expected's items as a subset of actual's; item equality is the partial -// comparison itself — node matches object items with subset semantics -// (Set([{a:1,b:2}]) partially contains Set([{a:1}])). +// Expected's members as a subset of actual's (node's setEquiv + partialObjectSetEquiv). A +// member actual holds by identity is settled by one lookup, and a primitive it does not hold +// can match nothing else. The remaining objects are matched with subset semantics +// (Set([{a:1,b:2}]) partially contains Set([{a:1}])) while actual is walked once; the actual +// members expected also holds were settled by the lookup and stay reserved for their twin. static bool setSubset(JSC::JSGlobalObject* globalObject, JSC::MarkedArgumentBuffer& gcBuffer, CycleState& cycles, JSC::ThrowScope& scope, JSValue actual, JSValue expected) { auto& vm = globalObject->vm(); JSC::JSSet* actualSet = uncheckedDowncast(actual.asCell()); JSC::JSSet* expectedSet = uncheckedDowncast(expected.asCell()); - const size_t itemsStart = gcBuffer.size(); - size_t itemCount = 0; + PendingExpected::Queue queued; { - auto iter = JSC::JSSetIterator::create(vm, globalObject->setIteratorStructure(), actualSet, JSC::IterationKind::Keys); + auto iter = JSC::JSSetIterator::create(vm, globalObject->setIteratorStructure(), expectedSet, JSC::IterationKind::Keys); RETURN_IF_EXCEPTION(scope, false); - JSValue item; - while (iter->next(globalObject, item)) { - gcBuffer.append(item); - itemCount++; + JSValue expectedMember; + while (iter->next(globalObject, expectedMember)) { + bool held = actualSet->has(globalObject, expectedMember); + RETURN_IF_EXCEPTION(scope, false); + if (held) + continue; + if (!expectedMember.isObject()) + return false; + gcBuffer.append(expectedMember); + queued.append(expectedMember); } } - WTF::Vector usedIndices; - usedIndices.fill(false, itemCount); + if (queued.isEmpty()) + return true; - auto expectedIter = JSC::JSSetIterator::create(vm, globalObject->setIteratorStructure(), expectedSet, JSC::IterationKind::Keys); + PendingExpected pending(std::move(queued)); + auto iter = JSC::JSSetIterator::create(vm, globalObject->setIteratorStructure(), actualSet, JSC::IterationKind::Keys); RETURN_IF_EXCEPTION(scope, false); - JSValue expectedItem; - while (expectedIter->next(globalObject, expectedItem)) { - bool matched = false; - for (size_t i = 0; i < itemCount; i++) { - if (usedIndices[i]) - continue; - bool equal = compareBranch(globalObject, gcBuffer, cycles, scope, gcBuffer.at(itemsStart + i), expectedItem); + size_t visited = 0; + JSValue actualMember; + while (iter->next(globalObject, actualMember)) { + visited++; + if (actualMember.isObject()) { + bool reserved = expectedSet->has(globalObject, actualMember); RETURN_IF_EXCEPTION(scope, false); - if (equal) { - usedIndices[i] = true; - matched = true; - break; + if (!reserved) { + Pairing pairing = pending.claimWith(scope, [&](JSValue expectedMember) -> bool { + return compareBranch(globalObject, gcBuffer, cycles, scope, actualMember, expectedMember); + }); + RETURN_IF_EXCEPTION(scope, false); + if (pairing == Pairing::Complete) + return true; } } - if (!matched) + const size_t size = actualSet->size(); + const size_t unvisited = size > visited ? size - visited : 0; + if (unvisited < pending.openCount()) return false; } - return true; + return false; } // Errors compare name/message/errors leniently: `undefined` (or an empty diff --git a/test/js/node/assert/deep-equal.test.ts b/test/js/node/assert/deep-equal.test.ts index 9e391b7706ec..ff5903cacb19 100644 --- a/test/js/node/assert/deep-equal.test.ts +++ b/test/js/node/assert/deep-equal.test.ts @@ -2,6 +2,7 @@ // Expectations come from the documented semantics of assert.deepStrictEqual/deepEqual, // cross-checked against Node.js. Cases Bun gets wrong today are marked `test.failing`. import { describe, expect, test } from "bun:test"; +import { bunEnv, bunExe } from "harness"; import assert from "node:assert"; import util from "node:util"; @@ -842,6 +843,234 @@ describe("detached ArrayBuffer", () => { }); }); +// assert.partialDeepStrictEqual pairs off Set members and Map entries the way node's +// setEquiv/mapEquiv do (lib/internal/util/comparisons.js; for Sets, the path node takes once +// actual has three or more members): whatever a hash lookup can settle is settled by one +// lookup, and only the expected objects left over are matched structurally, each claiming an +// actual entry of its own, while actual is walked once. Every expectation below was +// cross-checked against node v26. +describe("assert.partialDeepStrictEqual on Sets and Maps", () => { + const set = (...members: unknown[]) => new Set(members); + const map = (...entries: [unknown, unknown][]) => new Map(entries); + const twin = { a: 1, b: 2 }; + const fn = () => {}; + // [description, actual, expected, whether expected is partially contained in actual] + const cases: [string, unknown, unknown, boolean][] = [ + ["Set: a member both sides hold is paired with itself", set(twin, { a: 1, c: 3 }, 1), set({ a: 1 }, twin), true], + ["Set: a member both sides hold, other order", set({ a: 1, c: 3 }, twin, 1), set(twin, { a: 1 }), true], + ["Set: members match with subset semantics", set({ a: 1, b: 2 }, { c: 3, d: 4 }, 0), set({ c: 3 }, { a: 1 }), true], + ["Set: each expected object claims a member of its own", set({ a: 1 }, 5, 6), set({ a: 1 }, { a: 1 }), false], + ["Set: duplicates pair off one to one", set({ a: 1 }, { a: 1 }, 5), set({ a: 1 }, { a: 1 }), true], + [ + "Set: an expected object without a counterpart", + set({ a: 1 }, { b: 2 }, { c: 3 }), + set({ c: 3 }, { z: 0 }), + false, + ], + ["Set: a primitive actual does not hold", set({}, 1, 3), set(2), false], + ["Set: an object when actual holds only primitives", set(1, 2, 3), set({}), false], + ["Set: a function both sides hold", set(fn, 1, 2), set(fn), true], + ["Set: a function only expected holds", set(() => {}, 1, 2), set(() => {}), false], + ["Set: nested collections", set(set(1, 2, 3), [4, 5], 0), set([5], set(2)), true], + [ + "Set: own properties are still compared", + Object.assign(set(1, 2), { x: 1 }), + Object.assign(set(1), { x: 2 }), + false, + ], + ["Map: a primitive key actual does not hold", map(["a", 1], ["c", 1]), map(["b", 1]), false], + ["Map: a primitive key with a different value", map(["a", 1], ["b", 2]), map(["a", 2]), false], + [ + "Map: a primitive key, value matched with subset semantics", + map(["a", { x: 1, y: 2 }]), + map(["a", { x: 1 }]), + true, + ], + ["Map: a key holding undefined", map(["a", undefined], ["b", 1]), map(["a", undefined]), true], + ["Map: a missing key is not a key holding undefined", map(["b", 1]), map(["a", undefined]), false], + [ + "Map: an object key matches on key and value together", + map([twin, { x: 1, y: 2 }]), + map([{ a: 1 }, { x: 1 }]), + true, + ], + ["Map: an object key whose value differs", map([twin, { x: 1 }]), map([{ a: 1 }, { x: 2 }]), false], + [ + "Map: each expected entry claims an entry of its own", + map([{ a: 1 }, 1], ["k", 0]), + map([{ a: 1 }, 1], [{ a: 1 }, 1]), + false, + ], + [ + "Map: duplicate keys pair off one to one", + map([{ a: 1 }, 1], [{ a: 1 }, 1], ["k", 0]), + map([{ a: 1 }, 1], [{ a: 1 }, 1]), + true, + ], + [ + "Map: equal keys carrying each other's values", + map([{ k: 1 }, "x"], [{ k: 1 }, "y"]), + map([{ k: 1 }, "y"], [{ k: 1 }, "x"]), + true, + ], + [ + "Map: a key both sides hold, its value under a structurally equal key", + map([twin, 1], [{ a: 1, b: 2 }, 2]), + map([twin, 2]), + true, + ], + ["Map: a key both sides hold with a different value", map([twin, 1], [{ a: 1 }, 2]), map([twin, 2]), false], + [ + "Map: object and primitive keys in another order", + map(["p", 0], [{ k: 1 }, 1], [{ k: 2 }, 2]), + map([{ k: 2 }, 2], ["p", 0], [{ k: 1 }, 1]), + true, + ], + ["Map: an object key when actual holds only primitive keys", map(["a", 1], ["b", 1]), map([{}, 1]), false], + [ + "Map: nested collections as keys and values", + map([map(["a", 1], ["b", 2]), [1, 2, 3]]), + map([map(["a", 1]), [2]]), + true, + ], + [ + "Map: own properties are still compared", + Object.assign(map([1, 1]), { x: 1 }), + Object.assign(map([1, 1]), { x: 2 }), + false, + ], + ]; + + test.each(cases)("%s", (_, actual, expected, contained) => { + if (contained) { + assert.partialDeepStrictEqual(actual, expected); + } else { + expect(() => assert.partialDeepStrictEqual(actual, expected)).toThrow(assert.AssertionError); + } + }); + + // Expected in a stride order, so neither the front nor the back guess fits and most members + // are found by scanning the open window and swap-removed from the middle of it. + test("a permuted expected side is paired off completely", () => { + const n = 24; + const actual = Array.from({ length: n }, (_, i) => ({ id: i, extra: true })); + const expected = Array.from({ length: n }, (_, i) => ({ id: (i * 7 + 3) % n })); + assert.partialDeepStrictEqual(new Set(actual), new Set(expected)); + assert.partialDeepStrictEqual(new Set(actual), new Set(expected.slice(0, n / 2))); + expect(() => assert.partialDeepStrictEqual(new Set(actual), new Set([...expected.slice(1), { id: n }]))).toThrow( + assert.AssertionError, + ); + + const actualMap = new Map(actual.map(key => [key, key.id])); + assert.partialDeepStrictEqual(actualMap, new Map(expected.map(key => [key, key.id]))); + expect(() => + assert.partialDeepStrictEqual(actualMap, new Map(expected.map(key => [key, key.id === 5 ? -1 : key.id]))), + ).toThrow(assert.AssertionError); + }); + + test("self-referential members terminate", () => { + const selfSet = () => { + const self = new Set(); + self.add(self); + return self; + }; + const selfMap = () => { + const self = new Map(); + self.set("self", self); + return self; + }; + assert.partialDeepStrictEqual(set(selfSet(), 1), set(selfSet())); + assert.partialDeepStrictEqual(map([{ k: 1 }, selfMap()], ["s", 1]), map([{ k: 1 }, selfMap()])); + assert.partialDeepStrictEqual(map(["s", selfMap()]), map(["s", selfMap()])); + }); + + test("an exception thrown while comparing propagates", () => { + const throwing = () => ({ + get x(): number { + throw new Error("boom"); + }, + }); + expect(() => assert.partialDeepStrictEqual(set(throwing()), set(throwing()))).toThrow("boom"); + expect(() => assert.partialDeepStrictEqual(map(["k", throwing()]), map(["k", throwing()]))).toThrow("boom"); + expect(() => assert.partialDeepStrictEqual(map([throwing(), 1]), map([throwing(), 1]))).toThrow("boom"); + expect(() => assert.partialDeepStrictEqual(map([{ k: 1 }, throwing()]), map([{ k: 1 }, throwing()]))).toThrow( + "boom", + ); + }); + + // Each actual member is compared against one or two expected members: the front guess keeps + // hitting while the sides were built in the same order, the back guess while they were built + // in opposite orders, so the getters are read 2n times (2n + 2 reversed). Rescanning every + // unclaimed actual member per expected member, which this replaced, read them about n*n + // times in the reversed case. + describe("number of structural comparisons", () => { + const n = 128; + function members(onRead: () => void) { + return Array.from({ length: n }, (_, i) => ({ + get id() { + onRead(); + return i; + }, + })); + } + const orders: [string, boolean][] = [ + ["same order", false], + ["opposite order", true], + ]; + + test.each(orders)("Set members, %s", (_, reversed) => { + let reads = 0; + const onRead = () => reads++; + const actual = new Set(members(onRead)); + const other = members(onRead); + const expected = new Set(reversed ? other.reverse() : other); + assert.partialDeepStrictEqual(actual, expected); + expect(reads).toBeLessThanOrEqual(4 * n); + }); + + test.each(orders)("Map entries with object keys, %s", (_, reversed) => { + let reads = 0; + const onRead = () => reads++; + const actual = new Map(members(onRead).map((key, i) => [key, i] as const)); + const other = members(onRead).map((key, i) => [key, i] as const); + const expected = new Map(reversed ? other.reverse() : other); + assert.partialDeepStrictEqual(actual, expected); + expect(reads).toBeLessThanOrEqual(4 * n); + }); + }); + + // Primitive members and primitive keys are settled by hash lookups, which nothing can + // observe, so the size is the discriminator: at these sizes the rescan per member that this + // replaced needs well over a minute for either collection in a debug build, the lookups well + // under a second (the child spends its few seconds starting up and building the + // collections), and the spawn timeout sits in between. + test("primitive members and keys are settled by lookups, not rescans", async () => { + const fixture = ` + const assert = require("node:assert"); + const ints = Array.from({ length: 100_000 }, (_, i) => i); + assert.partialDeepStrictEqual(new Set(ints), new Set(ints)); + const entries = Array.from({ length: 12_000 }, (_, i) => ["key" + i, i]); + assert.partialDeepStrictEqual(new Map(entries), new Map(entries)); + console.log("done"); + `; + await using proc = Bun.spawn({ + cmd: [bunExe(), "-e", fixture], + env: bunEnv, + stdout: "pipe", + stderr: "pipe", + timeout: 60_000, + killSignal: "SIGKILL", + }); + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + expect({ stdout: stdout.trim(), stderr, exitCode, signalCode: proc.signalCode }).toEqual({ + stdout: "done", + stderr: "", + exitCode: 0, + signalCode: null, + }); + }, 90_000); +}); + describe("AssertionError", () => { test("deepStrictEqual reports actual, expected and operator", () => { const error = caught(() => assert.deepStrictEqual({ a: 1 }, { a: 2 })) as any; From 406614f93862c77c56f8b8f6c1ea277d35b61cd9 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 14 Aug 2026 16:22:21 +0000 Subject: [PATCH 2/5] partialDeepStrictEqual: treat stray Set members and non-object Map keys the way node does A Set member that can match nothing (a primitive or function only actual holds) was skipped without touching the probe direction; node probes it, so the member after it is tried against the front of the window again, and the outcome can differ. Record the reset instead of skipping it. Map keys were classified with isObject(), which admits functions; node uses typeof, so function keys are settled by lookup like primitives and function-keyed actual entries are passed over. Use the file's isSpecialValue predicate in all four places. --- src/jsc/modules/NodeUtilTypesModule.cpp | 51 ++++++++++++++----------- test/js/node/assert/deep-equal.test.ts | 45 ++++++++++++++++++++++ 2 files changed, 74 insertions(+), 22 deletions(-) diff --git a/src/jsc/modules/NodeUtilTypesModule.cpp b/src/jsc/modules/NodeUtilTypesModule.cpp index 889ad2b3133c..da6aba271b19 100644 --- a/src/jsc/modules/NodeUtilTypesModule.cpp +++ b/src/jsc/modules/NodeUtilTypesModule.cpp @@ -393,6 +393,14 @@ static bool arraySubsequence(JSC::JSGlobalObject* globalObject, JSC::MarkedArgum return nonIndexObjectSubset(globalObject, gcBuffer, cycles, scope, actual, expected); } +// Node's `typeof x !== "object" || x === null`: primitives, null, and callables. Such a value +// never matches structurally; in compareBranch full strict deep equality decides it, and as a +// Set member or Map key only an identical counterpart can satisfy it. +static bool isSpecialValue(JSValue value) +{ + return !value.isObject() || value.isCallable(); +} + enum class Pairing { Open, Complete }; @@ -468,9 +476,10 @@ struct PendingMapEntry { }; // Expected's entries as a subset of actual's (node's mapEquiv + partialObjectMapEquiv). A -// primitive key is settled by one lookup: actual must hold that key and the values must -// match, since no other entry can stand in for it. Object keys, identical ones included, are -// queued and matched structurally, key and value together, while actual is walked once. +// special (non-object or callable) key is settled by one lookup: actual must hold that key and +// the values must match, since no other entry can stand in for it. Object keys, identical ones +// included, are queued and matched structurally, key and value together, while actual's +// object-keyed entries are walked once; its other entries are passed over, as in node. static bool mapSubset(JSC::JSGlobalObject* globalObject, JSC::MarkedArgumentBuffer& gcBuffer, CycleState& cycles, JSC::ThrowScope& scope, JSValue actual, JSValue expected) { auto& vm = globalObject->vm(); @@ -483,7 +492,7 @@ static bool mapSubset(JSC::JSGlobalObject* globalObject, JSC::MarkedArgumentBuff RETURN_IF_EXCEPTION(scope, false); JSValue expectedKey, expectedValue; while (iter->nextKeyValue(globalObject, expectedKey, expectedValue)) { - if (expectedKey.isObject()) { + if (!isSpecialValue(expectedKey)) { gcBuffer.append(expectedKey); gcBuffer.append(expectedValue); queued.append({ expectedKey, expectedValue }); @@ -514,7 +523,7 @@ static bool mapSubset(JSC::JSGlobalObject* globalObject, JSC::MarkedArgumentBuff JSValue actualKey, actualValue; while (iter->nextKeyValue(globalObject, actualKey, actualValue)) { visited++; - if (actualKey.isObject()) { + if (!isSpecialValue(actualKey)) { Pairing pairing = pending.claimWith(scope, [&](const PendingMapEntry& entry) -> bool { bool keyEqual = compareBranch(globalObject, gcBuffer, cycles, scope, actualKey, entry.key); RETURN_IF_EXCEPTION(scope, false); @@ -535,10 +544,11 @@ static bool mapSubset(JSC::JSGlobalObject* globalObject, JSC::MarkedArgumentBuff } // Expected's members as a subset of actual's (node's setEquiv + partialObjectSetEquiv). A -// member actual holds by identity is settled by one lookup, and a primitive it does not hold -// can match nothing else. The remaining objects are matched with subset semantics -// (Set([{a:1,b:2}]) partially contains Set([{a:1}])) while actual is walked once; the actual -// members expected also holds were settled by the lookup and stay reserved for their twin. +// member actual holds by identity is settled by one lookup, and a special (non-object or +// callable) member it does not hold can match nothing else. The remaining objects are matched +// with subset semantics (Set([{a:1,b:2}]) partially contains Set([{a:1}])) while actual is +// walked once; the actual members expected also holds were settled by the lookup and stay +// reserved for their twin. static bool setSubset(JSC::JSGlobalObject* globalObject, JSC::MarkedArgumentBuffer& gcBuffer, CycleState& cycles, JSC::ThrowScope& scope, JSValue actual, JSValue expected) { auto& vm = globalObject->vm(); @@ -555,7 +565,7 @@ static bool setSubset(JSC::JSGlobalObject* globalObject, JSC::MarkedArgumentBuff RETURN_IF_EXCEPTION(scope, false); if (held) continue; - if (!expectedMember.isObject()) + if (isSpecialValue(expectedMember)) return false; gcBuffer.append(expectedMember); queued.append(expectedMember); @@ -571,10 +581,15 @@ static bool setSubset(JSC::JSGlobalObject* globalObject, JSC::MarkedArgumentBuff JSValue actualMember; while (iter->next(globalObject, actualMember)) { visited++; - if (actualMember.isObject()) { - bool reserved = expectedSet->has(globalObject, actualMember); - RETURN_IF_EXCEPTION(scope, false); - if (!reserved) { + bool reserved = expectedSet->has(globalObject, actualMember); + RETURN_IF_EXCEPTION(scope, false); + if (!reserved) { + if (isSpecialValue(actualMember)) { + // Node probes such a stray member too (unlike a stray Map key, which it passes + // over): every probe misses, and all a full miss leaves behind is the direction + // reset, which the pairing of the members after it depends on. + pending.probeFront = true; + } else { Pairing pairing = pending.claimWith(scope, [&](JSValue expectedMember) -> bool { return compareBranch(globalObject, gcBuffer, cycles, scope, actualMember, expectedMember); }); @@ -678,14 +693,6 @@ static bool setSubsetAndProps(JSC::JSGlobalObject* globalObject, JSC::MarkedArgu return objectSubset(globalObject, gcBuffer, cycles, scope, actual, expected); } -static bool isSpecialValue(JSValue value) -{ - // `typeof x !== "object"`: primitives, null, and callables are decided - // by full strict deep equality. Every specific type (Error, Date, RegExp, - // boxed primitives, ...) has already been handled by its own arm above. - return !value.isObject() || value.isCallable(); -} - static bool compareBranch(JSC::JSGlobalObject* globalObject, JSC::MarkedArgumentBuffer& gcBuffer, CycleState& cycles, JSC::ThrowScope& scope, JSValue actual, JSValue expected) { auto& vm = globalObject->vm(); diff --git a/test/js/node/assert/deep-equal.test.ts b/test/js/node/assert/deep-equal.test.ts index ff5903cacb19..a932ee9fa122 100644 --- a/test/js/node/assert/deep-equal.test.ts +++ b/test/js/node/assert/deep-equal.test.ts @@ -927,6 +927,15 @@ describe("assert.partialDeepStrictEqual on Sets and Maps", () => { true, ], ["Map: an object key when actual holds only primitive keys", map(["a", 1], ["b", 1]), map([{}, 1]), false], + ["Map: a function key both sides hold", map([fn, 1], ["k", 2]), map([fn, 1]), true], + ["Map: a function key both sides hold with a different value", map([fn, 1]), map([fn, 2]), false], + ["Map: a function key only expected holds", map([() => {}, 1], ["k", 1]), map([() => {}, 1]), false], + [ + "Map: a function key only expected holds, next to entries that would pair", + map([{ a: 1 }, 1], ["k", 1]), + map([{ a: 1 }, 1], [fn, 1]), + false, + ], [ "Map: nested collections as keys and values", map([map(["a", 1], ["b", 2]), [1, 2, 3]]), @@ -949,6 +958,42 @@ describe("assert.partialDeepStrictEqual on Sets and Maps", () => { } }); + // The pairing is greedy, and which pairing it finds depends on whether a member that can + // match nothing (a primitive or a function neither side shares) sits between the objects: + // node probes such a Set member, which sends the next member back to the front of the + // window, and skips such a Map key, which leaves the next entry probing the back. Bun follows + // node in both, so the same four objects pair off differently as Set members and as Map keys. + // After `fitsC` claims C off the back of [A, B, C], `fitsAB` is offered A (Set) or B (Map); + // whether the last member can take what is left decides the outcome. + describe("a member that matches nothing, between members that do", () => { + const A = { a: 1 }; + const B = { b: 2 }; + const C = { c: 3 }; + const fitsC = { c: 3, w: 1 }; + const fitsAB = { a: 1, b: 2 }; + const fitsB = { b: 2, y: 1 }; + const fitsA = { a: 1, y: 1 }; + const strays: [string, unknown][] = [ + ["a primitive", 7], + ["a function", () => {}], + ]; + + test.each(strays)("%s in a Set", (_, stray) => { + assert.partialDeepStrictEqual(set(fitsC, stray, fitsAB, fitsB), set(A, B, C)); + expect(() => assert.partialDeepStrictEqual(set(fitsC, stray, fitsAB, fitsA), set(A, B, C))).toThrow( + assert.AssertionError, + ); + }); + + test.each(strays)("%s as a Map key", (_, stray) => { + const expected = map([A, 1], [B, 1], [C, 1]); + assert.partialDeepStrictEqual(map([fitsC, 1], [stray, 1], [fitsAB, 1], [fitsA, 1]), expected); + expect(() => + assert.partialDeepStrictEqual(map([fitsC, 1], [stray, 1], [fitsAB, 1], [fitsB, 1]), expected), + ).toThrow(assert.AssertionError); + }); + }); + // Expected in a stride order, so neither the front nor the back guess fits and most members // are found by scanning the open window and swap-removed from the middle of it. test("a permuted expected side is paired off completely", () => { From d3000ddb9c209230da7f1ef00ba22beeba9f12b4 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 14 Aug 2026 16:31:14 +0000 Subject: [PATCH 3/5] partialDeepStrictEqual: shorten the Set/Map pairing comments --- src/jsc/modules/NodeUtilTypesModule.cpp | 33 ++++++------------------- 1 file changed, 7 insertions(+), 26 deletions(-) diff --git a/src/jsc/modules/NodeUtilTypesModule.cpp b/src/jsc/modules/NodeUtilTypesModule.cpp index da6aba271b19..1250abf122ac 100644 --- a/src/jsc/modules/NodeUtilTypesModule.cpp +++ b/src/jsc/modules/NodeUtilTypesModule.cpp @@ -393,9 +393,7 @@ static bool arraySubsequence(JSC::JSGlobalObject* globalObject, JSC::MarkedArgum return nonIndexObjectSubset(globalObject, gcBuffer, cycles, scope, actual, expected); } -// Node's `typeof x !== "object" || x === null`: primitives, null, and callables. Such a value -// never matches structurally; in compareBranch full strict deep equality decides it, and as a -// Set member or Map key only an identical counterpart can satisfy it. +// Node's `typeof x !== "object" || x === null`: such a value matches only an identical counterpart. static bool isSpecialValue(JSValue value) { return !value.isObject() || value.isCallable(); @@ -404,8 +402,7 @@ static bool isSpecialValue(JSValue value) enum class Pairing { Open, Complete }; -// The expected Set members / Map entries a hash lookup could not settle (copies; the caller -// rooted them in gcBuffer), claimed one by one while actual is walked once. +// Expected entries no lookup could settle; copies, kept alive by the caller's gcBuffer appends. template struct PendingExpected { using Queue = WTF::Vector; @@ -413,8 +410,7 @@ struct PendingExpected { Queue entries; size_t first { 0 }; size_t last; - // Front guesses keep hitting while actual arrives in expected's order, back guesses while - // it arrives reversed; only when both miss is the rest of the window scanned. + // Node's guess: keep probing the end that hit last, so same-order and reversed inputs stay linear. bool probeFront { true }; explicit PendingExpected(Queue&& queued) @@ -426,11 +422,7 @@ struct PendingExpected { size_t openCount() const { return last - first + 1; } - // One actual entry against the open window, in node's order (partialObjectSetEquiv / - // partialObjectMapEquiv, down to which entry is claimed when several would do): the front - // guess, the back guess, then the rest back to front. A claimed entry is swap-removed so it - // is never compared again; Complete means nothing is left to claim. `matches` may throw; - // callers RETURN_IF_EXCEPTION after this returns. + // Node's partialObject{Set,Map}Equiv probe order: front guess, back guess, then the rest back to front. template Pairing claimWith(JSC::ThrowScope& scope, const Matches& matches) { @@ -475,11 +467,7 @@ struct PendingMapEntry { JSValue value; }; -// Expected's entries as a subset of actual's (node's mapEquiv + partialObjectMapEquiv). A -// special (non-object or callable) key is settled by one lookup: actual must hold that key and -// the values must match, since no other entry can stand in for it. Object keys, identical ones -// included, are queued and matched structurally, key and value together, while actual's -// object-keyed entries are walked once; its other entries are passed over, as in node. +// Node's mapEquiv: special keys are settled by lookup; object keys, identical ones included, are paired off. static bool mapSubset(JSC::JSGlobalObject* globalObject, JSC::MarkedArgumentBuffer& gcBuffer, CycleState& cycles, JSC::ThrowScope& scope, JSValue actual, JSValue expected) { auto& vm = globalObject->vm(); @@ -543,12 +531,7 @@ static bool mapSubset(JSC::JSGlobalObject* globalObject, JSC::MarkedArgumentBuff return false; } -// Expected's members as a subset of actual's (node's setEquiv + partialObjectSetEquiv). A -// member actual holds by identity is settled by one lookup, and a special (non-object or -// callable) member it does not hold can match nothing else. The remaining objects are matched -// with subset semantics (Set([{a:1,b:2}]) partially contains Set([{a:1}])) while actual is -// walked once; the actual members expected also holds were settled by the lookup and stay -// reserved for their twin. +// Node's setEquiv: members actual holds are settled by lookup; the other objects are paired off partially. static bool setSubset(JSC::JSGlobalObject* globalObject, JSC::MarkedArgumentBuffer& gcBuffer, CycleState& cycles, JSC::ThrowScope& scope, JSValue actual, JSValue expected) { auto& vm = globalObject->vm(); @@ -585,9 +568,7 @@ static bool setSubset(JSC::JSGlobalObject* globalObject, JSC::MarkedArgumentBuff RETURN_IF_EXCEPTION(scope, false); if (!reserved) { if (isSpecialValue(actualMember)) { - // Node probes such a stray member too (unlike a stray Map key, which it passes - // over): every probe misses, and all a full miss leaves behind is the direction - // reset, which the pairing of the members after it depends on. + // Node probes a stray member too (unlike a stray Map key); all its misses leave behind is this. pending.probeFront = true; } else { Pairing pairing = pending.claimWith(scope, [&](JSValue expectedMember) -> bool { From a81f0382c61fc37dc3f13c9516a3f81be587b6bd Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 14 Aug 2026 20:54:00 +0000 Subject: [PATCH 4/5] partialDeepStrictEqual: settle Map keys both sides hold by identity, share the pairing window Object keys that both Maps hold went through the structural window like any other key, which made an identity-keyed Map quadratic when the two sides were built in different orders and, unlike every earlier Bun release, made its result depend on insertion order. Settle such keys by lookup in the first pass, as the Set path and node's own setEquiv do, and reserve their actual entries so the leftover keys cannot claim them. The window itself moves to PendingEntries.h so the strict deepEquals engine can use the same one: its result now says whether anything was claimed, an exhausted window reports zero open entries, and a stray member records its miss through a method instead of poking the flag. Tests: the two Map shapes where this differs from node, the reservation, a getter count showing shared keys are never compared structurally, and a GC test that empties the expected collection from inside a getter and reuses the freed cells, which fails (Set) or trips UBSan (Map) without the gcBuffer rooting of the pending copies. --- src/jsc/bindings/PendingEntries.h | 74 ++++++++++++++ src/jsc/modules/NodeUtilTypesModule.cpp | 128 ++++++++---------------- test/js/node/assert/deep-equal.test.ts | 92 ++++++++++++++++- 3 files changed, 204 insertions(+), 90 deletions(-) create mode 100644 src/jsc/bindings/PendingEntries.h diff --git a/src/jsc/bindings/PendingEntries.h b/src/jsc/bindings/PendingEntries.h new file mode 100644 index 000000000000..ae3bc5404d0c --- /dev/null +++ b/src/jsc/bindings/PendingEntries.h @@ -0,0 +1,74 @@ +#pragma once + +#include "root.h" +#include + +namespace Bun { + +enum class Claim : uint8_t { + Missed, // nothing claimed (also returned when `matches` threw; check the scope first) + Claimed, + Exhausted, // claimed the last open entry +}; + +// One side's entries still needing a counterpart, claimed one at a time while the other side is walked. Plain copies: the caller roots them. +template +struct PendingEntries { + using Queue = WTF::Vector; + + Queue entries; + size_t first { 0 }; + size_t end; + // Node's guess: keep probing the end that hit last, so same-order and reversed inputs stay linear. + bool probeFront { true }; + + explicit PendingEntries(Queue&& queued) + : entries(std::move(queued)) + , end(entries.size()) + { + ASSERT(end); + } + + size_t openCount() const { return end - first; } + + // What a walk leaves behind for an entry known to match nothing, without running the probes. + void recordMiss() { probeFront = true; } + + // Probe order of node's partialObject{Set,Map}Equiv: front guess, back guess, then the rest back to front. + template + Claim claimWith(JSC::ThrowScope& scope, const Matches& matches) + { + ASSERT(first < end); + size_t scanFrom = first; + if (probeFront) { + bool hit = matches(entries[first]); + RETURN_IF_EXCEPTION(scope, Claim::Missed); + if (hit) { + first++; + return first == end ? Claim::Exhausted : Claim::Claimed; + } + if (openCount() == 1) + return Claim::Missed; + probeFront = false; + scanFrom++; + } + size_t i = end - 1; + bool hit = matches(entries[i]); + RETURN_IF_EXCEPTION(scope, Claim::Missed); + if (!hit) { + probeFront = true; + while (!hit && i > scanFrom) { + i--; + hit = matches(entries[i]); + RETURN_IF_EXCEPTION(scope, Claim::Missed); + } + if (!hit) + return Claim::Missed; + entries[i] = entries[end - 1]; + } + end--; + return first == end ? Claim::Exhausted : Claim::Claimed; + } +}; + +} // namespace Bun diff --git a/src/jsc/modules/NodeUtilTypesModule.cpp b/src/jsc/modules/NodeUtilTypesModule.cpp index 1250abf122ac..b549da9c3561 100644 --- a/src/jsc/modules/NodeUtilTypesModule.cpp +++ b/src/jsc/modules/NodeUtilTypesModule.cpp @@ -34,6 +34,8 @@ #include "JSKeyObject.h" #include "NodeUtilTypesModule.h" +#include "PendingEntries.h" +#include using namespace JSC; @@ -399,120 +401,68 @@ static bool isSpecialValue(JSValue value) return !value.isObject() || value.isCallable(); } -enum class Pairing { Open, - Complete }; - -// Expected entries no lookup could settle; copies, kept alive by the caller's gcBuffer appends. -template -struct PendingExpected { - using Queue = WTF::Vector; - - Queue entries; - size_t first { 0 }; - size_t last; - // Node's guess: keep probing the end that hit last, so same-order and reversed inputs stay linear. - bool probeFront { true }; - - explicit PendingExpected(Queue&& queued) - : entries(std::move(queued)) - , last(entries.size() - 1) - { - ASSERT(!entries.isEmpty()); - } - - size_t openCount() const { return last - first + 1; } - - // Node's partialObject{Set,Map}Equiv probe order: front guess, back guess, then the rest back to front. - template - Pairing claimWith(JSC::ThrowScope& scope, const Matches& matches) - { - size_t scanFrom = first; - if (probeFront) { - bool hit = matches(entries[first]); - RETURN_IF_EXCEPTION(scope, Pairing::Open); - if (hit) { - if (first == last) - return Pairing::Complete; - first++; - return Pairing::Open; - } - if (first == last) - return Pairing::Open; - probeFront = false; - scanFrom++; - } - bool hit = matches(entries[last]); - RETURN_IF_EXCEPTION(scope, Pairing::Open); - if (!hit) { - probeFront = true; - size_t i = last; - while (!hit && i > scanFrom) { - i--; - hit = matches(entries[i]); - RETURN_IF_EXCEPTION(scope, Pairing::Open); - } - if (!hit) - return Pairing::Open; - entries[i] = entries[last]; - } - if (first == last) - return Pairing::Complete; - last--; - return Pairing::Open; - } -}; - struct PendingMapEntry { JSValue key; JSValue value; }; -// Node's mapEquiv: special keys are settled by lookup; object keys, identical ones included, are paired off. +// Every key actual holds is settled by lookup plus value comparison; the object keys it does not hold are paired off. static bool mapSubset(JSC::JSGlobalObject* globalObject, JSC::MarkedArgumentBuffer& gcBuffer, CycleState& cycles, JSC::ThrowScope& scope, JSValue actual, JSValue expected) { auto& vm = globalObject->vm(); JSC::JSMap* actualMap = uncheckedDowncast(actual.asCell()); JSC::JSMap* expectedMap = uncheckedDowncast(expected.asCell()); - PendingExpected::Queue queued; + Bun::PendingEntries::Queue queued; + WTF::Vector settledKeys; { auto iter = JSC::JSMapIterator::create(vm, globalObject->mapIteratorStructure(), expectedMap, JSC::IterationKind::Entries); RETURN_IF_EXCEPTION(scope, false); JSValue expectedKey, expectedValue; while (iter->nextKeyValue(globalObject, expectedKey, expectedValue)) { - if (!isSpecialValue(expectedKey)) { - gcBuffer.append(expectedKey); - gcBuffer.append(expectedValue); - queued.append({ expectedKey, expectedValue }); - continue; - } JSValue actualValue = actualMap->get(globalObject, expectedKey); RETURN_IF_EXCEPTION(scope, false); - if (actualValue.isUndefined()) { + bool settled = !actualValue.isUndefined(); + if (!settled) { // get() answers undefined both for a missing key and for a key holding undefined. - bool held = actualMap->has(globalObject, expectedKey); + settled = actualMap->has(globalObject, expectedKey); + RETURN_IF_EXCEPTION(scope, false); + } + if (settled) { + settled = compareBranch(globalObject, gcBuffer, cycles, scope, actualValue, expectedValue); RETURN_IF_EXCEPTION(scope, false); - if (!held) + } + if (isSpecialValue(expectedKey)) { + if (!settled) return false; + continue; } - bool equal = compareBranch(globalObject, gcBuffer, cycles, scope, actualValue, expectedValue); - RETURN_IF_EXCEPTION(scope, false); - if (!equal) - return false; + gcBuffer.append(expectedKey); + if (settled) { + // Node queues identical keys too (comparisons.js v26.3.0 L882-L891): order-dependent, and quadratic once reordered. + settledKeys.append(expectedKey.asCell()); + continue; + } + gcBuffer.append(expectedValue); + queued.append({ expectedKey, expectedValue }); } } if (queued.isEmpty()) return true; - PendingExpected pending(std::move(queued)); + // As node's setEquiv does for members: a settled key's actual entry is spoken for. + WTF::HashSet reserved; + for (JSC::JSCell* key : settledKeys) + reserved.add(key); + Bun::PendingEntries pending(std::move(queued)); auto iter = JSC::JSMapIterator::create(vm, globalObject->mapIteratorStructure(), actualMap, JSC::IterationKind::Entries); RETURN_IF_EXCEPTION(scope, false); size_t visited = 0; JSValue actualKey, actualValue; while (iter->nextKeyValue(globalObject, actualKey, actualValue)) { visited++; - if (!isSpecialValue(actualKey)) { - Pairing pairing = pending.claimWith(scope, [&](const PendingMapEntry& entry) -> bool { + if (!isSpecialValue(actualKey) && !reserved.contains(actualKey.asCell())) { + Bun::Claim claim = pending.claimWith(scope, [&](const PendingMapEntry& entry) -> bool { bool keyEqual = compareBranch(globalObject, gcBuffer, cycles, scope, actualKey, entry.key); RETURN_IF_EXCEPTION(scope, false); if (!keyEqual) @@ -520,7 +470,7 @@ static bool mapSubset(JSC::JSGlobalObject* globalObject, JSC::MarkedArgumentBuff return compareBranch(globalObject, gcBuffer, cycles, scope, actualValue, entry.value); }); RETURN_IF_EXCEPTION(scope, false); - if (pairing == Pairing::Complete) + if (claim == Bun::Claim::Exhausted) return true; } const size_t size = actualMap->size(); @@ -531,14 +481,14 @@ static bool mapSubset(JSC::JSGlobalObject* globalObject, JSC::MarkedArgumentBuff return false; } -// Node's setEquiv: members actual holds are settled by lookup; the other objects are paired off partially. +// Node's setEquiv (comparisons.js v26.3.0 L628-L775): members actual holds are settled by lookup, the rest paired off. static bool setSubset(JSC::JSGlobalObject* globalObject, JSC::MarkedArgumentBuffer& gcBuffer, CycleState& cycles, JSC::ThrowScope& scope, JSValue actual, JSValue expected) { auto& vm = globalObject->vm(); JSC::JSSet* actualSet = uncheckedDowncast(actual.asCell()); JSC::JSSet* expectedSet = uncheckedDowncast(expected.asCell()); - PendingExpected::Queue queued; + Bun::PendingEntries::Queue queued; { auto iter = JSC::JSSetIterator::create(vm, globalObject->setIteratorStructure(), expectedSet, JSC::IterationKind::Keys); RETURN_IF_EXCEPTION(scope, false); @@ -557,7 +507,7 @@ static bool setSubset(JSC::JSGlobalObject* globalObject, JSC::MarkedArgumentBuff if (queued.isEmpty()) return true; - PendingExpected pending(std::move(queued)); + Bun::PendingEntries pending(std::move(queued)); auto iter = JSC::JSSetIterator::create(vm, globalObject->setIteratorStructure(), actualSet, JSC::IterationKind::Keys); RETURN_IF_EXCEPTION(scope, false); size_t visited = 0; @@ -568,14 +518,14 @@ static bool setSubset(JSC::JSGlobalObject* globalObject, JSC::MarkedArgumentBuff RETURN_IF_EXCEPTION(scope, false); if (!reserved) { if (isSpecialValue(actualMember)) { - // Node probes a stray member too (unlike a stray Map key); all its misses leave behind is this. - pending.probeFront = true; + // Node probes a stray member too (unlike a stray Map key, which it passes over). + pending.recordMiss(); } else { - Pairing pairing = pending.claimWith(scope, [&](JSValue expectedMember) -> bool { + Bun::Claim claim = pending.claimWith(scope, [&](JSValue expectedMember) -> bool { return compareBranch(globalObject, gcBuffer, cycles, scope, actualMember, expectedMember); }); RETURN_IF_EXCEPTION(scope, false); - if (pairing == Pairing::Complete) + if (claim == Bun::Claim::Exhausted) return true; } } diff --git a/test/js/node/assert/deep-equal.test.ts b/test/js/node/assert/deep-equal.test.ts index a932ee9fa122..3a55a245d785 100644 --- a/test/js/node/assert/deep-equal.test.ts +++ b/test/js/node/assert/deep-equal.test.ts @@ -848,12 +848,19 @@ describe("detached ArrayBuffer", () => { // actual has three or more members): whatever a hash lookup can settle is settled by one // lookup, and only the expected objects left over are matched structurally, each claiming an // actual entry of its own, while actual is walked once. Every expectation below was -// cross-checked against node v26. +// cross-checked against node v26, except the two Map cases that say otherwise: node pairs off +// object keys that both Maps hold structurally like any other, which makes the outcome depend on +// insertion order; Bun settles them by identity, as node itself does for Set members and as Bun +// always has. describe("assert.partialDeepStrictEqual on Sets and Maps", () => { const set = (...members: unknown[]) => new Set(members); const map = (...entries: [unknown, unknown][]) => new Map(entries); const twin = { a: 1, b: 2 }; const fn = () => {}; + // Keys both Maps hold: token1/token2 are structurally interchangeable, shared is contained in {k:1,m:1}. + const token1 = {}; + const token2 = {}; + const shared = { k: 1 }; // [description, actual, expected, whether expected is partially contained in actual] const cases: [string, unknown, unknown, boolean][] = [ ["Set: a member both sides hold is paired with itself", set(twin, { a: 1, c: 3 }, 1), set({ a: 1 }, twin), true], @@ -920,6 +927,29 @@ describe("assert.partialDeepStrictEqual on Sets and Maps", () => { true, ], ["Map: a key both sides hold with a different value", map([twin, 1], [{ a: 1 }, 2]), map([twin, 2]), false], + [ + // Node rejects this: walking actual in order, token1's entry claims token2's structurally + // identical expected entry, and {a:1} then does not contain {a:1,b:1}. + "Map: entries both sides hold, in another order (node: rejected)", + map([token1, { a: 1, b: 1 }], [token2, { a: 1 }]), + map([token2, { a: 1 }], [token1, { a: 1, b: 1 }]), + true, + ], + [ + // Node accepts this by handing shared's expected entry to the {k:1,m:1} key (whose value + // contains {x:1}) and then matching {k:1} against shared's actual entry. Here shared's + // entries are settled with each other first, so {k:1} -> {y:2} has to fit {k:1,m:1} -> {x:1}. + "Map: a key both sides hold is settled with itself even when another pairing would work (node: accepted)", + map([{ k: 1, m: 1 }, { x: 1 }], [shared, { x: 1, y: 2 }]), + map([shared, { x: 1 }], [{ k: 1 }, { y: 2 }]), + false, + ], + [ + "Map: a key both sides hold cannot also stand in for another entry", + map([shared, 3], [{ q: 1 }, 3]), + map([shared, 3], [{ k: 1 }, 3]), + false, + ], [ "Map: object and primitive keys in another order", map(["p", 0], [{ k: 1 }, 1], [{ k: 2 }, 2]), @@ -1043,6 +1073,52 @@ describe("assert.partialDeepStrictEqual on Sets and Maps", () => { ); }); + // The expected objects still waiting for a counterpart are held as plain copies while user code + // runs. Here a getter on the first actual member probed deletes every entry from the expected + // collection (entry by entry: clear() leaves the old table, and the objects in it, reachable + // from iterators), collects garbage and allocates look-alikes into the freed cells; the rest of + // the pairing then reads every pending object, so they have to have been kept alive by the + // comparison itself. There are enough of them that the copies live on the heap, out of reach of + // the conservative stack scan. (Bun has always compared the entries as they were when the + // comparison started; node re-reads Map values while pairing and so rejects the Map case.) + describe("keeps the pending expected entries alive across a GC", () => { + const n = 64; + function firstActual(expected: Set | Map) { + let probed = false; + return { + get id() { + if (!probed) { + probed = true; + for (const entry of expected.keys()) expected.delete(entry); + Bun.gc(true); + const lookAlikes: object[] = []; + for (let i = 0; i < 4 * n; i++) lookAlikes.push({ id: -1 }); + } + return 0; + }, + }; + } + const others = () => Array.from({ length: n - 1 }, (_, i) => ({ id: i + 1 })); + const fresh = () => Array.from({ length: n }, (_, i) => ({ id: i })); + + test("Set", () => { + const expected = new Set(fresh()); + const actual = new Set([firstActual(expected), ...others()]); + assert.partialDeepStrictEqual(actual, expected); + expect(expected.size).toBe(0); + }); + + test("Map", () => { + const expected = new Map(fresh().map(key => [key, { v: key.id }])); + const actual = new Map([ + [firstActual(expected), { v: 0, extra: true }], + ...others().map(key => [key, { v: key.id, extra: true }] as [object, object]), + ]); + assert.partialDeepStrictEqual(actual, expected); + expect(expected.size).toBe(0); + }); + }); + // Each actual member is compared against one or two expected members: the front guess keeps // hitting while the sides were built in the same order, the back guess while they were built // in opposite orders, so the getters are read 2n times (2n + 2 reversed). Rescanning every @@ -1082,6 +1158,20 @@ describe("assert.partialDeepStrictEqual on Sets and Maps", () => { assert.partialDeepStrictEqual(actual, expected); expect(reads).toBeLessThanOrEqual(4 * n); }); + + // Members and keys both sides hold are settled by lookup, so their contents are never read, + // in whatever order the sides were built. + test.each(["Set", "Map"])("%s contents both sides hold, shuffled", kind => { + let reads = 0; + const keys = members(() => reads++); + // A fixed stride permutation, so neither the same-order nor the reversed-order guess fits. + const shuffled = keys.map((_, i) => keys[(i * 37) % n]); + const position = new Map(keys.map((key, i) => [key, i])); + const actual = kind === "Set" ? new Set(keys) : new Map(keys.map(key => [key, position.get(key)])); + const expected = kind === "Set" ? new Set(shuffled) : new Map(shuffled.map(key => [key, position.get(key)])); + assert.partialDeepStrictEqual(actual, expected); + expect(reads).toBe(0); + }); }); // Primitive members and primitive keys are settled by hash lookups, which nothing can From 235f97c1ed9bb92b51ac27f61520026077f347ef Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 14 Aug 2026 22:09:23 +0000 Subject: [PATCH 5/5] ci: retrigger