Skip to content

[compiler] Remove tryRecord, add catch-all error handling, fix remaining throws#558

Closed
everettbu wants to merge 10 commits into
mainfrom
pr35837
Closed

[compiler] Remove tryRecord, add catch-all error handling, fix remaining throws#558
everettbu wants to merge 10 commits into
mainfrom
pr35837

Conversation

@everettbu

@everettbu everettbu commented Feb 21, 2026

Copy link
Copy Markdown

Mirror of facebook/react#35837
Original author: josephsavona


Remove tryRecord() from the compilation pipeline now that all passes record
errors directly via env.recordError() / env.recordErrors(). A single
catch-all try/catch in Program.ts provides the safety net for any pass that
incorrectly throws instead of recording.

Key changes:

  • Remove all ~64 env.tryRecord() wrappers in Pipeline.ts
  • Delete tryRecord() method from Environment.ts
  • Add CompileUnexpectedThrow logger event so thrown errors are detectable
  • Log CompileUnexpectedThrow in Program.ts catch-all for non-invariant throws
  • Fail snap tests on CompileUnexpectedThrow to surface pass bugs in dev
  • Convert throwTodo/throwDiagnostic calls in HIRBuilder (fbt, this),
    CodegenReactiveFunction (for-in/for-of), and BuildReactiveFunction to
    record errors or use invariants as appropriate
  • Remove try/catch from BuildHIR's lower() since inner throws are now recorded
  • CollectOptionalChainDependencies: return null instead of throwing on
    unsupported optional chain patterns (graceful optimization skip)

Stack created with Sapling. Best reviewed with ReviewStack.

  • #35838
  • -> #35837
  • #35836
  • #35835
  • #35834
  • #35833
  • #35832
  • #35831
  • #35830
  • #35829
  • #35828

Add detailed plan for making the React Compiler fault-tolerant by
accumulating errors across all passes instead of stopping at the first
error. This enables reporting multiple compilation errors at once.
Add error accumulation methods to the Environment class:
- #errors field to accumulate CompilerErrors across passes
- recordError() to record a single diagnostic (throws if Invariant)
- recordErrors() to record all diagnostics from a CompilerError
- hasErrors() to check if any errors have been recorded
- aggregateErrors() to retrieve the accumulated CompilerError
- tryRecord() to wrap callbacks and catch CompilerErrors
…erance

- Change runWithEnvironment/run/compileFn to return Result<CodegenFunction, CompilerError>
- Wrap all pipeline passes in env.tryRecord() to catch and record CompilerErrors
- Record inference pass errors via env.recordErrors() instead of throwing
- Handle codegen Result explicitly, returning Err on failure
- Add final error check: return Err(env.aggregateErrors()) if any errors accumulated
- Update tryCompileFunction and retryCompileFunction in Program.ts to handle Result
- Keep lint-only passes using env.logErrors() (non-blocking)
- Update 52 test fixture expectations that now report additional errors

This is the core integration that enables fault tolerance: errors are caught,
recorded, and the pipeline continues to discover more errors.
…rs on env

Update 9 validation passes to record errors directly on fn.env instead of
returning Result<void, CompilerError>:
- validateHooksUsage
- validateNoCapitalizedCalls (also changed throwInvalidReact to recordError)
- validateUseMemo
- dropManualMemoization
- validateNoRefAccessInRender
- validateNoSetStateInRender
- validateNoImpureFunctionsInRender
- validateNoFreezingKnownMutableFunctions
- validateExhaustiveDependencies

Each pass now calls fn.env.recordErrors() instead of returning errors.asResult().
Pipeline.ts call sites updated to remove tryRecord() wrappers and .unwrap().
… tolerance

Update remaining validation passes to record errors on env:
- validateMemoizedEffectDependencies
- validatePreservedManualMemoization
- validateSourceLocations (added env parameter)
- validateContextVariableLValues (changed throwTodo to recordError)
- validateLocalsNotReassignedAfterRender (changed throw to recordError)
- validateNoDerivedComputationsInEffects (changed throw to recordError)

Update inference passes:
- inferMutationAliasingEffects: return void, errors on env
- inferMutationAliasingRanges: return Array<AliasingEffect> directly, errors on env

Update codegen:
- codegenFunction: return CodegenFunction directly, errors on env
- codegenReactiveFunction: same pattern

Update Pipeline.ts to call all passes directly without tryRecord/unwrap.
Also update AnalyseFunctions.ts which called inferMutationAliasingRanges.
Add test fixture demonstrating fault tolerance: the compiler now reports
both a mutation error and a ref access error in the same function, where
previously only one would be reported before bailing out.

Update plan doc to mark all phases as complete.
…ing throws

Remove `tryRecord()` from the compilation pipeline now that all passes record
errors directly via `env.recordError()` / `env.recordErrors()`. A single
catch-all try/catch in Program.ts provides the safety net for any pass that
incorrectly throws instead of recording.

Key changes:
- Remove all ~64 `env.tryRecord()` wrappers in Pipeline.ts
- Delete `tryRecord()` method from Environment.ts
- Add `CompileUnexpectedThrow` logger event so thrown errors are detectable
- Log `CompileUnexpectedThrow` in Program.ts catch-all for non-invariant throws
- Fail snap tests on `CompileUnexpectedThrow` to surface pass bugs in dev
- Convert throwTodo/throwDiagnostic calls in HIRBuilder (fbt, this),
  CodegenReactiveFunction (for-in/for-of), and BuildReactiveFunction to
  record errors or use invariants as appropriate
- Remove try/catch from BuildHIR's lower() since inner throws are now recorded
- CollectOptionalChainDependencies: return null instead of throwing on
  unsupported optional chain patterns (graceful optimization skip)
@everettbu everettbu added CLA Signed React Core Team Opened by a member of the React Core Team labels Feb 21, 2026
@greptile-apps

greptile-apps Bot commented Feb 21, 2026

Copy link
Copy Markdown

Greptile Summary

This PR completes the fault tolerance refactor for the React Compiler by removing all ~64 env.tryRecord() wrappers from Pipeline.ts and replacing them with direct error recording via env.recordError() / env.recordErrors() on the Environment. The compilation pipeline now accumulates errors instead of stopping at the first one, with a final env.hasErrors() check at the end of runWithEnvironment() to return aggregated errors.

  • Error accumulation: Environment.ts gains #errors, recordError(), recordErrors(), hasErrors(), and aggregateErrors() methods. Invariant-category errors are still immediately thrown since they represent unrecoverable internal bugs.
  • Pipeline simplification: Pipeline.ts removes all .unwrap() calls from validation/pass results. Functions like lower(), codegenFunction(), and all validators now return void or direct values instead of Result types, recording errors on the environment.
  • Catch-all safety net: Program.ts adds CompileUnexpectedThrow logger event detection in catch blocks for both tryCompileFunction and retryCompileFunction, so passes that incorrectly throw instead of recording are detectable in development.
  • Graceful degradation in BuildHIR: Adds best-effort handling for for(;;) (empty init/test), var declarations (treated as let), and unsupported for-loop inits. Instead of aborting on these patterns, errors are recorded and compilation continues with reasonable fallbacks.
  • Test infrastructure: Snap tests now fail on CompileUnexpectedThrow events. New fault tolerance test fixtures validate that multiple independent errors are reported together.
  • ~70 test fixture updates: Expected outputs updated to reflect multi-error reporting and changed error formatting.

Confidence Score: 4/5

  • This PR is a well-structured refactor with comprehensive test coverage; safe to merge with only minor style suggestions.
  • Score reflects a large but systematic refactor that consistently applies one pattern (error recording instead of throwing) across ~20 source files. The changes are well-tested with new fault tolerance fixtures and updated snapshot expectations. The only issues found are minor style inconsistencies (unconditional recordErrors calls, one as any cast). No logical bugs or regressions identified.
  • compiler/packages/babel-plugin-react-compiler/src/HIR/BuildHIR.ts has the most complex behavioral changes (graceful for-loop/var handling) and deserves careful review of the fallback logic.

Important Files Changed

Filename Overview
compiler/packages/babel-plugin-react-compiler/src/Entrypoint/Pipeline.ts Core pipeline changes: removes all ~15 .unwrap() calls from validation/pass results, changes runWithEnvironment to return Result<CodegenFunction, CompilerError>, and adds final env.hasErrors() check at pipeline end. Clean, systematic refactor.
compiler/packages/babel-plugin-react-compiler/src/Entrypoint/Program.ts Adds CompileUnexpectedThrow logging in catch-all handlers for both tryCompileFunction and retryCompileFunction. Uses Result pattern to distinguish expected errors from unexpected throws. Correct handling of invariant vs non-invariant errors.
compiler/packages/babel-plugin-react-compiler/src/HIR/Environment.ts Adds #errors field and recordError/recordErrors/hasErrors/aggregateErrors methods. The recordError method correctly rethrows Invariant-category errors immediately since they represent unrecoverable internal bugs.
compiler/packages/babel-plugin-react-compiler/src/HIR/BuildHIR.ts Significant changes: lower() now returns HIRFunction directly instead of Result, records errors on env after builder.build(). Adds graceful handling for for(;;) (empty init/test), var declarations (treated as let), and removes early returns on nested function lowering failures. The effects field is correctly removed from the return object to match the updated HIRFunction type.
compiler/packages/babel-plugin-react-compiler/src/HIR/HIRBuilder.ts Converts throwDiagnostic/throwTodo calls for fbt, this, and unreachable hoisted declarations to builder.errors.push() instead of throwing, enabling error accumulation.
compiler/packages/babel-plugin-react-compiler/src/HIR/CollectOptionalChainDependencies.ts Returns null instead of throwing on unsupported optional chain patterns, gracefully skipping the optimization.
compiler/packages/babel-plugin-react-compiler/src/ReactiveScopes/CodegenReactiveFunction.ts Converts throwTodo to error recording with early return t.emptyStatement() for for-in/for-of StoreContext and non-trivial init cases. Changes codegenFunction/codegenReactiveFunction return types from Result to direct values, recording errors on fn.env.
compiler/packages/babel-plugin-react-compiler/src/ReactiveScopes/BuildReactiveFunction.ts Converts throwTodo for unexpected terminal kind to CompilerError.invariant(false, ...), which is appropriate since this represents an internal logic error that should not be silently swallowed.
compiler/packages/snap/src/compiler.ts Adds snap test check for CompileUnexpectedThrow events, failing tests when passes throw instead of recording. Uses (l.event as any).data type assertion.
compiler/packages/babel-plugin-react-compiler/src/Validation/ValidateNoRefAccessInRender.ts Refactored to pass errors: CompilerError through the recursive implementation. Uses innerErrors for function expressions to determine ref access effects without polluting the outer error list — consistent with previous behavior.
compiler/packages/babel-plugin-react-compiler/src/Inference/InferMutationAliasingRanges.ts Changes return type from Result to direct array. Adds fn.env.enableValidations guard to match the previous Pipeline.ts caller behavior.

Last reviewed commit: 6163309

@greptile-apps greptile-apps Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

98 files reviewed, 2 comments

Edit Code Review Agent Settings | Greptile

kind: 'err',
msg:
`Compiler pass(es) threw instead of recording errors:\n` +
unexpectedThrows.map(l => (l.event as any).data).join('\n'),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Unsafe as any type cast
The (l.event as any).data cast bypasses type safety when the type could be narrowed from the filter. Consider using a type guard or asserting the narrowed event type directly:

Suggested change
unexpectedThrows.map(l => (l.event as any).data).join('\n'),
unexpectedThrows.map(l => (l.event as CompileUnexpectedThrowEvent).data).join('\n'),

Alternatively, a type predicate on the filter would avoid the cast entirely.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

Prompt To Fix With AI
This is a comment left during a code review.
Path: compiler/packages/snap/src/compiler.ts
Line: 389

Comment:
**Unsafe `as any` type cast**
The `(l.event as any).data` cast bypasses type safety when the type could be narrowed from the filter. Consider using a type guard or asserting the narrowed event type directly:

```suggestion
        unexpectedThrows.map(l => (l.event as CompileUnexpectedThrowEvent).data).join('\n'),
```

Alternatively, a type predicate on the filter would avoid the cast entirely.

<sub>Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!</sub>

How can I resolve this? If you propose a fix, please make it concise.

const errors = new CompilerError();
visitReactiveFunction(fn, new Visitor(), errors);
return errors.asResult();
fn.env.recordErrors(errors);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Unconditional recordErrors call
This calls fn.env.recordErrors(errors) without checking errors.hasAnyErrors() first. While harmless (empty details array is a no-op), it's inconsistent with the pattern used in most other validators (e.g., ValidateHooksUsage, ValidateUseMemo, ValidateNoCapitalizedCalls). The same inconsistency also appears in ValidatePreservedManualMemoization, ValidateNoDerivedComputationsInEffects, and ValidateSourceLocations.

Suggested change
fn.env.recordErrors(errors);
if (errors.hasAnyErrors()) {
fn.env.recordErrors(errors);
}

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

Prompt To Fix With AI
This is a comment left during a code review.
Path: compiler/packages/babel-plugin-react-compiler/src/Validation/ValidateMemoizedEffectDependencies.ts
Line: 54

Comment:
**Unconditional `recordErrors` call**
This calls `fn.env.recordErrors(errors)` without checking `errors.hasAnyErrors()` first. While harmless (empty details array is a no-op), it's inconsistent with the pattern used in most other validators (e.g., `ValidateHooksUsage`, `ValidateUseMemo`, `ValidateNoCapitalizedCalls`). The same inconsistency also appears in `ValidatePreservedManualMemoization`, `ValidateNoDerivedComputationsInEffects`, and `ValidateSourceLocations`.

```suggestion
  if (errors.hasAnyErrors()) {
    fn.env.recordErrors(errors);
  }
```

<sub>Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!</sub>

How can I resolve this? If you propose a fix, please make it concise.

@everettbu

Copy link
Copy Markdown
Author

Upstream PR was closed or merged. Code is synced via branch mirror.

@everettbu everettbu closed this Feb 21, 2026
@everettbu
everettbu deleted the pr35837 branch February 21, 2026 04:00
@everettbu
everettbu restored the pr35837 branch February 21, 2026 04:38
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CLA Signed React Core Team Opened by a member of the React Core Team

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants