Backtestsvuerun-20261001-022054#15496
looseEqual: comparing Map/Set values with circular references throws RangeError (regression in 3.5.42)
Our patch was judged better than the merged fix.
In this judgment, Patch A = our agent, Patch B = the merged fix.
Both patches fix the root cause. Each threads a recursion-stack 'seen' structure through array, Map/Set, and plain-object comparison, and removes entries after each comparison. That removal keeps failed trial matches in looseCompareCollections from leaking into later comparisons. Both handle the issue's three repro cases: mutually-referencing Sets, Maps holding cyclic values, and self-containing Sets.
The difference is cycle semantics. Patch A tracks in-progress (a, b) pairs and assumes a re-encountered pair is equal. This is the standard coinductive approach the issue suggests ('tracking visited pairs … returning true on re-encounter'), and it gives true for structures that unroll identically. Patch B enforces a strict on-stack bijection: if either side was seen paired with a different partner, it returns false. That produces false negatives for structurally indistinguishable graphs. A self-loop node compared with a 2-cycle is one example, and Patch B's own test asserts false for it. Another is X.child = X versus Y.child = Y', Y'.child = Y'. For a 'loose' equality used by v-model, this is a more surprising rule than the issue asked for.
Patch B also widens the public `looseEqual` signature with an optional third `seen` parameter. If looseEqual is ever passed directly as a callback, such as to an array method, an unrelated third argument would be misread as state. Patch A keeps the public signature unchanged and uses an internal `looseEqualImpl`, which is safer.
On tests, Patch A is more thorough. It adds a component-level vModel test matching the issue's `<select v-model>` scenario. Its unit tests cover Sets and Maps of mutually-referencing objects (both equal and unequal cases), self-containing Sets and Maps, and cyclic plain objects. It also explicitly checks that failed trial matches don't leak into later comparisons. Patch B's tests are fewer and include only one negative cyclic case.
On craft, both are similar. Patch A's helper comment clearly explains why entries are removed after each comparison. Overall, Patch A is the better fix.
The judge saw only the two patches, labelled A and B in random order, with issue links and version numbers removed. The reasoning above is shown verbatim.
Solve
3m 42s14 turns
Wall-clock time in the container
Full test suite
No new failures
3,743 passed · 6 skipped · 3,749 total
Contamination audit
Clean
No sign the agent saw the real fix
Patch size
210vs 138 merged
Changed lines, ours vs merged
The issue
View on GitHubVue version
3.5.42 (also reproduced on current main, commit 5409708)
Link to minimal reproduction
Steps to reproduce
Open the reproduction above: a <select v-model> whose option :values are Sets containing mutually-referencing objects. The component throws during mount, before any interaction.
<script setup>
import { ref } from 'vue'
const makeGraph = () => {
const n1 = { id: 1 }
const n2 = { id: 2 }
n1.peer = n2
n2.peer = n1 // circular reference
return new Set([n1, n2])
}
const optA = makeGraph()
const optB = makeGraph()
const selected = ref(optB)
</script>
<template>
<select v-model="selected">
<option :value="optA">A</option>
<option :value="optB">B</option>
</select>
</template>
What is expected?
Mounting the select should not throw. looseEqual should safely terminate on cyclic structures (e.g. by tracking already-visited pairs) and return true for two structurally identical cyclic Sets/Maps.
What is actually happening?
Mounting throws RangeError: Maximum call stack size exceeded:
RangeError: Maximum call stack size exceeded
at looseCompareCollections (packages/shared/src/looseEqual.ts:16)
at looseEqual (packages/shared/src/looseEqual.ts:64)
at looseCompareCollections (packages/shared/src/looseEqual.ts:22)
at looseEqual (packages/shared/src/looseEqual.ts:64)
...
[Vue warn]: Unhandled error during execution of directive hook
System Info
Reproduced locally with vuejs/core@main (5409708) via vitest: both the unit-level looseEqual calls and the component-level render path (same shape as the test added in #15328) throw RangeError.
Any additional comments?
This is a regression introduced by #15328 ("fix(shared): correctly compare Map and Set values", released in v3.5.42), which added looseCompareCollections in packages/shared/src/looseEqual.ts:
function looseCompareCollections(
a: Map<any, any> | Set<any>,
b: Map<any, any> | Set<any>,
) {
if (a.size !== b.size) return false
const candidates = Array.from(b)
const matched = new Uint8Array(candidates.length)
for (const item of a) {
let index = -1
for (let i = 0; i < candidates.length; i++) {
if (!matched[i] && looseEqual(item, candidates[i])) {
index = i
break
}
}
if (index < 0) return false
matched[index] = 1
}
return true
}
looseEqual(item, candidates[i]) recurses into each [key, value] pair (Map) or element (Set), so a Map/Set whose entries point back to the collection itself or to each other causes unbounded recursion. Before 3.5.42, Maps/Sets never recursed into their entries (they fell through to String() comparison), so this exact code path — a <select v-model> with Map/Set values, which is precisely the scenario #15320/#15328 added support for — did not throw on 3.5.41; it silently compared wrong, which #15328 fixed.
Note: #5318 covers the same root cause for cyclic plain objects (pre-existing, still open). The Map/Set case is new in 3.5.42: cyclic Maps/Sets did not throw before.
Suggested fix: make looseEqual cycle-safe by tracking visited (a, b) pairs (e.g. with a WeakMap<object, Set<object>> and returning true on re-encounter), which also fixes #5318.
Additional local repro cases that all throw RangeError on current main:
looseEqual(new Set([a1, a2]), new Set([b1, b2]))wherea1.peer = a2; a2.peer = a1andb1.peer = b2; b2.peer = b1looseEqual(mapA, mapB)where both maps hold mutually-referencing valueslooseEqual(s1, s2)wheres1.add(s1)ands2.add(s2)
The two patches
packages/runtime-dom/__tests__/directives/vModel.spec.tsindex a94cb8e0d..f30132a21 100644@@ -1902,4 +1902,41 @@ describe('vModel', () => { expect(root.querySelector('select').selectedIndex).toBe(1) })++ it('selects the matching option when values are cyclic sets', () => {+ const makeGraph = (idOffset = 0) => {+ const n1: any = { id: 1 + idOffset }+ const n2: any = { id: 2 + idOffset }+ n1.peer = n2+ n2.peer = n1+ return new Set([n1, n2])+ }+ const renderSelect = (optA: Set<any>, optB: Set<any>) => {+ const value = ref(optB)+ const component = defineComponent(+ () => () =>+ withVModel(+ h(+ 'select',+ {+ 'onUpdate:modelValue': (val: Set<any>) => (value.value = val),+ },+ [+ h('option', { value: optA }, 'A'),+ h('option', { value: optB }, 'B'),+ ],+ ),+ value.value,+ ),+ )+ expect(() => render(h(component), root)).not.toThrow()+ return root.querySelector('select').selectedIndex+ }++ // loosely equal graphs: the first matching option wins+ expect(renderSelect(makeGraph(), makeGraph())).toBe(0)+ render(null, root)+ // differing graphs: only the bound option matches+ expect(renderSelect(makeGraph(10), makeGraph())).toBe(1)+ }) })packages/shared/__tests__/looseEqual.spec.tsindex 777f3cfad..62596048c 100644@@ -288,4 +288,96 @@ describe('utils/looseEqual', () => { expect(looseEqual(new Set<any>([1, '1']), new Set<any>([1, 2]))).toBe(false) expect(looseEqual(new Set(), new Map())).toBe(false) })++ test('compares circular structures without infinite recursion', () => {+ const makePair = (id1: number, id2: number) => {+ const n1: any = { id: id1 }+ const n2: any = { id: id2 }+ n1.peer = n2+ n2.peer = n1+ return [n1, n2]+ }+ const [a1, a2] = makePair(1, 2)+ const [b1, b2] = makePair(1, 2)+ const [c1, c2] = makePair(1, 3)++ // Sets of mutually-referencing objects+ expect(looseEqual(new Set([a1, a2]), new Set([b1, b2]))).toBe(true)+ expect(looseEqual(new Set([a1, a2]), new Set([c1, c2]))).toBe(false)++ // Maps holding mutually-referencing values+ expect(+ looseEqual(+ new Map([+ ['x', a1],+ ['y', a2],+ ]),+ new Map([+ ['x', b1],+ ['y', b2],+ ]),+ ),+ ).toBe(true)+ expect(+ looseEqual(+ new Map([+ ['x', a1],+ ['y', a2],+ ]),+ new Map([+ ['x', c1],+ ['y', c2],+ ]),+ ),+ ).toBe(false)++ // Self-containing sets and maps+ const s1 = new Set<any>()+ const s2 = new Set<any>()+ s1.add(s1)+ s2.add(s2)+ expect(looseEqual(s1, s2)).toBe(true)+ const m1 = new Map<any, any>()+ const m2 = new Map<any, any>()+ m1.set('self', m1)+ m2.set('self', m2)+ expect(looseEqual(m1, m2)).toBe(true)++ // Cyclic plain objects (#5318)+ const o1: any = { a: 1 }+ const o2: any = { a: 1 }+ const o3: any = { a: 2 }+ o1.self = o1+ o2.self = o2+ o3.self = o3+ expect(looseEqual(o1, o2)).toBe(true)+ expect(looseEqual(o1, o3)).toBe(false)+ expect(looseEqual(a1, b1)).toBe(true)+ expect(looseEqual(a1, c1)).toBe(false)++ // failed trial matches inside collections must not leak into later+ // comparisons (the cycle is reached before the differing id)+ const makeSelfRef = (id: number) => {+ const n: any = {}+ n.self = n+ n.id = id+ return n+ }+ const [x1, x2, x3] = [1, 2, 3].map(makeSelfRef)+ const [y1, y2, y3] = [1, 2, 3].map(makeSelfRef)+ expect(looseEqual(new Set([x1, x2, x3]), new Set([y3, y2, y1]))).toBe(true)+ expect(+ looseEqual(new Set([x1, x2, x3]), new Set([y2, y3, makeSelfRef(4)])),+ ).toBe(false)+ // (x1, y2) fails as a trial match inside the set, then is compared again+ expect(looseEqual([new Set([x1, x2]), x1], [new Set([y2, y1]), y2])).toBe(+ false,+ )+ const [p1, p2] = makePair(1, 2)+ const [q1, q2] = makePair(1, 2)+ const [r1, r2] = makePair(2, 1)+ expect(looseEqual(new Set([p2, p1]), new Set([q1, q2]))).toBe(true)+ expect(looseEqual(new Set([p1, p2]), new Set([r1, r2]))).toBe(true)+ expect(looseEqual(new Set([p1, p2]), new Set([r1, c2]))).toBe(false)+ }) })packages/shared/src/looseEqual.tsindex d037b0a57..88790e79e 100644@@ -1,10 +1,12 @@ import { isArray, isDate, isMap, isObject, isSet, isSymbol } from './general' -function looseCompareArrays(a: any[], b: any[]) {+type Seen = Map<object, Set<object>>++function looseCompareArrays(a: any[], b: any[], seen: Seen) { if (a.length !== b.length) return false let equal = true for (let i = 0; equal && i < a.length; i++) {- equal = looseEqual(a[i], b[i])+ equal = looseEqualImpl(a[i], b[i], seen) } return equal }@@ -12,6 +14,7 @@ function looseCompareArrays(a: any[], b: any[]) { function looseCompareCollections( a: Map<any, any> | Set<any>, b: Map<any, any> | Set<any>,+ seen: Seen, ) { if (a.size !== b.size) return false const candidates = Array.from(b)@@ -19,7 +22,7 @@ function looseCompareCollections( for (const item of a) { let index = -1 for (let i = 0; i < candidates.length; i++) {- if (!matched[i] && looseEqual(item, candidates[i])) {+ if (!matched[i] && looseEqualImpl(item, candidates[i], seen)) { index = i break }@@ -30,7 +33,52 @@ function looseCompareCollections( return true } +function looseCompareObjects(a: any, b: any, seen: Seen) {+ if (Object.keys(a).length !== Object.keys(b).length) {+ return false+ }+ for (const key in a) {+ const aHasKey = a.hasOwnProperty(key)+ const bHasKey = b.hasOwnProperty(key)+ if (+ (aHasKey && !bHasKey) ||+ (!aHasKey && bHasKey) ||+ !looseEqualImpl(a[key], b[key], seen)+ ) {+ return false+ }+ }+ return true+}++// Tracks the (a, b) pairs currently being compared on the recursion stack so+// that cyclic structures are assumed equal on re-entry instead of recursing+// forever. The pair is removed afterwards so that a failed trial match (e.g. in+// looseCompareCollections) cannot affect later comparisons of the same pair.+function compareGuarded<T>(+ a: T,+ b: T,+ seen: Seen | undefined,+ compare: (a: T, b: T, seen: Seen) => boolean,+): boolean {+ if (!seen) seen = new Map()+ let inProgress = seen.get(a as object)+ if (!inProgress) {+ seen.set(a as object, (inProgress = new Set()))+ } else if (inProgress.has(b as object)) {+ return true+ }+ inProgress.add(b as object)+ const result = compare(a, b, seen)+ inProgress.delete(b as object)+ return result+}+ export function looseEqual(a: any, b: any): boolean {+ return looseEqualImpl(a, b)+}++function looseEqualImpl(a: any, b: any, seen?: Seen): boolean { if (a === b) return true let aValidType = isDate(a) let bValidType = isDate(b)@@ -45,7 +93,9 @@ export function looseEqual(a: any, b: any): boolean { aValidType = isArray(a) bValidType = isArray(b) if (aValidType || bValidType) {- return aValidType && bValidType ? looseCompareArrays(a, b) : false+ return aValidType && bValidType+ ? compareGuarded(a, b, seen, looseCompareArrays)+ : false } aValidType = isObject(a) bValidType = isObject(b)@@ -56,29 +106,20 @@ export function looseEqual(a: any, b: any): boolean { aValidType = isMap(a) bValidType = isMap(b) if (aValidType || bValidType) {- return aValidType && bValidType ? looseCompareCollections(a, b) : false+ return aValidType && bValidType+ ? compareGuarded(a, b, seen, looseCompareCollections)+ : false } aValidType = isSet(a) bValidType = isSet(b) if (aValidType || bValidType) {- return aValidType && bValidType ? looseCompareCollections(a, b) : false+ return aValidType && bValidType+ ? compareGuarded(a, b, seen, looseCompareCollections)+ : false }- const aKeysCount = Object.keys(a).length- const bKeysCount = Object.keys(b).length- if (aKeysCount !== bKeysCount) {+ if (!compareGuarded(a, b, seen, looseCompareObjects)) { return false }- for (const key in a) {- const aHasKey = a.hasOwnProperty(key)- const bHasKey = b.hasOwnProperty(key)- if (- (aHasKey && !bHasKey) ||- (!aHasKey && bHasKey) ||- !looseEqual(a[key], b[key])- ) {- return false- }- } } return String(a) === String(b) }
packages/shared/__tests__/looseEqual.spec.tsindex 777f3cfad..bc1bc3acd 100644@@ -288,4 +288,45 @@ describe('utils/looseEqual', () => { expect(looseEqual(new Set<any>([1, '1']), new Set<any>([1, 2]))).toBe(false) expect(looseEqual(new Set(), new Map())).toBe(false) })++ test('compares circular references correctly', () => {+ const makeGraph = () => {+ const n1: any = { id: 1 }+ const n2: any = { id: 2 }+ n1.peer = n2+ n2.peer = n1+ return [n1, n2]+ }++ expect(looseEqual(new Set(makeGraph()), new Set(makeGraph()))).toBe(true)+ expect(+ looseEqual(new Map([['a', makeGraph()]]), new Map([['a', makeGraph()]])),+ ).toBe(true)+ expect(looseEqual(makeGraph(), makeGraph())).toBe(true)+ expect(looseEqual({ n: makeGraph() }, { n: makeGraph() })).toBe(true)++ const selfSet = new Set<any>()+ selfSet.add(selfSet)+ const otherSelfSet = new Set<any>()+ otherSelfSet.add(otherSelfSet)+ expect(looseEqual(selfSet, otherSelfSet)).toBe(true)+ expect(looseEqual(selfSet, new Set([new Set()]))).toBe(false)++ const shared = { id: 1 }+ expect(+ looseEqual({ a: shared, b: shared }, { a: { id: 1 }, b: { id: 1 } }),+ ).toBe(true)+ })++ test('compares circular references symmetrically', () => {+ const self: any = {}+ self.next = self+ const first: any = {}+ const second: any = {}+ first.next = second+ second.next = first++ expect(looseEqual(self, first)).toBe(false)+ expect(looseEqual(first, self)).toBe(false)+ }) })packages/shared/src/looseEqual.tsindex d037b0a57..7e3e7f44e 100644@@ -1,10 +1,12 @@ import { isArray, isDate, isMap, isObject, isSet, isSymbol } from './general' -function looseCompareArrays(a: any[], b: any[]) {+type ComparisonState = [Map<any, any>, Map<any, any>]++function looseCompareArrays(a: any[], b: any[], seen: ComparisonState) { if (a.length !== b.length) return false let equal = true for (let i = 0; equal && i < a.length; i++) {- equal = looseEqual(a[i], b[i])+ equal = looseEqual(a[i], b[i], seen) } return equal }@@ -12,6 +14,7 @@ function looseCompareArrays(a: any[], b: any[]) { function looseCompareCollections( a: Map<any, any> | Set<any>, b: Map<any, any> | Set<any>,+ seen: ComparisonState, ) { if (a.size !== b.size) return false const candidates = Array.from(b)@@ -19,7 +22,7 @@ function looseCompareCollections( for (const item of a) { let index = -1 for (let i = 0; i < candidates.length; i++) {- if (!matched[i] && looseEqual(item, candidates[i])) {+ if (!matched[i] && looseEqual(item, candidates[i], seen)) { index = i break }@@ -30,7 +33,62 @@ function looseCompareCollections( return true } -export function looseEqual(a: any, b: any): boolean {+function looseCompareObjects(a: any, b: any, seen: ComparisonState) {+ let aValidType = isMap(a)+ let bValidType = isMap(b)+ if (aValidType || bValidType) {+ return aValidType && bValidType+ ? looseCompareCollections(a, b, seen)+ : false+ }+ aValidType = isSet(a)+ bValidType = isSet(b)+ if (aValidType || bValidType) {+ return aValidType && bValidType+ ? looseCompareCollections(a, b, seen)+ : false+ }+ const aKeysCount = Object.keys(a).length+ const bKeysCount = Object.keys(b).length+ if (aKeysCount !== bKeysCount) {+ return false+ }+ for (const key in a) {+ const aHasKey = a.hasOwnProperty(key)+ const bHasKey = b.hasOwnProperty(key)+ if (+ (aHasKey && !bHasKey) ||+ (!aHasKey && bHasKey) ||+ !looseEqual(a[key], b[key], seen)+ ) {+ return false+ }+ }+ return String(a) === String(b)+}++function looseCompareNested(+ a: any,+ b: any,+ seen: ComparisonState | undefined,+ compare: (a: any, b: any, seen: ComparisonState) => boolean,+) {+ if (!seen) {+ seen = [new Map(), new Map()]+ }+ const [seenA, seenB] = seen+ if (seenA.has(a) || seenB.has(b)) {+ return seenA.get(a) === b && seenB.get(b) === a+ }+ seenA.set(a, b)+ seenB.set(b, a)+ const equal = compare(a, b, seen)+ seenA.delete(a)+ seenB.delete(b)+ return equal+}++export function looseEqual(a: any, b: any, seen?: ComparisonState): boolean { if (a === b) return true let aValidType = isDate(a) let bValidType = isDate(b)@@ -45,7 +103,9 @@ export function looseEqual(a: any, b: any): boolean { aValidType = isArray(a) bValidType = isArray(b) if (aValidType || bValidType) {- return aValidType && bValidType ? looseCompareArrays(a, b) : false+ return aValidType && bValidType+ ? looseCompareNested(a, b, seen, looseCompareArrays)+ : false } aValidType = isObject(a) bValidType = isObject(b)@@ -53,32 +113,7 @@ export function looseEqual(a: any, b: any): boolean { if (!aValidType || !bValidType) { return false }- aValidType = isMap(a)- bValidType = isMap(b)- if (aValidType || bValidType) {- return aValidType && bValidType ? looseCompareCollections(a, b) : false- }- aValidType = isSet(a)- bValidType = isSet(b)- if (aValidType || bValidType) {- return aValidType && bValidType ? looseCompareCollections(a, b) : false- }- const aKeysCount = Object.keys(a).length- const bKeysCount = Object.keys(b).length- if (aKeysCount !== bKeysCount) {- return false- }- for (const key in a) {- const aHasKey = a.hasOwnProperty(key)- const bHasKey = b.hasOwnProperty(key)- if (- (aHasKey && !bHasKey) ||- (!aHasKey && bHasKey) ||- !looseEqual(a[key], b[key])- ) {- return false- }- }+ return looseCompareNested(a, b, seen, looseCompareObjects) } return String(a) === String(b) }
What the agent reported
looseEqual no longer recurses forever on cyclic data. The <select v-model> from the report now mounts without the RangeError, and the targeted tests pass (112/112).
What was wrong: #15328 added looseCompareCollections, which calls looseEqual on every Map entry and Set element. Nothing tracked what had already been compared. So once the values pointed back at each other or at the collection itself, the recursion never ended. Cyclic plain objects (#5318) had the same problem from before 3.5.42.
What I changed (packages/shared/src/looseEqual.ts only):
looseEqual(a, b)keeps its public signature. It now calls an internallooseEqualImpl(a, b, seen?), whereseenrecords which(a, b)pairs are currently being compared.- A new helper,
compareGuarded, wraps every array, Map, Set and plain-object comparison. If the same pair comes up again while it is still being compared, it is treated as equal. Otherwise the pair is recorded, compared, and then removed. - Removing the pair matters: when a Set or Map tries an element against a candidate and the match fails, a leftover record would make a later comparison of that pair wrongly return
true. - The old object-key loop moved into
looseCompareObjectsunchanged. Plain objects still fall through to the finalString(a) === String(b)check. Theseenmap is only created when the first object-level comparison is reached, not for primitives, dates or identical values.
Test evidence:
- Shared tests: a new test,
compares circular structures without infinite recursion, covers cyclic Sets, Maps and plain objects. It also checks that failed trial matches don't carry over into later comparisons. - Component test: a new test,
selects the matching option when values are cyclic sets, sits next to the #15320 test invModel.spec.ts. It uses the report'smakeGraphsetup. - Before the fix: the test-writer ran both new tests against the original code and both failed with
RangeError. - Pair removal: the reviewer pointed out that the first version of the trial-match check would pass even without removing pairs. I added a case that compares the same pair twice and confirmed it fails when the removal line is deleted (
expected true to be false), then restored the line. - Test runs:
./bt-test packages/shared packages/runtime-dom/__tests__/directives/vModel.spec.ts: 7 files, 112 tests passed.- The other code that calls
looseEqual(v-model directives, SSR directive helpers, component props/rendering): 156 + 44 tests passed. - Prettier check passed.
- Review: the reviewer found no correctness problems, no API change and nothing unrelated in the diff.
Requirements:
| Item from the report | Status |
|---|---|
<select v-model> with cyclic Set option values mounts without throwing | Done; covered by the vModel test (with identical graphs the first option is selected, with different graphs the bound one is) |
looseEqual stops on cyclic structures by tracking visited pairs | Done; uses an in-progress pair map |
Returns true for two structurally identical cyclic Sets/Maps | Done; covered by the new shared test |
| Repro 1: Sets of mutually-referencing objects | Done; tested both equal and different |
| Repro 2: Maps holding mutually-referencing values | Done; tested both equal and different |
Repro 3: s1.add(s1) vs s2.add(s2) | Done; self-containing Maps tested too |
| Also fixes #5318 (cyclic plain objects) | Done; tested both equal and different |
No existing tests were changed, and the changes are uncommitted in the working tree with no scratch files left behind.