Repository navigation
fix(gateway): defer ajv schema compilation to prevent stack overflow during channel plugin loading - #61323
fix(gateway): defer ajv schema compilation to prevent stack overflow during channel plugin loading#61323openperf wants to merge 1 commit into
Conversation
Greptile SummaryDefers all 104 Confidence Score: 5/5Safe to merge; fix is well-scoped, fully preserves the existing validator API surface, and is backed by new tests. All remaining findings are P2 style suggestions. The lazyCompile implementation is correct, validateSchema: false is appropriate for static schemas, $schema stripping is applied defensively at both generation time and runtime, and the emergency bypass is properly gated and logged. No files require special attention. Prompt To Fix All With AIThis is a comment left during a code review.
Path: src/gateway/protocol/index.ts
Line: 296-308
Comment:
**`lazyCompile` doesn't memoize failed compilations**
If `ajv.compile(schema)` throws, `cached` stays `undefined` and every subsequent call will retry compilation and re-throw rather than failing fast. Since all schemas here are static constants and `validateSchema: false` is set this is very low-risk in practice, but a failed compilation would produce repeated error spam instead of a single startup failure. Consider assigning `cached` before invoking it:
```suggestion
function lazyCompile<T = unknown>(schema: object): import("ajv").ValidateFunction<T> {
let cached: import("ajv").ValidateFunction<T> | undefined;
let compileError: unknown;
const proxy = function validate(data: unknown) {
if (!cached) {
if (compileError !== undefined) throw compileError;
try {
cached = ajv.compile<T>(schema);
} catch (err) {
compileError = err;
throw err;
}
}
const valid = cached(data);
proxy.errors = cached.errors;
return valid;
} as import("ajv").ValidateFunction<T>;
proxy.errors = null;
return proxy;
}
```
How can I resolve this? If you propose a fix, please make it concise.
---
This is a comment left during a code review.
Path: src/channels/plugins/bundled.ts
Line: 197-199
Comment:
**Consider a TODO comment tracking planned removal**
The `OPENCLAW_SKIP_CHANNEL_PLUGINS` bypass is described in the PR as a temporary workaround until the upstream jiti stack-depth issue is resolved. A brief inline comment linking to the tracking issue would make that intent discoverable without digging into PR history:
```suggestion
// TODO(#61259): remove once jiti loading depth is addressed upstream.
if (process.env.OPENCLAW_SKIP_CHANNEL_PLUGINS === "1") {
```
How can I resolve this? If you propose a fix, please make it concise.Reviews (1): Last reviewed commit: "fix(gateway): defer ajv schema compilati..." | Re-trigger Greptile |
e054e2f to
cc7461a
Compare
…during channel plugin loading Replace 104 eager ajv.compile() calls in gateway/protocol/index.ts with lazyCompile() wrappers that defer compilation to first invocation. This eliminates all schema compilation work from the module loading phase, preventing RangeError: Maximum call stack size exceeded when bundled channel plugins are loaded through jiti's recursive CJS↔ESM bridge. Supporting changes: - Add validateSchema: false to all ajv instances - Strip $schema from bundled channel config metadata - Add OPENCLAW_SKIP_CHANNEL_PLUGINS env var bypass Fixes openclaw#61259
cc7461a to
4d179ff
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 4d179ff509
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
…during channel plugin loading Cherry-pick of openclaw#61323. Resolves Telegram/channel init failures on 4.2 (issue openclaw#61273). Conflict resolved: HEAD still had ajv.compile on cron/skills/devicePair validators not yet converted; took PR's full lazyCompile conversion + new SkillsSearch/Detail/ExecApprovalGet validators.
|
Closing this as stale. The startup path this patches has already been reworked on |
|
Closing as stale: current |
Summary
Problem: All bundled channel plugins fail to load with
RangeError: Maximum call stack size exceededduring gateway startup. The crash occurs insrc/gateway/protocol/index.ts(lines 288–475), where 104ajv.compile()calls execute synchronously at module level. When channel extensions load through jiti's recursive CJS↔ESM bridge (dist-runtime/extensions/<channel>/index.js→dist/extensions/<channel>/index.js), the call stack is already deep; the eager compilation of every protocol schema exhausts it.Root Cause: Three factors compound to cause the overflow:
ajv.compile()calls at module top-level insrc/gateway/protocol/index.ts— each call recursively walks the schema tree, adding frames forschemaHasRulesForType,compileSchema, and keyword validators. Executed duringimport, they consume stack before any application code runs.channel extension → channel-core → extension-shared → runtime → command-secret-gateway → call → method-scopes) adds 2–3 stack frames (jitiRequire→eval_evalModule→ anonymous wrapper), consuming ~40–60 frames before reachinggateway/protocol.$schemameta-schema URIs in bundled channel config metadata — 22 entries insrc/config/bundled-channel-config-metadata.generated.tscarry$schema: "http://json-schema.org/draft-07/schema#", causing ajv to attempt compiling the self-referential JSON Schema meta-schema duringajv.compile( ), further deepening the stack.Fix: The primary fix replaces all 104 eager
ajv.compile()calls with alazyCompile()wrapper that defers actual compilation to first invocation. This eliminates all schema compilation work from the module loading phase, directly addressing the root cause. Supporting changes strip$schemafrom bundled metadata (both at generation time and runtime collection), addvalidateSchema: falseto all ajv instances to prevent meta-schema validation overhead, and provide anOPENCLAW_SKIP_CHANNEL_PLUGINSenvironment variable as an emergency bypass. The lazy approach was chosen over alternatives (e.g., increasing--stack-size, splitting the module) because it preserves the existing API surface — every exported validator remains a callableValidateFunction<T>with an.errorsproperty — while completely decoupling schema compilation from module initialization.What changed:
src/gateway/protocol/index.ts— replaced 104 eagerajv.compile()withlazyCompile()wrappers; addedvalidateSchema: falseto ajv constructorsrc/plugins/schema-validator.ts— addedvalidateSchema: falseto the shared ajv factorysrc/plugins/bundled-plugin-metadata.ts— addedstripSchemaProperty()helper; applied it incollectBundledChannelConfigs()to remove$schemafrom runtime schemasscripts/generate-bundled-channel-config-metadata.ts— addedstripSchemaProperty()helper; applied it during metadata generationsrc/config/bundled-channel-config-metadata.generated.ts— regenerated without$schemaproperties (22 removals)src/channels/plugins/bundled.ts— addedOPENCLAW_SKIP_CHANNEL_PLUGINS=1environment variable bypass inloadGeneratedBundledChannelEntries()src/gateway/protocol/index.test.ts— added 3 tests for lazy compile behavior (callable, errors property, caching)src/plugins/schema-validator.test.ts— added test for$schemapassthrough withvalidateSchema: falsesrc/plugins/bundled-plugin-metadata.test.ts— added test verifying$schemais stripped from collected channel config schemassrc/channels/plugins/bundled.shape-guard.test.ts— added test forOPENCLAW_SKIP_CHANNEL_PLUGINSbypassWhat did NOT change (scope boundary):
schema.tsremain identicallazyCompile()returnsValidateFunction<T>with the same.errorspropertydist-runtimeproxy layerbundled-channel-config-runtime.tsfallback path (static metadata) is unaffectedReproduction
pnpm install && pnpm buildpnpm start(or./start-openclaw.ps1)[openclaw] Failed to start CLI: RangeError: Maximum call stack size exceededschemaHasRulesForTypein ajv →method-scopes→jitiRequire→eval_evalModulechainRisk / Mitigation
Risk: Lazy compilation shifts schema errors from startup to first use, potentially delaying detection of invalid schemas.
Mitigation: All protocol schemas are static constants defined in
schema.tsand validated by existing test suites (index.test.ts,cron-validators.test.ts,talk-config.contract.test.ts). The new lazy compile tests verify that validators are callable, expose.errors, and cache correctly. Additionally,validateSchema: falseonly skips meta-schema validation — ajv still fully validates data against schemas at runtime.Risk:
OPENCLAW_SKIP_CHANNEL_PLUGINSbypass could mask real issues if left enabled.Mitigation: The bypass logs an explicit info message when active. It is documented as a temporary workaround in the Issue and should be removed once the underlying jiti loading depth is addressed upstream.
Change Type (select all)
Scope (select all touched areas)
Linked Issue/PR
Fixes #61259