Repository navigation
fix(stream): respect backpressure/cancellation - #827
Conversation
…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.
📝 WalkthroughWalkthroughStreaming 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. ChangesStreaming pipeline hardening
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
Possibly related PRs
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
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. Comment |
… 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().
📦 Bundle Size✅ No notable changes All bundles (14)
⚡ Performance (directional)
All benchmarks (14)
Baseline: main @ 179db94 · 2026-07-14 · gzipped is the headline size metric · perf is directional (shared-runner, gated) |
There was a problem hiding this comment.
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
📒 Files selected for processing (2)
packages/unhead/src/stream/server.tspackages/unhead/test/streaming/stream-lifecycle.test.ts
… 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
🔗 Linked issue
N/A
❓ Type of change
📚 Description
wrapStreamdrained the whole upstream insidestart(), 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 closingendsuffix never emitted after an upstream error. The reader is acquired in an asyncstart(), so a locked or invalid upstream yields an errored stream instead of a synchronous throw, and upstreamcancel()rejections are swallowed so fire-and-forget cancellation can't crash the process with an unhandled rejection.Separately,
renderSSRHeadSuspenseChunk,renderSSRHeadShell, andprepareStreamingTemplateclearedhead.entriesbefore 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,renderSSRHeadSuspenseChunkdrops 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. CorewrapStreamnow takes an optionalflushChunkhook for interleaving head-update scripts, and Vue'screateStreamableHeaddelegates to it instead of forking.Successful output is byte-identical to before. New
stream-lifecycle.test.tscovers 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 contextwrapStream.Benchmarks
packages/unhead/test/bench/stream.bench.ts(from #835), interleaved A/B against main on the same machine, no-op baselines within 2%: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