Skip to content

fix(jsx): Fix "Invalid state: Controller is already closed"#4770

Merged
yusukebe merged 3 commits intohonojs:mainfrom
gaearon:streaming-bug-crash
Mar 4, 2026
Merged

fix(jsx): Fix "Invalid state: Controller is already closed"#4770
yusukebe merged 3 commits intohonojs:mainfrom
gaearon:streaming-bug-crash

Conversation

@gaearon
Copy link
Copy Markdown
Contributor

@gaearon gaearon commented Feb 25, 2026

Fixes #4769

The fix is authored by Claude. I steered it to make failing tests first.

All three tests are failing before the fix and passing after the fix.

@yusukebe
Copy link
Copy Markdown
Member

@gaearon Hey Dan, Thank you for the PR.

The issue #4769 you faced, and honojs/node-server#233 are different problems, and we should think about them separately (right? @usualoma ). But I think this fix is resolvable and acceptable. @usualoma What do you think of this?

@gaearon
Copy link
Copy Markdown
Contributor Author

gaearon commented Feb 25, 2026

Ah maybe that's a different message and I got them confused

@usualoma
Copy link
Copy Markdown
Member

Hi @gaearon
Thank you for creating the pull request!
I agree with @yusukebe's comment—it seems unrelated to the node-server issue, but I still think the fix in this PR is valid.

Would you please consider the following changes?

Continue processing until the end

Currently, there is an inconsistency in whether “processing is interrupted” or “continues until completion” at the following two points.

To unify this with the latter approach, I would like to implement it as follows.

diff --git i/src/jsx/streaming.ts w/src/jsx/streaming.ts
index 0c0c5b2d..e21d40c7 100644
--- i/src/jsx/streaming.ts
+++ w/src/jsx/streaming.ts
@@ -158,10 +158,9 @@ export const renderToReadableStream = (
           true,
           context
         )
-        if (cancelled) {
-          return
+        if (!cancelled) {
+          controller.enqueue(textEncoder.encode(resolved))
         }
-        controller.enqueue(textEncoder.encode(resolved))
 
         let resolvedCount = 0
         const callbacks: Promise<void>[] = []

Simplify Testing

To minimize the use of try blocks within test code and delays via setTimeout(), I want to change it as follows.

diff --git i/src/jsx/streaming.test.tsx w/src/jsx/streaming.test.tsx
index 3c7f53b7..75c70cf8 100644
--- i/src/jsx/streaming.test.tsx
+++ w/src/jsx/streaming.test.tsx
@@ -887,55 +887,38 @@ d.replaceWith(c.content)
     const onRejection = (e: unknown) => unhandled.push(e)
     process.on('unhandledRejection', onRejection)
 
-    try {
-      const SubContent = () => {
-        const content = new Promise<HtmlEscapedString>((resolve) =>
-          setTimeout(() => resolve(<h2>World</h2>), 50)
-        )
-        return content
-      }
+    const SubContent = async () => <h2>World</h2>
+    const Content = async () => (
+      <>
+        <h1>Hello</h1>
+        <Suspense fallback={<p>Loading sub...</p>}>
+          <SubContent />
+        </Suspense>
+      </>
+    )
 
-      const Content = () => {
-        const content = new Promise<HtmlEscapedString>((resolve) =>
-          setTimeout(
-            () =>
-              resolve(
-                <>
-                  <h1>Hello</h1>
-                  <Suspense fallback={<p>Loading sub...</p>}>
-                    <SubContent />
-                  </Suspense>
-                </>
-              ),
-            20
-          )
-        )
-        return content
-      }
+    const onError = vi.fn()
+    const stream = renderToReadableStream(
+      <Suspense fallback={<p>Loading...</p>}>
+        <Content />
+      </Suspense>,
+      onError
+    )
 
-      const onError = vi.fn()
-      const stream = renderToReadableStream(
-        <Suspense fallback={<p>Loading...</p>}>
-          <Content />
-        </Suspense>,
-        onError
-      )
+    const reader = stream.getReader()
+    const firstChunk = await reader.read()
+    expect(firstChunk.done).toBe(false)
 
-      const reader = stream.getReader()
-      const firstChunk = await reader.read()
-      expect(firstChunk.done).toBe(false)
+    // Simulate client disconnect
+    await reader.cancel()
 
-      // Simulate client disconnect
-      await reader.cancel()
+    // Wait for nested Suspense callbacks to fire against the closed controller
+    await new Promise((resolve) => setTimeout(resolve))
 
-      // Wait for nested Suspense callbacks to fire against the closed controller
-      await new Promise((resolve) => setTimeout(resolve, 200))
+    expect(unhandled).toHaveLength(0)
+    expect(onError).not.toHaveBeenCalled()
 
-      expect(unhandled).toHaveLength(0)
-    } finally {
-      process.off('unhandledRejection', onRejection)
-      suspenseCounter++
-    }
+    process.off('unhandledRejection', onRejection)
   })
 
   it('should not call onError when reader is cancelled during a slow callback resolution', async () => {
@@ -943,51 +926,42 @@ d.replaceWith(c.content)
     const onRejection = (e: unknown) => unhandled.push(e)
     process.on('unhandledRejection', onRejection)
 
-    try {
-      let signalCallbackStarted!: () => void
-      const callbackStarted = new Promise<void>((r) => {
-        signalCallbackStarted = r
-      })
+    let signalCallbackStarted!: () => void
+    const callbackStarted = new Promise<void>((r) => {
+      signalCallbackStarted = r
+    })
 
-      const Content = () => {
-        return new Promise<HtmlEscapedString>((resolve) => {
-          setTimeout(() => {
-            const html = raw('<p>content</p>', [
-              ((opts: any) => {
-                if (opts.phase === HtmlEscapedCallbackPhase.BeforeStream) {
-                  signalCallbackStarted()
-                  return new Promise<string>((r) => setTimeout(() => r(''), 50))
-                }
-                return undefined
-              }) as any,
-            ])
-            resolve(html as unknown as HtmlEscapedString)
-          }, 10)
-        })
-      }
+    const Content = async () =>
+      raw('<p>content</p>', [
+        ((opts: any) => {
+          if (opts.phase === HtmlEscapedCallbackPhase.BeforeStream) {
+            signalCallbackStarted()
+            return new Promise<string>((r) => setTimeout(() => r('')))
+          }
+          return undefined
+        }) as any,
+      ])
 
-      const onError = vi.fn()
-      const stream = renderToReadableStream(
-        <Suspense fallback={<p>Loading...</p>}>
-          <Content />
-        </Suspense>,
-        onError
-      )
+    const onError = vi.fn()
+    const stream = renderToReadableStream(
+      <Suspense fallback={<p>Loading...</p>}>
+        <Content />
+      </Suspense>,
+      onError
+    )
 
-      const reader = stream.getReader()
-      await reader.read()
+    const reader = stream.getReader()
+    await reader.read()
 
-      await callbackStarted
-      await reader.cancel()
+    await callbackStarted
+    await reader.cancel()
 
-      await new Promise((resolve) => setTimeout(resolve, 200))
+    await new Promise((resolve) => setTimeout(resolve))
 
-      expect(onError).not.toHaveBeenCalled()
-      expect(unhandled).toHaveLength(0)
-    } finally {
-      process.off('unhandledRejection', onRejection)
-      suspenseCounter++
-    }
+    expect(unhandled).toHaveLength(0)
+    expect(onError).not.toHaveBeenCalled()
+
+    process.off('unhandledRejection', onRejection)
   })
 
   it('should not throw when cancelled before initial content resolves', async () => {
@@ -995,24 +969,20 @@ d.replaceWith(c.content)
     const onRejection = (e: unknown) => unhandled.push(e)
     process.on('unhandledRejection', onRejection)
 
-    try {
-      const onError = vi.fn()
-      const stream = renderToReadableStream(
-        new Promise<HtmlEscapedString>((resolve) =>
-          setTimeout(() => resolve(raw('<p>slow content</p>') as HtmlEscapedString), 50)
-        ),
-        onError
-      )
+    const onError = vi.fn()
+    const stream = renderToReadableStream(
+      Promise.resolve(raw('<p>slow content</p>') as HtmlEscapedString),
+      onError
+    )
 
-      const reader = stream.getReader()
-      await reader.cancel()
+    const reader = stream.getReader()
+    await reader.cancel()
 
-      await new Promise((resolve) => setTimeout(resolve, 200))
+    await new Promise((resolve) => setTimeout(resolve))
 
-      expect(onError).not.toHaveBeenCalled()
-      expect(unhandled).toHaveLength(0)
-    } finally {
-      process.off('unhandledRejection', onRejection)
-    }
+    expect(unhandled).toHaveLength(0)
+    expect(onError).not.toHaveBeenCalled()
+
+    process.off('unhandledRejection', onRejection)
   })
 })

@yusukebe yusukebe changed the title Fix "Invalid state: Controller is already closed" fix(jsx): Fix "Invalid state: Controller is already closed" Mar 4, 2026
Co-authored-by: Taku Amano <[email protected]>
Copy link
Copy Markdown
Member

@yusukebe yusukebe left a comment

Choose a reason for hiding this comment

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

LGTM!

@codecov
Copy link
Copy Markdown

codecov bot commented Mar 4, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 91.46%. Comparing base (b1df304) to head (63d908f).
⚠️ Report is 13 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #4770      +/-   ##
==========================================
- Coverage   91.48%   91.46%   -0.02%     
==========================================
  Files         177      177              
  Lines       11551    11579      +28     
  Branches     3353     3368      +15     
==========================================
+ Hits        10567    10591      +24     
- Misses        983      987       +4     
  Partials        1        1              

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@yusukebe
Copy link
Copy Markdown
Member

yusukebe commented Mar 4, 2026

The @usualoma patch should be applied as a refactoring, and I did it myself.

@usualoma Can you review this again?

@usualoma
Copy link
Copy Markdown
Member

usualoma commented Mar 4, 2026

@yusukebe Thank you :shipit:

@yusukebe
Copy link
Copy Markdown
Member

yusukebe commented Mar 4, 2026

@gaearon @usualoma Thanks! I'll merge.

@yusukebe yusukebe merged commit b8cff18 into honojs:main Mar 4, 2026
20 checks passed
@gaearon
Copy link
Copy Markdown
Contributor Author

gaearon commented Mar 7, 2026

thanks for the changes! i'm not very familiar with streams myself so i don't have opinions about what's the best way to do this

@gaearon gaearon deleted the streaming-bug-crash branch March 7, 2026 01:12
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

ERR_INVALID_STATE when canceling during nested Suspense

3 participants