-
Notifications
You must be signed in to change notification settings - Fork 8.6k
Oom/combined zod patch lazy loading #264342
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
Closed
sdesalas
wants to merge
6
commits into
elastic:main
from
sdesalas:oom/combined-zod-patch-lazy-loading
Closed
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
8bbe2f1
migrate from zod.merge to zod.extend
maximpn 72c664f
avoid exporting schemas
maximpn 2134993
load Zod schemas lazily
maximpn ec22beb
use WeakMap to make Zod schemas GCable
maximpn 0e71ca4
extract generic lazyGCableObject utility function
maximpn 817fcf4
use local patched Zod v4 version
maximpn File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
There are no files selected for viewing
Binary file not shown.
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
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,3 +1,51 @@ | ||
| # @kbn/lazy-object | ||
|
|
||
| Empty package generated by @kbn/generate | ||
| Utilities for deferring the construction of objects until they are first used, | ||
| so that modules that declare many objects at load-time don't pay the | ||
| construction cost (time and memory) for the ones that are never touched. | ||
|
|
||
| The package offers several variants that differ in granularity, caching, and | ||
| how they're authored: | ||
|
|
||
| ## `lazyObject(obj)` + Babel plugin | ||
|
|
||
| Author object literals normally; a Babel plugin rewrites `lazyObject({ ... })` | ||
| call sites into `createLazyObjectFromFactories({ key: () => expr, ... })` so | ||
| each property is built on first access and cached forever. At runtime without | ||
| the Babel plugin this is an identity function. | ||
|
|
||
| Use when: you want ergonomic lazy fields on an object without changing source | ||
| style. Requires the Babel plugin in the build. | ||
|
|
||
| ## `createLazyObjectFromFactories(factories)` | ||
|
|
||
| Runtime-only version of the above. Takes an object whose values are factory | ||
| functions and returns an object whose properties materialize on first read | ||
| (cached forever). No build-time support needed. | ||
|
|
||
| Use when: you want per-property laziness without the Babel plugin. | ||
|
|
||
| ## `createLazyObjectFromAnnotations(obj)` + `annotateLazy(fn)` | ||
|
|
||
| Like `createLazyObjectFromFactories`, but you mark individual factory values | ||
| with `annotateLazy(...)` so an object can mix eagerly-defined fields with | ||
| lazily-computed ones. | ||
|
|
||
| Use when: only some fields of an object benefit from laziness. | ||
|
|
||
| ## `lazyGCableObject(factory)` | ||
|
|
||
| Whole-object lazy with GC-reclaimable caching. Returns a Proxy that builds the | ||
| underlying object on first property access, caches it behind a `WeakRef`, and | ||
| lets the GC reclaim it once no consumer is holding a reference. The next access | ||
| rebuilds it. | ||
|
|
||
| Use when: you declare many similar objects at module-load time, expect only a | ||
| subset to be used, and want transiently-used ones to be collectible rather than | ||
| pinned for the process lifetime. | ||
|
|
||
| ## Metrics | ||
|
|
||
| `getLazyObjectMetrics()` returns a `{ count, called }` snapshot for the | ||
| annotation-based variants (how many lazy keys were registered vs. materialized), | ||
| useful when evaluating whether laziness is paying off in a given module graph. |
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
99 changes: 99 additions & 0 deletions
99
src/platform/packages/shared/kbn-lazy-object/src/lazy_gcable_object.test.ts
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,99 @@ | ||
| /* | ||
| * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one | ||
| * or more contributor license agreements. Licensed under the "Elastic License | ||
| * 2.0", the "GNU Affero General Public License v3.0 only", and the "Server Side | ||
| * Public License v 1"; you may not use this file except in compliance with, at | ||
| * your election, the "Elastic License 2.0", the "GNU Affero General Public | ||
| * License v3.0 only", or the "Server Side Public License, v 1". | ||
| */ | ||
|
|
||
| import { lazyGCableObject } from './lazy_gcable_object'; | ||
|
|
||
| describe('lazyGCableObject', () => { | ||
| it('defers factory invocation until first property access', () => { | ||
| const factory = jest.fn(() => ({ value: 1 })); | ||
| const obj = lazyGCableObject(factory); | ||
|
|
||
| expect(factory).not.toHaveBeenCalled(); | ||
|
|
||
| // Access a property to trigger materialization. | ||
| void obj.value; | ||
|
|
||
| expect(factory).toHaveBeenCalledTimes(1); | ||
| }); | ||
|
|
||
| it('caches the materialized object while it is still reachable', () => { | ||
| const factory = jest.fn(() => ({ value: 1 })); | ||
| const obj = lazyGCableObject(factory); | ||
|
|
||
| // A single retained reference pins the instance, so all reads reuse it. | ||
| expect(obj.value).toBe(1); | ||
| expect(obj.value).toBe(1); | ||
| expect(obj.value).toBe(1); | ||
|
|
||
| expect(factory).toHaveBeenCalledTimes(1); | ||
| }); | ||
|
|
||
| // The materialized object is held via `WeakRef`, so if the GC reclaims it | ||
| // between turns (under memory pressure), the next access rebuilds it from | ||
| // the factory. We verify the rebuild path by simulating cache eviction — | ||
| // V8's heuristics are not deterministic enough to assert collection itself. | ||
| it('rebuilds the object after the WeakRef is cleared', () => { | ||
| const factory = jest.fn(() => ({ value: 1 })); | ||
| const RealWeakRef = globalThis.WeakRef; | ||
|
|
||
| let onlyRef: WeakRef<object> | undefined; | ||
|
|
||
| class EvictableWeakRef<T extends object> { | ||
| private target: T | undefined; | ||
| constructor(target: T) { | ||
| this.target = target; | ||
| onlyRef = this as unknown as WeakRef<object>; | ||
| } | ||
| deref(): T | undefined { | ||
| return this.target; | ||
| } | ||
| evict(): void { | ||
| this.target = undefined; | ||
| } | ||
| } | ||
| (globalThis as { WeakRef: unknown }).WeakRef = EvictableWeakRef; | ||
|
|
||
| try { | ||
| const obj = lazyGCableObject(factory); | ||
|
|
||
| void obj.value; | ||
| expect(factory).toHaveBeenCalledTimes(1); | ||
|
|
||
| // Simulate the GC reclaiming the object. | ||
| (onlyRef as unknown as EvictableWeakRef<object>).evict(); | ||
|
|
||
| void obj.value; | ||
| expect(factory).toHaveBeenCalledTimes(2); | ||
| } finally { | ||
| (globalThis as { WeakRef: unknown }).WeakRef = RealWeakRef; | ||
| } | ||
| }); | ||
|
|
||
| it('binds function-valued properties to the materialized object', () => { | ||
| const obj = lazyGCableObject(() => ({ | ||
| value: 42, | ||
| getValue() { | ||
| return this.value; | ||
| }, | ||
| })); | ||
|
|
||
| // Destructuring loses the original `this`; the Proxy must bind the method | ||
| // to the materialized target so the call still resolves correctly. | ||
| const { getValue } = obj; | ||
| expect(getValue()).toBe(42); | ||
| expect(obj.getValue()).toBe(42); | ||
| }); | ||
|
|
||
| it('supports the `in` operator via the has trap', () => { | ||
| const obj = lazyGCableObject(() => ({ a: 1, b: 2 })); | ||
|
|
||
| expect('a' in obj).toBe(true); | ||
| expect('missing' in obj).toBe(false); | ||
| }); | ||
| }); |
57 changes: 57 additions & 0 deletions
57
src/platform/packages/shared/kbn-lazy-object/src/lazy_gcable_object.ts
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,57 @@ | ||
| /* | ||
| * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one | ||
| * or more contributor license agreements. Licensed under the "Elastic License | ||
| * 2.0", the "GNU Affero General Public License v3.0 only", and the "Server Side | ||
| * Public License v 1"; you may not use this file except in compliance with, at | ||
| * your election, the "Elastic License 2.0", the "GNU Affero General Public | ||
| * License v3.0 only", or the "Server Side Public License, v 1". | ||
| */ | ||
|
|
||
| /** | ||
| * Wraps an object factory in a Proxy that defers construction of the underlying | ||
| * object until any property is first accessed. The materialized object is cached | ||
| * behind a `WeakRef`, so once no external consumer keeps it alive the GC is free | ||
| * to reclaim it; the next access rebuilds it from the factory. Function-valued | ||
| * properties are bound to the materialized object so methods observe a stable | ||
| * `this`. | ||
| * | ||
| * Intended for cases where many objects are declared at module-load time but | ||
| * only a subset is used at runtime. Unused entries stay as a single Proxy | ||
| * instance plus a closure, keeping baseline heap low; transiently-used entries | ||
| * are collectible after their last reference is dropped. | ||
| * | ||
| * Trade-off: if the same object is used repeatedly across GC cycles without | ||
| * callers retaining a reference, each cycle pays the cost of rebuilding it. | ||
| * Hold on to a reference (e.g. `const o = LazyThing; o.method(...)` inside a | ||
| * hot path) if that matters. | ||
| * | ||
| * Caveat: `instanceof` checks on the returned value will be `false` because the | ||
| * Proxy target is an empty object. Structural checks on properties of the | ||
| * materialized object work as expected. | ||
| */ | ||
| export function lazyGCableObject<T extends object>(factory: () => T): T { | ||
| let ref: WeakRef<T> | undefined; | ||
| const materialize = (): T => { | ||
| const cached = ref?.deref(); | ||
| if (cached) { | ||
| return cached; | ||
| } | ||
| const fresh = factory(); | ||
| ref = new WeakRef(fresh); | ||
| return fresh; | ||
| }; | ||
|
|
||
| return new Proxy({} as T, { | ||
| get(_target, prop) { | ||
| const real = materialize() as unknown as Record<PropertyKey, unknown>; | ||
| const value = real[prop]; | ||
| if (typeof value === 'function') { | ||
| return (value as (...args: unknown[]) => unknown).bind(real); | ||
| } | ||
| return value; | ||
| }, | ||
| has(_target, prop) { | ||
| return prop in (materialize() as unknown as object); | ||
| }, | ||
| }); | ||
| } | ||
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
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
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
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -9,3 +9,4 @@ | |
|
|
||
| export * from 'zod/v4'; | ||
| export { isZod } from './util'; | ||
| export { lazySchema } from './lazy_schema'; | ||
Oops, something went wrong.
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🟢 Low
src/lazy_gcable_object.ts:44The
Proxylacks asettrap, so assignments likelazyThing.prop = valuewrite to the empty{}target rather than the materialized object. The value is stored on the proxy target but never propagated to the real object; subsequent reads return the unmodified value from the materialized object, causing the assignment to be silently lost.🤖 Copy this AI Prompt to have your agent fix this: