codex-plugin-cc icon indicating copy to clipboard operation
codex-plugin-cc copied to clipboard

`sendBrokerShutdown` has no timeout — SessionEnd hook can hang indefinitely

Open SmidaOps opened this issue 7 months ago • 5 comments

Summary

sendBrokerShutdown in plugins/codex/scripts/lib/broker-lifecycle.mjs awaits a Promise that resolves only on socket data, error, or close events. If the broker accepts the connection but stops responding mid-RPC (no data, no error, no close), the Promise never resolves and the SessionEnd hook hangs indefinitely.

Affected code

plugins/codex/scripts/lib/broker-lifecycle.mjs:43-57 (v1.0.3)

export async function sendBrokerShutdown(endpoint) {
  await new Promise((resolve) => {
    const socket = connectToEndpoint(endpoint);
    socket.setEncoding("utf8");
    socket.on("connect", () => {
      socket.write(`${JSON.stringify({ id: 1, method: "broker/shutdown", params: {} })}\n`);
    });
    socket.on("data", () => {
      socket.end();
      resolve();
    });
    socket.on("error", resolve);
    socket.on("close", resolve);
  });
}

Asymmetry with startup path

waitForBrokerEndpoint in the same file (line 24) explicitly takes timeoutMs = 2000 and bounds its wait loop. Startup path is timed; shutdown path isn't. Same module — looks like an oversight rather than intent.

Observed symptoms

Running Claude Code in unattended (cron/launchd) invocations on macOS:

  • Multiple sessions hung at SessionEnd after content rendered cleanly. One held its lock 19.5 hours before something external (a new Claude Code session creating a fresh broker socket) unwedged it.
  • In a separate session the harness's hook timeout fired with Hook cancelled and exit 1 — content was already delivered, but the misleading exit code surfaced as a failure in launchd telemetry.
  • Correlation suggests macOS DarkWake during long-running SSE streams wedges the broker. We mitigated with caffeinate -ims on the wrapper, but the shutdown await still hangs when a wedge does happen.

Proposed fix

Mirror the timeout pattern used in waitForBrokerEndpoint:

export async function sendBrokerShutdown(endpoint, timeoutMs = 5000) {
  await new Promise((resolve) => {
    const socket = connectToEndpoint(endpoint);
    let settled = false;
    const finish = () => {
      if (settled) return;
      settled = true;
      clearTimeout(timer);
      try { socket.destroy(); } catch {}
      resolve();
    };
    const timer = setTimeout(finish, timeoutMs);
    socket.setEncoding("utf8");
    socket.on("connect", () => {
      socket.write(`${JSON.stringify({ id: 1, method: "broker/shutdown", params: {} })}\n`);
    });
    socket.on("data", finish);
    socket.on("error", finish);
    socket.on("close", finish);
  });
}

5s is generous for a local socket RPC and can be tuned. Caller in session-lifecycle-hook.mjs:99 requires no change.

Environment

  • Plugin: @openai/codex-plugin-cc v1.0.3
  • Platform: macOS Darwin 25.4 (arm64)
  • Node: >= 18.18 (per engines)
  • Trigger: launchd-scheduled claude --agent ... -p ... --permission-mode bypassPermissions heartbeat invocations

SmidaOps avatar May 02 '26 16:05 SmidaOps

I opened a PR for this: https://github.com/openai/codex-plugin-cc/pull/300

The fix adds a bounded timeout to sendBrokerShutdown(endpoint, timeoutMs = 5000) and uses a guarded cleanup path for data, error, close, and timeout.

I also added a regression test that simulates the reported failure mode: a broker accepts the socket connection, receives broker/shutdown, but never replies or closes the socket.

Validation passed locally:

node --test tests/broker-lifecycle.test.mjs
npm test

Full suite: 87 passed, 0 failed.

dhruvac29 avatar May 05 '26 21:05 dhruvac29

Same observation on macOS (Claude Code with codex@openai-codex v1.0.4). The silent-resolve on socket error/close in sendBrokerShutdown means SessionEnd can't be relied on for cleanup — that's what produces the orphan tree we see (node codex app-server plus Rust codex app-server reparented to launchd, persisting across sessions). Tracking PR #343 as the candidate fix.

Pelton avatar May 22 '26 22:05 Pelton

Thanks for the additional repro/details. I think this is related but not the same failure mode as #300.

#300 addresses the unbounded wait in sendBrokerShutdown: if the shutdown socket connects but never receives data, error, or close, SessionEnd can hang indefinitely. That PR adds a timeout and guarded socket cleanup for the shutdown RPC itself.

The orphaned codex app-server process case described here looks broader: stale broker/session cleanup needs to terminate the recorded broker process, which #343 appears to address.

So I see #300 and #343 as complementary:

  • #300: prevent SessionEnd from hanging forever during shutdown RPC
  • #343: clean up stale/orphaned broker processes and state races

Happy to rebase/resolve conflicts if #343 lands first.

dhruvac29 avatar May 22 '26 23:05 dhruvac29

This is scenario 2 in the broker-leak map in #163 — a separate class from the orphan case (scenario 1). The key distinction: the idle-timeout in PR #490 lives inside the broker process, so it does not cure a hung client-side sendBrokerShutdown. This class needs a client-side bounded RPC timeout (mine is sendBrokerShutdown(endpoint, 2000) with a hard cutoff on the fork). PR #490 is still worth merging — it closes scenario 1 — but it doesn't touch this one. See #163 for the full three-scenario map.

axisrow avatar Jul 16 '26 04:07 axisrow

Windows/named-pipe reproduction — intermittent, and the two state roots make it recur

Adding a Windows data point, since the reports in this thread (and the caffeinate mitigation in the OP) are macOS/Unix-socket specific. Same failure mode, but the pipe transport explains an intermittency that wasn't obvious to me from the existing reports.

Environment: codex@openai-codex v1.0.6 · Windows 11 Pro build 26200 · Node v24.13.0 · Claude Code, SessionEnd timeout 5s (hooks/hooks.json)

Symptom: SessionEnd hook [node "${CLAUDE_PLUGIN_ROOT}/scripts/session-lifecycle-hook.mjs" SessionEnd] failed: Hook cancelled on exit — intermittently, not every time.

What I confirmed locally. On Windows createBrokerEndpoint returns pipe:\.\pipe\<sessionDir>-codex-app-server (scripts/lib/broker-endpoint.mjs:10-17), so connectToEndpoint opens a named pipe rather than a Unix socket. The hang reproduces when broker.json names a broker that is gone — in my case pid dead, the named pipe absent, and the sessionDir under %TEMP% already reclaimed by Windows. sendBrokerShutdown then awaits a pipe that never emits data, error or close, exceeds the 5s hook timeout, and the harness cancels it.

Timing, same machine, hook invoked directly with synthetic SessionEnd stdin:

  • state dir without broker.json: 1.3–1.8s, exit 0
  • after deleting a stale broker.json: 2.3–2.5s, exit 0

So the hook itself fits well inside 5s; the entire overage is the unbounded shutdown RPC. That matches @axisrow's scenario-2 framing in #163 — a broker-side idle timeout (#490) can't cure this, it needs the client-side bound in #300.

Why it's intermittent here. A dead named pipe on Windows doesn't fail uniformly: sometimes connectToEndpoint gets a prompt ENOENT/ECONNREFUSED (the error handler fires, cleanup completes normally) and sometimes the connect attempt just sits there. Same stale broker.json, different outcome per exit. On a Unix socket a missing path errors deterministically, which I think is why this reads as "hangs indefinitely" on macOS and as "fails maybe one exit in three" on Windows. The bounded timeout in #300 fixes both; I mention it only because an intermittent repro can look like a different bug.

It recurs, and #743 is why. I deleted a stale broker.json and the error went away for two days, then came back. The new one was under a different state root:

~/.claude/plugins/data/codex-inline/state/<workspace-hash>/broker.json        ← deleted
~/.claude/plugins/data/codex-openai-codex/state/<workspace-hash>/broker.json  ← reappeared here

Same workspace hash, two roots — the CLAUDE_PLUGIN_DATA split in #636. Combined with #743 (broker.json only removed by a SessionEnd whose cwd matches), every broker that dies unclean leaves a fresh landmine for the next exit, so this isn't self-limiting.

Worth noting the pid-reuse risk in #743 is real on Windows too: while checking one of these I found the recorded pid "alive" — it had been recycled for an unrelated SearchProtocolHost.exe started days later. Anything that trusts that pid without an argv/start-time check would have signalled the wrong process.

Not a blocker for me — cleanup succeeds on most exits and nothing accumulates (after ~5 days uptime the stale files and broker processes were gone on their own). Filing the detail because the Windows transport difference isn't represented in the thread yet. +1 on #300.

EricSanzLuna avatar Sep 22 '26 17:09 EricSanzLuna