Skip to content

fix(handler): don't stream a background refresh to a stale request - #116

Open
RihanArfan wants to merge 1 commit into
unjs:mainfrom
RihanArfan:fix/resolution-status
Open

RihanArfan wants to merge 1 commit into
unjs:mainfrom
RihanArfan:fix/resolution-status

Conversation

@RihanArfan

@RihanArfan RihanArfan commented Nov 16, 2026 •

Copy link
Copy Markdown

With stream: true, a cached handler decides whether to stream the body to the request, and which x-cache value to send, from a status stored per request event. Every cached call made with the same event writes to it and nothing clears it, so another cached call on the same request can change both decisions.

This shows up in two ways:

  • With swr, if middleware calls a cached function with the event first, a request for an expired entry waits for the full render and gets the new body with x-cache: MISS. It should get the stored copy right away with x-cache: STALE.
  • A cached function called inside the handler sets the streamed x-cache to its own status.
const getSession = defineCachedFunction(async (event) => loadSession(event), { maxAge: 60 });
const page = defineCachedHandler(renderPage, { stream: true, swr: true, maxAge: 60 });

await getSession(event); // middleware
await page(event); // page entry has expired
// expected: x-cache: STALE, stored body sent right away
// actual:   x-cache: MISS, new body sent after the full render

Each resolution now passes its own status to serialize as ctx.status, and the per-event status is removed. Handlers without stream: true aren't affected. Regression tests for both cases are included.

@pi0x found this while reviewing #109 and #110 (1, 2, 3). It also happens on main without those PRs, so it's split out here. #109 and #110 are stacked on this PR, for nitrojs/nitro#4904.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes

    • Cached streaming responses now use the status of their own request, preventing nested or concurrent cache calls from affecting response streams or cache-status headers.
    • Requests served stale data no longer receive a stream from a background refresh.
  • Documentation

    • Clarified that custom serializers receive the call’s arguments and cache status, including what each status means.
    • Removed the resolveStatus API reference; the helper is no longer available.

@vercel

vercel Bot commented Nov 16, 2026

Copy link
Copy Markdown

@RihanArfan is attempting to deploy a commit to the unjs Team on Vercel.

A member of the Team first needs to authorize it.

@coderabbitai

coderabbitai Bot commented Nov 16, 2026 •

Copy link
Copy Markdown

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

The cache serialization context now includes the initiating resolution’s status. HTTP response serialization uses that status to decide whether to stream. Regression tests cover stale responses and status isolation with nested cached calls.

Changes: Cache status propagation

Layer / File(s) Summary
Resolution status contract and propagation
src/types.ts, src/cache.ts, src/http/index.ts, README.md, docs/docs/2.functions.md
The serialize context adds the initiating resolution’s cache status, and the HTTP handler passes that status to response serialization. The event-based resolveStatus helper and its README reference are removed.
HTTP stream gating and regression coverage
src/http/entry.ts, test/index.test.ts, .agents/cache.md, .agents/http/stream.md
Response serialization streams only when its eligibility checks pass and the status is not stale. Regression tests cover stale responses and status isolation with nested cached calls. Documentation describes the status flow.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Bug fix

Possibly related PRs

  • unjs/ocache#110: Adds getCacheStatus(event), which uses the event-level cache status path that this PR replaces for serialization.

Suggested reviewers: pi0, pi0x, unjica

Merge Risk: Minimal · up to dab23

This fix stops cached streaming handlers from reusing another call's status on the same request event. Stale requests now get the stored body immediately, and the x-cache header reflects the handler's own entry. The removed resolveStatus helper is a public API removal, but the change documents it. No actionable merge risk remains.

Pre-merge checks: Passed 4

Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title "fix(handler): don't stream a background refresh to a stale request" matches the main change. The PR stops a stale-request handler from streaming an SWR background refresh. It passes each re…
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.
Full details: Title check

Explanation

The title "fix(handler): don't stream a background refresh to a stale request" matches the main change. The PR stops a stale-request handler from streaming an SWR background refresh. It passes each resolution's status to serialize as ctx.status and removes the per-event resolveStatus registry. The title names the fix, the affected component (handler), and the behavior, which fits the changeset. It is a Conventional Commits style title and is under 70 characters.

Finishing Touches

Generate unit tests (beta)

  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: d7be6450-2d3d-485d-96ab-d113e0b96d0b
Commits

Reviewing files that changed from the base of the PR and between ad801e2 and dab231a.

Files selected for processing: 9

  • .agents/cache.md
  • .agents/http/stream.md
  • README.md
  • docs/docs/2.functions.md
  • src/cache.ts
  • src/http/entry.ts
  • src/http/index.ts
  • src/types.ts
  • test/index.test.ts
Files with no reviewable changes: 1

  • README.md

Included review availability: This review used your included allowance. Your plan provides up to 2 included reviews per hour; 1 remain after this review.

Comment thread src/cache.ts
let resolveStatuses: WeakMap<HTTPEvent, CacheStatus> | undefined;

/** The status of the foreground resolution this event leads, if it leads one. */
export function resolveStatus(event: HTTPEvent): CacheStatus | undefined {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This is a public api change!

This branch has not been deployed

No deployments
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.

2 participants