Backtestsvuerun-20261009-161443#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 stop the unbounded recursion by threading a per-call 'seen' state through arrays, objects, Maps and Sets. Both handle the issue's three repro shapes: mutually-referencing Set elements, Map values with peers, and self-containing Sets. Both also fix the plain-object cycle case. Correctness: Patch A tracks (a, b) pairs currently on the recursion stack and returns true when a pair is met again. This is exactly the approach the issue suggests, and it gives coinductive structural equality. A wraps the comparison in try/finally so the state is always cleaned up, and it keeps the public `looseEqual(a, b)` signature unchanged by adding an internal `looseEqualImpl`. Patch B enforces a bijection between visited nodes. That is also cycle-safe, and it deliberately treats a self-loop and a 2-cycle as unequal (a stricter semantics than the issue asks for, but defensible). However, B adds an optional third `seen` parameter to the exported `looseEqual`. This leaks an internal detail into the public API. It is also risky: any caller that passes `looseEqual` directly as a callback which supplies a third argument would hand it a bogus state tuple. B also has no try/finally, though that matters little because the state is per call. Tests: A adds unit tests for Sets, Maps (including self-reference), and cyclic objects and arrays. It also adds a runtime-dom `vModel` test that reproduces the issue's actual scenario (`<select v-model>` with cyclic Set and Map option values) and checks that the correct option is selected. B only adds shared unit tests, including a reasonable symmetry test, but has no component-level coverage of the reported failure. Scope and craft: Both are comparably scoped. A's change is a cleaner wrapper around the existing logic. B moves the object, Map and Set logic into a new helper and introduces a callback indirection (`looseCompareNested`), which is somewhat harder to follow. Overall A is the better fix: it follows the issue's suggested semantics, keeps the API clean, and tests the reported scenario end-to-end.
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
4m 44s
Wall-clock time in the container
Full test suite
No new failures
3,745 passed · 6 skipped · 3,751 total
Contamination audit
Clean
No sign the agent saw the real fix
Patch size
147vs 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..bd1b065c9 100644@@ -1902,4 +1902,49 @@ describe('vModel', () => { expect(root.querySelector('select').selectedIndex).toBe(1) })++ it('selects the matching option when Set/Map values contain circular references', () => {+ const makeNodes = (base: number) => {+ const n1: any = { id: base }+ const n2: any = { id: base + 1 }+ n1.peer = n2+ n2.peer = n1+ return [n1, n2]+ }+ const makeSet = (base: number) => new Set(makeNodes(base))+ const makeMap = (base: number) => {+ const [n1, n2] = makeNodes(base)+ return new Map<string, any>([+ ['n1', n1],+ ['n2', n2],+ ])+ }++ for (const make of [makeSet, makeMap] as ((base: number) => any)[]) {+ const optA = make(1)+ const optB = make(3)+ // structurally identical to optB, but a different instance+ const value = ref(make(3))+ const component = defineComponent(+ () => () =>+ withVModel(+ h(+ 'select',+ {+ 'onUpdate:modelValue': (val: any) => (value.value = val),+ },+ [+ h('option', { value: optA }, 'A'),+ h('option', { value: optB }, 'B'),+ ],+ ),+ value.value,+ ),+ )++ render(h(component), root)+ expect(root.querySelector('select').selectedIndex).toBe(1)+ render(null, root)+ }+ }) })packages/shared/__tests__/looseEqual.spec.tsindex 777f3cfad..ee9da7c37 100644@@ -288,4 +288,58 @@ 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 sets with circular references without throwing', () => {+ const makeSet = (id1: number, id2: number) => {+ const n1: any = { id: id1 }+ const n2: any = { id: id2 }+ n1.peer = n2+ n2.peer = n1+ return new Set([n1, n2])+ }+ expect(looseEqual(makeSet(1, 2), makeSet(1, 2))).toBe(true)+ expect(looseEqual(makeSet(1, 2), makeSet(1, 3))).toBe(false)++ const s1 = new Set<any>()+ s1.add(s1)+ const s2 = new Set<any>()+ s2.add(s2)+ expect(looseEqual(s1, s2)).toBe(true)+ s2.add('foo')+ expect(looseEqual(s1, s2)).toBe(false)+ })++ test('compares maps with circular references without throwing', () => {+ const makeMap = (id1: number, id2: number) => {+ const n1: any = { id: id1 }+ const n2: any = { id: id2 }+ n1.peer = n2+ n2.peer = n1+ const map = new Map<any, any>([+ ['n1', n1],+ ['n2', n2],+ ])+ map.set('self', map)+ return map+ }+ expect(looseEqual(makeMap(1, 2), makeMap(1, 2))).toBe(true)+ expect(looseEqual(makeMap(1, 2), makeMap(1, 3))).toBe(false)+ })++ test('compares objects and arrays with circular references without throwing', () => {+ const makeObj = (id: number) => {+ const obj: any = { id, children: [] }+ obj.self = obj+ obj.children.push(obj, { parent: obj })+ return obj+ }+ expect(looseEqual(makeObj(1), makeObj(1))).toBe(true)+ expect(looseEqual(makeObj(1), makeObj(2))).toBe(false)++ const a: any[] = []+ a.push(a)+ const b: any[] = []+ b.push(b)+ expect(looseEqual(a, b)).toBe(true)+ }) })packages/shared/src/looseEqual.tsindex d037b0a57..6b71411a6 100644@@ -1,10 +1,14 @@ import { isArray, isDate, isMap, isObject, isSet, isSymbol } from './general' -function looseCompareArrays(a: any[], b: any[]) {+// pairs of objects currently being compared on the recursion stack,+// used to terminate on cyclic structures+type SeenPairs = Map<object, Set<object>>++function looseCompareArrays(a: any[], b: any[], seen: SeenPairs) { 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 +16,7 @@ function looseCompareArrays(a: any[], b: any[]) { function looseCompareCollections( a: Map<any, any> | Set<any>, b: Map<any, any> | Set<any>,+ seen: SeenPairs, ) { if (a.size !== b.size) return false const candidates = Array.from(b)@@ -19,7 +24,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 }@@ -31,7 +36,32 @@ function looseCompareCollections( } export function looseEqual(a: any, b: any): boolean {+ return looseEqualImpl(a, b, new Map())+}++function looseEqualImpl(a: any, b: any, seen: SeenPairs): boolean { if (a === b) return true+ if (isObject(a) && isObject(b)) {+ // a pair already being compared further up the stack is assumed equal;+ // any actual difference is detected by the outer comparison+ let seenB = seen.get(a)+ if (seenB) {+ if (seenB.has(b)) return true+ } else {+ seen.set(a, (seenB = new Set()))+ }+ seenB.add(b)+ try {+ return looseCompareObjects(a, b, seen)+ } finally {+ seenB.delete(b)+ if (!seenB.size) seen.delete(a)+ }+ }+ return looseCompareObjects(a, b, seen)+}++function looseCompareObjects(a: any, b: any, seen: SeenPairs): boolean { let aValidType = isDate(a) let bValidType = isDate(b) if (aValidType || bValidType) {@@ -45,7 +75,7 @@ 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 ? looseCompareArrays(a, b, seen) : false } aValidType = isObject(a) bValidType = isObject(b)@@ -56,12 +86,16 @@ 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+ ? looseCompareCollections(a, b, seen)+ : false } aValidType = isSet(a) bValidType = isSet(b) if (aValidType || bValidType) {- return aValidType && bValidType ? looseCompareCollections(a, b) : false+ return aValidType && bValidType+ ? looseCompareCollections(a, b, seen)+ : false } const aKeysCount = Object.keys(a).length const bKeysCount = Object.keys(b).length@@ -74,7 +108,7 @@ export function looseEqual(a: any, b: any): boolean { if ( (aHasKey && !bHasKey) || (!aHasKey && bHasKey) ||- !looseEqual(a[key], b[key])+ !looseEqualImpl(a[key], b[key], seen) ) { return false }
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) }