Skip to content

codex app-server exits on stdin EOF or SIGTERM without draining an in-flight background ChatGPT OAuth refresh, leaving the retired refresh token in auth.json #62688

Open

Description

@xxchan

What version of Codex CLI is running?

codex-cli 0.171.0 (source locations below checked on main at a0a30c40)

What subscription do you have?

n/a (reproduced with a local mock OAuth server)

Which model were you using?

n/a (no turn submitted; reproduced with skills/list and account/read)

What platform is your computer?

Linux 6.12.93 x86_64 x86_64

What terminal emulator and version are you using (if applicable)?

n/a (stdio codex app-server --listen stdio:// subprocess)

Codex doctor report

Run in a credential-free temporary CODEX_HOME (with local paths redacted to <home>, <tmp-prefix>, and <tmp-codex-home>), so the auth.credentials and provider reachability failures below are expected.

<details>
<summary>codex doctor --json</summary>

{
  "schemaVersion": 1,
  "generatedAt": "1795158382s since unix epoch",
  "overallStatus": "fail",
  "codexVersion": "0.171.0",
  "checks": {
    "app_server.status": {
      "id": "app_server.status",
      "category": "app-server",
      "status": "ok",
      "summary": "background server is not running",
      "details": {
        "control socket": "<tmp-codex-home>/app-server-control/app-server-control.sock",
        "daemon state dir": "<tmp-codex-home>/app-server-daemon",
        "dedicated pid file": "<tmp-codex-home>/app-server-daemon/daemon.pid (missing)",
        "dedicated update-loop pid file": "<tmp-codex-home>/app-server-daemon/daemon-updater.pid (missing)",
        "mode": "ephemeral",
        "pid file": "<tmp-codex-home>/app-server-daemon/app-server.pid (missing)",
        "settings": "<tmp-codex-home>/app-server-daemon/settings.json (missing)",
        "status": "not running",
        "update-loop pid file": "<tmp-codex-home>/app-server-daemon/app-server-updater.pid (missing)"
      },
      "remediation": null,
      "durationMs": 0
    },
    "auth.credentials": {
      "id": "auth.credentials",
      "category": "auth",
      "status": "fail",
      "summary": "no Codex credentials were found",
      "details": {
        "auth file": "<tmp-codex-home>/auth.json",
        "auth storage mode": "File"
      },
      "remediation": "Run codex login or provide an API key through a supported auth env var.",
      "durationMs": 0
    },
    "config.load": {
      "id": "config.load",
      "category": "config",
      "status": "ok",
      "summary": "config loaded",
      "details": {
        "CODEX_HOME": "<tmp-codex-home>",
        "active thread overrides": "not inspected",
        "config.toml": "<tmp-codex-home>/config.toml",
        "config.toml parse": "ok",
        "configuration load ms": "4",
        "configuration scope": "invocation config, including cloud-managed policy",
        "configured TUI mode": "fullscreen",
        "cwd": "<tmp-codex-home>",
        "enabled feature flags": "daemon_auto_start, tui_workspace, shell_tool, view_image, sleep_tool, unified_exec, unified_exec_tty, shell_snapshot, content_item_kinds, untrusted_as_tool_output, code_mode_host, code_mode_host_grpc, code_mode_host_output_truncation, code_mode_interrupt, instant_interrupt, terminal_resize_reflow, sqlite, write_stdin_approval, hooks, api_key_model_discovery, cli_daybreak, api_key_cyber_access_programs, enable_request_compression, unbounded_connection_retries, worktrees, system_proxy_fallback, multi_agent, apps, mcp_oauth_refresh_coordination, tool_search_always_defer_mcp_tools, deferred_tool_world_state, incremental_tools, incremental_tools_legacy, incremental_tools_legacy_gcp, prediction_preserve_parent_tools, tool_suggest, plugins, in_app_browser, browser_annotation_api, in_app_chat, in_app_dictation, in_app_voice, in_app_local_automation, in_app_updates, browser_use, browser_use_full_cdp_access, browser_use_external, computer_use, remote_plugin, plugin_sharing, image_generation, unified_image_budget, resize_all_images, item_ids, skill_mcp_dependency_install, skill_search, mentions_v2, steer, guardian_approval, guardian_include_additional_context, guardian_reuse_parent_compaction, goals, reasoning_effort_override, collaboration_modes, tool_call_mcp_elicitation, auth_elicitation, bedrock_setup_wizard, fast_mode, ultrafast_mode, realtime_conversation, tui_app_server, compaction_image_budget, retain_client_tool_outputs, workspace_dependencies",
        "feature flag overrides": "none",
        "feature flags enabled": "74",
        "log dir": "<tmp-codex-home>/log",
        "mcp servers": "0",
        "model": "<default>",
        "model provider": "openai",
        "sqlite home": "<tmp-codex-home>"
      },
      "remediation": null,
      "durationMs": 0
    },
    "git.environment": {
      "id": "git.environment",
      "category": "git",
      "status": "ok",
      "summary": "git executable found; execution not verified",
      "details": {
        "PATH git #1": "/usr/bin/git",
        "PATH git #2": "/bin/git",
        "PATH git entries": "2",
        "git execution": "not inspected (PATH helpers are not executed)",
        "repo detected": "false",
        "selected git": "/usr/bin/git"
      },
      "remediation": null,
      "durationMs": 0
    },
    "installation": {
      "id": "installation",
      "category": "install",
      "status": "ok",
      "summary": "installation looks consistent",
      "details": {
        "PATH codex #1": "<tmp-prefix>/node_modules/.bin/codex",
        "PATH codex #2": "<home>/.local/bin/codex",
        "PATH codex entries": "2",
        "current executable": "<tmp-prefix>/node_modules/@openai/codex-linux-x64/vendor/x86_64-unknown-linux-musl/bin/codex",
        "install context": "npm (package <tmp-prefix>/node_modules/@openai/codex-linux-x64/vendor/x86_64-unknown-linux-musl, bin <tmp-prefix>/node_modules/@openai/codex-linux-x64/vendor/x86_64-unknown-linux-musl/bin, resources <tmp-prefix>/node_modules/@openai/codex-linux-x64/vendor/x86_64-unknown-linux-musl/codex-resources, path <tmp-prefix>/node_modules/@openai/codex-linux-x64/vendor/x86_64-unknown-linux-musl/codex-path)",
        "managed by Vite+": "false",
        "managed by bun": "false",
        "managed by npm": "true",
        "managed by pnpm": "false",
        "managed package root": "<tmp-prefix>/node_modules/@openai/codex",
        "npm update target": "not inspected (PATH helpers are not executed)"
      },
      "remediation": null,
      "durationMs": 0
    },
    "mcp.config": {
      "id": "mcp.config",
      "category": "mcp",
      "status": "ok",
      "summary": "no MCP servers configured",
      "details": {},
      "remediation": null,
      "durationMs": 0
    },
    "network.env": {
      "id": "network.env",
      "category": "network",
      "status": "ok",
      "summary": "network-related environment looks readable",
      "details": {
        "managed proxy": "not configured",
        "proxy env vars": "none",
        "respect system proxy": "disabled"
      },
      "remediation": null,
      "durationMs": 0
    },
    "network.provider_reachability": {
      "id": "network.provider_reachability",
      "category": "reachability",
      "status": "fail",
      "summary": "one or more required provider endpoints are unreachable over HTTP",
      "details": {
        "ChatGPT inference URL": "http://127.0.0.1:9/backend-api/<redacted> connect failed (required)",
        "reachability mode": "ChatGPT auth"
      },
      "remediation": "Check proxy, VPN, firewall, DNS, and custom CA configuration.",
      "durationMs": 34
    },
    "network.websocket_reachability": {
      "id": "network.websocket_reachability",
      "category": "websocket",
      "status": "warning",
      "summary": "Responses WebSocket failed; HTTPS fallback may still work",
      "details": {
        "DNS": "2 IPv4, 2 IPv6, first IPv4",
        "auth mode": "none",
        "connect timeout": "15000 ms",
        "endpoint": "wss://api.openai.com/v1/<redacted>",
        "handshake transport error": "http 401 Unauthorized: [redacted]",
        "model provider": "openai",
        "provider name": "OpenAI",
        "proxy env vars": "none",
        "supports websockets": "true",
        "wire API": "responses"
      },
      "remediation": "Check proxy, VPN, firewall, DNS, custom CA, and WebSocket policy support.",
      "durationMs": 106
    },
    "runtime.provenance": {
      "id": "runtime.provenance",
      "category": "runtime",
      "status": "ok",
      "summary": "running npm on linux-x86_64",
      "details": {
        "commit": "unknown",
        "current executable": "<tmp-prefix>/node_modules/@openai/codex-linux-x64/vendor/x86_64-unknown-linux-musl/bin/codex",
        "install method": "npm (package <tmp-prefix>/node_modules/@openai/codex-linux-x64/vendor/x86_64-unknown-linux-musl, bin <tmp-prefix>/node_modules/@openai/codex-linux-x64/vendor/x86_64-unknown-linux-musl/bin, resources <tmp-prefix>/node_modules/@openai/codex-linux-x64/vendor/x86_64-unknown-linux-musl/codex-resources, path <tmp-prefix>/node_modules/@openai/codex-linux-x64/vendor/x86_64-unknown-linux-musl/codex-path)",
        "platform": "linux-x86_64",
        "version": "0.171.0"
      },
      "remediation": null,
      "durationMs": 0
    },
    "runtime.search": {
      "id": "runtime.search",
      "category": "search",
      "status": "ok",
      "summary": "search command found (bundled); execution not verified",
      "details": {
        "search command": "<tmp-prefix>/node_modules/@openai/codex-linux-x64/vendor/x86_64-unknown-linux-musl/codex-path/rg",
        "search command readiness": "file exists",
        "search provider": "bundled"
      },
      "remediation": null,
      "durationMs": 0
    },
    "sandbox.filesystem_paths": {
      "id": "sandbox.filesystem_paths",
      "category": "sandbox",
      "status": "ok",
      "summary": "no explicit filesystem paths to probe",
      "details": {},
      "remediation": null,
      "durationMs": 0
    },
    "sandbox.helpers": {
      "id": "sandbox.helpers",
      "category": "sandbox",
      "status": "ok",
      "summary": "sandbox configuration is readable",
      "details": {
        "approval policy": "OnRequest",
        "codex-linux-sandbox helper": "<tmp-prefix>/node_modules/@openai/codex-linux-x64/vendor/x86_64-unknown-linux-musl/bin/codex",
        "denied-read glob rules": "0",
        "denied-read rules": "0",
        "filesystem sandbox": "restricted",
        "glob scan max depth": "unbounded",
        "managed filesystem source": "none",
        "network sandbox": "restricted"
      },
      "remediation": null,
      "durationMs": 0
    },
    "security.endpoint": {
      "id": "security.endpoint",
      "category": "security",
      "status": "ok",
      "summary": "endpoint protection is not inspected on this platform",
      "details": {
        "endpoint products": "not inspected on this platform"
      },
      "remediation": null,
      "durationMs": 0
    },
    "state.paths": {
      "id": "state.paths",
      "category": "state",
      "status": "ok",
      "summary": "state paths and databases are inspectable",
      "details": {
        "CODEX_HOME": "<tmp-codex-home> (dir)",
        "active rollout files": "0 files, 0 total bytes, 0 average bytes",
        "archived rollout files": "0 files, 0 total bytes, 0 average bytes",
        "goals DB": "<tmp-codex-home>/goals_1.sqlite (missing)",
        "goals DB integrity": "skipped (missing)",
        "log DB": "<tmp-codex-home>/logs_2.sqlite (missing)",
        "log DB integrity": "skipped (missing)",
        "log dir": "<tmp-codex-home>/log (missing)",
        "memories DB": "<tmp-codex-home>/memories_1.sqlite (missing)",
        "memories DB integrity": "skipped (missing)",
        "memories v2 DB": "<tmp-codex-home>/memories_v2_1.sqlite (missing)",
        "memories v2 DB integrity": "skipped (missing)",
        "queue DB": "<tmp-codex-home>/queue_1.sqlite (missing)",
        "queue DB integrity": "skipped (missing)",
        "sqlite home": "<tmp-codex-home> (dir)",
        "state DB": "<tmp-codex-home>/state_5.sqlite (missing)",
        "state DB integrity": "skipped (missing)",
        "thread history DB": "<tmp-codex-home>/thread_history_1.sqlite (missing)",
        "thread history DB integrity": "skipped (missing)"
      },
      "remediation": null,
      "durationMs": 0
    },
    "state.rollout_db_parity": {
      "id": "state.rollout_db_parity",
      "category": "threads",
      "status": "ok",
      "summary": "no rollout/state DB inventory to compare",
      "details": {
        "default model provider": "openai",
        "rollout DB active files": "0",
        "rollout DB archived files": "0",
        "rollout DB malformed file names": "0",
        "rollout DB rows": "skipped (state DB missing)",
        "rollout DB scan cap reached": "false",
        "rollout DB scan errors": "0"
      },
      "remediation": null,
      "durationMs": 0
    },
    "system.disk": {
      "id": "system.disk",
      "category": "disk",
      "status": "ok",
      "summary": "sufficient free disk space (72.7 GiB)",
      "details": {
        "CODEX_HOME available": "72.7 GiB",
        "failure threshold": "1.0 GiB",
        "warning threshold": "5.0 GiB",
        "worktree available": "72.7 GiB"
      },
      "remediation": null,
      "durationMs": 0
    },
    "system.environment": {
      "id": "system.environment",
      "category": "system",
      "status": "ok",
      "summary": "OS language C",
      "details": {
        "EDITOR": "not set",
        "LANG": "C.UTF-8",
        "VISUAL": "not set",
        "os": "Ubuntu 24.4.0 (noble) [64-bit]",
        "os language": "C",
        "os type": "Ubuntu",
        "os version": "24.4.0"
      },
      "remediation": null,
      "durationMs": 9
    },
    "terminal.env": {
      "id": "terminal.env",
      "category": "terminal",
      "status": "ok",
      "summary": "terminal metadata was detected",
      "details": {
        "TERM": "xterm-256color",
        "color output": "disabled (stdout is not a terminal)",
        "effective locale": "C.UTF-8",
        "stderr is terminal": "false",
        "stdin is terminal": "true",
        "stdout is terminal": "false",
        "terminal": "unknown",
        "terminal size": "80x24"
      },
      "remediation": null,
      "durationMs": 0
    },
    "terminal.title": {
      "id": "terminal.title",
      "category": "title",
      "status": "ok",
      "summary": "terminal title default",
      "details": {
        "terminal title activity": "true",
        "terminal title items": "activity, project-name",
        "terminal title project source": "cwd",
        "terminal title project value": "<tmp-codex-home>",
        "terminal title source": "default"
      },
      "remediation": null,
      "durationMs": 0
    },
    "updates.status": {
      "id": "updates.status",
      "category": "updates",
      "status": "ok",
      "summary": "update configuration is locally consistent",
      "details": {
        "check for update on startup": "true",
        "latest version": "0.171.0",
        "latest version status": "current version is not older",
        "npm update target": "not inspected (PATH helpers are not executed)",
        "update action": "npm install -g @openai/codex",
        "version cache": [
          "<tmp-codex-home>/version.json",
          "missing"
        ]
      },
      "remediation": null,
      "durationMs": 206
    }
  }
}

</details>

What issue are you seeing?

When codex app-server --listen stdio:// receives a graceful shutdown via stdin EOF or SIGTERM while a background ChatGPT OAuth token refresh (POST /oauth/token) is in flight, app-server exits with code 0 (18 ms on stdin EOF; 24 ms on SIGTERM alone with stdin kept open) without waiting for the refresh response to be received and written to auth.json.

Because ChatGPT OAuth refresh tokens are single-use, once the authorization server has received POST /oauth/token and rotated rt-1 -> rt-2, closing the client socket before persisting rt-2 leaves auth.json holding the retired rt-1. The next Codex process then submits rt-1, receives 401 refresh_token_reused, and drops the login (account: null).

Observed behavior

  1. Proactive startup refresh (safe): When auth.json has an expired JWT or last_refresh older than the proactive refresh window, codex app-server awaits POST /oauth/token and persists the rotated token before answering initialize / the first RPC (measured 2367 ms with a 2000 ms mock OAuth delay; auth.json already contains rt-2 before the RPC reply reaches the client).
  2. Background 401-triggered refresh (dropped on exit): When last_refresh is recent, initialize and local RPCs (such as skills/list) return while background startup tasks hit /backend-api/ps/plugins/installed and /backend-api/wham/accounts/check. When those requests receive 401, they trigger POST /oauth/token. If the client closes stdin (EOF) or sends SIGTERM (keeping stdin open) while POST /oauth/token is in flight, app-server closes the socket and exits with code 0 (18 ms for EOF, 24 ms for SIGTERM) without persisting rt-2.
  3. Why the existing graceful drain misses it (checked at a0a30c40):
    • codex-rs/app-server/src/lib.rs:1395-1404 calls processor.drain_background_tasks().await on graceful shutdown (both stdin EOF and the Unix SIGTERM handler in codex-rs/app-server-transport/src/transport/stdio.rs:82-98).
    • codex-rs/app-server/src/message_processor.rs:922-928 cancels models_refresh_worker (without awaiting its task in codex-rs/app-server/src/models_refresh_worker.rs:19-21) and turn_cost_worker, then calls self.thread_processor.drain_background_tasks().await.
    • codex-rs/app-server/src/request_processors/thread_processor.rs:1448-1456 waits up to 10s, but only for thread_processor.background_tasks.
    • Background plugin startup tasks started at codex-rs/app-server/src/message_processor.rs:594-613 (maybe_start_plugin_startup_tasks_for_config) and in-flight refreshes inside AuthManager (codex-rs/login/src/auth/manager.rs:2236, refresh methods at lines 3474-3540) are outside that 10 s drain scope.

This was found during a shutdown-path audit using a local mock OAuth server; we do not have a field user report of it yet. In real use it would require a background request hitting 401 while last_refresh is still recent (for example, an access token invalidated or expiring server-side ahead of the local proactive refresh interval) right before a short-lived app-server closes.

Related: #41133 reports the same shutdown-persistence race for MCP OAuth refresh tokens; this issue reproduces it for ChatGPT auth.json.

What steps can reproduce the bug?

Run the self-contained Node.js 20+ script below with codex on PATH (no real account or external network access is used). The mock server resolves a promise the instant POST /oauth/token arrives, atomically rotates rt-1 -> rt-2, and waits 250 ms before sending the 200 OK response so the refresh is deterministically in flight when Process 1 shuts down. It runs two independent cases: stdin EOF alone (eof) and SIGTERM alone with stdin kept open (sigterm-only).

const http = require("node:http");
const { spawn } = require("node:child_process");
const { mkdtempSync, readFileSync, writeFileSync, rmSync } = require("node:fs");
const { tmpdir } = require("node:os");
const path = require("node:path");

function makeJwt(expOffsetSec) {
  const h = Buffer.from(JSON.stringify({ alg: "none", typ: "JWT" })).toString("base64url");
  const p = Buffer.from(JSON.stringify({
    email: "[email protected]",
    exp: Math.floor(Date.now() / 1000) + expOffsetSec,
    "https://api.openai.com/auth": {
      chatgpt_plan_type: "pro",
      chatgpt_account_id: "acct-repro",
      chatgpt_user_id: "user-repro",
    },
  })).toString("base64url");
  return `${h}.${p}.sig`;
}

async function runScenario(stopMode) {
  const dir = mkdtempSync(path.join(tmpdir(), `codex-repro-${stopMode}-`));
  let activeRefresh = "rt-1";
  let activeAccess = "at-1";
  const events = [];
  let onFirstOAuthReceived;
  const firstOAuthReceived = new Promise((r) => { onFirstOAuthReceived = r; });

  const server = http.createServer((req, res) => {
    let body = "";
    req.on("data", (c) => (body += c));
    req.on("end", () => {
      if (req.url === "/oauth/token") {
        let submitted = "";
        try { submitted = JSON.parse(body).refresh_token || ""; }
        catch { submitted = new URLSearchParams(body).get("refresh_token") || ""; }
        if (submitted !== activeRefresh) {
          events.push({ kind: "oauth_reuse_error", submitted, expected: activeRefresh });
          res.writeHead(401, { "content-type": "application/json" });
          res.end(JSON.stringify({ error: { code: "refresh_token_reused", message: "Refresh token already used" } }));
          return;
        }
        activeRefresh = "rt-2";
        activeAccess = "at-2";
        events.push({ kind: "oauth_rotated_on_server", from: submitted, to: activeRefresh });
        onFirstOAuthReceived();
        setTimeout(() => {
          events.push({ kind: "oauth_response_sent", to: activeRefresh, socketDestroyed: res.destroyed });
          if (!res.destroyed) {
            res.writeHead(200, { "content-type": "application/json" });
            res.end(JSON.stringify({
              id_token: makeJwt(3600),
              access_token: activeAccess,
              refresh_token: activeRefresh,
              token_type: "Bearer",
              expires_in: 3600,
            }));
          }
        }, 250);
        return;
      }
      if (req.headers.authorization !== `Bearer ${activeAccess}` || activeAccess === "at-1") {
        res.writeHead(401, { "content-type": "application/json" });
        res.end(JSON.stringify({ detail: "token expired" }));
        return;
      }
      res.writeHead(200, { "content-type": "application/json" });
      res.end(JSON.stringify({}));
    });
  });

  await new Promise((r) => server.listen(0, "127.0.0.1", r));
  const { port } = server.address();
  writeFileSync(path.join(dir, "config.toml"), `cli_auth_credentials_store = "file"\nchatgpt_base_url = "http://127.0.0.1:${port}/backend-api"\n`);
  writeFileSync(path.join(dir, "auth.json"), JSON.stringify({
    auth_mode: "chatgpt",
    tokens: { id_token: makeJwt(3600), access_token: "at-1", refresh_token: "rt-1", account_id: "acct-repro" },
    last_refresh: new Date(Date.now() - 60_000).toISOString(),
  }));

  const env = {
    HOME: dir, USERPROFILE: dir, CODEX_HOME: dir, PATH: process.env.PATH,
    CODEX_REFRESH_TOKEN_URL_OVERRIDE: `http://127.0.0.1:${port}/oauth/token`,
    HTTP_PROXY: "http://127.0.0.1:9", HTTPS_PROXY: "http://127.0.0.1:9",
    ALL_PROXY: "http://127.0.0.1:9", NO_PROXY: "127.0.0.1,localhost",
  };

  function runAppServer(rpcCalls, waitFor, mode) {
    return new Promise((resolve) => {
      const child = spawn("codex", ["app-server", "--listen", "stdio://"], { cwd: dir, env, stdio: ["pipe", "pipe", "pipe"] });
      let buf = "", nextId = 1;
      const pending = new Map();
      child.stdout.on("data", (d) => {
        buf += d.toString();
        const lines = buf.split("\n"); buf = lines.pop();
        for (const l of lines) {
          if (!l.trim()) continue;
          const m = JSON.parse(l);
          if (m.id && pending.has(m.id)) { pending.get(m.id)(m); pending.delete(m.id); }
        }
      });
      const rpc = (method, params) => new Promise((r) => {
        const id = nextId++;
        pending.set(id, r);
        child.stdin.write(JSON.stringify({ id, method, params }) + "\n");
      });
      (async () => {
        await rpc("initialize", { clientInfo: { name: "repro", version: "0" }, capabilities: { experimentalApi: true } });
        child.stdin.write(JSON.stringify({ method: "initialized", params: {} }) + "\n");
        const answers = [];
        for (const [m, p] of rpcCalls) answers.push(await rpc(m, p));
        if (waitFor) await waitFor;
        const tStop = Date.now();
        if (mode === "eof") child.stdin.end();
        else child.kill("SIGTERM"); // stdin stays open
        child.once("exit", (code, sig) => resolve({ answers, exitCode: code, signal: sig, stopToExitMs: Date.now() - tStop }));
      })();
    });
  }

  const p1 = await runAppServer([["skills/list", { cwds: [dir] }]], firstOAuthReceived, stopMode);
  const authAfterP1 = JSON.parse(readFileSync(path.join(dir, "auth.json"), "utf8"));
  await new Promise((r) => setTimeout(r, 300));
  const p2 = await runAppServer([["account/read", { refreshToken: true }]], null, "eof");
  const authAfterP2 = JSON.parse(readFileSync(path.join(dir, "auth.json"), "utf8"));

  console.log(JSON.stringify({
    stopMode,
    p1: { exitCode: p1.exitCode, signal: p1.signal, stopToExitMs: p1.stopToExitMs },
    authAfterP1: authAfterP1?.tokens?.refresh_token,
    p2: { exitCode: p2.exitCode, accountRead: p2.answers[0] },
    authAfterP2: authAfterP2?.tokens?.refresh_token,
    events,
  }, null, 2));
  server.close();
  rmSync(dir, { recursive: true, force: true });
}

(async () => {
  await runScenario("eof");
  await runScenario("sigterm-only");
})();

Measured output (codex-cli 0.171.0)

{
  "stopMode": "eof",
  "p1": { "exitCode": 0, "signal": null, "stopToExitMs": 18 },
  "authAfterP1": "rt-1",
  "p2": {
    "exitCode": 0,
    "accountRead": {
      "id": 2,
      "result": { "account": null, "userId": null, "requiresOpenaiAuth": true, "workspaceRouting": null }
    }
  },
  "authAfterP2": "rt-1",
  "events": [
    { "kind": "oauth_rotated_on_server", "from": "rt-1", "to": "rt-2" },
    { "kind": "oauth_response_sent", "to": "rt-2", "socketDestroyed": true },
    { "kind": "oauth_reuse_error", "submitted": "rt-1", "expected": "rt-2" }
  ]
}
{
  "stopMode": "sigterm-only",
  "p1": { "exitCode": 0, "signal": null, "stopToExitMs": 24 },
  "authAfterP1": "rt-1",
  "p2": {
    "exitCode": 0,
    "accountRead": {
      "id": 2,
      "result": { "account": null, "userId": null, "requiresOpenaiAuth": true, "workspaceRouting": null }
    }
  },
  "authAfterP2": "rt-1",
  "events": [
    { "kind": "oauth_rotated_on_server", "from": "rt-1", "to": "rt-2" },
    { "kind": "oauth_response_sent", "to": "rt-2", "socketDestroyed": true },
    { "kind": "oauth_reuse_error", "submitted": "rt-1", "expected": "rt-2" }
  ]
}

What is the expected behavior?

Include in-flight OAuth token refreshes in app-server's existing bounded graceful-shutdown drain (drain_background_tasks, currently bounded to 10 s for thread background tasks), so an already-dispatched POST /oauth/token exchange finishes persisting the rotated refresh_token to auth.json before app-server exits on stdin EOF or SIGTERM.

Additional information

We maintain OAR (botiverse/oar), a library that runs codex app-server for host applications and closes short-lived model-list, account-usage, and inventory queries via stdin EOF once they answer, which is why we audited this shutdown path. This report and reproduction were prepared and reviewed by AI agents working on OAR, and posted from xxchan's account with permission.


Agent Cindy wrote this for @xxchan through Stamp (grant cgr_33b7192d4ffb06ab8373a0083bd5e2ac)

Activity

  1. added
    bug
    CLI
    app-server
    auth
    on Nov 20, 2026
  2. media-ctrl commented on Nov 21, 2026

    @media-ctrl

    Checked at main f342aa7 and the gap is still where you describe it: drain_background_tasks (message_processor.rs:922) shuts down models_refresh_worker and turn_cost_worker, then drains the thread processor, called at lib.rs:1403. Nothing in that chain reaches AuthManager.

    Two things a fix can reuse. Refresh is already serialized by a one-permit semaphore: refresh_lock at manager.rs:2250, acquired across the IdP exchange at :3494 and :3549. The drain needs an accessor that acquires and drops it, which waits out an in-flight refresh; the field is private today, so that accessor is the change.

    Persisting late is safe: persist_tokens (:1760) takes the storage write lock and refuses the write unless the stored refresh and access tokens still match the ones this refresh was issued with, returning "Account credentials changed during refresh". An awaited late persist therefore cannot clobber a newer rotation and needs no new CAS.

    Timing: the SIGTERM path arms a hard exit at 45s (stdio.rs:217), sized for the 30s RPC drain, so the added wait must fit under it and must not observe the same cancellation that ends the connection, or it returns at once instead of draining.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    CLIapp-serverauthbug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions