Skip to content

fix(core): propagate upstream error status instead of always 500 - #3379

Merged
hellofanny merged 2 commits into
devfrom
fix/bff-error-status-propagation
Jun 8, 2026
Merged

hellofanny merged 2 commits into
devfrom
fix/bff-error-status-propagation

Conversation

@hellofanny

@hellofanny hellofanny commented Jun 4, 2026 •

Copy link
Copy Markdown
Contributor

Summary

The GraphQL BFF (/api/graphql handler in @faststore/core) collapsed every error into HTTP 500, even when the upstream VTEX error was a client error (400/401/403/404/...). Example: an invalid postalCode in the shipping simulation makes VTEX Checkout return 400, but the storefront received 500.

Root cause: after useMaskedErrors, the errors array holds GraphQLError instances (name === 'GraphQLError'). The handler used errors.find(isFastStoreError), which checks name === 'FastStoreError' and therefore never matched — the real FastStoreError (carrying extensions.status) is nested in originalError. So the status always fell back to 500.

Changes

  • Added recoverFastStoreError to unwrap the FastStoreError whether it is the error itself or nested in originalError of a masked GraphQLError.
  • The handler now responds with the recovered extensions.status (still ?? 500 as the safe default).
  • For a recovered FastStoreError, the JSON body exposes extensions.type and extensions.status always; the free-text message is included only when NODE_ENV !== 'production' (and always logged server-side).
  • Non-FastStoreErrors keep the masked, body-less 500 (error masking unchanged).
  • Added unit tests covering 400/401/403/404, an unmapped 429, unwrapped FastStoreError, non-FastStore→500, multi-error selection, and prod vs non-prod body gating.

Security note

Per root AGENTS.md (Security & Data Handling), this touches error-surface behavior. Only FastStoreError-derived details are exposed; all other errors remain masked. The free-text upstream message is restricted to non-production responses; production responses expose only the type/status enum.

Known limitations / follow-ups (not in this PR)

  • The storefront SDK (src/sdk/graphql/request.ts → ParseInvalidRequest) short-circuits on any non-2xx before reading the body, building its error from response.status/statusText. So the new JSON body benefits external/direct consumers and server logs, not the storefront UI. The storefront still benefits from the now-correct status. Surfacing the message in the UI would require updating ParseInvalidRequest.
  • Error responses (both error branches) set no cache-control; with a broader range of statuses now emitted (e.g. 404), consider adding no-store.
  • The catch-block error path (parseRequest/refresh-token) is still untested and returns a body-less response (shape differs from the try branch).

Test plan

  • pnpm vitest run test/pages/api/graphql.test.ts --project node (10/10 pass)
  • Full @faststore/core node suite green (217/217)
  • Manually verified: invalid postalCode shipping simulation now returns 400 (was 500); genuine upstream 500 (intelligent search) stays 500
  • Reviewer: confirm the intended status behavior change (consumers branching on 500 will now see accurate codes)

Made with Cursor

before - generic error 500
image
after - bad request
image

server-side log:

Graphql execution returned with error: [
{
message: '{"error":{"code":"ORD006","message":"The postal code (555) field in the shipping attachment is invalid","exception":null},"operationId":"f2c92a0b-d1f8-4cb6-8a4e-cb721fe60039","fields":{}}',
status: 400,
type: 'BadRequestError'
}
]

Jira Task

Summary by CodeRabbit

  • Bug Fixes

    • GraphQL API now unwraps and propagates known error types so responses use appropriate HTTP status codes (400, 401, 403, 404, etc.) and preserve upstream status when available.
    • Responses include a structured error payload with type and status; message is omitted in production.
  • Tests

    • Added tests covering status propagation, masked/unmasked errors, multi-error handling, and production vs. development response bodies.

The GraphQL BFF handler collapsed every error into HTTP 500 because
`errors.find(isFastStoreError)` never matched the masked GraphQLError
instances (the FastStoreError lives in `originalError`). Recover it so the
real upstream status (400/401/403/404/etc.) is propagated.

For a recovered FastStoreError the JSON body now exposes `extensions.type`
and `extensions.status`; the free-text `message` is included only outside
production (always logged server-side). Non-FastStore errors keep the
masked, body-less 500.

Co-authored-by: Cursor <[email protected]>
@hellofanny
hellofanny requested a review from a team as a code owner June 4, 2026 13:47
@hellofanny
hellofanny requested review from ommeirelles and renatomaurovtex and removed request for a team June 4, 2026 13:47
@codesandbox-ci

codesandbox-ci Bot commented Jun 4, 2026 •

Copy link
Copy Markdown

This pull request is automatically built and testable in CodeSandbox.

To see build info of the built libraries, click here or the icon next to each commit SHA.

@coderabbitai

coderabbitai Bot commented Jun 4, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: b01399f9-98ea-4567-b792-9ba94d45cb82

📥 Commits

Reviewing files that changed from the base of the PR and between c4f16a6 and 71b84f0.

📒 Files selected for processing (1)
  • packages/core/src/pages/api/graphql.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/core/src/pages/api/graphql.ts

Walkthrough

Adds a helper to unwrap masked FastStoreError instances from GraphQLErrors, updates /api/graphql to recover and log those errors and to derive/propagate HTTP status and structured error JSON when recoverable, and adds tests validating status mapping and environment-dependent response shape.

Changes

GraphQL Error Recovery and Status Propagation

Layer / File(s) Summary
Error recovery helper
packages/core/src/pages/api/graphql.ts
Adds recoverFastStoreError to extract a FastStoreError from a GraphQLError or its originalError.
GraphQL handler error processing
packages/core/src/pages/api/graphql.ts
Maps all GraphQL errors through the recovery helper, logs structured details for each recovered error, selects HTTP status from the first recoverable FastStoreError (default 500), and returns either a status-only response or a single-item GraphQL errors JSON with extensions.type, extensions.status, and the message only outside production.
Error status propagation test coverage
packages/core/test/pages/api/graphql.test.ts
Adds test utilities and cases that mock execute to return masked/unmasked errors, assert mapped statuses (400, 401, 403, 404, custom), confirm fallback 500 behavior for non-recoverable errors, verify dev vs prod response bodies, and ensure first recoverable error is chosen when multiple exist.

Sequence Diagram

sequenceDiagram
  participant Client
  participant GraphQLHandler as /api/graphql handler
  participant execute as graphql.execute
  participant Logger
  participant Response as Next.js res

  Client->>GraphQLHandler: HTTP GraphQL request
  GraphQLHandler->>execute: run GraphQL execution
  execute-->>GraphQLHandler: { data?, errors[] }
  GraphQLHandler->>Logger: log each GraphQLError (with recovered FastStoreError details)
  GraphQLHandler->>Response: set HTTP status (from first recoverable FastStoreError or 500)
  alt recoverable FastStoreError found
    GraphQLHandler->>Response: send JSON { errors: [{ message?, extensions: { type, status } }] }
  else no recoverable FastStoreError
    GraphQLHandler->>Response: end() (status-only, no body)
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Suggested labels

bug

Suggested reviewers

  • ommeirelles
  • renatomaurovtex
  • lemagnetic

Poem

Errors masked no more unwind,
Statuses found, cleanly defined,
Dev gets messages, prod keeps hush,
First fault rules the HTTP rush,
Logged and tested — handled, refined.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and specifically describes the main change: propagating upstream error status codes instead of defaulting all errors to HTTP 500.
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.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ 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/bff-error-status-propagation

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

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/core/src/pages/api/graphql.ts`:
- Around line 204-207: The current check sets hasErrors = Array.isArray(errors)
which is true for empty arrays and can wrongly treat successful responses as
failures; update the condition to require a non-empty array (e.g. hasErrors =
Array.isArray(errors) && errors.length > 0) so only errors.length > 0 enters the
error-handling branch that expects GraphQLError entries (the block using
hasErrors after the execution result).
🪄 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: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 7c99cd45-1749-48bc-acc8-9827c912f889

📥 Commits

Reviewing files that changed from the base of the PR and between 25a03d5 and c4f16a6.

📒 Files selected for processing (2)
  • packages/core/src/pages/api/graphql.ts
  • packages/core/test/pages/api/graphql.test.ts

Comment thread packages/core/src/pages/api/graphql.ts Resolved
@hellofanny hellofanny self-assigned this Jun 4, 2026

@renatomaurovtex renatomaurovtex left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Reviewed the diff against the root + @faststore/core conventions. Solid, well-scoped fix — the root-cause writeup (masked GraphQLError carrying the real FastStoreError in originalError) matches the code, the prod/non-prod message gating is the right call, and the test coverage (status mapping, unwrapped vs wrapped, multi-error selection, prod/non-prod body) is thorough. A few things to confirm before merge.


🟠 [bug/UX] Error responses set no cache-control — now more impactful · packages/core/src/pages/api/graphql.ts:226-251

The error branch returns before the cache-control block (line 256+), so error responses go out with no cache-control. This was already true for the old body-less 500, but now you're emitting a wider range of statuses on GET queries (400/401/403/404). A CDN/edge applying default caching could cache a 401/403/transient error keyed by URL+vars. You flagged this as a follow-up, but since this PR is what broadens the status surface, I'd set no-store on both error returns here rather than defer it:

+      response.setHeader('cache-control', 'no-cache, no-store')
       // No recoverable FastStoreError: keep the masked, body-less 500.
       if (!fastStoreError) {
         response.status(status).end()
         return
       }

(or set it once before the if). Cheap, and it closes the only real correctness gap I see.


🟡 [defensive] hasErrors = Array.isArray(errors) matches [] too · packages/core/src/pages/api/graphql.ts:204

CodeRabbit already flagged this. Worth noting for context: execute returns GraphQL's ExecutionResult, which omits errors (leaves it undefined) on success rather than returning [], so in practice this branch isn't hit by a successful op — and it was already this way before your PR. So not a regression. Still, with the new code an empty array now routes to a body-less 500, so the guard is cheap insurance:

-    const hasErrors = Array.isArray(errors)
+    const hasErrors = Array.isArray(errors) && errors.length > 0

Take it or leave it — your call given it's a latent, currently-unreachable case.


💬 [nit] recoverFastStoreError runs twice per error · packages/core/src/pages/api/graphql.ts:211-224

find(Boolean) and the log map both call recoverFastStoreError over errors. Negligible cost, but you could map once into { graphqlError, fsError } and reuse for both the log and the .find. Not blocking.


💬 [question] Body shape vs standard GraphQL error · packages/core/src/pages/api/graphql.ts:238-246

The error body is { errors: [{ extensions, message? }] } — no top-level message, which is the standard GraphQL error field. You already noted the storefront SDK short-circuits before reading the body, so this only matters for direct/external consumers. Is the extensions-only shape the intended contract for them, or would a top-level message (non-prod) be friendlier? Fine to keep as-is if intentional.


Verdict: Approved with comments

Blocking (🔴/🟠):

  • 🟠 Add cache-control: no-store to the error responses before merge — broadening to 4xx makes the missing header a real caching risk.

Non-blocking (🟡/💬):

  • 🟡 Defensive errors.length > 0 guard (latent, currently unreachable).
  • 💬 Dedupe the double recoverFastStoreError call in the log path.
  • 💬 Confirm the extensions-only error body shape is the intended external contract.

Checks to confirm before merge: pnpm lint · build · pnpm vitest run test/pages/api/graphql.test.ts --project node · full core node suite. No pnpm size impact (runtime-only, no new deps). fix(core) scope is valid.

@hellofanny

Copy link
Copy Markdown
Contributor Author

🟠 Add cache-control: no-store to the error responses before merge — broadening to 4xx makes the missing header a real caching risk.

Not adding now: downside is marginally higher origin/VTEX load on repeated identical errors and slightly less stampede dampening — both small and largely already neutralized by POST + the v cache-buster however not changing this behaviour now.

@pkg-pr-new

pkg-pr-new Bot commented Jun 8, 2026

Copy link
Copy Markdown

Open in StackBlitz

@faststore/api

npm i https://pkg.pr.new/vtex/faststore/@faststore/api@71b84f0

@faststore/cli

npm i https://pkg.pr.new/vtex/faststore/@faststore/cli@71b84f0

@faststore/components

npm i https://pkg.pr.new/vtex/faststore/@faststore/components@71b84f0

@faststore/core

npm i https://pkg.pr.new/vtex/faststore/@faststore/core@71b84f0

@faststore/diagnostics

npm i https://pkg.pr.new/vtex/faststore/@faststore/diagnostics@71b84f0

@faststore/lighthouse

npm i https://pkg.pr.new/vtex/faststore/@faststore/lighthouse@71b84f0

@faststore/sdk

npm i https://pkg.pr.new/vtex/faststore/@faststore/sdk@71b84f0

@faststore/ui

npm i https://pkg.pr.new/vtex/faststore/@faststore/ui@71b84f0

commit: 71b84f0

@sonar-workflows

Copy link
Copy Markdown

Failed Quality Gate failed

  • 2 New Issues (is greater than 0)

Project ID: vtex_faststore_f0a862d5-9557-49f9-8d09-de40caa76622

View in SonarQube

@hellofanny
hellofanny merged commit c03d3df into dev Jun 8, 2026
9 of 10 checks passed
@hellofanny
hellofanny deleted the fix/bff-error-status-propagation branch June 8, 2026 14:03
@eduardoformiga eduardoformiga mentioned this pull request Jun 17, 2026
2 tasks
eduardoformiga added a commit that referenced this pull request Jun 17, 2026
## Summary

Graduate the `4.3.0-dev.8` prerelease cycle to the stable `4.3.0`
release on `latest`.

Merging this PR triggers CD on `main`, which runs `lerna version
--conventional-graduate` and publishes all `@faststore/*` packages to
the `latest` dist-tag.

### Features
- Password Protection (v4) (#3276)
- File upload via Order Entry Service (OES) (#3334)
- Add sitemap to CMS Landing Page content-type (#3386)

### Bug Fixes
- **core:** use authenticator route for setpassword (#3380)
- migrate partytown `@builder.io` → `@[email protected]` (#3394)
- **api:** use account-scoped cookie in orderEntry headers (#3395)
- forward auth token only via account-scoped cookie (#3381)
- **core:** propagate upstream error status instead of always 500
(#3379)

## Pre-flight (faststore-release skill)
- Working tree clean; `release.yml` has `fetch-depth: 0`
- All 8 packages have `repository.url`
- No breaking changes since `v4.2.0`
- `dev → main` merges cleanly (no CHANGELOG/codegen conflicts)
- No unmerged hotfixes on `main` (accidental `4.2.1` was fully reverted
in #3375)

## Test plan
- [ ] CI green on this PR
- [ ] After merge, confirm CD publishes all 8 packages at `4.3.0` under
`latest`

Made with [Cursor](https://cursor.com)

---------

Co-authored-by: Matheus P. Silva <[email protected]>
Co-authored-by: vtexgithubbot <[email protected]>
Co-authored-by: Lucas Feijó <[email protected]>
Co-authored-by: Luiz Falcão <[email protected]>
Co-authored-by: Artur Santiago <[email protected]>
Co-authored-by: Larícia Mota <[email protected]>
Co-authored-by: Sahan Jayawardana <[email protected]>
Co-authored-by: Mateus Pontes <[email protected]>
Co-authored-by: Matheus Martins <[email protected]>
Co-authored-by: renatomaurovtex <[email protected]>
Co-authored-by: Leandro Rodrigues <[email protected]>
Co-authored-by: Fanny Chien <[email protected]>
Co-authored-by: Arthur Andrade <[email protected]>
Co-authored-by: Leandro Rodrigues <[email protected]>
Co-authored-by: Cursor <[email protected]>
Co-authored-by: Thiago Pereira <[email protected]>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: Giuliana Rigaud <[email protected]>
Co-authored-by: renato <[email protected]>
Co-authored-by: Bruna Santos <[email protected]>
Co-authored-by: BrunaCubos <[email protected]>
Co-authored-by: Ícaro Oliveira <[email protected]>
Co-authored-by: Bruna Santos <[email protected]>
Co-authored-by: Everton Ataide <[email protected]>
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
Co-authored-by: Otavio Moreira Meirelles <[email protected]>
Co-authored-by: Marco Cardoso <[email protected]>
Co-authored-by: Gabriel Paladino <[email protected]>
Co-authored-by: CodeRabbit <[email protected]>
Co-authored-by: dk-portal[bot] <134092483+dk-portal[bot]@users.noreply.github.com>
Co-authored-by: Rodrigo Tavares <[email protected]>
Co-authored-by: vitorflg <[email protected]>
Co-authored-by: Claude Sonnet 4.6 <[email protected]>
Co-authored-by: Válber Laux <[email protected]>
hellofanny added a commit that referenced this pull request Sep 14, 2026
## What

A pre-emptive guard: `onErrorRetry` never retries a `429`, and
reproduces SWR's default for every other status.

This is the v4 half of the crawler/bot traffic work. The
status-legibility half already shipped on `dev` via #3379, so this PR
touches only the client retry policy. The `3.x` counterpart — which
needs both halves, since v3's BFF still reports upstream `429`s as `500`
— is #3420.

## Why

An upstream `429` means a VTEX service (Session Manager, checkout,
Intelligent Search) is already shedding load against a per-account rate
limit. Retrying it multiplies exactly the traffic that upstream is
trying to reject, so the correct client policy is to never retry it.

`DEFAULT_OPTIONS` asks for retries on every status (`errorRetryCount:
3`, `shouldRetryOnError: true`). The moment those retries actually run,
a `429` would be retried 3× along with everything else. This PR makes
sure that never happens.

> An earlier version of this description attributed a documented
incident's amplification (11,512 distinct product requests becoming
roughly 20k) to those SWR retries. **That attribution was wrong** — see
*Status* below. The policy is still correct; only its justification
changed.

## Status: this policy is inert today

Worth stating up front, because it changes how the PR should be read.
`useQuery`'s fetcher never lets a rejection reach SWR:

```ts
fetcher: () =>
  new Promise((resolve) => {
    setTimeout(async () => {
      resolve(await request(...)) // a rejection is dropped here
    })
  })
```

If `request()` rejects, the `await` throws inside the `async` callback,
`resolve` is never called, and the outer promise stays pending forever.
SWR never sees an error, so `onErrorRetry`, `errorRetryCount` and
`shouldRetryOnError` have never taken effect — that config has been in
`DEFAULT_OPTIONS` since the commit that created `@faststore/core`
(#1629), alongside this same fetcher.

What follows from that:

- **No client retry amplification exists today**, on either branch. The
incident's request volume has other causes — chiefly the per-page-view
fanout of `ValidateSession` and `ValidateCartMutation`, which are
uncacheable POST mutations that never touch SWR.
- **This PR changes no observable behavior right now.**
- **It is still worth landing.** It is correct, pinned by tests against
[email protected]'s default, and in place *before* the fetcher fix makes retries
live — so a `429` is never amplified during that transition. Landing the
guard first is what removes the window where retries would be live for
`429` too.

Full analysis, with the re-derived incident numbers and the
verification, is in [this
comment](#3453 (comment)).

## How

`onErrorRetry` returns early on `error.status === 429`, and otherwise
reproduces SWR's default.

The important subtlety: **supplying `onErrorRetry` replaces SWR's
default implementation entirely — it does not compose with it.** A bare
predicate would have silently dropped the `errorRetryCount` ceiling and
the jittered exponential backoff for every other status. The
fall-through branch therefore mirrors [email protected]'s default, and the tests
pin that behavior so a future SWR upgrade surfaces any drift.

`3.x` mirrors [email protected]; the default `onErrorRetry` is identical in both
versions, so the two branches carry the same policy.

The truncation is written as `Math.trunc` rather than SWR's `~~` (Sonar
flags the doubled bitwise operator). The jitter stays far below 2^31,
where the two are equivalent, so the timings are unchanged.

## Tests

New `packages/core/test/sdk/graphql/retryPolicy.test.ts` (18 cases):

- `429` schedules no revalidation
- `400`, `401`, `403`, `404`, `409`, `422`, `500`, `502`, `503` and
status-less errors still retry
- the `errorRetryCount` ceiling still applies (retries at the limit,
stops past it)
- backoff timings match SWR's, including the exponent cap at 8

Full `packages/core` sdk suite passes (255 tests).

Because the policy is unreachable in production today (see *Status*),
these tests are what actually exercise it — they call `onErrorRetry`
directly rather than through `useQuery`.

## Follow-ups (not in this PR)

1. **The fetcher.** The dropped rejection is a real bug independent of
`429`: today any query error leaves the component loading forever, with
no error state. It needs its own PR, because fixing it switches on an
error path that has never executed. Two consumers use `suspense: true`,
where a rejecting fetcher throws to the nearest boundary even with
retries enabled; the global `ErrorBoundary` answers an uncaught error
with a hard `window.location.href = '/500'`, which is itself a fresh
page load firing two more uncacheable mutations. Where the boundaries
belong, and whether 3 retries for `5xx` is the default we want, are
decisions that deserve a dedicated review.
2. **The validation fanout.** `ValidateSession` and
`ValidateCartMutation` fire once per page load, unconditionally,
**including with an empty cart**. In the incident's one occurrence with
a per-operation breakdown they are 13,116 and 9,545 requests against
2,866 product queries. An empty-cart gate would remove most of the
second, taking care to preserve the sales-channel sync `validateCart`
also performs.
3. **Spec and RFC correction.** Both attribute the amplification to SWR
retries and should be updated, along with the RFC's G3, which is already
satisfied today.

## Notes

- No behavior change today for any status (see *Status*); once retries
are live, no behavior change for any status other than `429`.
- The `401` / refresh-token recovery is an explicit path in the session
SDK, not SWR-retry-driven, so it is unaffected.
- No API surface or schema change.

## Spec

`specs/crawler-bot-traffic-resilience/spec.md` — Phase 0b. Derived from
the crawler/bot traffic resilience RFC. Note that FR-7 is satisfied as
written, but the spec's "bot burst becomes a non-event" scenario names
`ValidateSession`/`ValidateCartMutation` — operations this policy cannot
reach, since they do not go through SWR. See follow-up 3.

Made with [Cursor](https://cursor.com)

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **Bug Fixes**
  * Improved GraphQL request retries with jittered exponential backoff.
  * Requests receiving HTTP 429 responses no longer retry automatically.
* Retry attempts now respect configured limits and use a maximum backoff
interval.
* Retry timing is now more consistent and resilient during temporary
request failures.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Cursor <[email protected]>
hellofanny added a commit that referenced this pull request Nov 26, 2026
## What's the purpose of this pull request?

Two related fixes to how **v3** reports and reacts to upstream failures.
They are bundled because they only work together (see *Why one PR*).

Automated crawlers periodically hit a store's public routes and trip the
*"Increased 5XX error rate by account and cluster"* alert, remediated so
far only by manual, per-incident IP blocks that never converge (the
offender rotates IPs). Investigation showed the "5xx" is largely an
**artifact**:

1. A low-volume bot (~20 req/s) trips VTEX **per-account upstream rate
limits**, which answer `429`.
2. The v3 BFF **mislabels that `429` as `500`**, which is what fires the
5xx alert.

This PR fixes (2), and adds a client-side guard so a `429` is never
retried once retries are actually live (see *Status* below — that guard
does nothing observable today on `3.x`). Nothing here blocks or
throttles legitimate crawlers.

### Why one PR

The status fix and the retry guard are reviewed together because the
retry guard needs the status fix to ever see a `429` client-side (today
the BFF's `500` masks it) — but see *Status*, the retry guard is not
currently reachable at all, for an independent reason.

## Status: the retry guard is inert on `3.x` today

Corrected after review from [lariciamota on this
PR](#3420 (comment)) and the
identical finding on the `dev` sibling,
[#3453](#3453) (verified
independently on both branches):

`useQuery`'s fetcher never lets a rejection reach SWR:

```ts
// packages/core/src/sdk/graphql/useQuery.ts
fetcher: () => new Promise((resolve) => {
  setTimeout(async () => { resolve(await request(...)) }) // a rejection is dropped here
})
```

If `request()` rejects, the `await` throws inside the `async` callback,
`resolve` is never called, and the outer promise stays pending forever.
SWR never sees an error, so `onErrorRetry`, `errorRetryCount: 3` and
`shouldRetryOnError: true` on `DEFAULT_OPTIONS` have never taken effect
for `useQuery` — on either branch, and since the commit that created
`@faststore/core`.

What follows from that, specifically for `3.x`:

- **The "storefront retries 3×, tripling the load" premise does not
hold.** Product-query traffic goes through `useQuery`, and that path
cannot retry today. The originally-cited amplification has other causes
— chiefly the per-page-view fanout of
`ValidateSession`/`ValidateCartMutation`, which call `request()`
directly with no SWR involved and no retry loop, and are outside what
this policy (even once live) can reach.
- **This half of the PR changes no observable behavior right now.**
- **It's still worth landing here.** It's correct (mirrors `[email protected]`'s
default exactly, tests pin both branches), and landing it now means it's
already in place *before* the `useQuery` fetcher bug is fixed elsewhere
— so there's no window where retries go live for `429` without the
guard.

The status-propagation half (part 1) does **not** depend on this and
stands on its own: it fixes real 5xx mislabeling and log/consumer
visibility regardless of whether client retries are active.

## How it works?

### 1. Propagate the upstream error status (backport of
[#3379](#3379))

The GraphQL BFF (`/api/graphql` handler in `@faststore/core`) collapsed
**every** error into HTTP `500`, even when the upstream VTEX error was a
client error (`400/401/403/404/429/...`). For example, an invalid
`postalCode` in the shipping simulation makes VTEX Checkout return
`400`, but the storefront received `500`, hiding the real cause from
consumers and server logs.

**Root cause:** after `useMaskedErrors`, the `errors` array holds
`GraphQLError` instances (`name === 'GraphQLError'`). The handler used
`errors.find(isFastStoreError)`, which checks `name ===
'FastStoreError'` and therefore never matched — the real
`FastStoreError` (carrying `extensions.status`) is nested in
`originalError`. So the status always fell back to `500`.

Changes in `packages/core/src/pages/api/graphql.ts`:

- Added `recoverFastStoreError` to unwrap the `FastStoreError` whether
it is the error itself or nested in the `originalError` of a masked
`GraphQLError`.
- `hasErrors` now also checks `errors.length > 0`. Without this, an
empty `errors` array fell into the error branch, found nothing
recoverable, and answered `500` — another spurious 5xx.
- The handler responds with the recovered `extensions.status` (still `??
500` as the safe default).
- For a recovered `FastStoreError`, the JSON body exposes
`extensions.type` and `extensions.status` always; the free-text
`message` is included **only when `NODE_ENV !== 'production'`** (and
always logged server-side).
- Non-`FastStoreError`s keep the masked, body-less `500` (error masking
unchanged).
- The error branch now sets `cache-control: no-store`. A bare
`404`/`410` (previously always a `500`) is heuristically cacheable by
intermediaries per RFC 9111 §4.2.2; without this an error for a given
`/api/graphql?operationName=...` could get cached at a CDN. *(Added per
review.)*

`fetchAPI` already preserved the upstream status (its `default` branch
throws `FastStoreError({ status, type: 'UnknownError' })`), so **no
change to `@faststore/api`** was needed — the status was being produced
correctly and discarded downstream.

> **v3 adaptation notes.** The handler code is a 1:1 port of #3379, with
two deliberate deviations. (a) The original test targets the `dev`/v4
toolchain (Vitest + graphql 16); on `3.x` core uses **Jest** and
**graphql 15**, so the test was adapted: `vi` → `jest`, `vi.stubEnv` →
manual `NODE_ENV` handling, and the masked-error helper uses graphql
15's positional `originalError` constructor argument. (b) v4's version
of this block also calls `OTELLogger`, which does not exist anywhere in
`3.x`; here the structured payload goes to `console.error` only, rather
than adding that dependency to a maintenance branch.

### 2. Never retry an upstream `429` (pre-emptive guard, see *Status*)

`DEFAULT_OPTIONS` in `packages/core/src/sdk/graphql/useQuery.ts` sets
`errorRetryCount: 3` and `shouldRetryOnError: true`. Retrying a `429`
would multiply exactly the traffic the upstream is trying to reject,
whenever those retries do run — so the guard is added now rather than
left for whoever fixes the fetcher bug to remember.

- The policy lives in a new
`packages/core/src/sdk/graphql/retryPolicy.ts` and is wired in as
`DEFAULT_OPTIONS.onErrorRetry`. It is a separate module so it can be
unit-tested without pulling the session/SDK graph in through `useQuery`.
- No plumbing was needed to see the status client-side: `baseRequest` in
`request.ts` already builds `{ status, message }` from `response.status`
and `request` throws it. Note it is a **plain object, not an `Error`**,
hence the `error?.status` read.
- **Important for review:** providing `onErrorRetry` **replaces SWR's
default implementation entirely** — it does not compose. So the
fall-through branch mirrors `[email protected]`'s default (the `errorRetryCount`
ceiling plus the jittered exponential backoff, capped at `1 << 8`) to
keep every other status retrying exactly as it does today. The tests pin
both branches, and `Math.random` is stubbed so the backoff assertions
are exact. This is the one spot to revisit on an SWR upgrade.
- Narrowing to `429` is deliberate: it is the only status the bot
induces, and touching other 4xx risks regressing flows that may rely on
a retry. The `401`/refresh-token recovery is a separate explicit path in
the session SDK, not SWR-retry-driven, so the retry policy does not
affect it. (The status propagation in part 1 does; see *Behavior
changes*.)

## Behavior changes (for the changelog)

- The BFF now returns accurate upstream statuses (`429`/`400`/`404`/...)
instead of a blanket `500`. Intended, from #3379. Consumers treating
"any non-200" as failure are unaffected; consumers branching
specifically on `500` will now see the real code.
- BFF error responses now set `cache-control: no-store`.
- An empty `errors` array is treated as success instead of `500`.
- An `UnauthorizedError` raised inside GraphQL execution previously
reached the client as `500`; it now arrives as `401`.
`sdk/session/index.ts` branches on `error?.status === 401`, so with
`experimental.refreshToken` enabled it now triggers `handleRefreshToken`
for these errors. During a crawler wave this can add one refresh request
per failure.
- A `429` is no longer retried by the client, but this has **no
observable effect today** — see *Status*. Once the unrelated `useQuery`
fetcher bug is fixed, all other statuses will retry exactly as before;
only `429` changes.
- No schema or public-API signature changes.

As a side effect, once bot-induced `429`s stop being reported as `500`,
they drop out of the `5xx` metric and the existing alert self-corrects —
no suppression rules to maintain. This holds regardless of the retry
guard's status.

## How to test it?

Unit tests (30 assertions across the two halves):

```sh
cd packages/core
pnpm test -- test/pages/api/graphql.test.ts        # 12 passing
pnpm test -- test/sdk/graphql/retryPolicy.test.ts  # 18 passing
```

The handler tests were also confirmed to **fail** against `3.x` without
this change (9 of 11), so they are pinning real behavior rather than the
implementation.

Manually, against a store:

- Trigger a shipping simulation with an invalid `postalCode` (e.g.
`555`) → `/api/graphql` should return `400` (was `500`).
- Confirm a genuine upstream `500` still returns `500`.
- In a non-production build, confirm the JSON error body carries
`extensions.type`, `extensions.status` and `message`; in production the
`message` is omitted.
- The `429`-no-retry behavior is exercised directly in
`retryPolicy.test.ts`; it is not currently observable end-to-end (see
*Status*).

## Follow-ups (not in this PR)

- **The `useQuery` fetcher bug.** The dropped rejection is a real bug
independent of `429`: today any query error leaves the component loading
forever, with no error state. Needs its own PR and review: two consumers
use `suspense: true`, where a rejecting fetcher throws to the global
`ErrorBoundary`, which does a hard `window.location.href = '/500'` —
itself a fresh page load firing more uncacheable mutations. Fixing this
is also what makes the `429` guard in this PR load-bearing for the first
time.
- **The validation fanout.** `ValidateSession`/`ValidateCartMutation`
fire once per page load, unconditionally, including with an empty cart,
and are the dominant source of bot-induced traffic per SO-631 (not
reachable by any SWR-level retry policy since they bypass SWR entirely).
An empty-cart gate would remove most of it, taking care to preserve the
sales-channel sync `validateCart` also performs.
- The "elevated `429` rate across multiple client IPs" signal and the
detect → stopgap → recommend runbook are Grafana/process work,
meaningful once the fetcher bug is fixed and the guard becomes live.
- Honoring `Retry-After` (instead of just skipping the retry) would need
the header captured in `fetchAPI`, carried on the error, set on the BFF
response and honored in SWR — a cross-package change, deliberately out
of scope.

## References

- Original v4 PR: [#3379](#3379)
- v4 sibling for the retry guard:
[#3453](#3453) (same "inert today"
finding, same resolution)
- [Jira Task SFS-2997](https://vtex-dev.atlassian.net/browse/SFS-2997)
- [Jira SO-631](https://vtex-dev.atlassian.net/browse/SO-631) — "Avaliar
FS para lidar com comportamentos de crawlers/bots em rotas públicas"


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **Bug Fixes**
* Improved GraphQL error responses with accurate HTTP status and error
type details.
* Preserved secure production responses while providing additional
diagnostic messages in non-production environments.
  * Prevented automatic retries for rate-limit errors.
* Added controlled retries with exponential backoff for other GraphQL
failures.
  * Disabled caching for GraphQL error responses.

* **Tests**
* Added coverage for error handling, status propagation, retry limits,
rate limiting, and backoff behavior.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->


---
_Generated by [Claude Code](https://claude.ai/code)_

---------

Co-authored-by: fanny <[email protected]>
Co-authored-by: Cursor <[email protected]>
Co-authored-by: Claude <[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.

3 participants