Skip to content

fix(tanstack,blocks): device no dedup de página e slot inflight liberado após 10s - #664

Open
aline-pereira wants to merge 2 commits into
7.xfrom
fix/inflight-device-and-slot-timeout
Open

aline-pereira wants to merge 2 commits into
7.xfrom
fix/inflight-device-and-slot-timeout

Conversation

@aline-pereira

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

Copy link
Copy Markdown
Contributor

Problema

Dois mapas de dedup de módulo, ambos medidos em produção na oficina-tanstack (QA da PLP, 08–09/10):

  1. pageInflight (cmsRoute.ts) sem device na chave. Requisições concorrentes ao mesmo path, uma de desktop e outra de iPhone, recebiam o MESMO PageResult — device e saída dos section loaders de quem ganhou a corrida. O HTML errado era gravado no cache de borda sob o segmento certo: 1 em ~25 pares concorrentes, servido aos iPhones seguintes por ~50 min (texto de SEO sem o corte de 80 caracteres, espaçamentos de desktop). Antes: 8/8 iPads com o render de celular (smart banner de 56 px).
  2. moduleInflight (createCachedLoaderFromModule) sem limite. Diferente do cachedLoader (que usa withInflightTimeout, Memory leak: 4 module-level inflight Maps in start retain hung Promises (exceededMemory in prod) #223), uma chamada upstream que nunca resolve prende todo caller seguinte com a mesma chave até o cliente desistir. Sintoma na PLP: "Ver mais produtos" e o preview de filtros sem resposta em ~20% das chamadas numa janela (curl: nenhuma resposta após 130 s).

Mudança

  • cmsRoute: detectDevice(user-agent) entra na chave do pageInflight.
  • Novo releaseInflightSlotAfter(map, key, promise, ms = 10s): depois do limite, se o slot ainda é dessa promise, ele é apagado — novos callers começam do zero, e o dono continua esperando o próprio trabalho (sem rejeitar um render apenas lento, diferente de withInflightTimeout).
  • Aplicado a pageInflight e moduleInflight; o finally só apaga o slot se ele ainda for seu.
  • Export @decocms/blocks/sdk/inflightTimeout.

Testes

  • inflightTimeout.test.ts: libera slot pendente após o limite; não apaga promise mais nova.
  • cachedLoaderModule.test.ts: caller após 10 s não entra em voo pendurado.
  • bun run --filter @decocms/blocks typecheck / @decocms/tanstack typecheck ✅. As 3 falhas de workerEntry.test.ts (draft preview / CDN-Cache-Control) já existem em main.

🤖 Generated with Claude Code

Review follow-up

  • Hung slot never released on Workers — releaseInflightSlotAfter relied on setTimeout, which never fires once the owning request has finished/been cancelled, so the zombie slot stayed in the isolate. → Replaced by getLiveInflight / setInflight (@decocms/blocks/sdk/inflightTimeout): slots store startedAt and a slot older than the bound is ignored and deleted when the next caller reads it; setInflight also sweeps expired slots of other keys. No timer. Owners keep waiting on their own work; finally only clears its own slot. Applied to pageInflight and moduleInflight. → Tests with Date.now mocked and no timer advanced (setTimeout asserted never called): expired slot not reused, owner still resolves, a late-settling old flight doesn't evict the newer one, sweep of other keys; cachedLoaderModule.test.ts hung-upstream case rewritten timer-free (fails on the previous commit).
  • Page dedup key ignored the rest of the edge segment (region, sales channel, logged-in, geo, A/B cohort, bot, __fetch, custom fields) → concurrent requests from different regions shared one render. → The worker entry publishes the __* dimension params of buildCacheKey for the request in the RequestContext bag (EDGE_SEGMENT_BAG_KEY, derived from buildCacheKey itself so new dimensions follow automatically; a throwing site buildSegment falls back to the device-only key); loadCmsPage folds it into the key via pageInflightKey (device kept for sites without the worker entry). → Tests: pageInflightKey separates segments/devices/buckets; worker entry publishes different values for two regions and for bot vs human, the same for the same segment.
  • Known limitation (unchanged, pre-existing): within one edge segment, two concurrent logged-in requests can still share a render (the edge bypasses its cache for them, but the in-isolate dedup does not). Follow-up proposal: skip pageInflight when the segment is loggedIn.

Summary by cubic

Fixes two request-deduplication bugs in @decocms/tanstack and @decocms/blocks: concurrent requests from different devices or edge-cache segments shared one render (serving the wrong page), and dedup slots stuck on never-resolving upstream calls hung every later caller.

  • pageInflight now folds the full edge segment into its key (device plus region, sales channel, A/B cohort, bot, geo, and other dimensions published by the worker entry), so requests the edge cache keeps apart never share a render.
  • Dedup slots now expire by age (startedAt) instead of via setTimeout, which never fires on Workers for requests whose response already went out.
  • Expiry is checked when the next caller arrives: new callers start fresh past the 10s bound, while callers already waiting keep awaiting their own work, and an expired slot never evicts a newer flight.
  • moduleInflight gets the same age-based expiry through getLiveInflight/setInflight, exported as @decocms/blocks/sdk/inflightTimeout.
  • Known limitation (pre-existing): within one edge segment, two concurrent logged-in requests can still share a render. Follow-up proposal: skip pageInflight when the segment is loggedIn.

Written for commit dd7db50. Summary will update on new commits.

View guided diff Turn on auto-fix

@aline-pereira
aline-pereira requested a review from a team October 9, 2026 12:32
aline-pereira and others added 2 commits October 9, 2026 17:26
…ight slots

pageInflight keyed only by path, so concurrent mobile and desktop requests
shared one PageResult (device, section loader output) and the wrong render
was edge-cached under the other segment. createCachedLoaderFromModule's
moduleInflight had no bound at all: one upstream call that never settles
pinned every later caller with the same key until the client gave up.

- cmsRoute: add detectDevice(ua) to the inflight key
- releaseInflightSlotAfter(): after 10s a still-pending slot is freed so new
  callers start fresh; the owner keeps awaiting its own work (no rejection)
- applied to pageInflight and moduleInflight; finally() only deletes its own slot

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
… the edge segment

Two review findings on the inflight dedup maps.

1. `releaseInflightSlotAfter` freed a hung slot with `setTimeout`. On Workers a
   timer registered by a request whose response already went out (or that was
   cancelled) never fires, so the slot stayed pinned in the isolate — exactly
   the zombie case it was meant to handle (reproduced in workerd). Slots now
   record `startedAt`, and `getLiveInflight` treats one older than the bound as
   absent (deleting it) when the next caller arrives; `setInflight` also sweeps
   expired slots of other keys. No timer involved. Callers already waiting on
   the old flight keep waiting on it, and its `finally` only clears the slot if
   it is still its own. Replaces `releaseInflightSlotAfter` in both
   `pageInflight` (cmsRoute) and `moduleInflight` (cachedLoader).

2. The page dedup key carried the device but none of the other dimensions the
   edge cache splits on (region, sales channel, logged-in, geo, A/B cohort, bot,
   programmatic fetch, custom fields). On a regionalized store two concurrent
   requests from different regions shared one render, and the joiner cached the
   winner's page under its own key. The worker entry now publishes the dimension
   params of `buildCacheKey` for the request in the RequestContext bag
   (`EDGE_SEGMENT_BAG_KEY`), derived from `buildCacheKey` itself so a new
   dimension reaches the dedup automatically, and `loadCmsPage` folds it into
   the key (device stays for sites without the worker entry).

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

Copy link
Copy Markdown
Contributor Author

Rebase sobre main (0d125f1) para resolver o conflito.

  • O que conflitou: só packages/tanstack/src/sdk/workerEntry.test.ts — main adicionou no fim do arquivo os blocos "Set-Cookie deduplication…" (fix(tanstack): dedupe Set-Cookie by name + Domain + Path, not name alone #642) e "/live/invoke alias" (fix(tanstack): serve /live/invoke as an alias of /deco/invoke, 400 on malformed JSON #645), e o PR adicionou "edge segment published for the render dedup" no mesmo ponto. Mantive os três; os imports já tinham mergeado sozinhos.
  • workerEntry.ts, cmsRoute.ts e cachedLoader.ts mergearam sem conflito. main não mexeu na lógica de inflight/dedup, então não havia nada a deduplicar.
  • Testes: typecheck de @decocms/blocks e @decocms/tanstack ✅. inflightTimeout, cachedLoaderModule, cmsRoute e workerEntry: 117/120. As 3 falhas (draft preview ×2, CDN-Cache-Control no-store) também acontecem em origin/main. Na suíte completa de packages/blocks* + packages/tanstack, o conjunto de falhas é idêntico ao de main (43, pré-existentes), e o PR passa 11 testes a mais.

@aline-pereira
aline-pereira force-pushed the fix/inflight-device-and-slot-timeout branch from 0e54123 to dd7db50 Compare October 9, 2026 20:36
@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]>
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