Skip to content

refactor: remove recursion from schema utilities to prevent call stack overflows #4044

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: main
Choose a base branch
from

Conversation

MegaManSec
Copy link

@MegaManSec MegaManSec commented Mar 21, 2025

This PR rewrites getDiscriminator, processError, and mergeValues to use a stack-based iterative approach to deeply nested errors/discriminators, in order to avoid infinite recursion (which could result in a stack overflow, resulting in a crash of the interpreter).

Note: deepPartialify also suffers from this issue, but I'm unsure how to approach fixing it.

Summary by CodeRabbit

  • Refactor
    • Improved internal error handling and data processing for more reliable error reporting.
    • Streamlined merging and extraction of values, enhancing overall stability and maintainability.

These updates enhance system robustness and performance, ensuring a smoother and more dependable experience for end-users while preserving backward compatibility.

This avoids potential crashes of the interpretor due to massive amounts
of recursion.

Signed-off-by: Joshua Rogers <MegaManSec@users.noreply.github.com>
This avoids potential crashes of the interpretor due to massive amounts
of recursion.

Signed-off-by: Joshua Rogers <MegaManSec@users.noreply.github.com>
This avoids potential crashes of the interpretor due to massive amounts
of recursion.

Signed-off-by: Joshua Rogers <MegaManSec@users.noreply.github.com>
Copy link
Contributor

coderabbitai bot commented Mar 21, 2025

Walkthrough

This pull request refactors error processing and type-handling functions across both the Deno and source libraries. In the ZodError implementations (in both deno/lib/ZodError.ts and src/ZodError.ts), a recursive approach in the processError function has been replaced with an iterative, stack-based implementation. Similarly, the getDiscriminator and mergeValues functions in both deno/lib/types.ts and src/types.ts have been restructured to iterate over inputs using a stack instead of deep recursive calls. Minor signature updates improve clarity without altering the exported public interfaces.

Changes

File(s) Change Summary
deno/lib/ZodError.ts, src/ZodError.ts Refactored the processError method: replaced recursive error processing with an iterative stack-based loop. In src/ZodError.ts, the parameter is renamed from error to rootError for clarity. No changes to exported entities.
deno/lib/types.ts, src/types.ts Updated getDiscriminator and mergeValues functions to use an iterative, stack-based approach instead of recursion. This streamlines control flow and reduces nested conditionals. Function signatures are updated for clarity while preserving the existing behavior and exports.

Sequence Diagram(s)

sequenceDiagram
    participant Caller as Caller
    participant ZodError as ZodError
    participant Stack as ErrorStack

    Caller->>ZodError: processError(rootError)
    ZodError->>Stack: Push rootError
    loop While Stack not empty
        Stack->>ZodError: Pop current error
        ZodError->>ZodError: Iterate over error issues
        alt Issue is union/return/arguments
            ZodError->>Stack: Push related errors
        else
            ZodError->>ZodError: Update fieldErrors
        end
    end
    ZodError->>Caller: Return processed error result
Loading
sequenceDiagram
    participant Caller as Caller
    participant Types as TypeFunctions
    participant Stack as TypeStack

    Caller->>Types: Call getDiscriminator(type) / mergeValues(a, b)
    Types->>Stack: Initialize stack with input(s)
    loop While Stack not empty
       Stack->>Types: Pop current element
       alt Element needs further processing
           Types->>Stack: Push inner element(s)
       else
           Types->>Types: Process and accumulate result
       end
    end
    Types->>Caller: Return final result
Loading

Poem

I'm a rabbit with a hop so spry,
Coding through changes, oh my!
Replacing recursion with a stack,
Clearing out loops with no looking back.
With each line of refactored art,
My heart jumps high—a joyful start!

✨ Finishing Touches
  • 📝 Generate Docstrings

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

netlify bot commented Mar 21, 2025

Deploy Preview for guileless-rolypoly-866f8a ready!

Built without sensitive environment variables

Name Link
🔨 Latest commit f8a4a42
🔍 Latest deploy log https://app.netlify.com/sites/guileless-rolypoly-866f8a/deploys/67dd7828e5d98500090100b7
😎 Deploy Preview https://deploy-preview-4044--guileless-rolypoly-866f8a.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site configuration.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🔭 Outside diff range comments (1)
src/types.ts (1)

3415-3505: ⚠️ Potential issue

Risk of infinite looping on cyclical references.

While the iterative approach in mergeValues prevents stack overflows from recursion, there is no mechanism for detecting or breaking out of cyclical references. If either input contains objects with circular links, the loop could become infinite when repeatedly merging shared keys, arrays, or nested structures.

To mitigate this, track visited pairs of objects or otherwise detect cycles. This will ensure reliable merging without the risk of hanging the process.

🧹 Nitpick comments (3)
deno/lib/ZodError.ts (1)

248-271: Consider removing obsolete commented code
Lines 257-263 are commented out. If no longer needed, removing them would simplify the code and improve readability. Otherwise, clarify under which conditions you might need to reintroduce that logic.

-                // if (typeof el === "string") {
-                //   curr[el] = curr[el] || { _errors: [] };
-                // } else if (typeof el === "number") {
-                //   const errorArray: any = [];
-                //   errorArray._errors = [];
-                //   curr[el] = curr[el] || errorArray;
-                // }
src/ZodError.ts (1)

248-271: Remove or clarify commented mapping code
The commented code in lines 257-263 looks like a remnant from the previous implementation. For maintainability, remove this block if it’s not needed, or document why it must remain.

-                // if (typeof el === "string") {
-                //   curr[el] = curr[el] || { _errors: [] };
-                // } else if (typeof el === "number") {
-                //   const errorArray: any = [];
-                //   errorArray._errors = [];
-                //   curr[el] = curr[el] || errorArray;
-                // }
deno/lib/types.ts (1)

3419-3501: Validate partial merges for objects with unequal key sets.

The iterative strategy merges two structures only when their types align (objects with objects, arrays with arrays), handling shared keys recursively. This works well for symmetrical objects. However, spread merging objects (const newObj = { ...a, ...b }) silently includes extra properties from the second object that aren't in the first. This is acceptable unless you require strict structural equality. If that’s the case, you might want to explicitly flag differences in object keys.

Additionally, consider adding a mechanism to short-circuit early if either structure is extremely large or deeply nested, as the stack-based merging can become costly.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f204123 and f8a4a42.

📒 Files selected for processing (4)
  • deno/lib/ZodError.ts (1 hunks)
  • deno/lib/types.ts (2 hunks)
  • src/ZodError.ts (1 hunks)
  • src/types.ts (2 hunks)
🧰 Additional context used
🧬 Code Definitions (3)
src/ZodError.ts (1)
deno/lib/ZodError.ts (1) (1)
  • ZodError (200-332)
deno/lib/ZodError.ts (1)
src/ZodError.ts (1) (1)
  • ZodError (200-332)
src/types.ts (3)
deno/lib/types.ts (5) (5)
  • ZodTypeAny (50-50)
  • ZodLazy (4266-4291)
  • ZodEffects (4656-4821)
  • ZodEffects (4823-4823)
  • ZodCatch (4981-5055)
deno/lib/helpers/util.ts (3) (3)
  • getParsedType (166-220)
  • ZodParsedType (141-162)
  • ZodParsedType (164-164)
src/helpers/util.ts (3) (3)
  • getParsedType (166-220)
  • ZodParsedType (141-162)
  • ZodParsedType (164-164)
🔇 Additional comments (8)
deno/lib/ZodError.ts (3)

230-233: Rename parameter to improve clarity
The new parameter name rootError clarifies the purpose more effectively compared to a generic error. Initializing the stack with [rootError] is a good setup for the following iterative approach.


234-245: Check for potential infinite loops in error stacks
The new while (stack.length > 0) iteration is clear and should avoid deep recursion. However, if there's a cyclical reference in unionErrors, returnTypeError, or argumentsError, you could risk an infinite loop. Consider adding a mechanism (e.g. a visited set) to guard against cycles if it’s possible in practice.

Could you confirm whether cyclical references across union errors can occur in real scenarios?


246-247: Appending errors with no path
Storing top-level issues in fieldErrors._errors ensures clarity and consistency. This straightforward approach aligns with existing logic.

src/ZodError.ts (3)

230-233: Rename parameter to rootError
Switching from error to rootError makes the code more understandable. Initializing the stack with a single root error is a clean entry point to the iterative approach.


234-245: Avoid infinite loops with nested or cyclical errors
The while (stack.length > 0) logic properly replaces deep recursion. As a best practice, guard against potential cycles if the library or user code can produce self-referential error graphs.

If cyclic error graphs are possible, consider a visited set or similar mechanism to avoid infinite loops.


246-247: Top-level errors appended to _errors
Placing top-level issues in fieldErrors._errors mirrors the preexisting approach and keeps the handling of pathless issues consistent.

deno/lib/types.ts (1)

3221-3260: Ensure cyclic references are handled to avoid infinite loops.

This iterative approach replaces recursion with a stack-based procedure for extracting potential discriminator values. While it correctly unwinds complex types (lazy schemas, optional/nullable wrappers, etc.), there's no check for cyclic or repeated references. If a schema refers to itself (directly or indirectly), the while loop can run indefinitely. Consider introducing a visited set or similar mechanism to prevent infinite loops when encountering cyclic references.

Do you want me to provide a helper function or script to identify potential self-referential schemas in your codebase?

src/types.ts (1)

3220-3260: Iterative refactor approved with a minor caveat regarding potential loops.

This iterative approach in getDiscriminator is a clean replacement for recursion and effectively avoids stack overflows. However, be mindful of cyclical or deeply nested schemas that might repeatedly push the same item to the stack. Consider a safeguard (e.g., a visited set) to prevent infinite loops if future changes allow cycles.

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