Skip to content

fix(react-db): release Suspense binding when compile() ends in terminal status - #2511

Open
saudademjj wants to merge 2 commits into
TanStack:mainfrom
saudademjj:saudademjj/fix-suspense-sync-compile-release
Open

saudademjj wants to merge 2 commits into
TanStack:mainfrom
saudademjj:saudademjj/fix-suspense-sync-compile-release

Conversation

@saudademjj

@saudademjj saudademjj commented Dec 1, 2026 •

Copy link
Copy Markdown

🎯 Changes

Fixes #2504.

In SuspenseBinding.resolve() (packages/react-db/src/useLiveSuspenseQuery.ts), compile(owned, windowOwner) can return a Collection whose status has already synchronously transitioned to error, crashed, or cleaned-up before collection.on('status:change', ...) is attached (for example, when startSync: true compiles a derived query over an already-failed/crashed source, or when a pre-cleaned-up collection is compiled). Because the status:change event had already fired, release() was never called or scheduled, leaving the terminal entry pinned in suspenseCollectionsByClient indefinitely and preventing ErrorBoundary retries from starting a fresh attempt.

This PR extracts scheduleRelease(status) (tracking a single releaseTimer cleared in release()) and invokes scheduleRelease(collection.status) immediately after registering the status:change listener:

  • cleaned-up -> calls release() immediately (removes the cache entry and detaches the status listener).
  • error or crashed -> schedules a single setTimeout(release, 0) (preserving failures through React's immediate same-turn retry, then releasing the cache entry for subsequent ErrorBoundary resets/remounts).

🔬 Oracle Coverage

  • Coverage-map oracle owner: packages/react-db/tests/suspense-lifecycle-oracle.test.tsx (react.suspense-retry-history, documented under React Suspense initial-view lifecycle in docs/contributing/oracle-coverage.md).
  • Violated law: A settled initial load must make retry progress; cleanup and retry retire stale failures (react.suspense-retry-history law: "The current initial attempt determines fallback, rows and boundary errors; cleanup and retry retire stale failures and successful peers own independent outputs.").
  • Exercised histories & production paths:
    • Extended retryArbitrary, retryExamples, retryStates, and constructed cases in suspense-lifecycle-oracle.test.tsx with sync-fail (params.fail(cause) before mount so compile() synchronously produces status === 'error') and sync-crash (synchronous throw in sync() before mount so compile() synchronously produces status === 'crashed'), using default gcTime (without gcTime: 0) and source-only source.cleanup() (without { dependents: true }) across all none / provider / explicit client scopes and derived / keyed modes, for both ErrorBoundary reset and root remount, with Error, record, and undefined causes.
    • Supplemented packages/react-db/tests/useLiveSuspenseQuery-recovery.test.tsx with direct SuspenseBinding.resolve() tests covering synchronous cleaned-up (immediate release without pinning), synchronous error / crashed same-turn retry preservation, and next-turn release.
  • Observation checkpoints: initial sync compile failure / initial sync compile crash (data-phase="error" + boundary cause), new attempt pending (data-phase="pending" + run === 2), retired source rejects during new attempt, settled load makes retry progress (data-phase="ready" + exact rows), successful peer (exclusive output), and source stops after readiness.
  • RED / GREEN evidence:
    • RED (on main c54b6f30, before the fix): vitest run tests/suspense-lifecycle-oracle.test.tsx -t "provider/derived retry" failed 8/30 cases (including fixed history: retry 2 / retry 3, constructed sync-failed boundary reset & sync-crashed root remount, and generated histories) at checkpoint new attempt pending (expected 'error' to be 'pending'), confirming the failed entry stayed pinned in suspenseCollectionsByClient.
    • GREEN (with the fix): suspense-lifecycle-oracle.test.tsx, useLiveSuspenseQuery-recovery.test.tsx, and useLiveSuspenseQuery.test.tsx all pass (325/325 passed, 0 type errors, useLiveSuspenseQuery.ts 97.54% line / 100% function coverage).
  • Remaining limits: Finite React 19/jsdom histories with controlled source sync runs (fail/sync-fail/sync-crash/crash/abandon); synchronous cleaned-up during compile() is verified via supplemental SuspenseBinding.resolve() tests because Collection.cleanup() is observably asynchronous on live source sync runs.

✅ Checklist

  • I have tested this code locally with @tanstack/react-db build, vitest --run (325 passed across suspense-lifecycle-oracle.test.tsx, useLiveSuspenseQuery-recovery.test.tsx, useLiveSuspenseQuery.test.tsx), pnpm lint:changed, pnpm lint:run-budgets, eslint, test:build (publint + attw), and prettier --check.

🚀 Release Impact

  • This change affects published code, and I have generated a changeset.
  • This change is docs/CI/dev-only (no release).

Summary by CodeRabbit

  • Bug Fixes
    • Fixed Suspense query recovery when a collection reaches a terminal state during synchronous compilation. Cleaned-up collections are released from the retry cache, while failed or crashed collections remain available for same-turn retries and are released afterward.
  • Documentation
    • Updated lifecycle coverage guidance to include synchronous source failures, crashes, and terminal states observed during compilation.

…al status

Check collection.status immediately after registering the status:change
listener in SuspenseBinding.resolve() so collections that synchronously
transition to cleaned-up, error, or crashed during compile() release their
retry-cache entry instead of staying pinned indefinitely.

Fixes TanStack#2504
@coderabbitai

coderabbitai Bot commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

The Suspense binding now handles collection terminal statuses that occur during compilation. Recovery tests and the retry oracle cover synchronous failures and crashes, including same-turn retries and later fresh compilations.

Changes: Suspense cache release

Layer / File(s) Summary
Cache release and retry behavior
packages/react-db/src/useLiveSuspenseQuery.ts, packages/react-db/tests/useLiveSuspenseQuery-recovery.test.tsx
The binding checks the collection’s current status after attaching its listener. It releases cleaned-up entries immediately and schedules release for error or crashed entries. Tests cover same-turn retries and later fresh compilations.

Synchronous terminal retry coverage

Layer / File(s) Summary
Synchronous terminal retry coverage
packages/react-db/tests/suspense-lifecycle-oracle.test.tsx, docs/contributing/oracle-coverage.md, .changeset/fix-suspense-sync-compile-release.md
The retry oracle adds synchronous failure and crash histories, including source-only cleanup. The coverage documentation and changeset describe these cases.

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

Change: Bug fix

Possibly related issues

  • Issue 2397: This change retains zero-delay release for error and crashed statuses. It does not address the asynchronous case described by the issue.

Possibly related PRs

  • TanStack/db#2168: This PR defines the crashed status and cleanup semantics used by the Suspense binding.

Suggested reviewers: kyleamathews

Merge Risk: Minimal · up to 21757

This change fixes a case where a failed Suspense query could stay cached after a synchronous failure, which blocked a fresh retry after an error boundary reset. No remaining merge-blocking concerns were found.

Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title names the fix and its scope: releasing the Suspense binding when compile() returns a collection already in a terminal status. The changeset adds the cleaned-up, error, and crashed handling i…
Description check Passed The description follows the template. It has the Changes section, which explains the bug (a synchronously terminal status before the status:change listener is attached) and the fix (scheduleRelease in…
Linked Issues check Passed [#2504] requires that a collection already terminal after compile() is handled. At head, SuspenseBinding.resolve() defines releaseOnTerminal(status). It calls release() for cleaned-up and schedules se…
Out of Scope Changes check Passed All changes support #2504. The source change in packages/react-db/src/useLiveSuspenseQuery.ts is the fix. The incremental change since the previous review only refactors the terminal-status handling i…
Full details: Title check

Explanation

The title names the fix and its scope: releasing the Suspense binding when compile() returns a collection already in a terminal status. The changeset adds the cleaned-up, error, and crashed handling in SuspenseBinding.resolve(), and the tests cover those paths. The title is specific and matches the main change.

Full details: Description check

Explanation

The description follows the template. It has the Changes section, which explains the bug (a synchronously terminal status before the status:change listener is attached) and the fix (scheduleRelease invoked after listener registration, with immediate release for cleaned-up and a next-turn release for error/crashed). The Oracle Coverage section names the coverage-map owner, the violated law, the exercised histories and production paths, the observation checkpoints, RED/GREEN evidence, and remaining limits. The checklist and release impact sections are filled in. Minor gap: the description cites a PR number (#2511) in the objectives but the description itself references issue #2504; this is consistent. The description is complete.

Full details: Linked Issues check

Explanation

[#2504] requires that a collection already terminal after compile() is handled. At head, SuspenseBinding.resolve() defines releaseOnTerminal(status). It calls release() for cleaned-up and schedules setTimeout(release, 0) for error or crashed. The status:change listener routes through releaseOnTerminal. After the listener is attached, the code calls releaseOnTerminal(collection.status), which covers the synchronous case. The removeStatusListener binding is initialized before that call, so release() can run safely. The change since the previous reviewed head (850ffc9) is a refactor that extracts the terminal-status handling into releaseOnTerminal. It keeps the same outcomes. The PR description names scheduleRelease and releaseTimer, which do not exist at head. The code at head governs this verdict. Test coverage was not re-run. The code evidence alone establishes the required behavior.

Full details: Out of Scope Changes check

Explanation

All changes support #2504. The source change in packages/react-db/src/useLiveSuspenseQuery.ts is the fix. The incremental change since the previous review only refactors the terminal-status handling into releaseOnTerminal and adds the CollectionStatus type import, with no new behavior. The oracle and recovery tests cover the synchronous error, crashed, and cleaned-up paths. The docs/contributing/oracle-coverage.md edit and the changeset describe this fix. No unrelated behavior change appears in the reviewed material.

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: 1f8732c1-42cf-4dcb-86c6-f27b3d66a263
Commits

Reviewing files that changed from the base of the PR and between 850ffc9 and 217576e.

Files selected for processing: 3

  • docs/contributing/oracle-coverage.md
  • packages/react-db/src/useLiveSuspenseQuery.ts
  • packages/react-db/tests/useLiveSuspenseQuery-recovery.test.tsx
Files skipped from review as they are similar to previous changes: 2

  • docs/contributing/oracle-coverage.md
  • packages/react-db/tests/useLiveSuspenseQuery-recovery.test.tsx

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

@changeset-bot

changeset-bot Bot commented Dec 2, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 217576e

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
Name Type
@tanstack/react-db Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

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.

react-db: useLiveSuspenseQuery pins a failed Suspense binding forever if the collection errors or cleans up synchronously during compile()

1 participant