[9.4] fix(zod): reduce per-schema heap cost via shared method references (#263121)#265044
Merged
kibanamachine merged 1 commit intoelastic:9.4from Apr 22, 2026
Merged
Conversation
…lastic#263121) ## Summary Applies a memory optimization patch to Zod v4 to address significant heap cost regression introduced with the upgrade to Zod 4.x (see upstream issue [elastic#5760](colinhacks/zod#5760)). ### Problem Zod v4 assigns every method (`parse`, `check`, `optional`, `email`, etc.) as an **own-property arrow function** on each schema instance. Because each arrow function closes over `inst`, each instance allocates ~91 unique function objects. V8 switches from fast-property mode to slow "dictionary mode" when an object accumulates more than ~27 own properties, causing an extra heap tax on top of the closure overhead. In practice this costs **~12.8 KB of heap per schema** (vs ~1.5 KB with Zod 3). ### Fix — Shadow-Proto Architecture Introduces a hidden intermediate prototype layer (`internalProto`) between `_.prototype` (the user-visible class prototype) and the parent. Library methods are placed on `internalProto` via `_initProto` (once per concrete type, lazily), so they become **inherited** rather than own properties. ``` instance → _.prototype (user space, empty by default) → internalProto (library space: 69 shared methods) → Parent ``` Key properties: - **Own-property count**: ~91 → **~22** (well below V8's dictionary-mode threshold of ~27) - **Shared methods**: all 69 builder/parse methods are prototype-inherited; instances share the same function objects (`s1.optional === s2.optional`) - **Backward-compatible**: user-added prototype extensions on `_.prototype` still shadow `internalProto` transparently - **Covers both variants**: classic and mini Zod APIs (6 files patched) Six Zod files are patched (both CJS and ESM variants): - `zod/v4/classic/schemas.cjs` / `schemas.js` — `_initProto` helper + moves all builder methods to `internalProto` - `zod/v4/mini/schemas.cjs` / `schemas.js` — same for the mini API surface - `zod/v4/core/core.cjs` / `core.js` — wires `_.prototype → internalProto`, exposes `$internalProto` symbol; copy-loop left as no-op for library methods The patch is managed by `patch-package` and lives in `patches/zod+4.3.6.patch`. An upstream PR is being prepared: [colinhacks/zod#5870](colinhacks/zod#5870). ### Result | Metric | Before (Zod v4, unpatched) | After (shadow-proto patch) | | ------------------------------- | -------------------------- | -------------------------- | | Own properties per instance | ~91 | **~22** | | V8 property storage mode | Dictionary (slow) | **Fast** | | Heap cost per `z.string()` | ~12.8 KB | **~2.5 KB** | | Shared method references | ✗ (per-instance closures) | **✓** (prototype-inherited)| | **Memory reduction** | — | **~80%** | | `z.iso.datetime().optional()` | ✅ | ✅ | | Prototype augmentation | ✅ | ✅ | | All parse/validate/chain APIs | ✅ | ✅ | > Validated by full Kibana heap snapshot comparison: ~113 MB reduction at startup. ### Patch persistence The patch is applied automatically during `yarn kbn bootstrap` (after `yarn install`) via `patch-package --error-on-fail`. The `patches/` directory is committed and version-controlled. **Removal criteria**: remove `patches/zod+4.3.6.patch` (and the `patch-package` devDependency) once the upstream Zod issue is resolved and Kibana upgrades to the patched version. ### New dependency: `patch-package` | | | |---|---| | **Purpose** | Applies and maintains the shadow-proto patch to `node_modules/zod` across `yarn install` runs. Invoked as `patch-package --error-on-fail` in the bootstrap step. | | **Justification** | The optimization requires modifying Zod's compiled JavaScript internals (`$constructor` wiring, `_initProto` helper, builder method placement). These changes cannot be applied at the TypeScript/import level, so a post-install patch is the correct mechanism. `patch-package` is the industry-standard tool for this pattern, with a simple invocation model and deterministic patch application. | | **Alternatives explored** | (1) **Custom patching script** — Kibana used a bespoke `src/dev/node_modules_patches/` mechanism in an earlier iteration of this PR; `patch-package` is strictly simpler and more maintainable. (2) **`@kbn/zod` wrapper** — the wrapper re-exports `zod/v4` but cannot intercept the compiled `$constructor` and prototype wiring needed for this optimization. (3) **Private Elastic fork/registry** — viable but significantly heavier: requires maintaining a fork, publishing to a registry, and updating consumers; disproportionate effort for a temporary vendor patch. | | **Existing dependencies** | Kibana has no existing dependency providing `patch-package`-equivalent functionality. `yarn patch` (a built-in Yarn Berry feature) is not available since Kibana uses Yarn Classic. | ### Test plan - `npx patch-package --error-on-fail` applies cleanly from scratch - `z.iso.datetime().optional()` works - `z.string().email().optional()`, `obj.pick()`, `enum.extract()` all work - `z.httpUrl()` correctly rejects `ftp://`, `file:///` URLs (only `http`/`https` accepted) - Shared references confirmed: `z.string().optional === z.string().optional` → `true` - Own-property count confirmed: `Object.getOwnPropertyNames(z.string()).length` → `22` - Memory benchmark: ~2.5 KB per `z.string()` (down from ~12.8 KB) - `node scripts/check_changes.ts` passes - Heap snapshot comparison: ~113 MB reduction at Kibana startup --------- Co-authored-by: kibanamachine <42973632+kibanamachine@users.noreply.github.com> Co-authored-by: macroscopeapp[bot] <170038800+macroscopeapp[bot]@users.noreply.github.com> (cherry picked from commit ae70b77)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Backport
This will backport the following commits from
mainto9.4:Questions ?
Please refer to the Backport tool documentation