Skip to content

Conversation

edison1105
Copy link
Member

@edison1105 edison1105 commented Aug 27, 2025

close vitejs/vite-plugin-vue#599

Summary by CodeRabbit

  • New Features

    • None
  • Bug Fixes

    • Improved hot-reload stability by preventing updates on components that were just disposed, reducing rare errors, flicker, and inconsistent state during rapid edits; retains existing reload fallbacks and production behavior.
  • Tests

    • Added HMR test verifying nested component reloads (ensures inner component updates correctly when parent and child are reloaded).
  • Chores

    • None

Copy link

coderabbitai bot commented Aug 27, 2025

Walkthrough

Adds a DISPOSED/job-flag guard to the HMR reload path in runtime-core so the queued parent update runs only if the instance’s scheduler job is not disposed; preserves isHmrUpdating toggling and dirtyInstances cleanup inside the guarded block. Adds a nested-component HMR test verifying reload behavior.

Changes

Cohort / File(s) Summary
HMR reload guard
packages/runtime-core/src/hmr.ts
Wraps the queued parent update in a check that skips the update if the instance's scheduler job has the DISPOSED flag; retains isHmrUpdating toggling and calls dirtyInstances.delete(instance) within the guarded block; adds inline comments referencing related issue context.
HMR tests
packages/runtime-core/__tests__/hmr.spec.ts
Adds a new test case for nested component HMR reloads (Outer -> Inner) that updates Inner and asserts the DOM reflects the updated render after reloads.

Sequence Diagram(s)

sequenceDiagram
    autonumber
    participant Dev as Dev Server
    participant HMR as runtime-core HMR
    participant Inst as Component Instance
    participant Parent as Parent Instance

    Dev->>HMR: file change -> reload(instance)
    HMR->>HMR: queue update job

    rect rgba(200,230,255,0.25)
    note right of HMR: Guard added before parent update
    HMR->>HMR: if (instance.jobFlags & DISPOSED) then skip
    alt not disposed
        HMR->>HMR: isHmrUpdating = true
        HMR->>Parent: parent.update()
        HMR->>HMR: dirtyInstances.delete(instance)
        HMR->>HMR: isHmrUpdating = false
    else disposed
        HMR-->>HMR: skip parent.update()
    end
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Assessment against linked issues

Objective Addressed Explanation
Prevent HMR “Unhandled error during scheduler flush (TypeError: parent is null)” by avoiding updates on disposed/unmounted parents (#599)

Out-of-scope changes

No out-of-scope functional changes detected relative to the objectives in the linked issue.

Possibly related PRs

Suggested labels

ready to merge, scope: hmr, :hammer: p3-minor-bug

Suggested reviewers

  • Doctor-wu
  • LittleSound
  • KazariEX
  • baiwusanyu-c

Poem

I chewed a loop in HMR's quick path,
found a null parent—and spared the crash.
Now flags keep watch, updates stay kind,
Nested reloads no longer blind.
Thump-thump, the rabbit hops—safe build, peace of mind. 🐇

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch edison/fix/hmrReload

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

Size Report

Bundles

File Size Gzip Brotli
runtime-dom.global.prod.js 101 kB 38.4 kB 34.6 kB
vue.global.prod.js 159 kB 58.5 kB 52.2 kB

Usages

Name Size Gzip Brotli
createApp (CAPI only) 46.5 kB 18.2 kB 16.7 kB
createApp 54.5 kB 21.2 kB 19.4 kB
createSSRApp 58.7 kB 22.9 kB 20.9 kB
defineCustomElement 59.5 kB 22.8 kB 20.8 kB
overall 68.5 kB 26.4 kB 24 kB

Copy link

pkg-pr-new bot commented Aug 27, 2025

Open in StackBlitz

@vue/compiler-core

npm i https://pkg.pr.new/@vue/compiler-core@13815

@vue/compiler-dom

npm i https://pkg.pr.new/@vue/compiler-dom@13815

@vue/compiler-sfc

npm i https://pkg.pr.new/@vue/compiler-sfc@13815

@vue/compiler-ssr

npm i https://pkg.pr.new/@vue/compiler-ssr@13815

@vue/reactivity

npm i https://pkg.pr.new/@vue/reactivity@13815

@vue/runtime-core

npm i https://pkg.pr.new/@vue/runtime-core@13815

@vue/runtime-dom

npm i https://pkg.pr.new/@vue/runtime-dom@13815

@vue/server-renderer

npm i https://pkg.pr.new/@vue/server-renderer@13815

@vue/shared

npm i https://pkg.pr.new/@vue/shared@13815

vue

npm i https://pkg.pr.new/vue@13815

@vue/compat

npm i https://pkg.pr.new/@vue/compat@13815

commit: e86bfaf

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (1)
packages/runtime-core/src/hmr.ts (1)

150-158: Good guard; add try/finally and re-check parent at execution time to harden against throws/races.

This fixes the stale queued update. Two low-risk tweaks improve robustness: ensure isHmrUpdating is always reset even if update() throws, and re-check parent at execution time in case it became null after queueing.

-        // vite-plugin-vue/issues/599
-        // don't update if the job is already disposed
-        if (!(instance.job.flags! & SchedulerJobFlags.DISPOSED)) {
-          isHmrUpdating = true
-          instance.parent!.update()
-          isHmrUpdating = false
-          // #6930, #11248 avoid infinite recursion
-          dirtyInstances.delete(instance)
-        }
+        // vite-plugin-vue/issues/599
+        // don't update if the job is already disposed
+        const notDisposed =
+          !((instance.job.flags ?? 0) & SchedulerJobFlags.DISPOSED)
+        // re-check at execution time; parent may have become null after queueing
+        const parent = instance.parent
+        if (parent && notDisposed) {
+          isHmrUpdating = true
+          try {
+            parent.update()
+          } finally {
+            isHmrUpdating = false
+          }
+          // #6930, #11248 avoid infinite recursion
+          dirtyInstances.delete(instance)
+        }
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 24fccb4 and 3e4e19e.

📒 Files selected for processing (1)
  • packages/runtime-core/src/hmr.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: Redirect rules
  • GitHub Check: Header rules
  • GitHub Check: Pages changed

@edison1105 edison1105 added ready to merge The PR is ready to be merged. scope: hmr 🔨 p3-minor-bug Priority 3: this fixes a bug, but is an edge case that only affects very specific usage. labels Aug 27, 2025
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (3)
packages/runtime-core/__tests__/hmr.spec.ts (3)

947-958: Type the component definitions for better TS safety

Annotate Inner/Outer as ComponentOptions to avoid implicit any and align with createRecord expectations.

Apply:

-    let Inner = {
+    let Inner: ComponentOptions = {
       __hmrId: innerId,
       render() {
         return h('div', 'foo')
       },
     }
-    let Outer = {
+    let Outer: ComponentOptions = {
       __hmrId: outerId,
       render() {
         return h(Inner)
       },
     }

943-990: Assert absence of the original error signals to prevent silent regressions

Guard against regressions by asserting no console noise matching the reported messages.

Apply:

   test('reload nested components from shared dep update', async () => {
+    const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
+    const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
@@
     await nextTick()
 
     expect(serializeInner(root)).toBe('<div>bar</div>')
+    expect(errorSpy.mock.calls.join(' ')).not.toMatch(/parent is null/i)
+    expect(warnSpy.mock.calls.join(' ')).not.toMatch(/scheduler flush/i)
+    errorSpy.mockRestore()
+    warnSpy.mockRestore()
   })

984-987: Exercise both reload orderings for robustness

The linked bug can depend on reload ordering. Consider a second test that triggers inner-first to ensure symmetry.

You can append:

test('reload nested components from shared dep update (inner-first)', async () => {
  const innerId = 'nested-reload-inner-2'
  const outerId = 'nested-reload-outer-2'
  let Inner: ComponentOptions = { __hmrId: innerId, render: () => h('div', 'foo') }
  let Outer: ComponentOptions = { __hmrId: outerId, render: () => h(Inner) }
  createRecord(innerId, Inner)
  createRecord(outerId, Outer)
  const root = nodeOps.createElement('div')
  render(h({ render: () => h(Outer) }), root)

  Inner = { __hmrId: innerId, render: () => h('div', 'bar') }
  Outer = { __hmrId: outerId, render: () => h(Inner) }

  // inner-first
  reload(innerId, Inner)
  reload(outerId, Outer)
  await nextTick()
  expect(serializeInner(root)).toBe('<div>bar</div>')
})
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 3e4e19e and e86bfaf.

📒 Files selected for processing (1)
  • packages/runtime-core/__tests__/hmr.spec.ts (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
packages/runtime-core/__tests__/hmr.spec.ts (1)
packages/runtime-test/src/serialize.ts (1)
  • serializeInner (22-33)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: Redirect rules
  • GitHub Check: Header rules
  • GitHub Check: Pages changed
🔇 Additional comments (1)
packages/runtime-core/__tests__/hmr.spec.ts (1)

941-943: Fix typo in HMR test comment and optionally refine test title

The linked plugin issue describes importing and updating service.js, not server.js (github.com). The runtime HMR guard referencing this issue, the SchedulerJobFlags.DISPOSED check, and the dirtyInstances.delete cleanup are all present in packages/runtime-core/src/hmr.ts, so no further code changes are needed there.

• Location: packages/runtime-core/tests/hmr.spec.ts (around line 942)
• Change comment to match the issue’s filename
• Optional: clarify the test title to reference a shared dependency update

Suggested diff:

-  // Both Outer and Inner are reloaded when './server.js' changes
+  // Both Outer and Inner are reloaded when './service.js' changes

-  test('reload nested components from single update', async () => {
+  test('reload nested components from shared dep update', async () => {

@edison1105 edison1105 merged commit ef20b86 into main Sep 2, 2025
16 checks passed
@edison1105 edison1105 deleted the edison/fix/hmrReload branch September 2, 2025 09:07
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🔨 p3-minor-bug Priority 3: this fixes a bug, but is an edge case that only affects very specific usage. ready to merge The PR is ready to be merged. scope: hmr

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Hot reload: Unhandled error during execution of scheduler flush (TypeError: parent is null)

1 participant