Skip to content

perf: fix O(n²) allocation in jsonSchemaToZod required field handling#1857

Open
ctonneslan wants to merge 1 commit intobrowserbase:mainfrom
ctonneslan:fix/json-schema-to-zod-perf
Open

perf: fix O(n²) allocation in jsonSchemaToZod required field handling#1857
ctonneslan wants to merge 1 commit intobrowserbase:mainfrom
ctonneslan:fix/json-schema-to-zod-perf

Conversation

@ctonneslan
Copy link

@ctonneslan ctonneslan commented Mar 19, 2026

Summary

Fixes two issues in jsonSchemaToZod required field handling:

  1. O(n²) object allocation: The reduce with spread operator ({ ...acc, [field]: true }) copies the entire accumulator on every iteration. Replaced with a for...of loop that mutates a single object in O(n).

  2. Redundant type guard: Array.isArray(schema.required) is unnecessary since schema.required is already typed as string[] in the JsonSchemaProperty interface. The truthiness check alone is sufficient.

Before

if (schema.required && Array.isArray(schema.required)) {
  const requiredFields = schema.required.reduce<Record<string, true>>(
    (acc, field) => ({ ...acc, [field]: true }),
    {},
  );

After

if (schema.required) {
  const requiredFields: Record<string, true> = {};
  for (const field of schema.required) {
    requiredFields[field] = true;
  }

Fixes #1773


Summary by cubic

Improve performance of required-field handling in jsonSchemaToZod by replacing the O(n²) reduce/spread pattern with an O(n) loop to cut allocations on large schemas. Also remove the redundant Array.isArray(schema.required) check since schema.required is typed as string[].

Written for commit 332c4fb. Summary will update on new commits. Review in cubic

…andling

Replace the reduce with spread operator (which copies the entire
accumulator on every iteration) with a simple for-of loop that
mutates a single object. Also remove the redundant Array.isArray
guard since schema.required is already typed as string[].

Fixes browserbase#1773
@changeset-bot
Copy link

changeset-bot bot commented Mar 19, 2026

⚠️ No Changeset found

Latest commit: 332c4fb

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

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

@github-actions
Copy link
Contributor

This PR is from an external contributor and must be approved by a stagehand team member with write access before CI can run.
Approving the latest commit mirrors it into an internal PR owned by the approver.
If new commits are pushed later, the internal PR stays open but is marked stale until someone approves the latest external commit and refreshes it.

@github-actions github-actions bot added external-contributor Tracks PRs mirrored from external contributor forks. external-contributor:awaiting-approval Waiting for a stagehand team member to approve the latest external commit. labels Mar 19, 2026
@greptile-apps
Copy link
Contributor

greptile-apps bot commented Mar 19, 2026

Greptile Summary

This PR makes a focused, correct performance optimization to jsonSchemaToZod in packages/core/lib/utils.ts. It replaces the O(n²) reduce + object spread pattern used to build the requiredFields lookup map with a simple O(n) for...of mutation loop, and removes the now-redundant Array.isArray(schema.required) guard (the JsonSchemaProperty interface already types required as string[]).

Key points:

  • The functional behavior is fully preserved — the for...of loop produces the same Record<string, true> map fed into .partial().required(requiredFields)
  • The empty-array edge case (schema.required: []) is handled identically: the truthiness check still passes, the loop runs zero iterations, and .partial().required({}) is called, making all fields optional — consistent with JSON Schema semantics
  • The Array.isArray guard previously provided an implicit runtime safety net for callers passing non-array values; removing it is safe within this typed codebase, since all call sites are statically typed

Confidence Score: 5/5

  • This PR is safe to merge — it's a correct, well-scoped performance optimization with no behavioral changes.
  • The change is minimal (5 lines replaced by 5 lines), logically equivalent, and backed by correct reasoning about the TypeScript type system. No new code paths are introduced, and the edge cases (empty array, undefined) are handled identically to before.
  • No files require special attention.

Important Files Changed

Filename Overview
packages/core/lib/utils.ts Replaces O(n²) reduce+spread with an O(n) for...of mutation loop, and removes the now-redundant Array.isArray guard on schema.required. Logic and behavior are preserved correctly.

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart TD
    A["jsonSchemaToZod(schema)"] --> B{schema.type === 'object'?}
    B -- No --> C[Handle other types]
    B -- Yes --> D{schema.properties?}
    D -- No --> E["return z.object({})"]
    D -- Yes --> F["Build shape via for...in loop\nO(n)"]
    F --> G["zodObject = z.object(shape)"]
    G --> H{schema.required?}
    H -- No --> J{schema.description?}
    H -- Yes --> I["Build requiredFields via for...of loop\nO(n) — no spread allocation"]
    I --> K["zodObject = zodObject.partial().required(requiredFields)"]
    K --> J
    J -- No --> L["return zodObject"]
    J -- Yes --> M["zodObject = zodObject.describe(description)"]
    M --> L
Loading

Last reviewed commit: "perf: fix O(n²) obje..."

Copy link
Contributor

@cubic-dev-ai cubic-dev-ai bot left a comment

Choose a reason for hiding this comment

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

No issues found across 1 file

Confidence score: 5/5

  • Automated review surfaced no issues in the provided summaries.
  • No files require special attention.

Since this is your first cubic review, here's how it works:

  • cubic automatically reviews your code and comments on bugs and improvements
  • Teach cubic by replying to its comments. cubic learns from your replies and gets better over time
  • Add one-off context when rerunning by tagging @cubic-dev-ai with guidance or docs links (including llms.txt)
  • Ask questions if you need clarification on any suggestion

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

external-contributor:awaiting-approval Waiting for a stagehand team member to approve the latest external commit. external-contributor Tracks PRs mirrored from external contributor forks.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

jsonSchemaToZod: Redundant type guard and O(n²) object allocation in required field handling

1 participant