Skip to content

fix(channels): yield between channels loading legacy-state-migration detectors - #340

Merged
convyusboy merged 5 commits into
boonfrom
ridho/eng-23040-detector-load-yield
Nov 20, 2026
Merged

convyusboy merged 5 commits into
boonfrom
ridho/eng-23040-detector-load-yield

Conversation

@convyusboy

@convyusboy convyusboy commented Nov 20, 2026 •

Copy link
Copy Markdown
Collaborator

Related: ENG-23040 (Linear), follow-up to #337/#338 (merged into 2026.7.35-boon.2, re-canaried, still crashed identically).

What Problem This Solves

Fixes a gateway crash-loop on a host with on-disk legacy Telegram migration state. 2026.7.35-boon.2 (the fix in #337) was re-canaried on arief-openclaw-test and crash-looped with the exact same error, proving #337's fix — while a real, legitimate dead-code removal — was not the actual root cause.

Why This Change Was Made

listBundledChannelLegacyStateMigrationDetectors() required all five legacyStateMigrations-declaring channels' sidecar modules back-to-back in one synchronous require(esm) burst, zero turns of the event loop between them. telegram's and imessage's legacy-state-migrations-api.js chunks share several leaf dependency chunks (string-normalization/regular-file/security-runtime/string-coerce-runtime helpers). Requiring them back-to-back can hit Node's require(esm) bridge while one of those shared chunks' ESM module job hasn't settled yet, throwing Error [ERR_INTERNAL_ASSERTION]: Unexpected module status 0 — the exact error and stack shape of a confirmed, currently open upstream bug: nodejs/node#62130.

Node's own error message suggests the fix directly: "Try await-ing the import() sequentially in a loop instead." This PR changes the loader from a synchronous flatMap to an async for loop that yields a full event-loop turn (setImmediate, not just a microtask) after each channel's synchronous require, giving the previous channel's ESM module job time to settle before the next channel's require starts. The only production caller (collectChannelLegacyStateMigrationPlans) is already async, so this is a non-breaking signature change there.

Important caveat: even with OPENCLAW_DEBUG=1 and NODE_OPTIONS=--stack-trace-limit=100 captured on a real re-crash, Node's own stack trace elides the application call site for this specific internal assertion — it jumps straight from require(esm) internals to the async CLI-bootstrap chain. So the exact colliding channel pair is inferred from shared-chunk analysis (confirmed via the real published tarball), not directly observed in a stack frame. A local repro with a minimal config did not reproduce the crash at all, so this fix could not be verified pre-deployment beyond matching the upstream bug's own documented mitigation shape — the real test is the next canary re-run.

discord/feishu/whatsapp don't share leaf chunks with telegram/imessage per the same analysis, but the yield is applied uniformly across all five channels in the loop since the cost is negligible (a handful of setImmediate ticks, once per CLI invocation) and it's safer than guessing which specific pair needs it.

Follow-up, not in this PR: listBundledChannelLegacySessionSurfaces() (src/channels/plugins/bundled.ts:872) has the identical shape (synchronous flatMap over channel sidecars) and may be vulnerable to the same Node bug class. Not touched here since no crash has been observed on that path and its callers aren't all confirmed async — flagging for a follow-up look, not fixing speculatively.

User Impact

No behavior change beyond fixing the crash — same detection results, just loaded with a small bounded delay between channels at CLI/doctor startup (sub-millisecond scale, once per invocation).

Evidence

  • node scripts/run-vitest.mjs src/infra/state-migrations.test.ts src/commands/doctor-state-migrations.test.ts src/channels/plugins/bundled.shape-guard.test.ts — 150 tests pass (on Node 24.22.1; the repo's local Node 24.13.1 hits an unrelated pre-existing SQLite WAL-safety gate on these same tests, confirmed unrelated to this diff).
  • node scripts/run-tsgo.mjs -p tsconfig.core.json and -p test/tsconfig/tsconfig.core.test.json — clean.
  • node --import tsx scripts/check-import-cycles.ts — 0 cycles.
  • node scripts/tsdown-build.mjs — clean build, no [INEFFECTIVE_DYNAMIC_IMPORT].
  • node scripts/run-oxlint.mjs on all five touched files — clean.
  • Root cause confirmed via the actual published v2026.7.35-boon.2 tarball: legacy-state-migrations-api.js is genuinely only referenced by setup-entry.js (so fix(telegram,whatsapp): drop dead legacy-state-migration lifecycle wiring causing a gateway crash-loop #337's fix landed correctly), and grep across dist/extensions/{telegram,imessage} shows both channels' detector chunks statically import the same string-normalization-*/regular-file-*/security-runtime-*/string-coerce-runtime-* leaf chunks.

🤖 Generated with Claude Code


Summary by cubic

Fixes the gateway crash-loop (ENG-23040) on hosts with on-disk legacy Telegram migration state, where Node's require(esm) bridge threw ERR_INTERNAL_ASSERTION: Unexpected module status 0 (open upstream as nodejs/node#62130) because listBundledChannelLegacyStateMigrationDetectors() loaded all five channels' sidecar modules in one synchronous burst. The loader is now async: it yields a setImmediate between channels, and when a load hits that specific assertion it retries up to 3 times before throwing — the retry covers the case where a single yield isn't enough to settle a shared leaf chunk. The same race is no longer cached as a permanent null anywhere it can be hit: setup-entry, setup plugin, and setup secrets loads now propagate or locally skip it (falling back to an empty result) so a later retrying call can still recover. Non-retrying call sites behave unchanged. Each retry is logged with the channel id and attempt number so a canary rerun can confirm whether the mitigation fires. Its only production caller is already async; three test files were updated to await it, and a regression test asserts the between-channel yield is actually scheduled.

Rollout caveats

  • The colliding channel pair (telegram/imessage share leaf chunks) is inferred from shared-chunk analysis, since Node elides the application call site even at --stack-trace-limit=100; the crash couldn't be reproduced locally, so the next canary re-run is the real verification.
  • Detection results are unchanged — channels just load with a sub-millisecond bounded delay, once per CLI invocation.
  • listBundledChannelLegacySessionSurfaces() shares the loader shape and may be vulnerable too, but is left untouched since no crash has been observed there.

Written for commit ed642bd. Summary will update on new commits.

View guided diff Turn on auto-fix

…detectors

listBundledChannelLegacyStateMigrationDetectors() required all five
legacyStateMigrations-declaring channels' sidecar modules back-to-back
in one synchronous require(esm) burst with zero turns of the event
loop between them. telegram's and imessage's legacy-state-migrations-api.js
chunks share several leaf dependency chunks (string-normalization,
regular-file, security-runtime, string-coerce-runtime helpers), and
requiring them back-to-back can hit Node's require(esm) bridge while
one of those shared chunks' ESM module job hasn't settled yet, throwing
Error [ERR_INTERNAL_ASSERTION]: Unexpected module status 0 -- this is
ENG-23040's gateway crash-loop on hosts with on-disk legacy Telegram
migration state. The exact same error/stack shape is a confirmed,
currently open upstream bug: nodejs/node#62130.

Node's own error message suggests the fix: "await-ing the import()
sequentially in a loop instead." This changes the loader from a
synchronous flatMap to an async for-loop that yields a full event-loop
turn (setImmediate, not just a microtask) after each channel's
synchronous require, giving the previous channel's ESM module job time
to fully settle before the next channel's require starts. The only
production caller (collectChannelLegacyStateMigrationPlans in
src/infra/state-migrations.ts) is already async, so this is a
non-breaking signature change there; three test files mocking or
calling the function directly are updated to await it.

Root-caused in a prior PR attempt (#337) that removed a real but
unrelated duplicate wiring; this is the actual mechanism. Captured via
OPENCLAW_DEBUG=1 + NODE_OPTIONS=--stack-trace-limit=100 on a real
canary host re-crash -- Node's own stack trace elides the application
call site for this specific internal assertion even at that limit, so
the exact colliding channel pair is inferred from shared-chunk analysis,
not directly observed in a stack frame. A local repro with a minimal
config did not reproduce the crash, so this fix could not be verified
pre-deployment beyond matching the documented Node bug's own suggested
mitigation; the real test is the next canary re-run.

Validation: node scripts/run-vitest.mjs on the three affected test
files (150 tests) passes on Node 24.22.1. tsgo core + core-test lanes
clean. node scripts/check-import-cycles.ts: 0 cycles. node
scripts/tsdown-build.mjs: clean, no INEFFECTIVE_DYNAMIC_IMPORT.

Co-Authored-By: Claude Sonnet 5 <[email protected]>

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

cubic analysis

2 issues found across 5 files

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="src/channels/plugins/bundled.ts">

<violation number="1" location="src/channels/plugins/bundled.ts:915">
P3: This 6-line comment embeds incident narrative and an upstream issue link, and states the unverified mechanism as fact ("fully settles first"). Replace it with 1-3 lines that state the invariant and failure mode. The await also runs after the last channel, not only between channels.

(Based on your team's feedback about keeping changed source comments focused and ticket-free.)</violation>

<violation number="2" location="src/channels/plugins/bundled.ts:921">
P1: According to linked Linear issue ENG-23040, the crash comes from a concurrent dynamic import() racing the sync require. A single setImmediate is a one-turn timing heuristic, not a barrier, so it cannot guarantee that a pending import has finished. If that import needs more than one loop turn, the crash-loop recurs. The ticket's suggested fix is sequential await import() or routing the sync path through the same loader.</violation>
</file>

Linked issue analysis

Linked issue: ENG-23040: 2026.7.35-boon.1 gateway crash-loops on boot: ESM require/import race in channel-entry-contract legacy-state-migrations loader

Status Acceptance criteria Notes
⚠️ Prevent startup crashes during legacy-state detector loading The loader yields between channel sidecar requires, but the PR could not reproduce the crash to verify the fix.

Heads up: you’re close to your included review allowance. Set a flex budget so reviews don’t pause.

View guided diff | Turn on auto-fix | Re-trigger cubic

Comment thread src/channels/plugins/bundled.ts Resolved
Comment thread src/channels/plugins/bundled.ts Resolved
Comment thread src/channels/plugins/bundled.ts Resolved
…test

Addresses cubic review on #340:

- A single setImmediate is a timing heuristic, not a barrier -- if the
  colliding module needs more than one event-loop turn to settle, the
  crash-loop could still recur. Each channel's detector load is now
  wrapped in a bounded retry (3 attempts) that catches specifically
  ERR_INTERNAL_ASSERTION "Unexpected module status" errors and yields
  another turn before retrying, instead of relying solely on the
  preventive between-channel yield. Any other error still throws
  immediately, unchanged.
- Added a regression test using a synthetic two-channel fixture (the
  established pattern in this file) that asserts setImmediate is
  called exactly once for two channels, guarding against a future
  refactor silently reverting to the tight synchronous loop.
- Trimmed the inline comment to 1-3 lines per house style and fixed
  its inaccuracy: the yield now only runs between channels, not after
  the last one.

Co-Authored-By: Claude Sonnet 5 <[email protected]>

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

1 issue found across 2 files (changes from recent commits).

Reply with feedback, questions, or to request a fix.

View guided diff | Turn on auto-fix | Re-trigger cubic

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="src/channels/plugins/bundled.ts">

<violation number="1" location="src/channels/plugins/bundled.ts:946">
P2: Retries on `ERR_INTERNAL_ASSERTION` happen silently. Log each retry with the channel id and attempt number so the canary rerun can show whether the mitigation fires.</violation>
</file>

Comment thread src/channels/plugins/bundled.ts Resolved
Logs channel id and attempt number on each retry so a canary rerun can
show whether the mitigation actually fires.

Co-Authored-By: Claude Sonnet 5 <[email protected]>

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All reported issues were addressed across 1 file (changes from recent commits).

Reply with feedback, questions, or to request a fix.

View guided diff | Turn on auto-fix | Re-trigger cubic

Comment thread src/channels/plugins/bundled.ts Resolved
The setup-entry module's own require() can hit the same
ERR_INTERNAL_ASSERTION race as the legacy-state-migrations-api.js
sidecar, but loadGeneratedBundledChannelSetupEntry swallowed it
unconditionally and cached a permanent null, so the retry loop never
saw it. Let the race propagate from the loader instead of caching it,
and add a local fallback at the three non-retrying call sites so their
behavior is unchanged while the retrying caller can still recover.

Co-Authored-By: Claude Sonnet 5 <[email protected]>

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All reported issues were addressed across 1 file (changes from recent commits).

Reply with feedback, questions, or to request a fix.

View guided diff | Turn on auto-fix | Re-trigger cubic

Comment thread src/channels/plugins/bundled.ts Resolved
…setup plugin/secrets loads

loadSetupPlugin and loadSetupSecrets do the same sync ESM require that
can hit the ERR_INTERNAL_ASSERTION race, but their catch blocks cached
any failure (including this transient one) as a permanent null for
the process lifetime. Skip the cache write specifically for the
unsettled-ESM case so a later call gets a real chance to load it once
the race has passed, matching the invariant the previous commit
already claimed.

Co-Authored-By: Claude Sonnet 5 <[email protected]>

@boon-hermes-bot boon-hermes-bot Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM. The yield between channel sidecar requires combined with bounded retries on ERR_INTERNAL_ASSERTION (Unexpected module status) cleanly mitigates the Node require(esm) race without polluting module caches with permanent nulls. All CI checks pass and regression test guards against refactor regressions.

@convyusboy
convyusboy merged commit ab1a4eb into boon Nov 20, 2026
154 of 155 checks passed
@convyusboy
convyusboy deleted the ridho/eng-23040-detector-load-yield branch November 20, 2026 06:07
convyusboy added a commit that referenced this pull request Nov 20, 2026
Cuts the fork release carrying #339 (ENG-23048) and #340 (ENG-23040),
both merged to boon after the v2026.7.35-boon.2 tag. #340's fix is
untested against the real canary race that boon.2 failed on, so this
bump is what makes that fix installable for the re-canary attempt.

Version-only bump, same pattern as prior boon.N trains: upstream base
stays 2026.7.35; fork increment moves boon.2 -> boon.3. Bumps root
package.json/npm-shrinkwrap.json, all 142 bundled plugin manifests
(pnpm plugins:sync), and regenerates every extension's
npm-shrinkwrap.json (node scripts/generate-npm-shrinkwrap.mjs --all).
Adds the 2026.7.35-boon.3 CHANGELOG.md section.

Co-authored-by: Claude Sonnet 5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant