Backtestsvuerun-20261007-145226#15496

Issue #15496 Merged fix PR #15499 Run 7 Oct 2026 · run-20261007-145226 vuejs/core

looseEqual: comparing Map/Set values with circular references throws RangeError (regression in 3.5.42)

Better

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 comparison state through `looseEqual`, `looseCompareArrays` and `looseCompareCollections`. Both cover Maps, Sets, arrays and plain objects, so both also fix the cyclic-object case the issue mentions.

Correctness:
- Patch A follows the issue's suggested approach. It tracks `(a, b)` pairs that are in progress and returns true when it meets one again, so it treats two structures as equal if they look the same no matter how far you follow them.
- Patch A also caches pairs already proven unequal. This is safe: optimistic 'true' assumptions can only make a result more equal, so a false result reached under them is genuinely false. The cache avoids repeating work in the matching loop for Set/Map entries, and A tests this with a densely cyclic 8-node Set graph.
- Patch B uses a stricter rule. It keeps two maps along the current path and only accepts a re-encounter if the same pairing reappears. This always terminates. However, it returns false for structures that look the same no matter how far you follow them but have a different cycle layout (e.g. `self.next = self` vs a 2-cycle). B tests that as intended behaviour, but it departs from the issue's stated expectation.
- Patch B has no protection against repeated work, so dense cyclic Sets can take exponential time in its candidate-matching loop.
- Patch B adds an optional third `seen` parameter to the exported `looseEqual`. That leaks internal state into the public signature and could misbehave if `looseEqual` is passed directly as a callback that receives extra arguments. Patch A keeps the public signature unchanged by wrapping a private `looseEqualImpl`.

Tests:
- Patch A adds unit tests for cyclic Sets, cyclic Maps (including a map containing itself), cyclic objects and arrays, unequal cases, and the dense-cycle performance case.
- Patch A also adds a component-level `vModel` test matching the reported `<select v-model>` scenario.
- Patch B adds unit tests only. They are reasonable but have no component-level test and no Map self-reference test.

Craft: Patch A's dispatch is a bit redundant (it checks Map/Set, then `looseCompareObjects` re-dispatches), but it is clear, uses try/finally, and is well commented. Patch B's `looseCompareNested` helper is tidy, but the API leak and missing performance guard weigh against it.

Overall, A is more faithful to the requested semantics, more robust, and better tested.

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

13m 52s

Wall-clock time in the container

Full test suite

No new failures

3,746 passed · 6 skipped · 3,752 total

Contamination audit

Clean

No sign the agent saw the real fix

Patch size

203vs 138 merged

Changed lines, ours vs merged

Vue version

3.5.42 (also reproduced on current main, commit 5409708)

Link to minimal reproduction

https://play.vuejs.org/#eyJBcHAudnVlIjogIjxzY3JpcHQgc2V0dXA-XG5pbXBvcnQgeyByZWYgfSBmcm9tICd2dWUnXG5cbmNvbnN0IG1ha2VHcmFwaCA9ICgpID0-IHtcbiAgY29uc3QgbjEgPSB7IGlkOiAxIH1cbiAgY29uc3QgbjIgPSB7IGlkOiAyIH1cbiAgbjEucGVlciA9IG4yXG4gIG4yLnBlZXIgPSBuMSAgLy8gY2lyY3VsYXIgcmVmZXJlbmNlXG4gIHJldHVybiBuZXcgU2V0KFtuMSwgbjJdKVxufVxuXG5jb25zdCBvcHRBID0gbWFrZUdyYXBoKClcbmNvbnN0IG9wdEIgPSBtYWtlR3JhcGgoKVxuY29uc3Qgc2VsZWN0ZWQgPSByZWYob3B0Qilcbjwvc2NyaXB0PlxuXG48dGVtcGxhdGU-XG4gIDxzZWxlY3Qgdi1tb2RlbD1cInNlbGVjdGVkXCI-XG4gICAgPG9wdGlvbiA6dmFsdWU9XCJvcHRBXCI-QTwvb3B0aW9uPlxuICAgIDxvcHRpb24gOnZhbHVlPVwib3B0QlwiPkI8L29wdGlvbj5cbiAgPC9zZWxlY3Q-XG48L3RlbXBsYXRlPlxuIiwgImltcG9ydC1tYXAuanNvbiI6ICJ7XCJpbXBvcnRzXCI6IHtcInZ1ZVwiOiBcImh0dHBzOi8vdW5wa2cuY29tL0B2dWUvcnVudGltZS1kb21AMy41LjQyL2Rpc3QvcnVudGltZS1kb20uZXNtLWJyb3dzZXIuanNcIn19In0=

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])) where a1.peer = a2; a2.peer = a1 and b1.peer = b2; b2.peer = b1
  • looseEqual(mapA, mapB) where both maps hold mutually-referencing values
  • looseEqual(s1, s2) where s1.add(s1) and s2.add(s2)

The two patches

Our patch+180 −23
packages/runtime-dom/__tests__/directives/vModel.spec.tsindex a94cb8e0d..60d260347 100644@@ -1900,6 +1900,38 @@ describe('vModel', () => {      render(h(component), root) +    expect(root.querySelector('select').selectedIndex).toBe(1)+  })+  it('selects the matching option when values are cyclic sets', () => {+    const makeGraph = (id: number) => {+      const n1: any = { id }+      const n2: any = { id: id + 1 }+      n1.peer = n2+      n2.peer = n1+      return new Set([n1, n2])+    }+    const optA = makeGraph(1)+    const optB = makeGraph(3)+    const value = ref(makeGraph(3))+    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,+        ),+    )++    render(h(component), root)+     expect(root.querySelector('select').selectedIndex).toBe(1)   }) })packages/shared/__tests__/looseEqual.spec.tsindex 777f3cfad..d256286c4 100644@@ -288,4 +288,73 @@ 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 cyclic sets correctly', () => {+    const makeGraph = (id2 = 2) => {+      const n1: any = { id: 1 }+      const n2: any = { id: id2 }+      n1.peer = n2+      n2.peer = n1+      return new Set([n1, n2])+    }+    expect(looseEqual(makeGraph(), makeGraph())).toBe(true)+    expect(looseEqual(makeGraph(), makeGraph(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 cyclic maps correctly', () => {+    const makeMap = (value = 'a') => {+      const v1: any = { value }+      const v2: any = { value: 'b' }+      v1.peer = v2+      v2.peer = v1+      const map = new Map<any, any>([+        ['x', v1],+        ['y', v2],+      ])+      map.set('self', map)+      return map+    }+    expect(looseEqual(makeMap(), makeMap())).toBe(true)+    expect(looseEqual(makeMap(), makeMap('c'))).toBe(false)+  })++  test('compares cyclic objects and arrays correctly', () => {+    const makeObj = (id = 1) => {+      const a: any = { id }+      const b: any = { id: 2, list: [a] }+      a.peer = b+      b.list.push(b.list)+      return a+    }+    expect(looseEqual(makeObj(), makeObj())).toBe(true)+    expect(looseEqual(makeObj(), makeObj(3))).toBe(false)++    const arr1: any[] = [1]+    arr1.push(arr1)+    const arr2: any[] = [1]+    arr2.push(arr2)+    expect(looseEqual(arr1, arr2)).toBe(true)+  })++  test('compares densely cyclic sets without exponential blowup', () => {+    const makeNodes = (lastId: number) => {+      const nodes: any[] = []+      for (let i = 0; i < 8; i++) nodes.push({})+      nodes.forEach((node, i) => {+        node.peers = new Set(nodes)+        node.id = i+      })+      nodes[nodes.length - 1].id = lastId+      return nodes[0]+    }+    expect(looseEqual(makeNodes(7), makeNodes(7))).toBe(true)+    expect(looseEqual(makeNodes(7), makeNodes(99))).toBe(false)+  }) })packages/shared/src/looseEqual.tsindex d037b0a57..91a4a8bbf 100644@@ -1,10 +1,14 @@ import { isArray, isDate, isMap, isObject, isSet, isSymbol } from './general' -function looseCompareArrays(a: any[], b: any[]) {+// pairs of objects either currently being compared (true), used to terminate+// on cycles, or already proven unequal (false), to avoid exponential re-checks+type ComparingPairs = Map<object, Map<object, boolean>>++function looseCompareArrays(a: any[], b: any[], comparing: ComparingPairs) {   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], comparing)   }   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>,+  comparing: ComparingPairs, ) {   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], comparing)) {         index = i         break       }@@ -30,7 +35,63 @@ function looseCompareCollections(   return true } -export function looseEqual(a: any, b: any): boolean {+function looseCompareObjects(a: any, b: any, comparing: ComparingPairs) {+  let compared = comparing.get(a)+  const state = compared && compared.get(b)+  if (state !== undefined) {+    // true: already comparing this pair further up the stack (cyclic+    // structure), assume equal and let the outer comparison decide.+    // false: this pair was already proven unequal.+    return state+  }+  if (!compared) comparing.set(a, (compared = new Map()))+  compared.set(b, true)+  let equal = false+  try {+    return (equal = looseCompareObjectsImpl(a, b, comparing))+  } finally {+    // an unequal result never relies on an assumed-equal pair, so it is safe+    // to remember for the rest of this comparison+    if (equal) {+      compared.delete(b)+      if (!compared.size) comparing.delete(a)+    } else {+      compared.set(b, false)+    }+  }+}++function looseCompareObjectsImpl(+  a: any,+  b: any,+  comparing: ComparingPairs,+): boolean {+  if (isArray(a)) {+    return looseCompareArrays(a, b, comparing)+  }+  if (isMap(a) || isSet(a)) {+    return looseCompareCollections(a, b, comparing)+  }+  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) ||+      !looseEqualImpl(a[key], b[key], comparing)+    ) {+      return false+    }+  }+  return String(a) === String(b)+}++function looseEqualImpl(a: any, b: any, comparing?: ComparingPairs): boolean {   if (a === b) return true   let aValidType = isDate(a)   let bValidType = isDate(b)@@ -45,7 +106,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+      ? looseCompareObjects(a, b, comparing || new Map())+      : false   }   aValidType = isObject(a)   bValidType = isObject(b)@@ -56,33 +119,26 @@ 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+        ? looseCompareObjects(a, b, comparing || new Map())+        : 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 aValidType && bValidType+        ? looseCompareObjects(a, b, comparing || new Map())+        : false     }+    return looseCompareObjects(a, b, comparing || new Map())   }   return String(a) === String(b) } +export function looseEqual(a: any, b: any): boolean {+  return looseEqualImpl(a, b)+}+ export function looseIndexOf(arr: any[], val: any): number {   return arr.findIndex(item => looseEqual(item, val)) } 
Merged fix · PR #15499+107 −31
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) }