Backtestsvuerun-20261001-022054#15153
Custom elements: async components nested ≥3 levels crash with TypeError: Cannot read properties of null (reading 'provides') — chained child resolve races its parent's mount
The merged fix was judged better than our patch.
In this judgment, Patch B = our agent, Patch A = the merged fix.
Both patches fix the root cause the same way: the chained child's `_pendingResolve` now waits on the promise that settles after the element itself has loaded and mounted. - Patch B does this by returning `this._pendingResolve` after calling `_resolveDef()` inside the chain callback. - Patch A has `_resolveDef()` return the async loader promise (and the existing pending promise on early return), then returns that from the chain callback. In both, the chain promise a grandchild captured at connect time now settles only after the middle element's async load and mount. That restores ancestor-first ordering at any depth and removes the null `parent._instance` dereference. On correctness they are effectively equivalent for the reported scenario. Patch A also skips resolving a child that was disconnected while its parent was pending. This is extra hardening beyond the issue's ask, so it earns no credit on its own. It is small, guarded by `isConnected`, and covered by its own test, so it adds little risk. The tests separate the two patches: - Patch A's ancestor-first test uses manually controlled promises. It deterministically reproduces the exact race (inner and outer resolve first, middle resolves last) and checks both mount order and provide/inject inheritance through the shadow DOM output. It would fail before the fix and is not timing-sensitive. - Patch B's test reproduces the issue's delay-based scenario with real `setTimeout` delays and a 100ms wait. It would also fail before the fix and checks provide/inject too, but it depends on wall-clock timing and is more prone to flakiness. On craft, Patch B is slightly more minimal and has a helpful comment, while Patch A's `_resolveDef` return-value change is clean and consistent. Overall, the fixes are equal in correctness, and Patch A wins on its more deterministic tests.
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
1m 58s17 turns
Wall-clock time in the container
Full test suite
No new failures
3,631 passed · 6 skipped · 3,637 total
Contamination audit
Clean
No sign the agent saw the real fix
Patch size
57vs 119 merged
Changed lines, ours vs merged
The issue
View on GitHubVue version
3.5.40 (latest at the time of writing — the inline repro pins it; also reproduced on 3.5.13, 3.5.17, 3.5.30 and 3.6.0-rc.2; 3.4.38 — before the nested-async chaining existed — crashes with the same null dereference in the older _setParent provides copy inside vnode.ce)
Link to minimal reproduction
Steps to reproduce
- Open the reproduction link and watch the console:
mounted x-innernever appears — the element crashes with an unhandledTypeError: Cannot read properties of null (reading 'provides')and never mounts. (The playground variant inserts the nested markup dynamically after thedefine()calls; dynamic and parser-created markup crash identically.) - Parser-created (static server-HTML-style) variant — self-contained single file, no build step (save as
repro.html, serve statically, open in any browser; Chromium, Firefox and WebKit all reproduce):
<!doctype html>
<meta charset="utf-8" />
<title>nested async custom elements repro</title>
<x-outer>
<x-middle>
<div>
<x-inner>inner light dom</x-inner>
</div>
</x-middle>
</x-outer>
<script type="module">
import {
defineCustomElement,
defineAsyncComponent,
h,
} from "https://unpkg.com/vue@3.5.40/dist/vue.esm-browser.js";
// Delays chosen so the middle level settles AFTER its child: outer fast,
// middle slow, inner fast. This crashes on 100% of loads.
const delays = { "x-outer": 50, "x-middle": 300, "x-inner": 10 };
const makeComponent = (name) => ({
name,
mounted() {
console.log(`mounted ${name}`);
},
render() {
return h("div", { style: "display:block;padding:6px;border:1px solid #888" }, [name, h("slot")]);
},
});
const makeLoader = (tag) => () =>
new Promise((resolve) => setTimeout(() => resolve(makeComponent(tag)), delays[tag]));
// Define the three tags parent-first.
for (const tag of ["x-outer", "x-middle", "x-inner"]) {
customElements.define(tag, defineCustomElement(defineAsyncComponent(makeLoader(tag))));
}
window.addEventListener("error", (e) => console.error("UNCAUGHT:", e.message));
window.addEventListener("unhandledrejection", (e) =>
console.error("UNHANDLED REJECTION:", e.reason?.message ?? e.reason),
);
</script>
What is expected?
All three elements mount ancestor-first: mounted x-outer, mounted x-middle, mounted x-inner. The nested-async chaining added in 3.5.0 (37ccb9b, "delay mounting of custom elements with async parent", closing #9341 / #8127 / #9351) exists to guarantee exactly this.
What is actually happening?
mounted x-outer
UNHANDLED REJECTION: Cannot read properties of null (reading 'provides')
mounted x-middle
x-inner crashes in VueElement._mount → _inheritParentContext (runtime-dom — parent._instance.provides is dereferenced guarded only by parent && this._app), never mounts, and is left permanently half-resolved: _resolved: true, _instance: null, shadow root empty. Nothing ever retries it, no error surfaces through app.config.errorHandler, and any provide/inject inheritance it should have received is lost. Its own descendants (at deeper nesting) then crash against it in cascade.
Any additional comments?
Analysis (why depth ≥ 3 is the trigger)
connectedCallback of a child under a pending async parent chains:
this._pendingResolve = parent._pendingResolve.then(() => {
this._pendingResolve = undefined;
this._resolveDef();
});
- For an unchained parent (depth 2),
parent._pendingResolveis the parent's own_resolveDef()flow, which settles after the parent has mounted → 2-level nesting is safe. The variants table below confirms: 2 levels never crash. - For a chained parent (depth ≥ 3),
parent._pendingResolveis itself a chain promise — and that promise settles when the parent's_resolveDef()returns (i.e. when the parent's async load starts), not when the parent mounts.
So once the first unchained ancestor mounts, the whole chain unwinds within a few microtasks: every deeper level's loader fires nearly simultaneously and mount order degenerates to network settlement order. Any child whose async definition settles before its parent has mounted hits _inheritParentContext while parent._instance === null and throws. With real-network chunk timings the victim set varies per load, so in an app this presents as a flaky, page-dependent breakage; with the fixed delays above it is 100% deterministic.
Variants checked (each re-run in a real browser):
| Variant | Result |
|---|---|
| 3 levels, middle slowest | crashes every load |
| 3 levels, inner slowest | clean (race direction confirmed) |
| 2 levels | clean (chained parent required) |
plain <div> between levels | still crashes (structure-independent) |
markup inserted dynamically after all define() calls | still crashes |
| all loaders instant | clean (microtask FIFO protects when nothing is pending) |
_inheritParentContext (#13219, ~3.5.14) did not introduce the race — it converted a pre-existing silent misordering into a hard crash. 3.4.38 (no chaining) and 3.5.13 (chaining, pre-#13219) fail with the same null dereference in the older _setParent provides-copy path.
Suggested direction — either (or both):
- Chain the child to the parent's actual mount, not to
_resolveDef()returning — e.g. resolve the parent's_pendingResolveonly after_mount()has run, so the guarantee the chaining was built for ("ancestor mounts before descendant") holds at any depth. - Guard
_inheritParentContextagainstparent._instance === nulland defer context inheritance until the parent instance exists, instead of throwing away the child permanently on an unhandled rejection.
The two patches
packages/runtime-dom/__tests__/customElement.spec.tsindex a5bea20b8..9ac0109c8 100644@@ -2210,6 +2210,60 @@ describe('defineCustomElement', () => { expect(barVal).toBe('bar') }) + test('async & multiple levels of nested async custom elements (middle resolves last)', async () => {+ const mounted: string[] = []+ let fooVal: string | undefined = ''+ let barVal: string | undefined = ''+ const delays: Record<string, number> = {+ 'x-async-outer': 5,+ 'x-async-middle': 30,+ 'x-async-inner': 1,+ }+ const makeComponent = (name: string) => ({+ name,+ setup() {+ if (name === 'x-async-outer') provide('foo', 'foo')+ if (name === 'x-async-middle') provide('bar', 'bar')+ if (name === 'x-async-inner') {+ fooVal = inject('foo')+ barVal = inject('bar')+ }+ },+ mounted() {+ mounted.push(name)+ },+ render(this: any) {+ return h('div', null, [name, renderSlot(this.$slots, 'default')])+ },+ })+ for (const tag of Object.keys(delays)) {+ customElements.define(+ tag,+ defineCustomElement(+ defineAsyncComponent(+ () =>+ new Promise<any>(r =>+ setTimeout(() => r(makeComponent(tag)), delays[tag]),+ ),+ ),+ ),+ )+ }+ container.innerHTML =+ `<x-async-outer><x-async-middle><div>` ++ `<x-async-inner></x-async-inner>` ++ `</div></x-async-middle></x-async-outer>`++ await new Promise(r => setTimeout(r, 100))+ expect(mounted).toEqual(['x-async-outer', 'x-async-middle', 'x-async-inner'])+ const inner = container.querySelector('x-async-inner') as VueElement+ expect(inner.shadowRoot!.innerHTML).toBe(+ `<div>x-async-inner<slot></slot></div>`,+ )+ expect(fooVal).toBe('foo')+ expect(barVal).toBe('bar')+ })+ describe('configureApp', () => { test('should work', () => { const E = defineCustomElement(packages/runtime-dom/src/apiCustomElement.tsindex 9e1f3a720..8e8b09490 100644@@ -314,6 +314,9 @@ export class VueElement this._pendingResolve = parent._pendingResolve.then(() => { this._pendingResolve = undefined this._resolveDef()+ // settle only after this element is resolved & mounted so that+ // descendants chained to it never mount before it does+ return this._pendingResolve }) } else { this._resolveDef()
packages/runtime-dom/__tests__/customElement.spec.tsindex a5bea20b8..27c7121c2 100644@@ -2210,6 +2210,118 @@ describe('defineCustomElement', () => { expect(barVal).toBe('bar') }) + test('nested async custom elements should mount ancestor-first', async () => {+ const mounted: string[] = []+ const OuterComp = defineComponent({+ setup() {+ provide('foo', 'foo')+ },+ mounted() {+ mounted.push('outer')+ },+ render() {+ return h('slot')+ },+ })+ const MiddleComp = defineComponent({+ setup() {+ provide('bar', 'bar')+ },+ mounted() {+ mounted.push('middle')+ },+ render() {+ return h('slot')+ },+ })+ const InnerComp = defineComponent({+ setup() {+ const foo = inject('foo')+ const bar = inject('bar')+ return () => h('div', `${foo}/${bar}`)+ },+ mounted() {+ mounted.push('inner')+ },+ })+ let resolveOuter!: (comp: typeof OuterComp) => void+ let resolveMiddle!: (comp: typeof MiddleComp) => void+ let resolveInner!: (comp: typeof InnerComp) => void+ const outerReady = new Promise<typeof OuterComp>(resolve => {+ resolveOuter = resolve+ })+ const middleReady = new Promise<typeof MiddleComp>(resolve => {+ resolveMiddle = resolve+ })+ const innerReady = new Promise<typeof InnerComp>(resolve => {+ resolveInner = resolve+ })++ const Outer = defineCustomElement(defineAsyncComponent(() => outerReady))+ const Middle = defineCustomElement(defineAsyncComponent(() => middleReady))+ const Inner = defineCustomElement(defineAsyncComponent(() => innerReady))++ customElements.define('async-chain-outer', Outer)+ customElements.define('async-chain-middle', Middle)+ customElements.define('async-chain-inner', Inner)+ container.innerHTML =+ `<async-chain-outer>` ++ `<async-chain-middle>` ++ `<async-chain-inner></async-chain-inner>` ++ `</async-chain-middle>` ++ `</async-chain-outer>`++ resolveInner(InnerComp)+ resolveOuter(OuterComp)+ await new Promise(resolve => setTimeout(resolve))+ resolveMiddle(MiddleComp)+ await new Promise(resolve => setTimeout(resolve))++ const inner = container.querySelector('async-chain-inner') as VueElement+ expect(mounted).toEqual(['outer', 'middle', 'inner'])+ expect(inner.shadowRoot!.innerHTML).toBe('<div>foo/bar</div>')+ })++ test('should not resolve nested custom element after disconnect', async () => {+ const mounted = vi.fn()+ const ParentComp = defineComponent({+ render() {+ return h('slot')+ },+ })+ let resolveParent!: (comp: typeof ParentComp) => void+ const parentReady = new Promise<typeof ParentComp>(resolve => {+ resolveParent = resolve+ })+ const Parent = defineCustomElement(defineAsyncComponent(() => parentReady))+ const Child = defineCustomElement({+ mounted,+ render() {+ return h('div', 'child')+ },+ })++ customElements.define('async-disconnect-parent', Parent)+ customElements.define('async-disconnect-child', Child)+ container.innerHTML =+ `<async-disconnect-parent>` ++ `<async-disconnect-child></async-disconnect-child>` ++ `</async-disconnect-parent>`++ const parent = container.firstChild as VueElement+ const child = parent.firstChild as VueElement+ child.remove()+ resolveParent(ParentComp)+ await new Promise(resolve => setTimeout(resolve))++ expect(mounted).not.toHaveBeenCalled()+ expect(child.shadowRoot!.innerHTML).toBe('')++ parent.appendChild(child)+ expect(mounted).toHaveBeenCalledOnce()+ expect(child.shadowRoot!.innerHTML).toBe('<div>child</div>')+ })+ describe('configureApp', () => { test('should work', () => { const E = defineCustomElement(packages/runtime-dom/src/apiCustomElement.tsindex 9e1f3a720..9422f58d6 100644@@ -313,7 +313,9 @@ export class VueElement if (parent && parent._pendingResolve) { this._pendingResolve = parent._pendingResolve.then(() => { this._pendingResolve = undefined- this._resolveDef()+ if (this.isConnected) {+ return this._resolveDef()+ } }) } else { this._resolveDef()@@ -371,7 +373,7 @@ export class VueElement */ private _resolveDef() { if (this._pendingResolve) {- return+ return this._pendingResolve } // set initial attrs@@ -428,6 +430,7 @@ export class VueElement def.configureApp = this._def.configureApp resolve((this._def = def), true) })+ return this._pendingResolve } else { resolve(this._def) }
What the agent reported
Async custom elements nested three or more levels deep now mount parent-first. The crash from the report is gone, and the full suite passes. The changes are uncommitted in the working tree.
What was wrong: In VueElement.connectedCallback (packages/runtime-dom/src/apiCustomElement.ts:313), a child under a parent that is still loading waits on that parent's pending promise. When the parent was itself waiting on its own parent, that promise was the parent's chain promise, which settled as soon as the parent's _resolveDef() returned. That is when the parent's async load starts, not when it mounts. So at depth 3, the inner element could finish loading and mount while the middle element's _instance was still null, and _inheritParentContext threw Cannot read properties of null (reading 'provides').
What I changed: One line plus a comment. The chain callback now ends with return this._pendingResolve. The chain promise then waits for the element's own async load, which settles only after resolve() → _mount(). Descendants therefore can't start before their parent has mounted, at any depth. For synchronous definitions _pendingResolve is undefined after _resolveDef(), so their behaviour doesn't change.
Test evidence:
- New test:
async & multiple levels of nested async custom elements (middle resolves last)inpackages/runtime-dom/__tests__/customElement.spec.tsuses the report's setup: three async levels where the middle loads slowest (5ms / 30ms / 1ms). It checks that the mount order is outer → middle → inner, that the inner shadow root rendered, and thatprovide/injectworks across all three levels. - Before the fix: the test failed on the inner element missing from the mount order, along with the exact
TypeError ... reading 'provides'at_inheritParentContext. - After the fix: the whole spec file passes (78 passed, 1 skipped).
- Full suite:
./bt-testwon't accept targeted arguments, so I ran single files with the repo's vitest binary (unit-jsdomproject) and then the full suite with./bt-test: 3,637 tests, 0 failures, 0 errors.
Blast radius: Only elements that were waiting on an async parent are affected; they now wait for the parent to mount instead of for its load to start. That ordering is what the 3.5.0 chaining was meant to guarantee. The existing 2-level and multi-level nested tests still pass.
Reviewer notes: The reviewer found no blocking issues. One minor side effect: if a loader rejects, each element waiting on it now also reports its own unhandled rejection. Before, only the loader's rejection surfaced. This matches what direct children of a failing element already did.
Requirements:
- 3-level nesting where the middle loads last crashes; expected order outer → middle → inner: fixed, with the new test as evidence (fails before, passes after).
- Inner element left half-resolved, with lost
provide/injectinheritance: fixed. The test checks the inner shadow root content and the injectedfooandbarvalues. - Suggested direction 1, wait for the parent's actual mount: implemented; this is the fix described above.
- Suggested direction 2, guard
_inheritParentContextagainst a null parent instance: not done. With direction 1 in place, a waiting child never reaches_inheritParentContextbefore its parent has mounted. A silent guard would only hide that ordering bug and skip context inheritance instead of failing loudly, and I kept the change minimal. - Variants table: the 2-level and instant-loader cases are covered by the existing nested-async tests, which still pass. The plain-
<div>-between-levels case is in the new test. I didn't add separate tests for parser-created vs dynamically inserted markup, or for the case where the inner element loads slowest. Both go through the sameconnectedCallbackcode, and the second never crashed.