Skip to content

fix(telegram,whatsapp): drop dead legacy-state-migration lifecycle wiring causing a gateway crash-loop - #337

Merged
convyusboy merged 1 commit into
boonfrom
ridho/eng-23040-telegram-whatsapp-legacy-migration-race
Nov 19, 2026
Merged

convyusboy merged 1 commit into
boonfrom
ridho/eng-23040-telegram-whatsapp-legacy-migration-race

Conversation

@convyusboy

@convyusboy convyusboy commented Nov 19, 2026 •

Copy link
Copy Markdown
Collaborator

Related: ENG-23040 (Linear) — https://linear.app/getboon/issue/ENG-23040/2026735-boon1-gateway-crash-loops-on-boot-esm-requireimport-race-in

What Problem This Solves

Fixes an issue where the gateway would crash-loop on every boot on a host with on-disk legacy Telegram state (bot-info/update-offset/thread-bindings/allowFrom files), on any build with this change missing. Caught during the 2026.7.35-boon.1 canary rollout on arief-openclaw-test: the gateway never bound its port and restarted ~16 times in ~10 minutes before the canary host was rolled back.

Why This Change Was Made

extensions/telegram/src/channel.ts and channel.setup.ts (and the same for whatsapp) statically imported detect*LegacyStateMigrations from ./state-migrations.js and wired it into ChannelPlugin.lifecycle.detectLegacyStateMigrations. This duplicated what the SDK's dedicated legacyStateMigrations setup-entry feature already exposes through a synchronous require() of legacy-state-migrations-api.js. src/channels/plugins/bundled.ts's listBundledChannelLegacyStateMigrationDetectors() always prefers the dedicated detector when it's declared — true for both channels — so the lifecycle wiring was unreachable dead code at runtime.

That static import nonetheless pulled state-migrations.js into channel.ts's module graph, which channel.ts's own createLazyRuntimeModule(() => import(...)) lazy chunks transitively reach. That made the same built ESM module simultaneously reachable via a synchronous require() (through legacy-state-migrations-api.js, the SDK's sync-require entry) and a dynamic import() (through a lazy runtime chunk) — the exact "mixed static/dynamic import of the same runtime surface" race src/plugin-sdk/CLAUDE.md forbids. Node's own crash message named it: Unexpected module status 0. Cannot require() ES Module .../legacy-state-migrations-api.js because it is not yet fully loaded. ... simultaneously dynamically import()-ed via Promise.all().

The fix is a pure deletion of the dead wiring + its now-unused import, in both channel.ts and channel.setup.ts for telegram and whatsapp. No SDK/contract change. discord/feishu/imessage were audited (grepped for a second static importer of their own migration sidecar module) and don't share this pattern, so they needed no change.

User Impact

Operators rolling a future 2026.7.35-boon.N (or any build containing this code) will no longer hit a gateway crash-loop on hosts carrying legacy Telegram migration state. No other behavior changes — the removed code path was never actually reachable.

Evidence

  • Root cause and fix verified via direct source/dist inspection in this session (see ENG-23040 for the full investigation trail from the canary crash).
  • node scripts/tsdown-build.mjs build succeeds; post-fix, grep -rl "legacy-state-migrations-api" dist/extensions/telegram/ returns only setup-entry.js (previously reachable from the plugin's main entry chunk too).
  • node scripts/run-vitest.mjs on the affected suites:
    • telegram: channel.gateway.test.ts, channel-actions.contract.test.ts, channel-actions.test.ts, channel.message-adapter.test.ts, channel.resolve-targets.test.ts, state-migrations.test.ts — 55/56 passed (the 1 failure is a pre-existing local Node 24.13.1-vs-required-24.15.0+ SQLite WAL-safety check, unrelated to this change — the failure trace never touches the edited files).
    • whatsapp: setup-entry.test.ts, channel.setup.test.ts, channel-actions.test.ts, channel-outbound.test.ts, channel-react-action.test.ts, channel.acp-bindings.test.ts — 63/63 passed.
  • node --import tsx scripts/check-import-cycles.ts — 0 runtime value cycles.
  • Confirmed no existing test asserts on the removed ChannelPlugin.lifecycle.detectLegacyStateMigrations field (grep across src/ shows src/channels/plugins/bundled.ts's fallback branch as the only reader, and it's unreachable for these two channels since the dedicated detector is always truthy).

🤖 Generated with Claude Code


Summary by cubic

Fixes a gateway crash-loop on boot for hosts with legacy Telegram/WhatsApp state on disk, resolving ENG-23040.

The lifecycle.detectLegacyStateMigrations wiring in the telegram and whatsapp channel.ts/channel.setup.ts files was unreachable dead code — the SDK's dedicated legacyStateMigrations setup-entry feature is always preferred. But the static imports it created pulled state-migrations.js into the channel's module graph, making the same ESM module reachable via both a synchronous require() and a dynamic import(). That race crashed the gateway on every boot with Unexpected module status 0, caught during the 2026.7.35-boon.1 canary rollout.

This change removes the dead wiring and its now-unused imports from all four files. No behavior changes, since the removed path was never actually reachable. discord, feishu, and imessage were audited and don't share this pattern, so no changes needed there.

Written for commit 51f427f. Summary will update on new commits.

View guided diff Turn on auto-fix

…ring causing a gateway crash-loop

channel.ts/channel.setup.ts statically imported detect*LegacyStateMigrations
from state-migrations.js and wired it into ChannelPlugin.lifecycle, duplicating
what the SDK's dedicated legacyStateMigrations setup-entry feature already
provides via a synchronous require(). src/channels/plugins/bundled.ts's
listBundledChannelLegacyStateMigrationDetectors() always takes the dedicated
detector path when it's declared (confirmed: it is, for both channels), making
the lifecycle wiring unreachable dead code.

That static import nonetheless pulled state-migrations.js into channel.ts's
module graph, which channel.ts's own createLazyRuntimeModule(() => import(...))
lazy chunks can transitively reach -- making the same ESM module simultaneously
reachable via a synchronous require() (through legacy-state-migrations-api.js)
and a dynamic import() (through a lazy runtime chunk). That race crashed the
gateway on every boot on a host with on-disk legacy telegram state
("Unexpected module status 0. Cannot require() ES Module
.../legacy-state-migrations-api.js because it is not yet fully loaded."),
caught during the 2026.7.35-boon.1 canary rollout (ENG-23040).

Removing the dead wiring breaks the shared-chunk edge. Post-fix dist build
confirms legacy-state-migrations-api.js is referenced only by its own
setup-entry.js. discord/feishu/imessage were audited and don't share this
pattern (no second static importer of their migration sidecar), so no change
needed there.

Closes ENG-23040.

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

All reported issues were addressed across 4 files

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
✅ Remove the competing migration-module import path The Telegram and WhatsApp plugin files no longer import or wire migration detectors, leaving detection to the dedicated setup-entry path.

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 extensions/telegram/src/channel.ts Resolved

@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. Verified:

  • Root cause: Static import of state-migrations.js in channel.ts and channel.setup.ts brought state-migrations into channel lazy runtime chunks, causing an ESM require() vs dynamic import() race on startup when legacy migration state existed on disk.
  • Best fix: The lifecycle.detectLegacyStateMigrations wiring was redundant dead code because listBundledChannelLegacyStateMigrationDetectors() always prefers setupEntry.loadLegacyStateMigrationDetector() when present. Removing the dead wiring and static imports cleanly eliminates the shared-chunk race without changing contracts or runtime behavior.
  • Siblings: Checked discord, feishu, and imessage; none have competing static imports.
  • CI and Verification: GPG commit signature is verified. CI gate is all green (ci-gate passed).

@convyusboy
convyusboy merged commit 502c460 into boon Nov 19, 2026
150 of 152 checks passed
@convyusboy
convyusboy deleted the ridho/eng-23040-telegram-whatsapp-legacy-migration-race branch November 19, 2026 12:16
convyusboy added a commit that referenced this pull request Nov 19, 2026
Cuts the fork release for #337 (telegram/whatsapp gateway crash-loop
fix), which merged to boon after the v2026.7.35-boon.1 tag. Upstream
base is unchanged at 2026.7.35.

Bump the root package.json and npm-shrinkwrap.json, all 142 bundled
plugin manifests (scripts/sync-plugin-versions.ts), and regenerate
every extension's npm-shrinkwrap.json (node scripts/generate-npm-shrinkwrap.mjs
--all) to the new version. Add the 2026.7.35-boon.2 CHANGELOG.md
section and the matrix plugin's changelog entry (auto-generated by
the sync script).

Validation: pnpm install --frozen-lockfile clean, node
scripts/generate-npm-shrinkwrap.mjs --all --check reports all 74
shrinkwraps current, test/package-manager-config.test.ts 13/13
passing.

Co-authored-by: Claude Sonnet 5 <[email protected]>
convyusboy added a commit that referenced this pull request Nov 20, 2026
…detectors (#340)

* fix(channels): yield between channels loading legacy-state-migration 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]>

* fix(340): retry on ERR_INTERNAL_ASSERTION, add scheduling regression 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]>

* fix(340): log retry attempts on ERR_INTERNAL_ASSERTION

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]>

* fix(340): cover setup-entry load in the unsettled-ESM retry

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]>

* fix(340): stop caching the unsettled-ESM race as a permanent null in 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]>

---------

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