Skip to content

fix(gateway): keep channel replies working after host wake - #163268

Merged
obviyus merged 1 commit into
openclaw:mainfrom
scotthuang:fix/channel-monitor-work-scope
Oct 2, 2026
Merged

obviyus merged 1 commit into
openclaw:mainfrom
scotthuang:fix/channel-monitor-work-scope

Conversation

@scotthuang

@scotthuang scotthuang commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

Related: #162318

What Problem This Solves

Fixes: long-lived channel listeners can reject new messages with Async work scope is closed after 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

  • Added a regression through the actual channel manager, Gateway scheduler, and thaw-restart operation. It finishes the maintenance tick before releasing a synthetic inbound message, then checks that the replacement monitor can track reply work and still stops when explicitly requested. The same test fails on the unmodified base with Async work scope is closed and passes with this fix.
  • Final channel/lifecycle run: 95 tests passed across the new regression, channel manager, ownership, and trust-refusal suites. Reused 46 passing tests in the unchanged host-thaw, scheduler, and shared async-scope contracts.
  • Changed-file static checks completed with exit 0, including core types, the 27 selected test type graphs, formatting, lint, line-growth guards, unused exports, and runtime import cycles. git diff --check also passed.
  • Scoped independent autoreview completed without actionable P0-P2 findings.
  • New test cost using 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
node scripts/run-vitest.mjs src/gateway/server-channels.work-scope.test.ts src/gateway/server-channels.test.ts src/gateway/server-channels.ownership.test.ts src/gateway/server-channels.trust-refusal.test.ts --maxWorkers=1
node scripts/check-changed.mjs -- src/gateway/server-channel-startup.ts src/gateway/server-channels.ts src/gateway/server-channels.work-scope.test.ts

Supplemental real HTTP transport evidence

Exact product HEAD H = 5d230d6833b970a8e680460f438edca6b3d937e6 was 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.

  • A real HTTP inbound POST was consumed by the production QA channel over HTTP long polling and produced one correlated HTTP outbound reply. The deterministic mock OpenAI provider was called once.
  • Only the owned test Gateway was suspended with SIGSTOP for 80 seconds and resumed with SIGCONT. Native host-thaw detection fired; the channel account returned to ready with a new lastStartAt. Gateway PID and processInstanceId remained unchanged.
  • A later maintenance tick was observed before the next inbound POST. That message received exactly one reply with the correct replyToId and one additional provider request.
  • Native channels.stop returned 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.
  • Native cleanup confirmed the owned Gateway stopped, its runtime temp root was removed, and all three loopback services closed.

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 build completed 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 = ca6353a8ff1065a99dfed6106f8d24f01a3b9df7 is a local, unpublished sole-parent child of H. H..E changes only test/e2e/qa-lab/runtime/channel-host-thaw-http-proof.ts; production code is unchanged. R = local-http-host-thaw, attempt 3, started 2026-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's openclaw/ci-gate is SUCCESS; transport proof and upstream proof acceptance are separate states.

SHA-256:

  • Trace JSON: b13a2c70cc4e03faf5c5cbbdb3dc494af3203998bdfccfa5df9f396b2ddec8dd
  • Harness: 448b190adb8f2b7542ff9e842a8043d8dc806cd480c39c5442649e98d7001750
  • Local sanitized stdout: 85dcbb1a7433778cb1f7a58717c4d461f0d5e25b9afc5e078196c357e4c889fd
  • Local sanitized stderr: 6919f9923a4584f15df0eacb87c196e8f347b718d9d2067c4530186152f87616

Outgoing 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
2026-10-02T14:15:11.266+08:00 [diagnostic] message received: channel=qa-channel chatId=dm:proof-before-wake messageId=52e0a2e6-0bc1-4c65-96e1-022232fceb82 sessionId=unknown sessionKey=agent:qa:main source=dispatchInboundMessage
2026-10-02T14:15:14.154+08:00 [diagnostic] message processed: channel=qa-channel chatId=dm:proof-before-wake messageId=52e0a2e6-0bc1-4c65-96e1-022232fceb82 sessionId=11bfbe64-28f2-4af8-9320-2f4ede1b8606 sessionKey=agent:qa:main outcome=completed duration=2881ms
2026-10-02T14:15:41.291+08:00 [scheduler] running maintenance:host-thaw
2026-10-02T14:17:01.384+08:00 [scheduler] running maintenance:host-thaw
2026-10-02T14:17:01.385+08:00 [health] host timing gap detected: process was frozen ~50093ms; restarting channels when idle and refreshing health
2026-10-02T14:17:01.388+08:00 [health] host thaw channel restart deferred: gateway still has active work
2026-10-02T14:17:01.418+08:00 [qa-channel] [default] channel exited without an error
2026-10-02T14:17:01.422+08:00 [qa-channel] [default] auto-restart attempt 1/10 in 5s
2026-10-02T14:17:31.519+08:00 [scheduler] running maintenance:host-thaw
2026-10-02T14:17:31.555+08:00 [diagnostic] message received: channel=qa-channel chatId=dm:proof-after-wake messageId=c19c606a-4d74-4b43-86bd-efd0ed70012b sessionId=unknown sessionKey=agent:qa:main source=dispatchInboundMessage
2026-10-02T14:17:32.455+08:00 [diagnostic] message processed: channel=qa-channel chatId=dm:proof-after-wake messageId=c19c606a-4d74-4b43-86bd-efd0ed70012b sessionId=11bfbe64-28f2-4af8-9320-2f4ede1b8606 sessionKey=agent:qa:main outcome=completed duration=900ms
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)
import assert from "node:assert/strict";
import { execFileSync } from "node:child_process";
import { existsSync, writeFileSync } from "node:fs";
import path from "node:path";
import { setTimeout as delay } from "node:timers/promises";
import {
  createQaBusState,
  createQaChannelTransport,
  createQaGatewayChild,
  startQaBusServer,
  startQaMockOpenAiServer,
  type MockOpenAiRequestSnapshot,
} from "../../../../extensions/qa-lab/api.js";

// A standalone release-tier proof; it is not registered in per-PR test suites.
const H = "5d230d6833b970a8e680460f438edca6b3d937e6";
const repoRoot = path.resolve(import.meta.dirname, "../../../..");
const E = execFileSync("git", ["rev-parse", "HEAD"], { cwd: repoRoot, encoding: "utf8" }).trim();
assert.equal(
  execFileSync("git", ["rev-parse", "HEAD^"], { cwd: repoRoot, encoding: "utf8" }).trim(),
  H,
);
assert.deepEqual(
  execFileSync("git", ["diff", "--name-only", H, E], { cwd: repoRoot, encoding: "utf8" })
    .trim()
    .split("\n"),
  ["test/e2e/qa-lab/runtime/channel-host-thaw-http-proof.ts"],
);
const attempt = 3;
const preservedLogs = path.join(repoRoot, `.artifacts/channel-http-proof-attempt-${attempt}-logs`);
assert.ok(!existsSync(preservedLogs));
const started = Date.now();
const trace: Array<Record<string, unknown>> = [];
const record = (event: string, facts: Record<string, unknown> = {}) => {
  const entry = { ms: Date.now() - started, event, ...facts };
  trace.push(entry);
  console.log(JSON.stringify(entry));
};
async function until<T>(
  label: string,
  read: () => T | undefined | Promise<T | undefined>,
  timeoutMs = 45_000,
): Promise<T> {
  const deadline = Date.now() + timeoutMs;
  while (Date.now() < deadline) {
    const value = await read();
    if (value !== undefined) return value;
    await delay(100);
  }
  throw new Error(`Timed out waiting for ${label}`);
}
async function json<T>(url: string, body?: unknown): Promise<T> {
  const response = await fetch(url, {
    ...(body === undefined
      ? {}
      : {
          method: "POST",
          headers: { "content-type": "application/json" },
          body: JSON.stringify(body),
        }),
    signal: AbortSignal.timeout(120_000),
  });
  assert.equal(response.status, 200, await response.clone().text());
  return (await response.json()) as T;
}
type Account = {
  accountId: string;
  running: boolean;
  connected: boolean;
  lifecycle: string;
  lastStartAt: number;
  lastStopAt?: number;
  restartPending?: boolean;
  lastError?: string | null;
};
type Message = {
  id: string;
  direction: string;
  text: string;
  accountId: string;
  replyToId?: string;
};
const state = createQaBusState();
let busOwner: Awaited<ReturnType<typeof startQaBusServer>> | undefined;
let providerOwner: Awaited<ReturnType<typeof startQaMockOpenAiServer>> | undefined;
const owner = createQaGatewayChild();
const transport = createQaChannelTransport(state);
let active: Awaited<ReturnType<typeof owner.start>> | undefined;
let paused = false;
let polls = 0;
let outboundPosts = 0;
const activePolls = new Set<object>();
let verdict = "failed";
let failure: string | undefined;
let tempRoot: string | undefined;
let gatewayUrl: string | undefined;
let cleanup: Record<string, unknown> = {};
let lastAccountSnapshot: Record<string, unknown> | undefined;
let initialLastStartAt: number | undefined;
try {
  const bus = await startQaBusServer({ state });
  busOwner = bus;
  const provider = await startQaMockOpenAiServer({ modelRefs: ["mock-openai/gpt-5.6-luna"] });
  providerOwner = provider;
  bus.server.on("request", (request, response) => {
    if (request.method === "POST" && request.url === "/v1/poll") {
      polls++;
      activePolls.add(response);
      response.once("close", () => activePolls.delete(response));
    }
    if (request.method === "POST" && request.url === "/v1/outbound/message") outboundPosts++;
  });
  active = await owner.start({
    repoRoot,
    command: {
      executablePath: process.execPath,
      argsPrefix: [path.join(repoRoot, "dist/index.js")],
      cwd: repoRoot,
      usePackagedPlugins: false,
    },
    providerMode: "mock-openai",
    forcedRuntime: "openclaw",
    providerBaseUrl: `${provider.baseUrl}/v1`,
    primaryModel: "mock-openai/gpt-5.6-luna",
    alternateModel: "mock-openai/gpt-5.6-luna",
    transport,
    transportBaseUrl: bus.baseUrl,
    controlUiEnabled: false,
    mutateConfig: (cfg) => ({
      ...cfg,
      logging: { ...cfg.logging, level: "trace", consoleLevel: "trace" },
      cron: { ...cfg.cron, enabled: false },
      agents: { ...cfg.agents, defaults: { ...cfg.agents?.defaults, heartbeat: { every: "0m" } } },
      plugins: {
        ...cfg.plugins,
        slots: { ...cfg.plugins?.slots, memory: "none" },
        entries: {
          ...cfg.plugins?.entries,
          acpx: { enabled: false },
          "memory-core": { enabled: false },
        },
      },
    }),
  });
  const gateway = active;
  tempRoot = gateway.tempRoot;
  gatewayUrl = gateway.baseUrl;
  const info = (await gateway.call("system.info", {})) as {
    pid: number;
    processInstanceId: string;
  };
  assert.equal(info.pid, gateway.pid);
  assert.ok(info.pid > 1 && info.pid !== process.pid);
  const account = async () => {
    const payload = (await gateway.call("channels.status", { probe: false })) as {
      channelAccounts: Record<string, Account[]>;
    };
    const value = payload.channelAccounts["qa-channel"].find((row) => row.accountId === "default");
    assert.ok(value);
    lastAccountSnapshot = {
      observedMs: Date.now() - started,
      running: value.running,
      connected: value.connected,
      lifecycle: value.lifecycle,
      lastStartAt: value.lastStartAt,
      lastStopAt: value.lastStopAt,
      restartPending: value.restartPending,
      lastError: value.lastError,
    };
    return value;
  };
  await transport.waitReady({ gateway });
  const initialAccount = await account();
  initialLastStartAt = initialAccount.lastStartAt;
  record("gateway-ready", {
    pid: info.pid,
    processInstanceId: info.processInstanceId,
    account: initialAccount.lifecycle,
  });
  const requests = () => json<MockOpenAiRequestSnapshot[]>(`${provider.baseUrl}/debug/requests`);
  const marker = "GATEWAY_REPEATED_REQUEST_QUEUED_OK";
  const sendAndReceive = async (phase: string) => {
    const priorRequests = await requests();
    const priorOutbound = outboundPosts;
    const priorPolls = polls;
    const inbound = await json<{ message: Message }>(`${bus.baseUrl}/v1/inbound/message`, {
      accountId: "default",
      conversation: { kind: "direct", id: `proof-${phase}` },
      senderId: "qa-operator",
      text: "repeated request queued reply gateway qa check",
    });
    record("http-inbound-accepted", { phase, inboundId: inbound.message.id });
    const observed = await json<{ match: Message }>(`${bus.baseUrl}/v1/wait`, {
      kind: "message-text",
      direction: "outbound",
      textIncludes: marker,
      timeoutMs: 90_000,
    });
    // /v1/wait can return an earlier matching message; the correlated bus snapshot
    // is authoritative for this inbound ID, rather than the first global match.
    const reply = await until(
      "correlated HTTP reply",
      async () => {
        const snapshot = await json<{ messages: Message[] }>(`${bus.baseUrl}/v1/state`);
        return snapshot.messages.find(
          (message) =>
            message.direction === "outbound" &&
            message.replyToId === inbound.message.id &&
            message.text === marker,
        );
      },
      90_000,
    );
    assert.equal(reply.accountId, "default");
    const event = state
      .getSnapshot()
      .events.find(
        (event) => event.kind === "inbound-message" && event.message.id === inbound.message.id,
      );
    assert.ok(event);
    await until("completed inbound acknowledgement", () =>
      state.getAcknowledgedPollCursor("default") >= event.cursor ? true : undefined,
    );
    const delta = (await requests()).slice(priorRequests.length);
    assert.equal(delta.length, 1);
    assert.equal(delta[0].requestKind, "agent-initial");
    assert.equal(delta[0].outcome, "success");
    assert.ok(delta[0].prompt.includes("repeated request queued reply gateway qa check"));
    assert.equal(outboundPosts - priorOutbound, 1);
    assert.ok(polls > priorPolls);
    const matches = (
      await json<{ messages: Message[] }>(`${bus.baseUrl}/v1/state`)
    ).messages.filter(
      (message) => message.direction === "outbound" && message.replyToId === inbound.message.id,
    );
    assert.equal(matches.length, 1);
    assert.equal(matches[0].text, marker);
    record("http-reply-acknowledged", {
      phase,
      inboundId: inbound.message.id,
      replyId: reply.id,
      replyToId: reply.replyToId,
      text: reply.text,
      providerCursor: delta[0].cursor,
      providerDelta: delta.length,
      providerOutcome: delta[0].outcome,
      outboundPostDelta: outboundPosts - priorOutbound,
      pollDelta: polls - priorPolls,
      acknowledgedCursor: state.getAcknowledgedPollCursor("default"),
      globalWaitMatchedId: observed.match.id,
    });
  };
  await sendAndReceive("before-wake");
  await until("first host-thaw cadence", () =>
    gateway.logs().includes("running maintenance:host-thaw") ? true : undefined,
  );
  const beforePauseLogs = gateway.markLogs();
  record("owned-gateway-sigstop", { pid: info.pid, minimumPauseMs: 80_000 });
  await gateway.signalProcess("SIGSTOP");
  paused = true;
  // The production detector requires >=75s between ticks. This pause creates
  // that missing-cadence condition; it is not a readiness synchronization sleep.
  await delay(40_000);
  record("owned-gateway-still-paused");
  await delay(40_000);
  await gateway.signalProcess("SIGCONT");
  paused = false;
  record("owned-gateway-sigcont", { pid: info.pid });
  const thawLog = await until("native host-thaw detection", () => {
    const line = gateway
      .readLogsSince(beforePauseLogs)
      .split("\n")
      .find((line) => line.includes("host timing gap detected"));
    return line;
  });
  record("native-host-thaw-detected", {
    detail: thawLog.match(/host timing gap detected:.*?refreshing health/)?.[0],
  });
  const successorLogMark = gateway.markLogs();
  const recovered = await until("replacement account ready", async () => {
    const row = await account();
    return row.running &&
      row.connected &&
      row.lifecycle === "ready" &&
      row.lastStartAt > initialAccount.lastStartAt
      ? row
      : undefined;
  });
  record("replacement-channel-ready", {
    lastStartAtChanged: recovered.lastStartAt > initialAccount.lastStartAt,
  });
  // A periodic successor is armed only by scheduler.finish, after the prior
  // AsyncWorkScope drain. Waiting for its start avoids a still-open-scope pass.
  const successorTick = await until(
    "successor host-thaw tick after recovery drain",
    () => {
      // The gap is already an observed fact. Trace-level event-loop sampling can
      // evict it from the bounded log ring before this successor starts.
      return gateway
        .readLogsSince(successorLogMark)
        .split("\n")
        .find((line) => line.includes("running maintenance:host-thaw"));
    },
    60_000,
  );
  record("recovery-scope-drained-successor-tick-observed", {
    detail: successorTick.match(/running maintenance:host-thaw/)?.[0],
  });
  await sendAndReceive("after-wake");
  const afterInfo = (await gateway.call("system.info", {})) as typeof info;
  assert.equal(afterInfo.pid, info.pid);
  assert.equal(afterInfo.processInstanceId, info.processInstanceId);
  assert.ok(!gateway.logs().includes("Async work scope is closed"));
  const stopped = (await gateway.call("channels.stop", {
    channel: "qa-channel",
    accountId: "default",
  })) as { stopped: boolean };
  assert.equal(stopped.stopped, true);
  const stoppedAccount = await until("account stopped", async () => {
    const row = await account();
    return !row.running && !row.connected && row.lifecycle === "stopped" ? row : undefined;
  });
  await until("all owned channel poll responses closed", () =>
    activePolls.size === 0 ? true : undefined,
  );
  record("channel-explicitly-stopped", {
    stopped: stopped.stopped,
    running: stoppedAccount.running,
    connected: stoppedAccount.connected,
    lifecycle: stoppedAccount.lifecycle,
    activePolls: activePolls.size,
  });
  const stopCounters = { polls, outboundPosts, providerRequests: (await requests()).length };
  const held = await json<{ message: Message }>(`${bus.baseUrl}/v1/inbound/message`, {
    accountId: "default",
    conversation: { kind: "direct", id: "proof-after-stop" },
    senderId: "qa-operator",
    text: "repeated request queued reply gateway qa check",
  });
  // A bus-owned bounded observation window spans four configured poll cadences.
  const noMatch = await fetch(`${bus.baseUrl}/v1/wait`, {
    method: "POST",
    headers: { "content-type": "application/json" },
    body: JSON.stringify({
      kind: "message-text",
      textIncludes: "NO_SUCH_SYNTHETIC_MARKER",
      timeoutMs: 1_000,
    }),
  });
  assert.equal(noMatch.status, 400);
  assert.deepEqual(await noMatch.json(), { error: "qa-bus wait timeout after 1000ms" });
  assert.equal(polls, stopCounters.polls);
  assert.equal(activePolls.size, 0);
  assert.equal(outboundPosts, stopCounters.outboundPosts);
  assert.equal((await requests()).length, stopCounters.providerRequests);
  assert.ok(
    !state
      .getSnapshot()
      .messages.some(
        (message) => message.direction === "outbound" && message.replyToId === held.message.id,
      ),
  );
  record("stopped-channel-did-not-consume-new-http-inbound", {
    inboundId: held.message.id,
    observationMs: 1_000,
    pollDelta: 0,
    providerDelta: 0,
    outboundDelta: 0,
  });
  verdict = "passed";
} catch (error) {
  failure = String(error);
  record("failure", { error: failure, initialLastStartAt, lastAccountSnapshot });
  if (active) writeFileSync(process.env.PROOF_LOG_PATH!, active.logs());
} finally {
  const errors: string[] = [];
  if (paused && active) {
    try {
      await active.signalProcess("SIGCONT");
    } catch (error) {
      errors.push(`resume: ${String(error)}`);
    }
  }
  let processState = "unconfirmed";
  try {
    const stopped = await owner.stop({ keepTemp: false, preserveToDir: preservedLogs });
    processState = stopped.process;
    errors.push(...stopped.errors.map(String));
  } catch (error) {
    errors.push(`gateway cleanup: ${String(error)}`);
  }
  const servers = await Promise.allSettled([providerOwner?.stop(), busOwner?.stop()]);
  for (const result of servers) {
    if (result.status === "rejected") errors.push(`server cleanup: ${String(result.reason)}`);
  }
  cleanup = {
    gatewayProcess: processState,
    errors,
    tempRootRemoved: tempRoot === undefined || !existsSync(tempRoot),
    busClosed: !busOwner?.server.listening,
  };
  record("cleanup", cleanup);
  if (
    processState !== "confirmed-stopped" ||
    errors.length ||
    !cleanup.tempRootRemoved ||
    !cleanup.busClosed
  )
    verdict = "failed";
  for (const url of [gatewayUrl, providerOwner?.baseUrl, busOwner?.baseUrl].filter(
    (url): url is string => Boolean(url),
  )) {
    try {
      await fetch(`${url}/healthz`, { signal: AbortSignal.timeout(1_000) });
      verdict = "failed";
    } catch {
      /* Refused/closed ports are the required post-cleanup outcome. */
    }
  }
}

const report = {
  repository: "openclaw/openclaw",
  pr: 163268,
  H,
  E,
  run: "local-http-host-thaw",
  attempt,
  date: new Date(started).toISOString(),
  verdict,
  failure,
  boundary:
    "Real isolated Gateway and HTTP qa-channel bus; deterministic mock OpenAI over HTTP; owned SIGSTOP/SIGCONT; no live WeChat or system sleep",
  durationMs: Date.now() - started,
  trace,
  cleanup,
};
writeFileSync(process.env.PROOF_REPORT_PATH!, JSON.stringify(report, null, 2) + "\n");
assert.equal(verdict, "passed", failure);

Independent before/after verification

Verified unchanged head 5d230d6833b970a8e680460f438edca6b3d937e6 against its original production base 86cbfeaaeb55de436e6a79113868dca86b818ae5 in 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 main 2ced53d8e736e11c1d082f8018dd09d575a55e7f.

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.

Check Original base Candidate
Normal-startup HTTP message Correlated successful reply; one provider request Correlated successful reply; one provider request
Message after recovery/scope drain Generic failure reply; zero provider requests Correlated successful reply; one provider request
Closed-scope diagnostic Two occurrences Zero occurrences
Explicit channel stop Cleanup stopped the owned Gateway channels.stop confirmed stopped before Gateway cleanup

Base log:

2026-10-02T10:44:25.023+00:00 [session-init] failed to record session participant error="Async work scope is closed"
2026-10-02T10:44:25.060+00:00 Embedded agent failed before reply: Async work scope is closed

Candidate log:

2026-10-02T10:54:56.183+00:00 [admission] reopened: suspend phase
2026-10-02T10:55:26.983+00:00 [diagnostic] message dispatch completed: channel=qa-channel sessionId=unknown sessionKey=agent:qa:main source=replyResolver outcome=completed duration=577ms

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-mini through 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.

@clawsweeper

clawsweeper Bot commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime size: S labels Oct 2, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Oct 2, 2026
@clawsweeper

clawsweeper Bot commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed October 2, 2026, 2:36 AM ET / 06:36 UTC (Revision 2).

ClawSweeper review

What this changes

Channel 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
Reviewed head: 5d230d6833b970a8e680460f438edca6b3d937e6

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused, maintainable repair with meaningful regression coverage and scoped real-transport recovery evidence.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (logs): The exact-head isolated Gateway trace exercises the changed channel-manager startup boundary through native recovery with real HTTP transport, observes a correlated reply afterward, and confirms explicit stop. Recovery used auto-restart after thaw deferral; the precise maintenance-scope closure is separately covered by the failing-base regression. No stored-data contract changes.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (logs): The exact-head isolated Gateway trace exercises the changed channel-manager startup boundary through native recovery with real HTTP transport, observes a correlated reply afterward, and confirms explicit stop. Recovery used auto-restart after thaw deferral; the precise maintenance-scope closure is separately covered by the failing-base regression. No stored-data contract changes.
Evidence reviewed 8 items Pinned introduced change: The pinned merge-base-to-head delta adds async-work-scope detachment at the existing channel startup boundary; the other three context exits are moved unchanged. The verified test-merge delta contains the same three paths.
Current main still needs the repair: Fetched main retains the prior startup wrapper without runOutsideAsyncWorkScope. Its startup owner also lacks the new boundary; no merged replacement was established.
Concrete lifetime mechanism: Each scheduler invocation creates and drains an AsyncWorkScope. Direct tracking against a closed scope rejects; the existing detach helper exits only work-scope carriers. Channel startup retains its account abort controller, capability lease, current-registration checks, and plugin monitor custody.
Findings None None.
Security None None.

How this fits together

The 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
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +6, Tests +100. Total +106 across 3 files.

View PR surface stats
Area Files Added Removed Net
Source 2 16 10 +6
Tests 1 100 0 +100
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 3 116 10 +106

Review metrics

None.

Technical review

Best 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.

Labels

Label changes:

  • add proof: sufficient: Contributor real behavior proof is sufficient. The exact-head isolated Gateway trace exercises the changed channel-manager startup boundary through native recovery with real HTTP transport, observes a correlated reply afterward, and confirms explicit stop. Recovery used auto-restart after thaw deferral; the precise maintenance-scope closure is separately covered by the failing-base regression. No stored-data contract changes.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (logs): The exact-head isolated Gateway trace exercises the changed channel-manager startup boundary through native recovery with real HTTP transport, observes a correlated reply afterward, and confirms explicit stop. Recovery used auto-restart after thaw deferral; the precise maintenance-scope closure is separately covered by the failing-base regression. No stored-data contract changes.
  • remove rating: 🦪 silver shellfish: Current PR rating is rating: 🐚 platinum hermit, so this older rating label is no longer current.
  • remove status: 📣 needs proof: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P2: This is a focused channel lifecycle repair for listeners that inherit a completed maintenance scope.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (logs): The exact-head isolated Gateway trace exercises the changed channel-manager startup boundary through native recovery with real HTTP transport, observes a correlated reply afterward, and confirms explicit stop. Recovery used auto-restart after thaw deferral; the precise maintenance-scope closure is separately covered by the failing-base regression. No stored-data contract changes.
  • proof: sufficient: Contributor real behavior proof is sufficient. The exact-head isolated Gateway trace exercises the changed channel-manager startup boundary through native recovery with real HTTP transport, observes a correlated reply afterward, and confirms explicit stop. Recovery used auto-restart after thaw deferral; the precise maintenance-scope closure is separately covered by the failing-base regression. No stored-data contract changes.

Evidence

What I checked:

  • Pinned introduced change: The pinned merge-base-to-head delta adds async-work-scope detachment at the existing channel startup boundary; the other three context exits are moved unchanged. The verified test-merge delta contains the same three paths. (src/gateway/server-channel-startup.ts:10, 5d230d6833b9)
  • Current main still needs the repair: Fetched main retains the prior startup wrapper without runOutsideAsyncWorkScope. Its startup owner also lacks the new boundary; no merged replacement was established. (src/gateway/server-channels.ts:1159, 25fbb38f16bd)
  • Concrete lifetime mechanism: Each scheduler invocation creates and drains an AsyncWorkScope. Direct tracking against a closed scope rejects; the existing detach helper exits only work-scope carriers. Channel startup retains its account abort controller, capability lease, current-registration checks, and plugin monitor custody. (src/infra/gateway-scheduler.ts:285, 5d230d6833b9)
  • Focused regression: The test invokes the real manager, scheduler, and thaw restart, waits for maintenance cancellation, then releases inbound work and verifies successful tracking plus explicit-stop cancellation. The contributor reports that it fails on the original base and passes after the fix; this review did not execute tests. (src/gateway/server-channels.work-scope.test.ts:72, 5d230d6833b9)
  • Complete captured proof inspected: The full GitHub body matches the captured 29,282 UTF-16 units and SHA-256 46dd6b5c1f7ba49326206ab3a0a2e5058c1351fed01f8fb1dfb6706b9f180530. Its inline harness and trace show an isolated Gateway at the exact head, real HTTP polling and outbound replies, an 80-second process suspension, native recovery, one correlated post-recovery reply, and explicit stop with zero subsequent polls/provider calls/replies during the bounded observation. (5d230d6833b9)
  • Proof scope and continuity: The previous review requested a real-transport reply after recovery and explicit-stop proof. The new trace provides both. It candidly records that the initial thaw restart was deferred and native auto-restart restored the listener; direct startup within the maintenance tick remains regression coverage. Attempt 2's uncaptured readiness timeout remains unexplained, and the passing sample does not claim to fix it. (5d230d6833b9)

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (1 earlier review cycle)
  • reviewed 2026-10-02T05:11:13.287Z sha 5d230d6 :: needs real behavior proof before merge. :: none

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Oct 2, 2026
@obviyus
obviyus merged commit 4c60fa0 into openclaw:main Oct 2, 2026
151 checks passed
@obviyus

obviyus commented Oct 2, 2026

Copy link
Copy Markdown
Collaborator

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.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 3, 2026
…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]>
obviyus added a commit that referenced this pull request Nov 30, 2026
…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]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 30, 2026
…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]>
tideclaw-bot pushed a commit that referenced this pull request Dec 1, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

gateway Gateway runtime P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: S status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants