Skip to content

fix(renderer): contain corrupt lazy chunks when the recovery reload never lands - #12950

Merged
AmethystLiang merged 7 commits into
mainfrom
fix/lazy-chunk-recovery-containment
Aug 6, 2026
Merged

AmethystLiang merged 7 commits into
mainfrom
fix/lazy-chunk-recovery-containment

Conversation

@AmethystLiang

@AmethystLiang AmethystLiang commented Aug 6, 2026 •

Copy link
Copy Markdown
Contributor

Description

Nine react-error-boundary crash reports filed to #orca-crashes (2026-08-05 → 08-06) share one ending: a corrupt lazy-loaded JS chunk fails import(), loadLazyWithRetry requests a recovery reload, the reload never lands, and the wrapper re-throws the raw SyntaxError/TypeError. RecoverableRenderErrorBoundary only suppresses LazyChunkLoadError, so a raw error files a user-facing crash report.

The crashes span four releases and all three platforms, so this is not one bad build:

Report Build Platform Boundary Error
131d2ed2 1.4.175 linux app.root Failed to fetch dynamically imported module
a7bc7be0 1.4.171 win32 app.root Failed to fetch dynamically imported module
e2c7e3b8 1.4.173 darwin overlay.update-card Unexpected token '}'
c7dd5914 1.4.173 darwin overlay.update-card Unexpected token '}'
5e6beae8 1.4.173 darwin overlay.floating-workspace Unexpected token '}'
bf55f7c4 1.4.173 darwin right-sidebar Invalid or unexpected token
6b619f79 1.4.174 darwin sidebar.worktrees Unexpected string
e6d5f954 1.4.171 darwin sidebar.worktrees Unexpected token '}'
9e424656 1.4.174 darwin terminal.workbench Unexpected token ':'

Root cause

LazyChunkLoadError — the only error the boundary suppresses — was unreachable in production. Its precondition is a reload guard written by a different document ('reload-landed'), but the finally block calls clearChunkReloadGuard() before the throw, deleting that precondition. The one path that could construct it never ran, so every failure reached the boundary raw.

CLEAR, UNDENIABLE fix evidence

1. Production telemetry, from the shipped diagnostics bundles of all 10 reports:

Measurement Value Meaning
lazy_chunk_reload_vetoed with outcome=never-landed 16 / 16 the reload never lands
outcome = unload-vetoed / checkpoint-refused / request-failed 0 / 16 it is not vetoed — it silently no-ops
renderer_bootstrap_started after any lazy_chunk_reload 0 location.reload() produced zero navigations
bundles containing a boundary-degraded breadcrumb 0 / 10 LazyChunkLoadError was never constructed
breadcrumbs carrying a real reloadKey 'unknown' 35 / 35 no crashing call site passes one

The veto signal is wired end-to-end (createMainWindow.ts:1057 → renderer-restart-wiring.ts:27 → window event), so a genuine beforeunload veto would have surfaced as unload-vetoed. Zero of those across 16 attempts proves the reload is not being blocked — it silently does nothing. The fix therefore must not depend on the reload landing.

2. Red → green. The new tests reproduce the exact production path. On unmodified main:

 × surfaces a recognizable LazyChunkLoadError so the boundary can contain it
 × does not strand a sibling lazy import that fails while a reload is pending
 × contains an unload-vetoed reload and records it as a distinct outcome
 × leaves no guard behind that would block a later document from recovering
 × shows the fallback without filing a crash report
 Tests  5 failed (5)

Every new test fails on main and passes with the fix — there are no vacuous tests left.

The boundary test fails on main for exactly the shipped reason — it files a report carrying [SyntaxError: Unexpected token '}'] with at Lazy (<anonymous>) in the component stack, byte-for-byte the shipped signature. With the fix: 35 passed (35) in the lazy-chunk/boundary suites, and 793 files / 7857 tests pass, 0 failures across lib, error-boundaries, editor, and terminal-pane.

3. Not already fixed. Both prior attempts (#11929 3f8654c26e, #12600 5f187e0836) are contained in v1.4.175, and no commit on main since touches lazy-with-retry.ts, lazy-chunk-recovery-reload.ts, or error-boundaries/. The defect is live on main.

ELI5

Orca loads parts of its UI on demand, like fetching a chapter of a book only when you turn to it. Sometimes a chapter comes back damaged and unreadable.

Orca's plan for that was "reload the whole book, that usually fixes it." So it asks for a reload and waits 10 seconds. The reload never actually happens — provably, because a reload would have restarted the app and nothing ever restarted.

After those 10 seconds Orca gives up and hands the damaged-chapter error upstairs. Upstairs there is a rule: "if this is the special damaged chapter error, quietly show a placeholder — don't alarm the user." But Orca handed up the original raw error, not the special one, so the rule never matched and you got a crash popup.

This change makes Orca label the error properly when it gives up, so the rule matches and you get a contained placeholder instead of a crash report.

Trade-offs and behaviour changes

These are real; please weigh them.

  1. Reduced visibility into chunk corruption — the significant one. Contained failures no longer file a crash report. Breadcrumbs live in an in-memory 30-entry ring and only leave the machine attached to some other crash report, so aggregate signal drops substantially. These 9 reports are the only reason we know this bug exists. Mitigations here: a lazy_chunk_recovery_exhausted breadcrumb carrying the call site, the real chunk error and the outcome, plus the boundary's existing console.error. Recommended follow-up: record a non-prompting crash report (a status getLatestPendingReport skips) so evidence still reaches us. Attempted here and reverted — see Rejected approaches.
  2. The root cause is still unfixed. location.reload() not navigating is untouched. This PR stops the crash reports; it does not repair the corrupt chunk. The affected panel stays broken until restart, and the fallback's Retry button cannot fix it (React caches the lazy rejection permanently). Users now get a quiet degraded surface instead of a crash dialog that at least implied "restart me".
  3. Module-evaluation SyntaxErrors are contained too. isKnownDynamicImportFailure matches any SyntaxError by name, so a SyntaxError thrown while evaluating a lazily imported module (e.g. a top-level JSON.parse) is indistinguishable here and would now be contained rather than reported. Verified currently latent: no top-level JSON.parse and only static new RegExp templates in src/renderer/src.
  4. Wider containment than before. Previously only a landed reload that still failed was contained; now any attempted-and-failed recovery is. That is the point of the fix, but it is a deliberate contract change, and several existing tests were updated to match (their titles now say "contains" rather than "surfaces/reports the original error").

Unchanged on purpose: when recovery is never attempted — no window (SSR), blocked sessionStorage, or a failed guard write — the raw error is still thrown, so normal crash reporting is unaffected.

Rejected approaches

  • Record-but-don't-prompt. Implemented, then reverted: crash-report-store.record() hardcodes status:'pending' and getLatestPending() re-reads it, so it would have deferred the prompt to the next launch rather than removing it — worse than the status quo. Doing it properly needs a new status the pending query skips (follow-up above).
  • Stack-frame discrimination for SyntaxError (would address trade-off 3). Parser errors carry no JS frames, and all 9 shipped error_stack values confirm zero frames — but it broke 19 tests and relies on V8 never adding frames to parse errors. A false negative silently restores the crash, so the risk outweighs the latent benefit.

Adversarial review

6 loops, each a fresh sub-agent, run until clean:

Loop Scope Findings Resolution
1 functional fix 1 CRITICAL, 3 HIGH, 2 MED, 3 LOW CRITICAL: a promptUser mechanism would have re-prompted on next launch (record() hardcodes status:'pending') → fully reverted. Breadcrumb renamed to avoid a schema collision. A suggested predicate tightening was rejected with evidence — it would break containment for 3 of the 4 observed messages.
2 functional fix 0 CRITICAL, 1 HIGH, 3 MED, 4 LOW Duplicate-breadcrumb suppression; per-reloadKey dedupe so a corrupt shared chunk cannot flush the 30-entry ring; guard-not-landed gated so an unrelated error cannot clear a guard it did not set; breadcrumb assertions added. HIGH (visibility) accepted and documented above.
3 functional fix 0 CRITICAL, 0 HIGH, 0 MED, 3 LOW Dedupe key now includes the error name; the guard test asserts containment; formatting. All 9 exit paths enumerated; no concurrency or reload-loop defect.
4 functional + perf 0 CRITICAL, 0 HIGH, 0 MED, 3 LOW Found that exhaustedRecoveryFailure ended in two adjacent booleans whose transposition would silently return the raw error and restore this very crash, uncatchable by tests. Parameter removed in a142828809.
5 perf delta 0 CRITICAL, 0 HIGH, 0 MED, 3 LOW Independently proved the regex hoist safe: all 7 patterns are /i-only, and a 660-case differential run showed zero lastIndex drift. Set eviction switched to oldest-first to match the stores it cites; bound test added.
6 cumulative, confirming 0 CRITICAL, 0 HIGH, 0 MED, 1 LOW Verdict: functionally correct and ready to merge. Empirically confirmed all new tests fail behaviorally against origin/main.
— post-review simplification — The breadcrumb machinery loops 2–6 kept hardening was deleted outright; it was optional scope that never fired on the dominant path. Red→green re-verified against origin/main afterwards: 5/5 fail, 5/5 pass.

One loop-6 observation is not reflected above because I could not confirm it: it suggested that call sites without a nearby boundary would still file crash reports, which would soften trade-off 1. The renderer has exactly two boundary classes (RecoverableRenderErrorBoundary, RichMarkdownErrorBoundary) and both suppress LazyChunkLoadError, so React propagates to one of them in every case. The visibility trade-off stands as written.

Size and scope

The production change is 44 insertions / 22 deletions, much of it comment. The logic is a 6-line helper plus four call sites:

function containedChunkFailure(lastError: unknown, reloadKey: string): unknown {
  return isKnownDynamicImportFailure(lastError)
    ? new LazyChunkLoadError(lastError, reloadKey)
    : lastError
}

The remaining ~250 lines are tests, which are the reproduction evidence.

An earlier revision of this PR was roughly twice the size. It added a lazy_chunk_recovery_exhausted breadcrumb, which then required a dedupe Set (to avoid flushing the 30-entry ring), a bound on that set (error.name is library-controlled), an oldest-first eviction policy, two more tests, and an extra boolean parameter that review flagged as a transposition trap capable of silently restoring this very crash. On the dominant never-landed path the breadcrumb did not even fire, because lazy_chunk_reload_vetoed already records the same reloadKey, message and outcome. It was all removed: observability on every path is back to the main baseline, and the diff is now the fix and nothing else.

Performance

No measurable impact. The success path is untouched — every change is after the retry loop, reachable only once factory() has rejected retries+1 times. On the failure path the change is strictly cheaper than main: previously a corrupt shared chunk failing N sibling imports produced N raw errors that each reached reportReactErrorBoundaryCrash, and because the renderer dedupe keys on componentStack, sibling boundaries did not dedupe against each other — each paid a dynamic import('@/store'), a JSON.stringify over the full component stack, and an IPC that persists a crash report to disk. That becomes zero.

Test plan

  • npx vitest run --config config/vitest.config.ts src/renderer/src/lib src/renderer/src/components/error-boundaries src/renderer/src/components/editor src/renderer/src/components/terminal-pane → 793 files / 7857 tests pass
  • npm run check:max-lines-ratchet → OK, no new bypasses
  • npm run check:reliability-gates → 69 gates pass
  • npx tsc --noEmit -p config/tsconfig.tc.web.json → clean
  • npx oxlint / npx oxfmt --check → clean

Not included

a69f8cb9 (win32, React #185 in TerminalPaneOverlayLayer) is a different defect and is not fixed here. It was diagnosed but not reproduced, so no speculative fix was shipped. Notably, its prior fix (#12600 5f187e0836) is contained in v1.4.174/175 and the crash still occurred on 1.4.175, so the existing flip damping is insufficient. Working hypothesis: recordParkVerdictFlips watches the post-gate parkedTerminalTabIds, while the effect's setState is the pre-gate setColdParkedTerminalTabIds; a pre-gate oscillation masked by a gate would loop forever, record no flips, and never engage damping — which is keyed on those same flip records. Consistent with the bundle containing zero park-verdict-flip breadcrumbs.

…ever lands

9 react-error-boundary crash reports across v1.4.171-1.4.175 (macOS, Linux,
Windows) all end the same way: a corrupt lazy chunk fails to import, recovery
requests a reload, the reload never lands, and loadLazyWithRetry re-throws the
raw SyntaxError/TypeError. RecoverableRenderErrorBoundary only suppresses
LazyChunkLoadError, so the raw error files a user-facing crash report.

LazyChunkLoadError was unreachable in production. Its precondition is a guard
written by a *different* document ('reload-landed'), but the finally block
clears that guard before the throw, so the only path that could construct it
never ran. Confirmed by the shipped bundles: 16/16 lazy_chunk_reload_vetoed
breadcrumbs carry outcome=never-landed, zero carry any other outcome, and no
bundle contains a boundary-degraded breadcrumb.

Route every exhausted-recovery path through exhaustedRecoveryFailure() so an
attempted-and-failed recovery yields a LazyChunkLoadError the boundary can
contain, and record a lazy_chunk_recovery_exhausted breadcrumb carrying the
call site, the real chunk error, and the outcome.

Deliberately unchanged: when recovery is never *attempted* (no window/SSR,
blocked sessionStorage, guard write failure) the raw error is still thrown so
normal crash reporting is unaffected. Only isKnownDynamicImportFailure matches
are contained, so module logic bugs keep reporting.
Hoist the dynamic-import message patterns to module scope so classification
stops allocating seven RegExp objects per call, thread the already-computed
classification into exhaustedRecoveryFailure so the guard-not-landed path does
not re-run it, and bound recordedExhaustionKeys the way the breadcrumb and
renderer-error key stores are bounded, since error.name is library-controlled.

Failure path only; the success path is unchanged.
…lure path

exhaustedRecoveryFailure ended in two adjacent booleans with opposite
consequences: transposing them would have returned the raw SyntaxError and
silently restored the crash this branch fixes, with no test able to catch it
(the only call site passed true for both). The isChunkFailure parameter saved
one regex scan on a path that only runs after a 10s reload wait, so drop it.

Also evict recordedExhaustionKeys oldest-first instead of clearing wholesale,
matching the breadcrumb and renderer-error key stores the comment cites, so an
overflow cannot re-open the entire set to a repeat burst.
@coderabbitai

coderabbitai Bot commented Aug 6, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: a51e8021-34bc-428d-b2fb-580d12e6f001

📥 Commits

Reviewing files that changed from the base of the PR and between accda29 and 9c33494.

📒 Files selected for processing (3)
  • src/renderer/src/components/error-boundaries/RecoverableRenderErrorBoundary.tsx
  • src/renderer/src/lib/lazy-with-retry.never-landed-reload.test.ts
  • src/renderer/src/lib/lazy-with-retry.ts

📝 Walkthrough

Walkthrough

Lazy chunk recovery now wraps known dynamic-import failures in LazyChunkLoadError when reload recovery is refused, incomplete, capped, or already in progress. It preserves unrelated errors and errors from unavailable recovery. Tests cover never-landed reloads, sibling failures, unload prevention, wrapped causes, breadcrumbs, repeated reload limits, and reload-guard cleanup. RecoverableRenderErrorBoundary skips duplicate crash reports for lazy chunk-load errors and renders its fallback when recovery does not complete.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 14.29% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
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.
Title check ✅ Passed The title clearly and concisely describes the main renderer fix for corrupt lazy chunks when recovery reloads do not complete.
Description check ✅ Passed The description thoroughly covers the bug, fix, behavior, trade-offs, platform impact, testing, and review findings, despite missing several template headings.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch

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

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

@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

🧹 Nitpick comments (1)
src/renderer/src/lib/lazy-with-retry.ts (1)

196-203: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Condense the incident-history comments.

Keep the behavior rationale in source and tests. Move release versions, report counts, and incident identifiers to issue or PR documentation.

  • src/renderer/src/lib/lazy-with-retry.ts#L196-L203: Keep the SyntaxError classification rationale and remove report-history detail.
  • src/renderer/src/lib/lazy-with-retry.never-landed-reload.test.ts#L3-L7: State the never-landed reload scenario without release and report statistics.
  • src/renderer/src/lib/lazy-with-retry.never-landed-reload.test.ts#L43-L45: State that location.reload() is mocked to avoid navigation.
  • src/renderer/src/lib/lazy-with-retry.never-landed-reload.test.ts#L93-L95: State the sibling-failure condition without incident identifiers or timings.

As per coding guidelines, “Comments must be concise, limited to non-obvious information, and preferably one line.”

Source: Coding guidelines


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 0d5c0dea-a0c8-422d-b3ad-f67b6d33b8fb

📥 Commits

Reviewing files that changed from the base of the PR and between ddf6419 and d4c32a9.

📒 Files selected for processing (5)
  • src/renderer/src/components/error-boundaries/RecoverableRenderErrorBoundary.never-landed-reload.test.tsx
  • src/renderer/src/components/error-boundaries/RecoverableRenderErrorBoundary.tsx
  • src/renderer/src/lib/lazy-with-retry.never-landed-reload.test.ts
  • src/renderer/src/lib/lazy-with-retry.test.ts
  • src/renderer/src/lib/lazy-with-retry.ts

Comment on lines +3 to +5
// The end-to-end shape of the 9 shipped lazy-chunk crash reports: a corrupt chunk
// fails, recovery requests a reload, the reload never lands, and the boundary files
// a react-error-boundary crash report instead of containing the failure.

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.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Remove the stale regression description.

Lines 3-5 describe the pre-fix failure as current behavior. Remove this comment. Lines 86-87 retain the relevant historical regression context.

As per coding guidelines, comments must be concise, limited to non-obvious information, and preferably one line.

Source: Coding guidelines

The bound had no coverage, unlike the crash-breadcrumb store it mirrors, so a
refactor could drop it or invert the comparison with every test still green.
Drive 200 distinct error names through the contained path and assert the set
stays capped. Also move MAX_RECORDED_EXHAUSTION_KEYS above the comment that
describes the set, not between them.

@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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/renderer/src/lib/lazy-with-retry.ts (1)

151-179: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Record the exhaustion breadcrumb after every exhausted recovery.

When alreadyRecorded is true, this function does not record lazy_chunk_recovery_exhausted. Lines 262-266 and 283-290 pass true after recording lazy_chunk_reload_vetoed. Those attempted recovery failures are contained, but they lack the required exhaustion breadcrumb.

Use recordedExhaustionKeys to deduplicate the exhaustion event. Do not use the veto breadcrumb as a substitute.

Proposed fix
 function exhaustedRecoveryFailure(
   lastError: unknown,
   reloadKey: string,
   failureMessage: string,
-  outcome: string,
-  alreadyRecorded = false
+  outcome: string
 ): unknown {
   // ...
-  if (!alreadyRecorded && !recordedExhaustionKeys.has(crumbKey)) {
+  if (!recordedExhaustionKeys.has(crumbKey)) {
     // ...
   }
 }

-throw exhaustedRecoveryFailure(lastError, reloadKey, failureMessage, outcome, true)
+throw exhaustedRecoveryFailure(lastError, reloadKey, failureMessage, outcome)

-throw exhaustedRecoveryFailure(lastError, reloadKey, failureMessage, 'guard-not-landed', true)
+throw exhaustedRecoveryFailure(lastError, reloadKey, failureMessage, 'guard-not-landed')

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: a9db5093-57de-4284-9e58-cfc8d7f93969

📥 Commits

Reviewing files that changed from the base of the PR and between d4c32a9 and f1d21c4.

📒 Files selected for processing (2)
  • src/renderer/src/lib/lazy-with-retry.never-landed-reload.test.ts
  • src/renderer/src/lib/lazy-with-retry.ts

Comment on lines +155 to +170
it('bounds the exhaustion dedupe set so a hostile error name cannot grow it forever', async () => {
installBreadcrumbSink()
// error.name is library-controlled, so drive far more distinct keys than the cap.
window.sessionStorage.setItem(RELOAD_GUARD_KEY, 'doc-before-the-reload')
for (let index = 0; index < 200; index += 1) {
const error = new SyntaxError("Unexpected token '}'")
error.name = `SyntaxError${index}`
void loadLazyWithRetry(() => Promise.reject(error), {
retries: 0,
reloadKey: 'right-sidebar'
}).catch(() => undefined)
}
await vi.advanceTimersByTimeAsync(0)

expect(getRecordedExhaustionKeyCountForTest()).toBeLessThanOrEqual(128)
})

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.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Assert the expected retained-key count.

toBeLessThanOrEqual(128) passes if eviction clears the full set at the limit. After 200 distinct keys, oldest-first eviction must retain exactly 128 keys.

Proposed fix
-    expect(getRecordedExhaustionKeyCountForTest()).toBeLessThanOrEqual(128)
+    expect(getRecordedExhaustionKeyCountForTest()).toBe(128)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
it('bounds the exhaustion dedupe set so a hostile error name cannot grow it forever', async () => {
installBreadcrumbSink()
// error.name is library-controlled, so drive far more distinct keys than the cap.
window.sessionStorage.setItem(RELOAD_GUARD_KEY, 'doc-before-the-reload')
for (let index = 0; index < 200; index += 1) {
const error = new SyntaxError("Unexpected token '}'")
error.name = `SyntaxError${index}`
void loadLazyWithRetry(() => Promise.reject(error), {
retries: 0,
reloadKey: 'right-sidebar'
}).catch(() => undefined)
}
await vi.advanceTimersByTimeAsync(0)
expect(getRecordedExhaustionKeyCountForTest()).toBeLessThanOrEqual(128)
})
it('bounds the exhaustion dedupe set so a hostile error name cannot grow it forever', async () => {
installBreadcrumbSink()
// error.name is library-controlled, so drive far more distinct keys than the cap.
window.sessionStorage.setItem(RELOAD_GUARD_KEY, 'doc-before-the-reload')
for (let index = 0; index < 200; index += 1) {
const error = new SyntaxError("Unexpected token '}'")
error.name = `SyntaxError${index}`
void loadLazyWithRetry(() => Promise.reject(error), {
retries: 0,
reloadKey: 'right-sidebar'
}).catch(() => undefined)
}
await vi.advanceTimersByTimeAsync(0)
expect(getRecordedExhaustionKeyCountForTest()).toBe(128)
})

The bound test asserted only the size cap, so it stayed green under the old
wholesale clear(): after 200 distinct keys a clear-on-overflow leaves 72, which
still satisfies the cap. Replay a key that oldest-first eviction retains and
assert it emits no second breadcrumb — that fails under clear(), which would
otherwise silently re-open the whole set to a repeat burst and flush the
30-entry ring the dedupe exists to protect.
The lazy_chunk_recovery_exhausted breadcrumb was an optional addition that paid
for itself in complexity and nothing else: it needed a dedupe set to avoid
flushing the 30-entry ring, the set needed a bound because error.name is
library-controlled, the bound needed an oldest-first eviction policy, and that
needed two more tests plus a boolean parameter that review flagged as a
transposition trap. On the dominant never-landed path it did not even fire,
because lazy_chunk_reload_vetoed already records the same reloadKey, message and
outcome.

Drop it. Observability on every path returns to the main baseline, and the fix
is what it always was: name an exhausted recovery so the boundary can contain
it. Also revert the unrelated regex hoist -- its only caller is the failure
path, so the saved allocations are noise.
Add test ensuring module evaluation bugs still surface despite
never-landed reload attempts. Clarify containment scope: recovery
only applies to known dynamic-import failures, not ordinary errors.
@AmethystLiang
AmethystLiang merged commit fe789c5 into main Aug 6, 2026
Jinwoo-H added a commit that referenced this pull request Aug 7, 2026
Reverts a gratuitous rename to reload-issued-not-landed. #12950 merged
with never-landed, fleet crash triage queries that value, and the rename
broke a merged test. The rename served nothing in this PR.
brennanb2025 added a commit that referenced this pull request Aug 15, 2026
…lazy chunk

After an update swaps assets under a live renderer, a lazy chunk import
rejects with a SyntaxError and the recovery reload never lands (all shipped
lazy_chunk_reload_vetoed breadcrumbs carry outcome=never-landed). Since
#12950 the boundary contains the failure silently, but React.lazy caches
the rejection forever, so its Retry button could never re-invoke the
factory: the surface stayed dead until a manual app restart.

lazyWithRetry now returns a wrapper that mints a fresh React.lazy when a
reset remounts it after a caught chunk failure. Minting is gated on a retry
epoch advanced only in the boundary's componentDidCatch, so React's own
settle-driven remounts reuse the cached rejection instead of refetching a
broken chunk in a loop; each fresh load costs a Retry press or a resetKey
change. For the case where the assets are still broken, a contained
LazyChunkLoadError fallback now explains that Orca may have updated and
offers Restart Orca via the existing main-driven app:relaunch IPC, which a
swallowed renderer-side location.reload cannot veto.
brennanb2025 added a commit that referenced this pull request Aug 16, 2026
…lazy chunk

After an update swaps assets under a live renderer, a lazy chunk import
rejects with a SyntaxError and the recovery reload never lands (all shipped
lazy_chunk_reload_vetoed breadcrumbs carry outcome=never-landed). Since
#12950 the boundary contains the failure silently, but React.lazy caches
the rejection forever, so its Retry button could never re-invoke the
factory: the surface stayed dead until a manual app restart.

lazyWithRetry now returns a wrapper that mints a fresh React.lazy when a
reset remounts it after a caught chunk failure. Minting is gated on a retry
epoch advanced only in the boundary's componentDidCatch, so React's own
settle-driven remounts reuse the cached rejection instead of refetching a
broken chunk in a loop; each fresh load costs a Retry press or a resetKey
change. For the case where the assets are still broken, a contained
LazyChunkLoadError fallback now explains that Orca may have updated and
offers Restart Orca via the existing main-driven app:relaunch IPC, which a
swallowed renderer-side location.reload cannot veto.
brennanb2025 added a commit that referenced this pull request Aug 17, 2026
…lazy chunk

After an update swaps assets under a live renderer, a lazy chunk import
rejects with a SyntaxError and the recovery reload never lands (all shipped
lazy_chunk_reload_vetoed breadcrumbs carry outcome=never-landed). Since
#12950 the boundary contains the failure silently, but React.lazy caches
the rejection forever, so its Retry button could never re-invoke the
factory: the surface stayed dead until a manual app restart.

lazyWithRetry now returns a wrapper that mints a fresh React.lazy when a
reset remounts it after a caught chunk failure. Minting is gated on a retry
epoch advanced only in the boundary's componentDidCatch, so React's own
settle-driven remounts reuse the cached rejection instead of refetching a
broken chunk in a loop; each fresh load costs a Retry press or a resetKey
change. For the case where the assets are still broken, a contained
LazyChunkLoadError fallback now explains that Orca may have updated and
offers Restart Orca via the existing main-driven app:relaunch IPC, which a
swallowed renderer-side location.reload cannot veto.
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…ever lands (stablyai#12950)

* fix(renderer): contain corrupt lazy chunks when the recovery reload never lands

9 react-error-boundary crash reports across v1.4.171-1.4.175 (macOS, Linux,
Windows) all end the same way: a corrupt lazy chunk fails to import, recovery
requests a reload, the reload never lands, and loadLazyWithRetry re-throws the
raw SyntaxError/TypeError. RecoverableRenderErrorBoundary only suppresses
LazyChunkLoadError, so the raw error files a user-facing crash report.

LazyChunkLoadError was unreachable in production. Its precondition is a guard
written by a *different* document ('reload-landed'), but the finally block
clears that guard before the throw, so the only path that could construct it
never ran. Confirmed by the shipped bundles: 16/16 lazy_chunk_reload_vetoed
breadcrumbs carry outcome=never-landed, zero carry any other outcome, and no
bundle contains a boundary-degraded breadcrumb.

Route every exhausted-recovery path through exhaustedRecoveryFailure() so an
attempted-and-failed recovery yields a LazyChunkLoadError the boundary can
contain, and record a lazy_chunk_recovery_exhausted breadcrumb carrying the
call site, the real chunk error, and the outcome.

Deliberately unchanged: when recovery is never *attempted* (no window/SSR,
blocked sessionStorage, guard write failure) the raw error is still thrown so
normal crash reporting is unaffected. Only isKnownDynamicImportFailure matches
are contained, so module logic bugs keep reporting.

* perf(renderer): trim redundant work on the lazy-chunk failure path

Hoist the dynamic-import message patterns to module scope so classification
stops allocating seven RegExp objects per call, thread the already-computed
classification into exhaustedRecoveryFailure so the guard-not-landed path does
not re-run it, and bound recordedExhaustionKeys the way the breadcrumb and
renderer-error key stores are bounded, since error.name is library-controlled.

Failure path only; the success path is unchanged.

* refactor(renderer): remove a transposition trap on the lazy-chunk failure path

exhaustedRecoveryFailure ended in two adjacent booleans with opposite
consequences: transposing them would have returned the raw SyntaxError and
silently restored the crash this branch fixes, with no test able to catch it
(the only call site passed true for both). The isChunkFailure parameter saved
one regex scan on a path that only runs after a 10s reload wait, so drop it.

Also evict recordedExhaustionKeys oldest-first instead of clearing wholesale,
matching the breadcrumb and renderer-error key stores the comment cites, so an
overflow cannot re-open the entire set to a repeat burst.

* test(renderer): cover the exhaustion dedupe bound

The bound had no coverage, unlike the crash-breadcrumb store it mirrors, so a
refactor could drop it or invert the comparison with every test still green.
Drive 200 distinct error names through the contained path and assert the set
stays capped. Also move MAX_RECORDED_EXHAUSTION_KEYS above the comment that
describes the set, not between them.

* test(renderer): pin the exhaustion eviction policy, not just the cap

The bound test asserted only the size cap, so it stayed green under the old
wholesale clear(): after 200 distinct keys a clear-on-overflow leaves 72, which
still satisfies the cap. Replay a key that oldest-first eviction retains and
assert it emits no second breadcrumb — that fails under clear(), which would
otherwise silently re-open the whole set to a repeat burst and flush the
30-entry ring the dedupe exists to protect.

* refactor(renderer): cut the breadcrumb machinery down to the actual fix

The lazy_chunk_recovery_exhausted breadcrumb was an optional addition that paid
for itself in complexity and nothing else: it needed a dedupe set to avoid
flushing the 30-entry ring, the set needed a bound because error.name is
library-controlled, the bound needed an oldest-first eviction policy, and that
needed two more tests plus a boolean parameter that review flagged as a
transposition trap. On the dominant never-landed path it did not even fire,
because lazy_chunk_reload_vetoed already records the same reloadKey, message and
outcome.

Drop it. Observability on every path returns to the main baseline, and the fix
is what it always was: name an exhausted recovery so the boundary can contain
it. Also revert the unrelated regex hoist -- its only caller is the failure
path, so the saved allocations are noise.

* Verify ordinary errors bypass lazy chunk containment

Add test ensuring module evaluation bugs still surface despite
never-landed reload attempts. Clarify containment scope: recovery
only applies to known dynamic-import failures, not ordinary errors.
@brennanb2025 brennanb2025 mentioned this pull request Nov 16, 2026
11 tasks done
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.

1 participant