Skip to content

fix(stream): respect backpressure/cancellation - #827

Merged
harlan-zw merged 6 commits into
mainfrom
fix/stream-lifecycle
Jul 14, 2026
Merged

harlan-zw merged 6 commits into
mainfrom
fix/stream-lifecycle

Conversation

@harlan-zw

@harlan-zw harlan-zw commented Jul 13, 2026 •

Copy link
Copy Markdown
Collaborator

🔗 Linked issue

N/A

❓ Type of change

  • 📖 Documentation
  • 🐞 Bug fix
  • 👌 Enhancement
  • ✨ New feature
  • 🧹 Chore
  • ⚠️ Breaking change

📚 Description

wrapStream drained the whole upstream inside start(), so downstream backpressure was ignored and cancelling the wrapped stream never propagated upstream. It now uses a standard pull/cancel implementation: one upstream read per downstream request, cancel(reason) forwarded to the upstream reader exactly once with the lock always released, and the closing end suffix never emitted after an upstream error. The reader is acquired in an async start(), so a locked or invalid upstream yields an errored stream instead of a synchronous throw, and upstream cancel() rejections are swallowed so fire-and-forget cancellation can't crash the process with an unhandled rejection.

Separately, renderSSRHeadSuspenseChunk, renderSSRHeadShell, and prepareStreamingTemplate cleared head.entries before producing output, so a serialization or template failure (cyclic value, BigInt, bad template) lost the entries. All three now clear entries only after output is produced. On serialization failure, renderSSRHeadSuspenseChunk drops just the unserializable entries so one bad input can't poison every later chunk render while valid entries still flush.

The Vue package shipped its own pre-fix copy of wrapStream (eager drain, no cancel handler), so none of these fixes reached Vue streaming users. Core wrapStream now takes an optional flushChunk hook for interleaving head-update scripts, and Vue's createStreamableHead delegates to it instead of forking.

Successful output is byte-identical to before. New stream-lifecycle.test.ts covers backpressure, cancellation (mid-read races, rejecting upstream cancel, already-errored upstream), error propagation, locked-upstream failure mode, and entry retention; Vue's streaming suite gains cancellation-propagation and backpressure tests for the context wrapStream.

Benchmarks

packages/unhead/test/bench/stream.bench.ts (from #835), interleaved A/B against main on the same machine, no-op baselines within 2%:

bench main (eager drain) this PR (pull-based)
wrapStream: drain 100-chunk stream 20,419 hz 16,796 hz
wrapStream: shell first-read then cancel 100,788 hz 133,960 hz
prepareStreamingTemplate x100 2,296 hz 2,305 hz
renderSSRHeadSuspenseChunk x100 (5 entries per chunk) 6,259 hz 6,110 hz

The drain case is volatile between rounds (a second round had this PR ahead of main); worst case is roughly 0.1-0.2 us of read handshake per chunk. That cost only shows when the consumer drains at full speed with zero per-chunk work, the one scenario eager draining wins. Real consumers are network sockets where throughput is bounded by the client, and the old version buffered the whole app output regardless. Cancel is consistently 30%+ faster because the wrapper stops reading instead of consuming the rest of the upstream.

Summary by CodeRabbit

  • Bug Fixes
    • Improved SSR head streaming: applies the shell/end in the right sequence, serializes queued head entries before emitting suspense chunks, and delays clearing queued entries until streaming steps succeed.
    • Refined stream lifecycle handling for correct backpressure and more reliable cancellation/error behavior, preventing unintended closing suffix output.
    • Updated Vue streaming head implementation to rely on the shared streaming wrapper and simplified the suspense patch injection.
  • Tests
    • Expanded wrap/consume lifecycle coverage (byte-identical output, backpressure, cancellation propagation/reasons, upstream lock and error handling, and retry/retention behavior).

…entries on failure

Two bug classes in the streaming SSR server helpers:

1. wrapStream drained the entire upstream inside start() regardless of
   downstream demand, had no cancel handler, and never propagated
   cancellation upstream. It now uses a standard pull/cancel
   implementation: the shell is enqueued once in start(), pull() reads at
   most one upstream chunk per downstream request, cancel(reason) is
   propagated to the upstream reader exactly once, and the reader is
   released on completion, cancellation, and failure. An upstream error
   errors the wrapped stream without emitting the closing suffix.
   Successful output remains byte-identical.

2. renderSSRHeadSuspenseChunk, renderSSRHeadShell, and
   prepareStreamingTemplate cleared head.entries before the output was
   safely produced, so a serialization failure (cyclic value, BigInt) or
   template failure lost the entries. They now clear only after the
   output is successfully produced; failures leave entries intact for
   retry and the original error propagates.
@coderabbitai

coderabbitai Bot commented Jul 13, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

Streaming SSR head rendering now retains queued entries when rendering or serialization fails. Stream wrapping uses pull-based backpressure with cancellation and error handling, Vue delegates to the shared wrapper, and tests cover lifecycle behavior and retry semantics.

Changes

Streaming pipeline hardening

Layer / File(s) Summary
Entry retention and template preparation
packages/unhead/src/stream/server.ts, packages/unhead/test/streaming/stream-lifecycle.test.ts
Shell rendering, suspense serialization, and template preparation clear head.entries only after successful output construction, while preserving valid entries when individual serialization fails.
Pull-based stream lifecycle
packages/unhead/src/stream/server.ts, packages/unhead/test/streaming/stream-lifecycle.test.ts
wrapStream reads incrementally through pull(), propagates upstream completion and errors, and cancels or releases the active reader when required.
Vue stream wrapper integration
packages/vue/src/stream/server.ts, packages/vue/test/streaming.test.ts
Vue delegates stream orchestration to wrapStream and provides serialized head patches through flushChunk; tests cover cancellation and non-eager consumption.
Streaming failure and retry validation
packages/unhead/test/streaming/stream-lifecycle.test.ts
Tests cover failed upstream and template operations, omitted closing output, retained entries, selective entry removal, and successful retries.

Estimated code review effort: 4 (Complex) | ~60 minutes

Sequence Diagram(s)

sequenceDiagram
  participant DownstreamConsumer
  participant wrapStream
  participant UpstreamReader
  participant VueHead
  DownstreamConsumer->>wrapStream: request next chunk
  wrapStream->>UpstreamReader: read one upstream chunk
  UpstreamReader-->>wrapStream: chunk, completion, or error
  wrapStream->>VueHead: generate serialized head patch
  wrapStream-->>DownstreamConsumer: enqueue chunk or closing HTML
  DownstreamConsumer->>wrapStream: cancel with reason
  wrapStream->>UpstreamReader: cancel and release reader
Loading

Possibly related PRs

  • unjs/unhead#750: Both changes modify prepareStreamingTemplate and streamed-content placement.
  • unjs/unhead#752: Both changes touch Vue streaming head serialization and suspense patch emission.
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title is concise, conventional, and accurately summarizes the main streaming backpressure/cancellation change.
Description check ✅ Passed The description follows the template and covers the linked issue, bug-fix type, and a detailed explanation of the changes.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/stream-lifecycle

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

… read

cancel() clears the shared reader while pull() may still be awaiting
reader.read(); when the cancelled read resolves, pull would touch an
undefined reader and enqueue the closing suffix on a cancelled stream.
pull() now captures the reader locally and re-checks ownership after the
awaited read: if cancel() won the race it returns immediately, leaving
reader teardown to cancel().
@github-actions

github-actions Bot commented Jul 13, 2026 •

Copy link
Copy Markdown
Contributor

📦 Bundle Size

✅ No notable changes

All bundles (14)
Bundle Gzipped Brotli Raw
Core
Client (Minimal) 5.1 kB 4.7 kB 12.8 kB ✅
Client (Full) 8.5 kB 7.7 kB 22 kB ✅
Client (Self-Contained) 5.5 kB 4.9 kB 13.5 kB ✅
Server (Minimal) 4.5 kB 4.1 kB 11.3 kB ✅
Server (Self-Contained) 4.9 kB 4.4 kB 12 kB ✅
Vue
Vue Client (Minimal) 5.6 kB 5.1 kB 13.8 kB ✅
Vue Client (Full) 9.2 kB 8.4 kB 23.9 kB ✅
Vue Server (Minimal) 5 kB 4.5 kB 12.3 kB ✅
React
React Client (Minimal) 5.6 kB 5 kB 13.8 kB ✅
React Client (Full) 9.4 kB 8.5 kB 24.4 kB ✅
React Server (Minimal) 4.8 kB 4.4 kB 12 kB ✅
Schema.org
Schema.org (Minimal) 9.6 kB 8.7 kB 26.4 kB ✅
Schema.org Imports 0.1 kB 0.1 kB 0.1 kB ✅
Schema.org Vue Meta 0.4 kB 0.3 kB 0.8 kB ✅

⚡ Performance (directional)

⚠️ 2 slower · past the per-metric noise gate

Benchmark base → PR Δ
SSR allocated / render 253 KiB → 273.6 KiB 🔴 +20.6 KiB (+8.1%)
Streaming allocated / drain 131.4 KiB → 161.9 KiB 🔴 +30.5 KiB (+23.2%)
All benchmarks (14)
Benchmark PR Δ RME
SSR render (CPU) 0.425 ms ~ noise ±11.7%
SSR render (wall) 0.284 ms ~ noise ±6.3%
SSR allocated / render 273.6 KiB 🔴 +20.6 KiB (+8.1%) —
Schema.org cached render (CPU) 0.397 ms ~ noise ±5.0%
Schema.org cached render (wall) 0.262 ms ~ noise ±1.9%
Schema.org cached allocated / render 145.3 KiB ~ noise —
Streaming wrapStream drain (CPU) 0.254 ms ~ noise ±3.5%
Streaming wrapStream drain (wall) 0.158 ms ~ noise ±3.9%
Streaming allocated / drain 161.9 KiB 🔴 +30.5 KiB (+23.2%) —
Streaming suspense chunk (CPU) 0.011 ms ~ noise ±5.7%
Streaming allocated / suspense chunk 4.6 KiB ~ noise —
CSR DOM mutations / nav 38 ~ noise —
CSR re-render (CPU) 0.853 ms ~ noise ±4.8%
CSR re-render (wall) 0.478 ms ~ noise ±1.9%

Baseline: main @ 179db94 · 2026-07-14 · gzipped is the headline size metric · perf is directional (shared-runner, gated)

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/unhead/src/stream/server.ts`:
- Around line 256-306: Update the ReadableStream cancel handler to always
release the lock for activeReader by placing activeReader.releaseLock() in a
finally block around activeReader.cancel(reason). Preserve the existing reader
cleanup and cancellation behavior.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 5712cfe4-5288-45f3-bad3-0e324156577f

📥 Commits

Reviewing files that changed from the base of the PR and between b9254db and 520c82a.

📒 Files selected for processing (2)
  • packages/unhead/src/stream/server.ts
  • packages/unhead/test/streaming/stream-lifecycle.test.ts

Comment thread packages/unhead/src/stream/server.ts Resolved
@harlan-zw harlan-zw mentioned this pull request Jul 13, 2026
4 of 6 tasks
@harlan-zw harlan-zw changed the title fix(stream): respect backpressure/cancellation in wrapStream, retain entries on failure fix(stream): respect backpressure/cancellation Jul 14, 2026
… core

Adversarial review findings:

- wrapStream: acquire the upstream reader in an async start() so a locked
  or invalid upstream yields an errored stream instead of a synchronous
  throw, and head.entries stay intact for retry on any start failure
- wrapStream: swallow upstream cancel() rejections (an errored upstream
  rejects with its stored error) so fire-and-forget cancellation cannot
  surface an unhandled rejection
- wrapStream: single cancel-race check in pull() via a tagged read result,
  skip enqueueing an empty end chunk, hoist the stateless TextEncoder
- renderSSRHeadSuspenseChunk: drop only unserializable entries on failure
  so one cyclic/BigInt input cannot poison every subsequent chunk render
- add an optional flushChunk hook to wrapStream and delete the Vue
  package's pre-fix fork of the implementation, so Vue streaming gets
  backpressure and cancellation propagation too
- dedupe shell construction shared by renderSSRHeadShell and the
  prepareStreamingTemplate no-split fallback
@harlan-zw harlan-zw mentioned this pull request Jul 14, 2026
1 of 6 tasks
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.

1 participant