Skip to content

perf: reduce validation and schema allocation overhead - #6588

Merged
colinhacks merged 9 commits into
mainfrom
perf-schema-benchmark-omnibus
Sep 12, 2026
Merged

colinhacks merged 9 commits into
mainfrom
perf-schema-benchmark-omnibus

Conversation

@colinhacks

@colinhacks colinhacks commented Sep 11, 2026 •

Copy link
Copy Markdown
Owner

Uses URL.canParse() for unconstrained URL and IPv6 checks, URL.parse() when validation needs the URL object, and constructor fallbacks when those APIs are unavailable. Compiled boolean URL validation skips unused output work; parsing retains sanitation, normalization, and the exported object-parser contract.

  • Skips one redundant trait-membership lookup immediately after allocating an empty trait set. Existing-instance guards, trait registration, and initializer ordering are unchanged.
  • Collects JSON Schema required keys without redundant Sets and replaces two wall-clock registry guards with deterministic map-scan checks.
  • Exposes typed checks options on string/number factories, including coercion and Mini, so callers can avoid constructing intermediate checked schemas.

The standalone boolean-pattern shortcut was removed in da373f8. It bypassed custom checks installed through trait composition. Boolean validation now uses its existing compiled route or ordinary runtime fallback; no standalone-format speedup is claimed. The speculative array-promise and empty-check-array edits were also removed.

All 8,307 tests pass locally with TypeScript 5.5, 6, and latest, including compile mode. Build, resolution, integration, formatting, lint, comments, circular-dependency, and semver checks pass. Exact-head CI is green on 2f6f898 after merging the latest main. Regression coverage includes custom trait checks, option accessors, compiled URL output, readonly factory checks, caller-array mutation, and check ordering.

Measurements and limits

Native Node 26.8.2 measurements use alternating separate processes, fixed iteration counts, consumed results, and GC between samples. Host load was explicitly permitted; small differences remain inconclusive.

Earlier isolated URL measurements observed roughly 98% lower invalid-URL latency. Valid normalized URLs were 4–5% slower in focused runs, a rejection-path tradeoff. Six isolated construction pairs measured a median ratio of 0.939 for Classic string construction with the fresh-set guard; product construction remained inconclusive. No published benchmark reranking or general parsing speedup is claimed.

The final removal comparison is 19aea70 → da373f8, not main → PR. Three alternating timing pairs per flavor at load 9–12 measured valid email latency about 2.2× higher and invalid email latency about 11× higher after removal, restoring the ordinary validation path. URL and compiled-product controls were approximately unchanged. Ordinary product parsing measured about 5% slower in Classic and 3% in Mini, while the Classic string control moved about 8%; these small shifts do not establish a regression.

Matched minified source-fixture gzip changes for removal alone:

Fixture Classic Mini
Object validation −91 B −64 B
URL validation −55 B −53 B
Email validation −85 B −83 B
Seven formats −97 B −88 B
Array validation −63 B 0 B
JSON Schema export −79 B 0 B

These fixtures are not interchangeable with the earlier full-PR bundle fixtures. Removal leaves retained product memory approximately unchanged at 63.3 KB Classic and 39.1 KB Mini. Compiled Mini product retention measured +167 B (about 0.4%); no memory reduction is claimed. Own descriptors, traits, and V8 fast properties match across all seven affected formats in Classic and Mini.

Single-pass checked construction

The factory option snapshots the caller's check array before passing it to the existing initializer. It accepts readonly tuples; later caller-array mutations cannot change compilation or JSON Schema independently of parsing. Parent tracking and trait initialization are unchanged. Subsequent chained checks still create immutable clones with live metadata inheritance.

const name = z.string({ checks: [z.minLength(1), z.maxLength(20)] });
const count = z.number({ checks: [z.gte(1), z.lte(20)] });

In the matched product fixture, this avoids 22 constructor allocations in Classic (71 → 49) and 11 in Mini (60 → 49). Four alternating native Node 26.8.2 rounds at load 12–16 observed approximately 62% lower Classic construction latency versus fluent builders, 43% versus batched checks, and 33–35% lower Mini latency versus batched checks before the snapshot fix. Retained memory is approximately 37.2 KB Classic and 30.5 KB Mini, including the fix.

The final snapshot operates on the freshly built definition so caller getters are read once. It adds 15–23 gzip bytes in the matched Classic/Mini leaf fixtures. The built Mini object fixture grows from 4,645 to 4,671 bytes; its ceiling is 4,699 including the documented 28-byte headroom. Four alternating rounds comparing the final snapshot against the original factory option at load 27–63 showed product-construction ratios of 0.966 Classic and 0.991 Mini. Mini leaf construction and parse samples were about 3% and 2% slower, with the plain-string control about 7% slower; these noisy results do not establish a precise marginal cost. Descriptor/trait/fast-property probes pass, and retained memory is approximately unchanged by the snapshot.

Existing fluent callers do not gain this construction improvement automatically. Initial Classic parse/validate samples were roughly 3–5%/3% slower with directly constructed schemas. A longer rerun at load 107–306 could not quantify that difference reliably. This is an opt-in construction tradeoff, not a claim of faster parsing.

Base update

Merged main through 413cce9 in 2f6f898, preserving the restoration of z.properties() as a check. The only textual conflict was the Mini object bundle ceiling. Remeasured built fixtures are 3,043 / 3,438 / 4,654 gzip bytes for Mini boolean/string/object; the string/object ceilings are 3,466 / 4,682, retaining 28 bytes of headroom for the factory snapshot. Earlier construction and chart measurements above describe the pre-merge head, not a new benchmark campaign against this base. Combined-code descriptor, trait, parent-inheritance, fast-property, and correctness probes pass. The short runtime comparison ran under high load and supports no precise new timing claim.

@colinhacks
colinhacks marked this pull request as ready for review September 11, 2026 06:19
Copilot AI lite review requested due to automatic review settings September 11, 2026 06:19

Copilot AI 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.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@pullfrog pullfrog 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.

Important

The standalone pattern shortcut can make z.validate() disagree with normal parsing after a schema definition changes.

Reviewed changes across the v4 validation, parsing, construction, and JSON Schema paths:

  • Native URL validation: selects URL.canParse(), URL.parse(), or constructor fallbacks according to whether validation needs a URL object.
  • Assert-only compilation: skips unused URL output sanitation and normalization while retaining checks and downstream value requirements.
  • Standalone format validation: adds a structural pattern shortcut for z.validate() on selected pure string formats.
  • Allocation reductions: lazily creates array promise lists and avoids empty local checks arrays during schema initialization.
  • JSON Schema generation: collects required object keys directly and replaces registry wall-clock guards with deterministic map-scan checks.
  • Coverage: adds URL fallback, compiled parity, async array, initializer-order, required-key-order, and complexity regressions.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using GPT Sol | 𝕏

Comment thread packages/zod/src/v4/core/parse.ts Resolved
@colinhacks
colinhacks marked this pull request as draft September 11, 2026 06:32

@pullfrog pullfrog 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.

✅ No new issues found.

Reviewed changes across the complete v4 performance patch, including the live-option fix at aca427f3:

  • Standalone format validation: the cached regex shortcut now rechecks live own and inherited coerce and when properties before bypassing the runtime parser.
  • Native URL validation: unconstrained checks use URL.canParse(), object-dependent checks use URL.parse(), and constructor fallbacks preserve older-runtime behavior.
  • Assert-only compilation: URL validation omits unused sanitation and normalization output without skipping chained checks or transforms.
  • Allocation reductions: synchronous arrays avoid a promise-list allocation, unchecked schemas avoid an empty checks array, and JSON Schema required keys are collected directly.
  • Regression coverage: deterministic registry work guards and targeted parity tests cover fallback APIs, mixed sync/async arrays, initializer ordering, key ordering, and mutable definitions.

Pullfrog  | View workflow run | Using GPT Sol | 𝕏

@colinhacks
colinhacks marked this pull request as draft September 11, 2026 16:27

@pullfrog pullfrog 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.

✅ No new issues found.

Reviewed changes across the complete current v4 performance patch, with emphasis on the final semantics-preservation commit at b949e4cf:

  • Native URL validation: unconstrained URL and IPv6 checks use URL.canParse(), object-dependent checks use URL.parse(), and constructor fallbacks preserve older-runtime behavior and output sanitation.
  • Standalone format validation: seven pure formats use the live regex definition in context-free z.validate() calls while retaining compiled-parser precedence and fallback behavior for checks, coercion, when, and explicit contexts.
  • Schema initialization: the final commit restores explicit format initializer composition, removes the unproven array and empty-check-array edits, and skips trait membership only for a freshly allocated empty set.
  • JSON Schema generation: required keys are collected without transient sets, while deterministic map-scan accounting replaces host-sensitive timing assertions for the registry complexity guards.
  • Verification: all changed-path projects passed, the full 8,307-test set passed across the pre-build and build-dependent runs, and the V8 probe kept schema instances and internals in fast-property mode.

Pullfrog  | View workflow run | Using GPT Sol | 𝕏

@pullfrog pullfrog 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.

Important

The new factory option retains caller-owned mutable state that can make interpreted parsing, JSON Schema output, and compiled validation disagree.

Reviewed changes since the prior Pullfrog review at b949e4cf, covering the new single-pass checked construction API:

  • Core factory parameters: Exposed typed prebuilt checks collections on plain string and number factories.
  • Classic and coercion surfaces: Propagated the option through existing shared parameter aliases and verified direct construction against fluent schemas.
  • Mini surface: Added direct checked construction coverage, including compiled validation and parent tracking.
  • Behavioral coverage: Exercised check ordering, coercion, asynchronous checks, metadata, JSON Schema output, and invalid cross-type checks.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using GPT Sol | 𝕏

Comment thread packages/zod/src/v4/core/api.ts Resolved

@pullfrog pullfrog 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.

Important

The caller-array inconsistency is resolved, but the snapshot helper still has observable repeated-read semantics and the updated bundle budget has no headroom.

Reviewed changes since the prior Pullfrog review at 3b999625, covering the factory-check snapshot fix:

  • Stable check collections: Snapshotted caller-owned check arrays before schema initialization so parsing, compilation, and JSON Schema generation retain one list.
  • Readonly factory options: Accepted readonly check tuples across plain and coercing string and number factories.
  • Regression coverage: Added Classic, Mini, compile-mode, coercion, and JSON Schema checks for post-construction caller-array mutation.
  • Bundle accounting: Raised the Mini object bundle ceiling for the snapshot implementation's measured gzip increase.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using GPT Sol | 𝕏

Comment thread packages/zod/src/v4/core/api.ts Resolved
Comment thread packages/treeshake/bundle-size.test.ts Resolved

@pullfrog pullfrog 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.

✅ No new issues found.

Reviewed changes since the prior Pullfrog review at 0e65d7f7, covering the final factory-check snapshot fix:

  • Single-read snapshots: Moved check collection copying onto the freshly assembled definition so caller-owned accessors are evaluated once while arrays remain detached.
  • Regression coverage: Added getter-read assertions across plain and coercing string and number factories in Classic, Mini, and compile-oriented tests.
  • Bundle accounting: Reset the Mini object ceiling to the final 4,671-byte gzip measurement plus the documented 28-byte headroom.

Pullfrog  | View workflow run | Using GPT Sol | 𝕏

@pullfrog pullfrog 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.

✅ No new code issues found.

Reviewed changes since the prior Pullfrog review at 19aea707, covering the removal of the standalone boolean-pattern shortcut:

  • Runtime validation: Removed the construction-time regex marker and routed uncompiled z.validate() calls through the full runtime parser again.
  • Format initialization: Removed marker installation from all seven affected standalone string-format constructors without changing their trait composition.
  • Regression coverage: Added a composed-format schema whose custom check disagreed with the removed shortcut; the test fails against 19aea707 and passes on this head across runtime, compile-mode, and type-check projects.

ℹ️ PR description still claims the removed optimization

The PR description still says this branch adds the standalone string-format shortcut and attributes runtime gains to it, although da373f84 removes that path. This does not affect code correctness, but the final description should distinguish the retained URL improvements from the reverted format-validation work.

Technical details
# Align the PR description with the current head

## Affected sites
- PR description — the standalone-format bullet, self-review paragraph, bundle table, and valid-email timing claim describe code no longer present

## Required outcome
- Remove or revise claims tied to the deleted boolean-pattern shortcut while retaining measurements that still apply to the URL and construction changes

Pullfrog  | View workflow run | Using GPT Sol | 𝕏

@pullfrog pullfrog 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.

✅ No new issues found.

Reviewed changes since the prior Pullfrog review at da373f84, covering the base merge and bundle-budget reconciliation:

  • Base integration: Merged main through 413cce9a, preserving the restored check-only z.properties() implementation and dropping obsolete schema-role imports.
  • Bundle accounting: Recalibrated the Mini string and object ceilings to 3,466 and 4,682 bytes; exact-head measurements of 3,438 and 4,654 retain the intended 28-byte margin.
  • Compatibility: Preserved single-pass string and number factory checks across the restored z.properties() check path in interpreted and compiled validation.

Pullfrog  | View workflow run | Using GPT Sol | 𝕏

@colinhacks
colinhacks merged commit ad32d75 into main Sep 12, 2026
9 checks passed
@colinhacks
colinhacks deleted the perf-schema-benchmark-omnibus branch September 12, 2026 19:49
@colinhacks

Copy link
Copy Markdown
Owner Author

Landed in v4.6.4.

This was referenced Oct 25, 2026

This branch was successfully deployed

1 active deployment
Preview – zod-v4 — 2f6f8980 Deployed Sep 12, 2026 by vercel[bot]
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.

2 participants