Skip to content

fix(blocks): inflight dedup survives a cancelled owner request - #672

Closed
aline-pereira wants to merge 1 commit into
7.xfrom
fix/blocks-inflight-joiner-survives-cancelled-owner
Closed

aline-pereira wants to merge 1 commit into
7.xfrom
fix/blocks-inflight-joiner-survives-cancelled-owner

Conversation

@aline-pereira

@aline-pereira aline-pereira commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

Problem

createCachedLoader (inflightRequests) and createCachedLoaderFromModule / createLoaderEntry (moduleInflight) dedup concurrent calls per isolate: the first caller's Promise sits in a module-level map and every later caller with the same key awaits it.

On Cloudflare Workers that Promise's subrequests and timers belong to the request that created it. When that client goes away (reload, SPA navigation, tab closed mid-call), the runtime cancels its pending I/O:

  • the shared Promise never settles, so its .finally() never frees the map slot;
  • withInflightTimeout does not rescue it — its setTimeout was armed in the cancelled request and never fires;
  • every later caller for that key joins the dead Promise and hangs, for the life of the isolate.

moduleInflight has no timeout at all, so it is affected even without the timer argument.

Fresh never had this: Deno does not cancel a handler's fetches when its client disconnects.

Repro / impact (deco-sites/oficina-tanstack, QA 08–10/10)

  • QA-145 (minicart Prime): getAdditionalMinicartData for a given cart stopped answering in an isolate after one aborted request for that cart.
  • QA-042 (PLP filters): "Aplicar" / filter preview (with-prime-price-table) hung for a given filter. Same window: ~20% of "Ver mais produtos" / filter-preview calls never answered; curl got no response after 130 s.
  • The site now works around it by wrapping every registry entry with cacheBackground (keepSharedWorkAlive, deco-sites/oficina-tanstack#490). That belongs in the framework.

Note: wrangler dev / Node do not cancel an aborted request's I/O, so it does not reproduce locally. The tests below simulate the cancellation: the owner's work never settles, and for createCachedLoader its timers are cleared with vi.clearAllTimers().

Fix (packages/blocks/src/sdk/cachedLoader.ts, inflightTimeout.ts)

  1. Keep the owner alive. The caller that starts a flight registers it with cacheBackground (ctx.waitUntil via the cache-storage bag the worker entry already binds). Its invocation then stays alive until the work settles, so joiners get the answer. Outside the worker entry this does nothing (no waitUntil bound).
  2. Timeout per joiner. The new joinInflight(shared, onStall, ms = 10s) arms the timer in the joiner's request. If shared has not settled by then, the joiner evicts the slot (only if it still holds that same Promise) and runs again: it becomes the new owner, or joins a flight another joiner already restarted. If shared settles first, the joiner gets that result, as before.
  3. Slots are freed only by their owner. .finally() deletes the entry only while it still holds its own Promise, so a late flight never evicts a newer one.

Semantics for the healthy path are unchanged: concurrent callers still share one upstream call, a live owner's withInflightTimeout still fires first (it was armed earlier), and nothing is retained by moduleInflight after settlement.

Related: #664 bounds slot age for new callers (getLiveInflight). That is complementary. It does not release callers that already joined a dead Promise, and it does not keep the owner's work alive. This PR touches the same lines in createCachedLoaderFromModule, so whichever lands second needs a small rebase.

Tests

packages/blocks/src/sdk/cachedLoaderCancelledOwner.test.ts (new, 9 tests). Without the fix, 8 of the 9 fail (two of them by hanging until the 5 s vitest timeout):

  • joinInflight: shared result wins in time; shared rejection propagates; falls back when shared never settles.
  • module loader: a joiner of a never-settling flight runs again after the timeout, and the dead slot is gone; an old flight settling late does not evict the newer one; the owner's work goes to waitUntil exactly once per flight (joiners do not register).
  • createCachedLoader: a joiner recovers when both the owner's Promise and its inflight timeout are dead, and its own result is cached (next call is a HIT); joiners of a live owner still share one call; the miss is registered with waitUntil.

How to test

# Node >= 24 (URLPattern)
cd packages/blocks
bun run test        # 986 passed
bun run typecheck   # clean

packages/tanstack tests: same 2 pre-existing failures as main (workerEntry.test.ts › draft preview), nothing new. biome check reports one formatting diff in withInflightTimeout. That code predates this PR and I left it alone.

Context: deco-sites/oficina-tanstack#490.

🤖 Generated with Claude Code


Summary by cubic

Fixes inflight dedup so a cancelled owner request no longer leaves later callers for the same key hanging forever.

On Cloudflare Workers a Promise's I/O and timers belong to the request that created it; when that client disconnects, the runtime cancels them, so the shared Promise left in the dedup map never settles and its withInflightTimeout never fires either. createCachedLoader and createCachedLoaderFromModule both kept joining that dead Promise, blocking every later caller for the life of the isolate. Node and wrangler dev don't cancel an aborted request's I/O, so this doesn't reproduce locally.

  • The owner's flight is registered with cacheBackground (ctx.waitUntil), keeping the work alive after its request ends.
  • Joiners arm joinInflight, a timeout of their own request: if the shared Promise hasn't settled in 10s, they evict the dead slot and run again.
  • Slots are freed only while they still hold that flight's Promise, so a late-settling old flight can't evict a newer one.
  • Healthy-path dedup is unchanged and waitUntil is inert outside the worker entry, so no migration is needed.

Written for commit 7954b5f. Summary will update on new commits.

View guided diff Turn on auto-fix

On Cloudflare Workers a Promise's subrequests and timers belong to the
request that created it. When that client disconnects (reload, navigation,
closed tab) the runtime cancels them: the Promise left in `inflightRequests`
(createCachedLoader) or `moduleInflight` (createCachedLoaderFromModule /
createLoaderEntry) never settles, its `.finally()` never frees the slot, and
`withInflightTimeout` is dead too (its timer was the cancelled request's).
Every later caller with that key hangs for the life of the isolate.

- The owner registers its flight with `cacheBackground` (ctx.waitUntil), so
  its invocation stays alive until the work settles.
- Joiners go through `joinInflight`: a timer of the joiner's own request.
  If the shared Promise has not settled in 10s, the joiner evicts the slot
  (only while it still holds that Promise) and runs again.
- `.finally()` only frees a slot it still owns, so a late flight never
  evicts a newer one.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@aline-pereira
aline-pereira requested a review from a team October 12, 2026 18:37
@tlgimenes
tlgimenes changed the base branch from main to 7.x October 12, 2026 19:07
@tlgimenes

Copy link
Copy Markdown
Contributor

Retargeted to 7.x: main is now v8 (@decocms/blocks 8.1.0, #671). The v7 line continues on the 7.x branch and releases to npm as @decocms/blocks@latest-7 (7.78.1 is out); v7-only packages (tanstack, nextjs, blocks-admin, blocks-cli, …) keep latest from 7.x.

JonasJesus42 added a commit that referenced this pull request Oct 13, 2026
…r inflight dedup) (#677)

## Problem: one closed tab leaves a URL hanging (524) for the life of
the isolate

Production, casaevideo (7.71.5), 13/10:
`https://www.casaevideo.com.br/4221?map=productClusterIds&order=OrderByTopSaleDESC&sort=orders%3Adesc`
returns **524 every time** on mobile. Desktop serves it only because the
edge cache still has a copy. Any variant of the URL (`&utm_source=x`,
`&page=2`, a different param order) renders in ~1 s with all 51
products. The upstream VTEX calls are healthy.

Evidence:
- **`wrangler tail` of the hung request:** `outcome: canceled`,
`cpuTime: 2`, `wallTime: 100003`, no logs, no exceptions. The worker
never starts rendering; it awaits a promise that never settles.
- **Not the edge cache:**
- with an `Authorization` header (`privateRequest`, which skips every
cache) the request still hangs, 4/4;
  - desktop forced past the cache hangs too, 3/3.
- **What it hangs on:** the module-global `pageInflight` in
`cmsRoute.ts`, keyed by URL only.
- **What leaves the dead promise there:** the owner request was
cancelled. On Workers, a client disconnect cancels the owner's pending
I/O and timers, so the shared promise never settles and `.finally()`
never frees the slot. That is the mechanism #672 describes.
- **How often the trigger fires:** `slow cancel: client disconnected`
appears 1,126 times in 6 h in `otel_logs` (casaevideo-tanstack).
- **Impact:** in `raw_cloudflare` the 524s are chronic, 10–90 per hour
across 10–25 distinct URIs for the last 3 days. Examples: PLPs, PDPs,
and `/fonts/lato-bold.woff2`, a lowercase miss that falls through to the
CMS 404 page.

## Fix: the two existing fixes, together on 7.x so they ship in one
release

Cherry-picked, original authors kept:

1. **#541 (@viktormarinho)**: `pageInflight` → per-request single flight
(`WeakMap<Request, …>`). A stalled or cancelled visitor can no longer
block later visitors of the same URL. Within one request, calls are
still deduplicated.
2. **#672 (@aline-pereira)**: the same failure in the loader layer
(`createCachedLoader`, `createCachedLoaderFromModule`).
- The owner's flight is kept alive with `cacheBackground` (`waitUntil`).
- Each joiner gets its own timer (`joinInflight`). It evicts a dead slot
and runs again.
   - Slots are only freed by their owner.

3. **Follow-up from review** (`046c8496`): `joinInflight` now runs
`onStall` through `Promise.resolve().then(onStall)`. Before, it was
called bare inside the timer. A synchronous throw escaped the timer and
left the joiner hanging; the throw can come from `cacheKeyFn`, from
`JSON.stringify` of circular props, or from `mod.default` before
`Promise.resolve` wraps it. A new test covers this; it fails without the
fix.

**Known trade-off (kept on purpose):** `moduleInflight` has no
owner-side timeout. A joiner cannot tell a *slow* owner from a *dead*
one, so after 10 s it evicts the slot and calls upstream again, even
when the owner's loader is healthy and just slow.
- The cost is bounded at one extra upstream call per key per 10 s, not
one per visitor: `releaseSlot` only evicts while the slot still holds
the old Promise, so concurrent joiners join the new flight.
- Before this PR the same case hung every joiner forever.
- If it matters, the follow-up is to wrap the module owner in
`withInflightTimeout`, as `createCachedLoader` already does.

Each fix alone leaves the other layer exposed. The page fix is the one
that resolves the URL above; the loader fix covers shelves and PLPs that
hang behind a dead loader flight.

**Relation to #664:**
- Its page part (device in the `pageInflight` key, plus a 10 s release
timer) becomes moot with per-request scoping. Its release timer is armed
in the owner request, so it dies with that request; #672 describes the
same trap.
- Its `moduleInflight` part overlaps with #672.

## Validation
- `packages/blocks`: 987/987 pass, including the 10 new tests in
`cachedLoaderCancelledOwner.test.ts`.
- `packages/tanstack`: 307/309. The 2 failures are `workerEntry.test.ts
› draft preview`, and they fail identically on `origin/7.x` without
these commits.
- Typecheck is clean for both packages.
- Both commits applied cleanly on top of 7.71.5. A casaevideo production
build in workerd served the URL above with 200 on mobile, desktop and
Googlebot. 6 concurrent requests to the same URL all returned 200, and
home, PDP and search pages returned 200.
- Caveat: `wrangler dev` does not cancel an aborted request's I/O, so
the production hang itself cannot be reproduced locally. The unit tests
simulate it.

Closes #541 and #672 once merged. #664 needs a rebase decision.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Stops a cancelled request from hanging later visitors of the same URL.
On Workers, a client disconnect cancels the owner's pending I/O and
timers, so the promise left in module-global inflight dedup maps never
settles and its cleanup never runs — every later caller waits forever
and gets a 524.

- Page loads dedupe only within one request (`WeakMap` keyed by
`Request`) instead of by URL, so a stalled visitor can't block later
ones.
- Loader flights are kept alive past their own request with
`cacheBackground` (`ctx.waitUntil`); joiners use `joinInflight`, a timer
owned by their own request, to evict dead slots and re-run.
- `joinInflight` runs `onStall` through `Promise.resolve()` so a
synchronous throw rejects the joiner instead of hanging it.
- A slot is only freed while it still holds the same promise, so a
late-settling flight never evicts a newer one.

<sup>Written for commit 046c849.
Summary will update on new commits.</sup>

<a href="https://cubic.dev/pr/decocms/blocks/pull/677?utm_source=github"
target="_blank" rel="noopener noreferrer"
data-no-image-dialog="true"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img
alt="View guided diff"
src="https://www.cubic.dev/buttons/review-in-cubic-light.svg"></picture></a>
<a
href="https://www.cubic.dev/action/auto-fix/pr/decocms/blocks/677?returnTo=https%3A%2F%2Fgithub.com%2Fdecocms%2Fblocks%2Fpull%2F677&source=description"
target="_blank" rel="noopener noreferrer"
data-no-image-dialog="true"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://www.cubic.dev/buttons/turn-on-auto-fix-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://www.cubic.dev/buttons/turn-on-auto-fix-light.svg"><img
alt="Turn on auto-fix"
src="https://www.cubic.dev/buttons/turn-on-auto-fix-light.svg"></picture></a>

<!-- End of auto-generated description by cubic. -->

---------

Co-authored-by: viktormarinho <[email protected]>
Co-authored-by: aline-pereira <[email protected]>
Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
@JonasJesus42

Copy link
Copy Markdown
Contributor

Closing: this landed on 7.x through #677 (page and cachedLoader dedup bounded by joinInflight, with cachedLoaderCancelledOwner.test.ts). Against today's 7.x the remaining diff only reverts later work (shouldCache, the ctx argument). The other in-flight maps are covered by #714.

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.

3 participants