Skip to content

fix(gateway): defer ajv schema compilation to prevent stack overflow during channel plugin loading - #61323

Closed
openperf wants to merge 1 commit into
openclaw:mainfrom
openperf:fix/channel-plugin-stack-overflow
Closed

openperf wants to merge 1 commit into
openclaw:mainfrom
openperf:fix/channel-plugin-stack-overflow

Conversation

@openperf

@openperf openperf commented Apr 5, 2026

Copy link
Copy Markdown
Member

Summary

  • Problem: All bundled channel plugins fail to load with RangeError: Maximum call stack size exceeded during gateway startup. The crash occurs in src/gateway/protocol/index.ts (lines 288–475), where 104 ajv.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:

    1. 104 eager ajv.compile() calls at module top-level in src/gateway/protocol/index.ts — each call recursively walks the schema tree, adding frames for schemaHasRulesForType, compileSchema, and keyword validators. Executed during import, they consume stack before any application code runs.
    2. jiti's recursive CJS↔ESM bridge — each module in the channel extension dependency chain (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 reaching gateway/protocol.
    3. $schema meta-schema URIs in bundled channel config metadata — 22 entries in src/config/bundled-channel-config-metadata.generated.ts carry $schema: "http://json-schema.org/draft-07/schema#", causing ajv to attempt compiling the self-referential JSON Schema meta-schema during ajv.compile( ), further deepening the stack.
  • Fix: The primary fix replaces all 104 eager ajv.compile() calls with a lazyCompile() 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 $schema from bundled metadata (both at generation time and runtime collection), add validateSchema: false to all ajv instances to prevent meta-schema validation overhead, and provide an OPENCLAW_SKIP_CHANNEL_PLUGINS environment 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 callable ValidateFunction<T> with an .errors property — while completely decoupling schema compilation from module initialization.

  • What changed:

    • src/gateway/protocol/index.ts — replaced 104 eager ajv.compile() with lazyCompile() wrappers; added validateSchema: false to ajv constructor
    • src/plugins/schema-validator.ts — added validateSchema: false to the shared ajv factory
    • src/plugins/bundled-plugin-metadata.ts — added stripSchemaProperty() helper; applied it in collectBundledChannelConfigs() to remove $schema from runtime schemas
    • scripts/generate-bundled-channel-config-metadata.ts — added stripSchemaProperty() helper; applied it during metadata generation
    • src/config/bundled-channel-config-metadata.generated.ts — regenerated without $schema properties (22 removals)
    • src/channels/plugins/bundled.ts — added OPENCLAW_SKIP_CHANNEL_PLUGINS=1 environment variable bypass in loadGeneratedBundledChannelEntries()
    • 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 $schema passthrough with validateSchema: false
    • src/plugins/bundled-plugin-metadata.test.ts — added test verifying $schema is stripped from collected channel config schemas
    • src/channels/plugins/bundled.shape-guard.test.ts — added test for OPENCLAW_SKIP_CHANNEL_PLUGINS bypass
  • What did NOT change (scope boundary):

    • No schema definitions were modified — all JSON Schemas in schema.ts remain identical
    • No validator signatures or return types changed — lazyCompile() returns ValidateFunction<T> with the same .errors property
    • No changes to jiti configuration, module resolution, or the dist-runtime proxy layer
    • No changes to channel plugin registration, lifecycle, or runtime behavior
    • No changes to any non-bundled plugin loading paths
    • The bundled-channel-config-runtime.ts fallback path (static metadata) is unaffected

Reproduction

  1. Clone the repository on Windows 11 with Node.js v22.18.0
  2. Run pnpm install && pnpm build
  3. Start the gateway: pnpm start (or ./start-openclaw.ps1)
  4. Observe crash: [openclaw] Failed to start CLI: RangeError: Maximum call stack size exceeded
  5. Stack trace shows schemaHasRulesForType in ajv → method-scopes → jitiRequire → eval_evalModule chain

Risk / 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.ts and 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: false only skips meta-schema validation — ajv still fully validates data against schemas at runtime.

  • Risk: OPENCLAW_SKIP_CHANNEL_PLUGINS bypass 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)

  • Bug fix

Scope (select all touched areas)

  • Gateway
  • Plugins
  • Channels
  • Config
  • Scripts

Linked Issue/PR

Fixes #61259

@openclaw-barnacle openclaw-barnacle Bot added app: web-ui App: web-ui gateway Gateway runtime scripts Repository scripts size: M labels Apr 5, 2026
@greptile-apps

greptile-apps Bot commented Apr 5, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

Defers all 104 ajv.compile() calls in src/gateway/protocol/index.ts from module-load time to first use via a new lazyCompile() wrapper, fixing the RangeError: Maximum call stack size exceeded crash that occurs when bundled channel plugins load through jiti's deep CJS↔ESM bridge on Windows / low-stack-limit environments. Supporting changes add validateSchema: false to ajv instances and strip $schema meta-schema URIs from both generated and runtime channel config schemas to further reduce recursive stack depth, plus an OPENCLAW_SKIP_CHANNEL_PLUGINS emergency bypass with appropriate logging.

Confidence Score: 5/5

Safe 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 AI
This 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

Comment thread src/gateway/protocol/index.ts Resolved
Comment thread src/channels/plugins/bundled.ts Resolved
…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
@openperf
openperf force-pushed the fix/channel-plugin-stack-overflow branch from cc7461a to 4d179ff Compare April 5, 2026 14:12

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 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".

Comment thread src/plugins/schema-validator.ts Resolved
amittell pushed a commit to amittell/openclaw that referenced this pull request Apr 5, 2026
…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.
@obviyus

obviyus commented Apr 6, 2026

Copy link
Copy Markdown
Collaborator

Closing this as stale. The startup path this patches has already been reworked on main: bundled channel discovery now loads lightweight entry contracts and defers full channel/runtime imports, so this no longer looks like the right fix for current HEAD. If there is still a repro on latest main, please open a fresh issue/PR with that current stack trace.

@obviyus

obviyus commented Apr 6, 2026

Copy link
Copy Markdown
Collaborator

Closing as stale: current main already reworked bundled channel startup to avoid this import-time path. If this still reproduces on latest main, please open a fresh issue/PR with the new stack trace.

@obviyus obviyus closed this Apr 6, 2026
@samzong samzong mentioned this pull request May 15, 2026
3 of 8 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

app: web-ui App: web-ui gateway Gateway runtime scripts Repository scripts size: M

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Bundled channel plugins cause stack overflow via jiti module loading

2 participants