Repository navigation
fix(gateway): keep channel replies working after host wake - #163268
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
Codex review: needs maintainer review before merge. Reviewed October 2, 2026, 2:36 AM ET / 06:36 UTC (Revision 2). ClawSweeper reviewWhat this changesChannel startup leaves its caller’s temporary work scope so restarted listeners can process later messages, with a regression covering maintenance completion and explicit stop. Merge readiness✅ Ready for maintainer review Keep open: current main still needs this focused lifecycle repair. No actionable patch defect was found, and the added HTTP recovery trace satisfies the previous proof request. Likely related people: @steipete is a medium-confidence routing candidate from recent channel lifecycle work. Priority: P2 Review scores
Verification
How this fits togetherThe Gateway channel manager owns long-lived plugin listeners. Wake recovery restarts those listeners, which receive channel messages and dispatch agent replies. flowchart TD
A[Host wake detection] --> B[Maintenance scheduler]
B --> C[Channel manager]
C --> D[Independent listener lifetime]
E[Inbound channel message] --> D
D --> F[Agent reply]
G[Explicit channel stop] --> D
Before mergeNone. Agent review detailsSecurityNone. PR surfaceSource +6, Tests +100. Total +106 across 3 files. View PR surface stats
Review metricsNone. Technical reviewBest possible solution: Keep channel listeners under channel-manager custody while preserving explicit stop, plugin retirement, and shutdown cancellation. Do we have a high-confidence way to reproduce the issue? Yes, source establishes the inherited-scope failure and the regression exercises its precise boundary; the contributor reports a failing-base run. This read-only review did not independently execute it. Is this the best way to solve the issue? Yes: fixing lifetime inheritance at channel startup is narrower than changing shared closed-scope rejection semantics and preserves the existing cancellation owners. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 25fbb38f16bd. LabelsLabel changes:
Label justifications:
EvidenceWhat I checked:
Likely related people:
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (1 earlier review cycle)
|
|
Landed as 4c60fa0. Thanks @scotthuang! We reproduced the closed-scope failure on the QA channel after a real wake recovery. Telegram was already insulated by the shared ingress drain, and WeChat was the case you hit. |
…163268) Long-running channel listeners are no longer tied to the temporary host-wake recovery-check work scope, so replies keep working after a wake instead of failing with "Async work scope is closed". Proof: real isolated Gateway with the QA channel HTTP listener (which inherits the scope) and native SIGSTOP/SIGCONT wake recovery. On main, after recovery the next reply failed with "Embedded agent failed before reply: Async work scope is closed" and made no provider call; with this change the reply was delivered. Telegram, whose shared ingress already detaches the scope, delivered replies before and after recovery with real gpt-5-mini as a non-regression control. Regression test fails on main and passes here. Co-authored-by: scotthuang <[email protected]> Co-authored-by: Ayaan Zaidi <[email protected]>
…econnect (#208736) Root cause: src/gateway/server-channel-account-lifetime.ts:116 runs a channel account's scheduled callbacks (`ctx.scheduler`) inside the job's own async work scope (`GatewayScheduler.run`, src/infra/gateway-scheduler.ts:366, 359 on 2026.11.12), and the scheduler closes that scope when the callback settles. A transport the plugin reconnects from such a job keeps the closed scope, so every later inbound turn on it fails with `AsyncWorkScopeClosedError` and an aborted signal until the Gateway restarts. Candidate fix for #208686 (not closing it yet). Thanks @itsnimbus for the detailed report and logs. This PR fixes the reconnect path below, which reproduces the reported failure signature exactly. It does not yet confirm that this is the path the reporter hit. @itsnimbus: which channel plugin and version are you running, and do your logs show that plugin reconnecting its transport shortly before the first failure? #208447 (same reporter, same `AsyncWorkScopeClosedError` at session init on a channel turn) may be the same cause. Unconfirmed. ## What changes Account-scheduled callbacks now run outside the scheduler job's work scope. The account task itself already runs that way (`runChannelAccountStartup`, #163268), and the job still waits for the promise the callback returns. The plugin docs describe this pattern: plugins own their reconnection and sockets and use the account scheduler for timed work, and the bundled imap and mcp-relay plugins do the same. Plugin service schedulers are unchanged, because their tests require them to wait for tracked child work. Unverified: the report ties the failure to a maintenance tick and a `session.maintenance.plan.read`. I haven't reproduced that trigger. A scope-leak probe on a built Gateway with two agents across ordinary 30 s maintenance ticks found no turn running in a closed scheduler scope, but that run didn't include a session-maintenance plan pass. ## Evidence The setup is a built Gateway, a local mock model, and two agents. Each agent has its own account and transport on a third-party channel stand-in: the repo's qa-channel, changed only to reconnect from `ctx.scheduler` after its transport drops. The test drops alpha's transport and lets the plugin reconnect from its scheduled job. - main 6c21817: alpha failed 3/3 later turns ("The request took too long"). Each logged the reported set: `failed to record session participant AsyncWorkScopeClosedError`, `requester settlement handler failed AbortError`, `Embedded agent failed before reply: This operation was aborted`. Beta replied 3/3. - This PR: alpha and beta replied 3/3 after the reconnect, with no failure lines. Regression: `server-channels.work-scope.test.ts`, "keeps channel work from an account-scheduled reconnect alive after its job settles". It fails on main with `AsyncWorkScopeClosedError` and passes here. ## Follow-ups (not changed here) - The native approval-handler bootstrap retry (`src/infra/approval-handler-bootstrap.ts`) and the mcp-relay service connect job also create long-lived connections inside scheduler jobs. This is the same class of bug, on paths not reported yet. - The prompt-cache keep-warm pass, started by cron maintenance, keeps running after its maintenance job's scope closes, so it reads an aborted work signal. Co-authored-by: Ayaan Zaidi <[email protected]>
…econnect (openclaw#208736) Root cause: src/gateway/server-channel-account-lifetime.ts:116 runs a channel account's scheduled callbacks (`ctx.scheduler`) inside the job's own async work scope (`GatewayScheduler.run`, src/infra/gateway-scheduler.ts:366, 359 on 2026.11.12), and the scheduler closes that scope when the callback settles. A transport the plugin reconnects from such a job keeps the closed scope, so every later inbound turn on it fails with `AsyncWorkScopeClosedError` and an aborted signal until the Gateway restarts. Candidate fix for openclaw#208686 (not closing it yet). Thanks @itsnimbus for the detailed report and logs. This PR fixes the reconnect path below, which reproduces the reported failure signature exactly. It does not yet confirm that this is the path the reporter hit. @itsnimbus: which channel plugin and version are you running, and do your logs show that plugin reconnecting its transport shortly before the first failure? openclaw#208447 (same reporter, same `AsyncWorkScopeClosedError` at session init on a channel turn) may be the same cause. Unconfirmed. ## What changes Account-scheduled callbacks now run outside the scheduler job's work scope. The account task itself already runs that way (`runChannelAccountStartup`, openclaw#163268), and the job still waits for the promise the callback returns. The plugin docs describe this pattern: plugins own their reconnection and sockets and use the account scheduler for timed work, and the bundled imap and mcp-relay plugins do the same. Plugin service schedulers are unchanged, because their tests require them to wait for tracked child work. Unverified: the report ties the failure to a maintenance tick and a `session.maintenance.plan.read`. I haven't reproduced that trigger. A scope-leak probe on a built Gateway with two agents across ordinary 30 s maintenance ticks found no turn running in a closed scheduler scope, but that run didn't include a session-maintenance plan pass. ## Evidence The setup is a built Gateway, a local mock model, and two agents. Each agent has its own account and transport on a third-party channel stand-in: the repo's qa-channel, changed only to reconnect from `ctx.scheduler` after its transport drops. The test drops alpha's transport and lets the plugin reconnect from its scheduled job. - main cd159a2: alpha failed 3/3 later turns ("The request took too long"). Each logged the reported set: `failed to record session participant AsyncWorkScopeClosedError`, `requester settlement handler failed AbortError`, `Embedded agent failed before reply: This operation was aborted`. Beta replied 3/3. - This PR: alpha and beta replied 3/3 after the reconnect, with no failure lines. Regression: `server-channels.work-scope.test.ts`, "keeps channel work from an account-scheduled reconnect alive after its job settles". It fails on main with `AsyncWorkScopeClosedError` and passes here. ## Follow-ups (not changed here) - The native approval-handler bootstrap retry (`src/infra/approval-handler-bootstrap.ts`) and the mcp-relay service connect job also create long-lived connections inside scheduler jobs. This is the same class of bug, on paths not reported yet. - The prompt-cache keep-warm pass, started by cron maintenance, keeps running after its maintenance job's scope closes, so it reads an aborted work signal. Co-authored-by: Ayaan Zaidi <[email protected]>
…econnect (#208736) Root cause: src/gateway/server-channel-account-lifetime.ts:116 runs a channel account's scheduled callbacks (`ctx.scheduler`) inside the job's own async work scope (`GatewayScheduler.run`, src/infra/gateway-scheduler.ts:366, 359 on 2026.11.12), and the scheduler closes that scope when the callback settles. A transport the plugin reconnects from such a job keeps the closed scope, so every later inbound turn on it fails with `AsyncWorkScopeClosedError` and an aborted signal until the Gateway restarts. Candidate fix for #208686 (not closing it yet). Thanks @itsnimbus for the detailed report and logs. This PR fixes the reconnect path below, which reproduces the reported failure signature exactly. It does not yet confirm that this is the path the reporter hit. @itsnimbus: which channel plugin and version are you running, and do your logs show that plugin reconnecting its transport shortly before the first failure? #208447 (same reporter, same `AsyncWorkScopeClosedError` at session init on a channel turn) may be the same cause. Unconfirmed. ## What changes Account-scheduled callbacks now run outside the scheduler job's work scope. The account task itself already runs that way (`runChannelAccountStartup`, #163268), and the job still waits for the promise the callback returns. The plugin docs describe this pattern: plugins own their reconnection and sockets and use the account scheduler for timed work, and the bundled imap and mcp-relay plugins do the same. Plugin service schedulers are unchanged, because their tests require them to wait for tracked child work. Unverified: the report ties the failure to a maintenance tick and a `session.maintenance.plan.read`. I haven't reproduced that trigger. A scope-leak probe on a built Gateway with two agents across ordinary 30 s maintenance ticks found no turn running in a closed scheduler scope, but that run didn't include a session-maintenance plan pass. ## Evidence The setup is a built Gateway, a local mock model, and two agents. Each agent has its own account and transport on a third-party channel stand-in: the repo's qa-channel, changed only to reconnect from `ctx.scheduler` after its transport drops. The test drops alpha's transport and lets the plugin reconnect from its scheduled job. - main 6c21817: alpha failed 3/3 later turns ("The request took too long"). Each logged the reported set: `failed to record session participant AsyncWorkScopeClosedError`, `requester settlement handler failed AbortError`, `Embedded agent failed before reply: This operation was aborted`. Beta replied 3/3. - This PR: alpha and beta replied 3/3 after the reconnect, with no failure lines. Regression: `server-channels.work-scope.test.ts`, "keeps channel work from an account-scheduled reconnect alive after its job settles". It fails on main with `AsyncWorkScopeClosedError` and passes here. ## Follow-ups (not changed here) - The native approval-handler bootstrap retry (`src/infra/approval-handler-bootstrap.ts`) and the mcp-relay service connect job also create long-lived connections inside scheduler jobs. This is the same class of bug, on paths not reported yet. - The prompt-cache keep-warm pass, started by cron maintenance, keeps running after its maintenance job's scope closes, so it reads an aborted work signal. Co-authored-by: Ayaan Zaidi <[email protected]> (cherry picked from commit e9aa48a) Co-authored-by: RomneyDa <[email protected]>
Related: #162318
What Problem This Solves
Fixes: long-lived channel listeners can reject new messages with
Async work scope is closedafter host sleep/resume recovery restarts them.User Impact
Channels restarted by wake recovery can continue processing later inbound messages without requiring a Gateway restart. Existing channel stop/abort and plugin lifecycle guards remain in place. No configuration change or state migration is required.
Why This Change Was Made
The scheduler closes its per-tick work scope after maintenance finishes. A channel monitor started inside that tick can inherit the short-lived scope even though the channel manager owns the monitor's longer lifetime.
Keep channel startup's existing context boundary in the startup owner and also leave the caller's async work scope before starting the account. The shared scope's close/drain behavior and rejection of late work remain unchanged.
Evidence
Async work scope is closedand passes with this fix.git diff --checkalso passed.node scripts/run-vitest.mjs src/gateway/server-channels.work-scope.test.ts --maxWorkers=1: 12.15 s warm wall / 28 ms test body. Cold failing-base reproduction took 31.98 s, including worker compilation. CI seconds have not been measured yet.This lifecycle regression uses a synthetic channel. The supplemental local transport scenario below exercises real HTTP I/O with an isolated Gateway and mock provider. No external messages were sent, and the installed OpenClaw package and running Gateway were not changed.
Validation commands
Supplemental real HTTP transport evidence
Exact product HEAD H =
5d230d6833b970a8e680460f438edca6b3d937e6was kept unchanged. On October 2, an isolated local Gateway built from H completed a continuous HTTP send/receive and stop scenario in 155.68 seconds.channels.stopreturned stopped=true. Account running/connected became false, lifecycle became stopped, and active HTTP polls became zero. Another inbound POST after stop caused no further poll, provider request or outbound reply during a one-second bus-owned observation window.Observed recovery path and proof limits: full logs show that the first host-thaw channel restart was deferred because the Gateway still had active work. The QA monitor exited cleanly, then the channel manager's native five-second auto-restart restored the account. This is real transport behavior after a freeze and native account recovery; it is not evidence that this particular replacement was started inside the original maintenance tick. The strict maintenance-scope close boundary remains covered by the regression above, which fails on the original code. The trace's successor-tick event establishes a successor to the initial recovery pass, not closure of every possible deferred retry. No live WeChat, real provider credentials, system-wide sleep or external messages were used.
Earlier local attempts: attempt 1 stopped at a log-capture false-negative because high-frequency trace output evicted the gap anchor from the 64 KiB ring; its retained log actually contained a later maintenance tick. That harness error was corrected without changing product H or extending timeouts. Attempt 2 detected the gap but did not observe the replacement-ready predicate within 45 seconds. Its early logs and final account status were not captured, so its cause remains unknown; the passing sample does not establish a fix for that timeout. Attempt 3 added final-account observations and native full sanitized-log preservation, then completed the scenario above.
A cold isolated
OPENCLAW_BUILD_PRIVATE_QA=1 pnpm buildcompleted with exit 0 in 896.97 seconds using pinned pnpm 12.5.1. Prepared dependencies were cloned into the proof worktree; no fresh dependency installation was claimed. Build-info.commit is H. The local build carrier was evidence attempt 1; its production files are identical to H and the final evidence commit. The build reported nonblocking UI-size advisories; this PR changes no UI files. The installed OpenClaw package, operator configuration, real tasks and running Gateway were not modified. No workflow was dispatched or rerun for this proof.Proof identity: evidence E =
ca6353a8ff1065a99dfed6106f8d24f01a3b9df7is a local, unpublished sole-parent child of H. H..E changes onlytest/e2e/qa-lab/runtime/channel-host-thaw-http-proof.ts; production code is unchanged. R = local-http-host-thaw, attempt 3, started2026-10-02T06:14:58.688Z; no Actions run/artifact ID applies. E's complete harness and the resulting trace are embedded below so the evidence is publicly reviewable without a local-file link. A = the inline JSON trace and harness, with SHA-256 recorded below. Local full stdout/stderr are supplementary sanitized diagnostics, not publicly hosted artifacts. The unchanged product'sopenclaw/ci-gateis SUCCESS; transport proof and upstream proof acceptance are separate states.SHA-256:
b13a2c70cc4e03faf5c5cbbdb3dc494af3203998bdfccfa5df9f396b2ddec8dd448b190adb8f2b7542ff9e842a8043d8dc806cd480c39c5442649e98d700175085dcbb1a7433778cb1f7a58717c4d461f0d5e25b9afc5e078196c357e4c889fd6919f9923a4584f15df0eacb87c196e8f347b718d9d2067c4530186152f87616Outgoing evidence was inspected: only synthetic account/message/session identifiers, fixture markers, process IDs and timing/counter facts are published; no config, token, credential, hostname or local absolute path is included. Inline evidence persists with this PR; local proof/runtime artifacts use task cleanup.
Native recovery and message log excerpt
Exact-head local trace (attempt 3)
{ "repository": "openclaw/openclaw", "pr": 163268, "H": "5d230d6833b970a8e680460f438edca6b3d937e6", "E": "ca6353a8ff1065a99dfed6106f8d24f01a3b9df7", "run": "local-http-host-thaw", "attempt": 3, "date": "2026-10-02T06:14:58.688Z", "verdict": "passed", "boundary": "Real isolated Gateway and HTTP qa-channel bus; deterministic mock OpenAI over HTTP; owned SIGSTOP/SIGCONT; no live WeChat or system sleep", "durationMs": 155680, "trace": [ { "ms": 12464, "event": "gateway-ready", "pid": 95676, "processInstanceId": "ce475804-20d1-4570-a2bb-545b103c1484", "account": "ready" }, { "ms": 12479, "event": "http-inbound-accepted", "phase": "before-wake", "inboundId": "52e0a2e6-0bc1-4c65-96e1-022232fceb82" }, { "ms": 15705, "event": "http-reply-acknowledged", "phase": "before-wake", "inboundId": "52e0a2e6-0bc1-4c65-96e1-022232fceb82", "replyId": "6be44134-8eb1-42ab-bdfa-8166ab939a71", "replyToId": "52e0a2e6-0bc1-4c65-96e1-022232fceb82", "text": "GATEWAY_REPEATED_REQUEST_QUEUED_OK", "providerCursor": 1, "providerDelta": 1, "providerOutcome": "success", "outboundPostDelta": 1, "pollDelta": 13, "acknowledgedCursor": 2, "globalWaitMatchedId": "6be44134-8eb1-42ab-bdfa-8166ab939a71" }, { "ms": 42649, "event": "owned-gateway-sigstop", "pid": 95676, "minimumPauseMs": 80000 }, { "ms": 82652, "event": "owned-gateway-still-paused" }, { "ms": 122657, "event": "owned-gateway-sigcont", "pid": 95676 }, { "ms": 122762, "event": "native-host-thaw-detected", "detail": "host timing gap detected: process was frozen ~50093ms; restarting channels when idle and refreshing health" }, { "ms": 128213, "event": "replacement-channel-ready", "lastStartAtChanged": true }, { "ms": 152850, "event": "recovery-scope-drained-successor-tick-observed", "detail": "running maintenance:host-thaw" }, { "ms": 152855, "event": "http-inbound-accepted", "phase": "after-wake", "inboundId": "c19c606a-4d74-4b43-86bd-efd0ed70012b" }, { "ms": 154007, "event": "http-reply-acknowledged", "phase": "after-wake", "inboundId": "c19c606a-4d74-4b43-86bd-efd0ed70012b", "replyId": "1bedd295-f674-4d0c-9666-4007feb22dd8", "replyToId": "c19c606a-4d74-4b43-86bd-efd0ed70012b", "text": "GATEWAY_REPEATED_REQUEST_QUEUED_OK", "providerCursor": 2, "providerDelta": 1, "providerOutcome": "success", "outboundPostDelta": 1, "pollDelta": 6, "acknowledgedCursor": 4, "globalWaitMatchedId": "6be44134-8eb1-42ab-bdfa-8166ab939a71" }, { "ms": 154074, "event": "channel-explicitly-stopped", "stopped": true, "running": false, "connected": false, "lifecycle": "stopped", "activePolls": 0 }, { "ms": 155095, "event": "stopped-channel-did-not-consume-new-http-inbound", "inboundId": "804ca7e3-db55-4a86-bb86-bbd0b30811b0", "observationMs": 1000, "pollDelta": 0, "providerDelta": 0, "outboundDelta": 0 }, { "ms": 155677, "event": "cleanup", "gatewayProcess": "confirmed-stopped", "errors": [], "tempRootRemoved": true, "busClosed": true } ], "cleanup": { "gatewayProcess": "confirmed-stopped", "errors": [], "tempRootRemoved": true, "busClosed": true } }Complete standalone evidence harness (release-only, not per-PR CI)
Independent before/after verification
Verified unchanged head
5d230d6833b970a8e680460f438edca6b3d937e6against its original production base86cbfeaaeb55de436e6a79113868dca86b818ae5in an isolated Linux/Node 24.21.0 container. The channel-startup, channel-manager, maintenance, thaw-recovery, and async-work-scope owners are unchanged between that base and inspected main2ced53d8e736e11c1d082f8018dd09d575a55e7f.The real Gateway used the existing QA channel's long-running HTTP polling listener and an HTTP mock model. Only the owned Gateway process was suspended with SIGSTOP for 80 seconds and resumed with SIGCONT; the system clock was not changed. Both builds detected host thaw, initially deferred for active work, and later completed the native deferred recovery pass. The harness waited for replacement readiness, recovery admission release, and a successor maintenance tick before sending the next message.
channels.stopconfirmed stopped before Gateway cleanupBase log:
Candidate log:
The existing focused regression independently failed on the original production code with
Async work scope is closed(16.21 seconds wall, 21 ms test body) and passed on the exact candidate (19.63 seconds wall, 29 ms test body). All owned QA Gateway processes were confirmed stopped with no cleanup errors.Telegram Test Server is a non-regression control, not a reproducer for this defect: its shared ingress drain already leaves the caller's async work scope. A correctly ordered base run delivered both normal-startup and post-recovery replies. The QA channel does not use that insulating ingress path, so it supplies the discriminating real-Gateway comparison. This does not claim a live WeChat test; WeChat is the external Tencent plugin.
No overlap with Pash/Sarah changes. Contributor scotthuang's production fix and regression remain unchanged. No CI workflow was dispatched or rerun.
The exact candidate also passed the live Telegram Test Server gate using embedded
gpt-5-minithrough a forward-only proxy, with heartbeats and utility routing disabled: two successful real provider requests total. The normal-startup reply arrived at 7011 ms; native recovery and its successor tick completed by 90424 ms; a fresh message sent at 150305 ms received its matching reply at 153695 ms. No closed-scope error occurred. The runner reported scratch cleanup after exit and its lease owner released the test credential.