Skip to content

[plugin installer] Checks url extension if unknown content-type#5760

Merged
epixa merged 1 commit intoelastic:masterfrom
BigFunger:plugin-installer-unknown-content-type
Dec 22, 2015
Merged

[plugin installer] Checks url extension if unknown content-type#5760
epixa merged 1 commit intoelastic:masterfrom
BigFunger:plugin-installer-unknown-content-type

Conversation

@BigFunger
Copy link
Copy Markdown
Contributor

Fixes #5759

If the plugin installer now gets that or any other unknown content-type in the response, it defaults to checking the source url for an extension.

@spalger
Copy link
Copy Markdown
Contributor

spalger commented Dec 22, 2015

LGTM

@spalger
Copy link
Copy Markdown
Contributor

spalger commented Dec 22, 2015

Would you mind merging this into #5755?

@jbudz
Copy link
Copy Markdown
Contributor

jbudz commented Dec 22, 2015

LGTM

@jbudz jbudz assigned BigFunger and unassigned jbudz Dec 22, 2015
epixa added a commit that referenced this pull request Dec 22, 2015
…ent-type

[plugin installer] Checks url extension if unknown content-type
@epixa epixa merged commit dd5770d into elastic:master Dec 22, 2015
@BigFunger BigFunger removed the v4.4.0 label Dec 22, 2015
gsoldevila added a commit that referenced this pull request Apr 22, 2026
…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 [#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>
kibanamachine added a commit that referenced this pull request Apr 22, 2026
…ces (#263121) (#265044)

# Backport

This will backport the following commits from `main` to `9.4`:
- [fix(zod): reduce per-schema heap cost via shared method references
(#263121)](#263121)

<!--- Backport version: 9.6.6 -->

### Questions ?
Please refer to the [Backport tool
documentation](https://github.com/sorenlouv/backport)

<!--BACKPORT [{"author":{"name":"Gerard
Soldevila","email":"gerard.soldevila@elastic.co"},"sourceCommit":{"committedDate":"2026-04-22T13:19:07Z","message":"fix(zod):
reduce per-schema heap cost via shared method references (#263121)\n\n##
Summary\n\nApplies a memory optimization patch to Zod v4 to address
significant\nheap cost regression introduced with the upgrade to Zod 4.x
(see\nupstream issue
[#5760](https://github.com/colinhacks/zod/issues/5760)).\n\n###
Problem\n\nZod v4 assigns every method (`parse`, `check`, `optional`,
`email`,\netc.) as an **own-property arrow function** on each schema
instance.\nBecause each arrow function closes over `inst`, each instance
allocates\n~91 unique function objects. V8 switches from fast-property
mode to slow\n\"dictionary mode\" when an object accumulates more than
~27 own\nproperties, causing an extra heap tax on top of the closure
overhead. In\npractice this costs **~12.8 KB of heap per schema** (vs
~1.5 KB with Zod\n3).\n\n### Fix — Shadow-Proto
Architecture\n\nIntroduces a hidden intermediate prototype layer
(`internalProto`)\nbetween `_.prototype` (the user-visible class
prototype) and the parent.\nLibrary methods are placed on
`internalProto` via `_initProto` (once per\nconcrete type, lazily), so
they become **inherited** rather than own\nproperties.\n\n```\ninstance
→ _.prototype (user space, empty by default)\n → internalProto (library
space: 69 shared methods)\n → Parent\n```\n\nKey properties:\n-
**Own-property count**: ~91 → **~22** (well below V8's
dictionary-mode\nthreshold of ~27)\n- **Shared methods**: all 69
builder/parse methods are\nprototype-inherited; instances share the same
function objects\n(`s1.optional === s2.optional`)\n-
**Backward-compatible**: user-added prototype extensions
on\n`_.prototype` still shadow `internalProto` transparently\n- **Covers
both variants**: classic and mini Zod APIs (6 files patched)\n\nSix Zod
files are patched (both CJS and ESM variants):\n\n-
`zod/v4/classic/schemas.cjs` / `schemas.js` — `_initProto` helper
+\nmoves all builder methods to `internalProto`\n-
`zod/v4/mini/schemas.cjs` / `schemas.js` — same for the mini
API\nsurface\n- `zod/v4/core/core.cjs` / `core.js` — wires `_.prototype
→\ninternalProto`, exposes `$internalProto` symbol; copy-loop left as
no-op\nfor library methods\n\nThe patch is managed by `patch-package`
and lives in\n`patches/zod+4.3.6.patch`. An upstream PR is being
prepared:\n[colinhacks/zod#5870](https://github.com/colinhacks/zod/pull/5870).\n\n###
Result\n\n| Metric | Before (Zod v4, unpatched) | After (shadow-proto
patch) |\n| ------------------------------- | --------------------------
|\n-------------------------- |\n| Own properties per instance | ~91 |
**~22** |\n| V8 property storage mode | Dictionary (slow) | **Fast**
|\n| Heap cost per `z.string()` | ~12.8 KB | **~2.5 KB** |\n| Shared
method references | ✗ (per-instance closures) |
**✓**\n(prototype-inherited)|\n| **Memory reduction** | — | **~80%**
|\n| `z.iso.datetime().optional()` | ✅ | ✅ |\n| Prototype augmentation |
✅ | ✅ |\n| All parse/validate/chain APIs | ✅ | ✅ |\n\n> Validated by
full Kibana heap snapshot comparison: ~113 MB reduction\nat
startup.\n\n### Patch persistence\n\nThe patch is applied automatically
during `yarn kbn bootstrap` (after\n`yarn install`) via `patch-package
--error-on-fail`. The `patches/`\ndirectory is committed and
version-controlled.\n\n**Removal criteria**: remove
`patches/zod+4.3.6.patch` (and the\n`patch-package` devDependency) once
the upstream Zod issue is resolved\nand Kibana upgrades to the patched
version.\n\n### New dependency: `patch-package`\n\n| | |\n|---|---|\n|
**Purpose** | Applies and maintains the shadow-proto patch
to\n`node_modules/zod` across `yarn install` runs. Invoked as
`patch-package\n--error-on-fail` in the bootstrap step. |\n|
**Justification** | The optimization requires modifying Zod's
compiled\nJavaScript internals (`$constructor` wiring, `_initProto`
helper,\nbuilder method placement). These changes cannot be applied at
the\nTypeScript/import level, so a post-install patch is the
correct\nmechanism. `patch-package` is the industry-standard tool for
this\npattern, with a simple invocation model and deterministic
patch\napplication. |\n| **Alternatives explored** | (1) **Custom
patching script** — Kibana\nused a bespoke
`src/dev/node_modules_patches/` mechanism in an earlier\niteration of
this PR; `patch-package` is strictly simpler and more\nmaintainable. (2)
**`@kbn/zod` wrapper** — the wrapper re-exports\n`zod/v4` but cannot
intercept the compiled `$constructor` and prototype\nwiring needed for
this optimization. (3) **Private Elastic\nfork/registry** — viable but
significantly heavier: requires maintaining\na fork, publishing to a
registry, and updating consumers;\ndisproportionate effort for a
temporary vendor patch. |\n| **Existing dependencies** | Kibana has no
existing dependency\nproviding `patch-package`-equivalent functionality.
`yarn patch` (a\nbuilt-in Yarn Berry feature) is not available since
Kibana uses Yarn\nClassic. |\n\n### Test plan\n\n- `npx patch-package
--error-on-fail` applies cleanly from scratch\n-
`z.iso.datetime().optional()` works\n- `z.string().email().optional()`,
`obj.pick()`, `enum.extract()` all\nwork\n- `z.httpUrl()` correctly
rejects `ftp://`, `file:///` URLs (only\n`http`/`https` accepted)\n-
Shared references confirmed: `z.string().optional
===\nz.string().optional` → `true`\n- Own-property count
confirmed:\n`Object.getOwnPropertyNames(z.string()).length` → `22`\n-
Memory benchmark: ~2.5 KB per `z.string()` (down from ~12.8 KB)\n- `node
scripts/check_changes.ts` passes\n- Heap snapshot comparison: ~113 MB
reduction at Kibana startup\n\n---------\n\nCo-authored-by:
kibanamachine
<42973632+kibanamachine@users.noreply.github.com>\nCo-authored-by:
macroscopeapp[bot]
<170038800+macroscopeapp[bot]@users.noreply.github.com>","sha":"ae70b77d9551d54563537c088b92f643f43e96fa","branchLabelMapping":{"^v9.5.0$":"main","^v(\\d+).(\\d+).\\d+$":"$1.$2"}},"sourcePullRequest":{"labels":["Team:Core","release_note:skip","ci:build-cloud-image","backport:version","v9.4.0","v9.5.0"],"title":"fix(zod):
reduce per-schema heap cost via shared method
references","number":263121,"url":"https://github.com/elastic/kibana/pull/263121","mergeCommit":{"message":"fix(zod):
reduce per-schema heap cost via shared method references (#263121)\n\n##
Summary\n\nApplies a memory optimization patch to Zod v4 to address
significant\nheap cost regression introduced with the upgrade to Zod 4.x
(see\nupstream issue
[#5760](https://github.com/colinhacks/zod/issues/5760)).\n\n###
Problem\n\nZod v4 assigns every method (`parse`, `check`, `optional`,
`email`,\netc.) as an **own-property arrow function** on each schema
instance.\nBecause each arrow function closes over `inst`, each instance
allocates\n~91 unique function objects. V8 switches from fast-property
mode to slow\n\"dictionary mode\" when an object accumulates more than
~27 own\nproperties, causing an extra heap tax on top of the closure
overhead. In\npractice this costs **~12.8 KB of heap per schema** (vs
~1.5 KB with Zod\n3).\n\n### Fix — Shadow-Proto
Architecture\n\nIntroduces a hidden intermediate prototype layer
(`internalProto`)\nbetween `_.prototype` (the user-visible class
prototype) and the parent.\nLibrary methods are placed on
`internalProto` via `_initProto` (once per\nconcrete type, lazily), so
they become **inherited** rather than own\nproperties.\n\n```\ninstance
→ _.prototype (user space, empty by default)\n → internalProto (library
space: 69 shared methods)\n → Parent\n```\n\nKey properties:\n-
**Own-property count**: ~91 → **~22** (well below V8's
dictionary-mode\nthreshold of ~27)\n- **Shared methods**: all 69
builder/parse methods are\nprototype-inherited; instances share the same
function objects\n(`s1.optional === s2.optional`)\n-
**Backward-compatible**: user-added prototype extensions
on\n`_.prototype` still shadow `internalProto` transparently\n- **Covers
both variants**: classic and mini Zod APIs (6 files patched)\n\nSix Zod
files are patched (both CJS and ESM variants):\n\n-
`zod/v4/classic/schemas.cjs` / `schemas.js` — `_initProto` helper
+\nmoves all builder methods to `internalProto`\n-
`zod/v4/mini/schemas.cjs` / `schemas.js` — same for the mini
API\nsurface\n- `zod/v4/core/core.cjs` / `core.js` — wires `_.prototype
→\ninternalProto`, exposes `$internalProto` symbol; copy-loop left as
no-op\nfor library methods\n\nThe patch is managed by `patch-package`
and lives in\n`patches/zod+4.3.6.patch`. An upstream PR is being
prepared:\n[colinhacks/zod#5870](https://github.com/colinhacks/zod/pull/5870).\n\n###
Result\n\n| Metric | Before (Zod v4, unpatched) | After (shadow-proto
patch) |\n| ------------------------------- | --------------------------
|\n-------------------------- |\n| Own properties per instance | ~91 |
**~22** |\n| V8 property storage mode | Dictionary (slow) | **Fast**
|\n| Heap cost per `z.string()` | ~12.8 KB | **~2.5 KB** |\n| Shared
method references | ✗ (per-instance closures) |
**✓**\n(prototype-inherited)|\n| **Memory reduction** | — | **~80%**
|\n| `z.iso.datetime().optional()` | ✅ | ✅ |\n| Prototype augmentation |
✅ | ✅ |\n| All parse/validate/chain APIs | ✅ | ✅ |\n\n> Validated by
full Kibana heap snapshot comparison: ~113 MB reduction\nat
startup.\n\n### Patch persistence\n\nThe patch is applied automatically
during `yarn kbn bootstrap` (after\n`yarn install`) via `patch-package
--error-on-fail`. The `patches/`\ndirectory is committed and
version-controlled.\n\n**Removal criteria**: remove
`patches/zod+4.3.6.patch` (and the\n`patch-package` devDependency) once
the upstream Zod issue is resolved\nand Kibana upgrades to the patched
version.\n\n### New dependency: `patch-package`\n\n| | |\n|---|---|\n|
**Purpose** | Applies and maintains the shadow-proto patch
to\n`node_modules/zod` across `yarn install` runs. Invoked as
`patch-package\n--error-on-fail` in the bootstrap step. |\n|
**Justification** | The optimization requires modifying Zod's
compiled\nJavaScript internals (`$constructor` wiring, `_initProto`
helper,\nbuilder method placement). These changes cannot be applied at
the\nTypeScript/import level, so a post-install patch is the
correct\nmechanism. `patch-package` is the industry-standard tool for
this\npattern, with a simple invocation model and deterministic
patch\napplication. |\n| **Alternatives explored** | (1) **Custom
patching script** — Kibana\nused a bespoke
`src/dev/node_modules_patches/` mechanism in an earlier\niteration of
this PR; `patch-package` is strictly simpler and more\nmaintainable. (2)
**`@kbn/zod` wrapper** — the wrapper re-exports\n`zod/v4` but cannot
intercept the compiled `$constructor` and prototype\nwiring needed for
this optimization. (3) **Private Elastic\nfork/registry** — viable but
significantly heavier: requires maintaining\na fork, publishing to a
registry, and updating consumers;\ndisproportionate effort for a
temporary vendor patch. |\n| **Existing dependencies** | Kibana has no
existing dependency\nproviding `patch-package`-equivalent functionality.
`yarn patch` (a\nbuilt-in Yarn Berry feature) is not available since
Kibana uses Yarn\nClassic. |\n\n### Test plan\n\n- `npx patch-package
--error-on-fail` applies cleanly from scratch\n-
`z.iso.datetime().optional()` works\n- `z.string().email().optional()`,
`obj.pick()`, `enum.extract()` all\nwork\n- `z.httpUrl()` correctly
rejects `ftp://`, `file:///` URLs (only\n`http`/`https` accepted)\n-
Shared references confirmed: `z.string().optional
===\nz.string().optional` → `true`\n- Own-property count
confirmed:\n`Object.getOwnPropertyNames(z.string()).length` → `22`\n-
Memory benchmark: ~2.5 KB per `z.string()` (down from ~12.8 KB)\n- `node
scripts/check_changes.ts` passes\n- Heap snapshot comparison: ~113 MB
reduction at Kibana startup\n\n---------\n\nCo-authored-by:
kibanamachine
<42973632+kibanamachine@users.noreply.github.com>\nCo-authored-by:
macroscopeapp[bot]
<170038800+macroscopeapp[bot]@users.noreply.github.com>","sha":"ae70b77d9551d54563537c088b92f643f43e96fa"}},"sourceBranch":"main","suggestedTargetBranches":["9.4"],"targetPullRequestStates":[{"branch":"9.4","label":"v9.4.0","branchLabelMappingKey":"^v(\\d+).(\\d+).\\d+$","isSourceBranch":false,"state":"NOT_CREATED"},{"branch":"main","label":"v9.5.0","branchLabelMappingKey":"^v9.5.0$","isSourceBranch":true,"state":"MERGED","url":"https://github.com/elastic/kibana/pull/263121","number":263121,"mergeCommit":{"message":"fix(zod):
reduce per-schema heap cost via shared method references (#263121)\n\n##
Summary\n\nApplies a memory optimization patch to Zod v4 to address
significant\nheap cost regression introduced with the upgrade to Zod 4.x
(see\nupstream issue
[#5760](https://github.com/colinhacks/zod/issues/5760)).\n\n###
Problem\n\nZod v4 assigns every method (`parse`, `check`, `optional`,
`email`,\netc.) as an **own-property arrow function** on each schema
instance.\nBecause each arrow function closes over `inst`, each instance
allocates\n~91 unique function objects. V8 switches from fast-property
mode to slow\n\"dictionary mode\" when an object accumulates more than
~27 own\nproperties, causing an extra heap tax on top of the closure
overhead. In\npractice this costs **~12.8 KB of heap per schema** (vs
~1.5 KB with Zod\n3).\n\n### Fix — Shadow-Proto
Architecture\n\nIntroduces a hidden intermediate prototype layer
(`internalProto`)\nbetween `_.prototype` (the user-visible class
prototype) and the parent.\nLibrary methods are placed on
`internalProto` via `_initProto` (once per\nconcrete type, lazily), so
they become **inherited** rather than own\nproperties.\n\n```\ninstance
→ _.prototype (user space, empty by default)\n → internalProto (library
space: 69 shared methods)\n → Parent\n```\n\nKey properties:\n-
**Own-property count**: ~91 → **~22** (well below V8's
dictionary-mode\nthreshold of ~27)\n- **Shared methods**: all 69
builder/parse methods are\nprototype-inherited; instances share the same
function objects\n(`s1.optional === s2.optional`)\n-
**Backward-compatible**: user-added prototype extensions
on\n`_.prototype` still shadow `internalProto` transparently\n- **Covers
both variants**: classic and mini Zod APIs (6 files patched)\n\nSix Zod
files are patched (both CJS and ESM variants):\n\n-
`zod/v4/classic/schemas.cjs` / `schemas.js` — `_initProto` helper
+\nmoves all builder methods to `internalProto`\n-
`zod/v4/mini/schemas.cjs` / `schemas.js` — same for the mini
API\nsurface\n- `zod/v4/core/core.cjs` / `core.js` — wires `_.prototype
→\ninternalProto`, exposes `$internalProto` symbol; copy-loop left as
no-op\nfor library methods\n\nThe patch is managed by `patch-package`
and lives in\n`patches/zod+4.3.6.patch`. An upstream PR is being
prepared:\n[colinhacks/zod#5870](https://github.com/colinhacks/zod/pull/5870).\n\n###
Result\n\n| Metric | Before (Zod v4, unpatched) | After (shadow-proto
patch) |\n| ------------------------------- | --------------------------
|\n-------------------------- |\n| Own properties per instance | ~91 |
**~22** |\n| V8 property storage mode | Dictionary (slow) | **Fast**
|\n| Heap cost per `z.string()` | ~12.8 KB | **~2.5 KB** |\n| Shared
method references | ✗ (per-instance closures) |
**✓**\n(prototype-inherited)|\n| **Memory reduction** | — | **~80%**
|\n| `z.iso.datetime().optional()` | ✅ | ✅ |\n| Prototype augmentation |
✅ | ✅ |\n| All parse/validate/chain APIs | ✅ | ✅ |\n\n> Validated by
full Kibana heap snapshot comparison: ~113 MB reduction\nat
startup.\n\n### Patch persistence\n\nThe patch is applied automatically
during `yarn kbn bootstrap` (after\n`yarn install`) via `patch-package
--error-on-fail`. The `patches/`\ndirectory is committed and
version-controlled.\n\n**Removal criteria**: remove
`patches/zod+4.3.6.patch` (and the\n`patch-package` devDependency) once
the upstream Zod issue is resolved\nand Kibana upgrades to the patched
version.\n\n### New dependency: `patch-package`\n\n| | |\n|---|---|\n|
**Purpose** | Applies and maintains the shadow-proto patch
to\n`node_modules/zod` across `yarn install` runs. Invoked as
`patch-package\n--error-on-fail` in the bootstrap step. |\n|
**Justification** | The optimization requires modifying Zod's
compiled\nJavaScript internals (`$constructor` wiring, `_initProto`
helper,\nbuilder method placement). These changes cannot be applied at
the\nTypeScript/import level, so a post-install patch is the
correct\nmechanism. `patch-package` is the industry-standard tool for
this\npattern, with a simple invocation model and deterministic
patch\napplication. |\n| **Alternatives explored** | (1) **Custom
patching script** — Kibana\nused a bespoke
`src/dev/node_modules_patches/` mechanism in an earlier\niteration of
this PR; `patch-package` is strictly simpler and more\nmaintainable. (2)
**`@kbn/zod` wrapper** — the wrapper re-exports\n`zod/v4` but cannot
intercept the compiled `$constructor` and prototype\nwiring needed for
this optimization. (3) **Private Elastic\nfork/registry** — viable but
significantly heavier: requires maintaining\na fork, publishing to a
registry, and updating consumers;\ndisproportionate effort for a
temporary vendor patch. |\n| **Existing dependencies** | Kibana has no
existing dependency\nproviding `patch-package`-equivalent functionality.
`yarn patch` (a\nbuilt-in Yarn Berry feature) is not available since
Kibana uses Yarn\nClassic. |\n\n### Test plan\n\n- `npx patch-package
--error-on-fail` applies cleanly from scratch\n-
`z.iso.datetime().optional()` works\n- `z.string().email().optional()`,
`obj.pick()`, `enum.extract()` all\nwork\n- `z.httpUrl()` correctly
rejects `ftp://`, `file:///` URLs (only\n`http`/`https` accepted)\n-
Shared references confirmed: `z.string().optional
===\nz.string().optional` → `true`\n- Own-property count
confirmed:\n`Object.getOwnPropertyNames(z.string()).length` → `22`\n-
Memory benchmark: ~2.5 KB per `z.string()` (down from ~12.8 KB)\n- `node
scripts/check_changes.ts` passes\n- Heap snapshot comparison: ~113 MB
reduction at Kibana startup\n\n---------\n\nCo-authored-by:
kibanamachine
<42973632+kibanamachine@users.noreply.github.com>\nCo-authored-by:
macroscopeapp[bot]
<170038800+macroscopeapp[bot]@users.noreply.github.com>","sha":"ae70b77d9551d54563537c088b92f643f43e96fa"}}]}]
BACKPORT-->

Co-authored-by: Gerard Soldevila <gerard.soldevila@elastic.co>
Co-authored-by: macroscopeapp[bot] <170038800+macroscopeapp[bot]@users.noreply.github.com>
tiansivive pushed a commit to tiansivive/kibana that referenced this pull request Apr 23, 2026
…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>
SoniaSanzV pushed a commit to SoniaSanzV/kibana that referenced this pull request Apr 27, 2026
…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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants