Skip to content

app-server: concurrent initialization of a fresh CODEX_HOME exits with SQLite state runtime error #50290

Closed

Description

@xxchan

What version of Codex CLI is running?

codex-cli 0.160.0, native Linux x64 binary from @openai/codex-linux-x64.

What platform is your computer?

Linux x64, Node.js 24.19.0 for the reproduction driver.

What issue are you seeing?

Starting eight native codex app-server --listen stdio:// processes concurrently against one new CODEX_HOME makes most exit with code 1 before answering initialize:

Error: failed to initialize sqlite state runtime under /tmp/oar-codex-startup-.../shared-fresh-0: failed to initialize state runtime at /tmp/oar-codex-startup-.../shared-fresh-0

This reproduction invokes the native executable directly, without an npm wrapper or an OAR adapter. It uses a disposable home with only a config file, a dummy API key and a loopback provider URL. It sends no model request and needs no login.

What steps can reproduce the bug?

Save the dependency-free TypeScript script below as codex-concurrent-startup.ts, then use Node.js 24:

node codex-concurrent-startup.ts /absolute/path/to/native/codex 8 3

Pass the native executable, not the npm JavaScript or .cmd launcher. Each round creates new homes. The script sends initialize, then initialized on success, and keeps successful processes running until all starts settle. It captures each PID, home, startup/exit timestamps, exit status and a bounded stderr tail in oar-trial-run/codex-startup-*/report.json.

Observed controls

Two completed runs of this driver on 2026-10-02 gave the same totals (three rounds of eight starts per condition):

Startup condition Initialized Exit 1 with SQLite initialization error
Concurrent starts, one fresh shared home 3/24 21/24
Concurrent starts, independent fresh homes 24/24 0/24
Concurrent starts after one initialization and full exit on the shared home 24/24 0/24
Same fresh shared home, wait for each initialize before spawning the next; earlier processes stay alive 24/24 0/24

The failure happens during startup, not at the driver's 15-second observation deadline. This isolates a concurrent first-initialization failure; it does not identify the specific SQLite lock or migration operation.

Expected behavior

Several app-server processes should be able to initialize a new shared CODEX_HOME without most exiting. This can occur when parallel agents first start in a new container or user profile.

Additional information

Related: #42447 reports missing thread-index rows from concurrent first-run codex exec sessions on 0.150.1, and #30105 reports shared-home app-server startup failure on macOS. This report isolates a hard startup failure on 0.160.0 with no model turn or authentication. I have not established whether these share an underlying cause. Mature user homes, upgrades of existing databases, and Windows process teardown are not covered by this reproduction.

Complete native reproduction script (Node.js standard library only)
/**
 * Native initialization only: no login, model turn, OAR adapter or npm wrapper.
 * pnpm tsx experiments/codex-concurrent-startup.ts /path/to/native/codex [width=8] [rounds=3]
 * Uses disposable homes; reports observations rather than asserting a vendor guarantee.
 */
import assert from "node:assert/strict";
import { execFileSync, spawn } from "node:child_process";
import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";

const [command, widthArg, roundsArg] = process.argv.slice(2);
assert.ok(command !== undefined, "pass the native codex binary, not an npm .cmd or JS wrapper");
const binary = path.resolve(command);
const width = Number(widthArg ?? 8);
const rounds = Number(roundsArg ?? 3);
assert.ok(Number.isInteger(width) && width > 0 && Number.isInteger(rounds) && rounds > 0);
const version = execFileSync(binary, ["--version"], { encoding: "utf8", timeout: 5000 }).trim();
const root = await mkdtemp(path.join(tmpdir(), "oar-codex-startup-"));
const out = path.resolve("oar-trial-run", `codex-startup-${new Date().toISOString().replaceAll(":", "-")}`);
await mkdir(out, { recursive: true });

interface Observation {
  home: string;
  pid: number | null;
  startedAt: string;
  settledAt: string | null;
  exitedAt: string | null;
  kind: "starting" | "ready" | "rpc_error" | "spawn_error" | "stdin_error" | "exited" | "timeout";
  error: string | null;
  exitCode: number | null;
  signal: NodeJS.Signals | null;
  stderr: string;
}

async function home(name: string): Promise<string> {
  const directory = path.join(root, name);
  await mkdir(directory, { recursive: true });
  await writeFile(path.join(directory, "config.toml"), [
    'model = "gpt-5.1"', 'model_provider = "startup-probe"',
    "[model_providers.startup-probe]", 'name = "startup-probe"',
    'base_url = "http://127.0.0.1:1/v1"', 'env_key = "OAR_STARTUP_PROBE_KEY"', 'wire_api = "responses"', "",
  ].join("\n"));
  return directory;
}

interface ProbeChild {
  observation: Observation;
  initialized: Promise<void>;
  stop(): Promise<Observation>;
}

function start(directory: string): ProbeChild {
  let stderr = Buffer.alloc(0);
  const child = spawn(binary, ["app-server", "--listen", "stdio://"], {
    env: { ...process.env, CODEX_HOME: directory, OAR_STARTUP_PROBE_KEY: "local-probe" },
    stdio: ["pipe", "pipe", "pipe"],
  });
  const observation: Observation = {
    home: directory, pid: child.pid ?? null, startedAt: new Date().toISOString(),
    settledAt: null, exitedAt: null, kind: "starting", error: null,
    exitCode: null, signal: null, stderr: "",
  };
  const initialized = Promise.withResolvers<void>();
  const exited = Promise.withResolvers<void>();
  const timer = setTimeout(() => { settle("timeout", "initialize exceeded the probe's 15 s observation window"); }, 15_000);
  function settle(kind: Observation["kind"], error: string | null = null): void {
    if (observation.kind !== "starting") { return; }
    clearTimeout(timer);
    observation.kind = kind;
    observation.error = error;
    observation.settledAt = new Date().toISOString();
    initialized.resolve();
  }
  child.stderr.on("data", (chunk: Buffer) => { stderr = Buffer.from(Buffer.concat([stderr, chunk]).subarray(-8192)); });
  child.on("error", (error) => { settle("spawn_error", error.message); });
  child.stdin.on("error", (error) => { settle("stdin_error", error.message); });
  child.on("exit", (code, signal) => {
    observation.exitCode = code;
    observation.signal = signal;
    observation.exitedAt = new Date().toISOString();
    settle("exited");
  });
  // close follows exit and drains the last stderr bytes before recording them.
  child.on("close", () => { exited.resolve(); });
  let buffer = "";
  child.stdout.setEncoding("utf8").on("data", (chunk: string) => {
    buffer += chunk;
    const lines = buffer.split("\n");
    buffer = lines.pop() ?? "";
    for (const line of lines) {
      let message: unknown;
      try { message = JSON.parse(line); } catch { continue; }
      if (typeof message === "object" && message !== null && "id" in message && message.id === 1) {
        const error = "error" in message ? message.error : undefined;
        if (error === undefined) {
          child.stdin.write(`${JSON.stringify({ method: "initialized", params: {} })}\n`);
        }
        settle(error === undefined ? "ready" : "rpc_error", error === undefined ? null : JSON.stringify(error));
      }
    }
  });
  child.stdin.write(`${JSON.stringify({ id: 1, method: "initialize", params: {
    clientInfo: { name: "oar-startup-probe", version: "0.0.0" }, capabilities: { experimentalApi: true },
  } })}\n`);
  return {
    observation,
    initialized: initialized.promise,
    async stop(): Promise<Observation> {
      child.stdin.end();
      child.kill("SIGTERM");
      const force = setTimeout(() => { child.kill("SIGKILL"); }, 2000);
      await exited.promise;
      clearTimeout(force);
      observation.stderr = stderr.toString("utf8");
      return observation;
    },
  };
}

type Mode = "shared-fresh" | "isolated-fresh" | "shared-warm" | "shared-serial-start";
interface ProbeResult {
  mode: Mode;
  round: number;
  warmup: Observation | null;
  observations: Observation[];
}
async function probe(mode: Mode, round: number): Promise<ProbeResult> {
  const prefix = `${mode}-${String(round)}`;
  const directories = mode === "isolated-fresh"
    ? await Promise.all(Array.from({ length: width }, async (_, i) => { const directory = await home(`${prefix}-${String(i)}`); return directory; }))
    : Array.from({ length: width }, () => path.join(root, prefix));
  if (mode !== "isolated-fresh") { await home(prefix); }
  let warmup: Observation | null = null;
  if (mode === "shared-warm") {
    const [directory] = directories;
    assert.ok(directory !== undefined);
    const child = start(directory);
    await child.initialized;
    warmup = await child.stop();
  }
  const children: ProbeChild[] = [];
  for (const directory of directories) {
    const child = start(directory);
    children.push(child);
    // Each successful initialization precedes the next start in this control.
    // oxlint-disable-next-line no-await-in-loop
    if (mode === "shared-serial-start") { await child.initialized; }
  }
  await Promise.all(children.map(async (child) => { await child.initialized; }));
  const observations = await Promise.all(children.map(async (child) => { const observation = await child.stop(); return observation; }));
  const result = { mode, round, warmup, observations };
  await writeFile(path.join(out, `${prefix}.json`), `${JSON.stringify(result, null, 2)}\n`);
  process.stdout.write(`${prefix}: ${String(observations.filter((entry) => entry.kind === "ready").length)}/${String(width)} initialized\n`);
  return result;
}

const results = [];
for (const mode of ["shared-fresh", "isolated-fresh", "shared-warm", "shared-serial-start"] as const) {
  for (let round = 0; round < rounds; round += 1) {
    // Run controls separately so resource load from one does not confound another.
    // oxlint-disable-next-line no-await-in-loop
    results.push(await probe(mode, round));
  }
}
await writeFile(path.join(out, "report.json"), `${JSON.stringify({ binary, version, platform: process.platform, arch: process.arch, width, rounds, results }, null, 2)}\n`);
await rm(root, { recursive: true, force: true, maxRetries: 3, retryDelay: 300 });
process.stdout.write(`observations: ${out}\n`);

Activity

  1. added
    bug
    CLI
    app-server
    on Oct 2, 2026
  2. aetherxeg-source commented on Oct 2, 2026

    @aetherxeg-source

    A useful invariant here is shared state path != shared initialization ownership.

    Once several app-server processes can target the same fresh CODEX_HOME, first-run schema creation/migration becomes a distributed initialization event. The runtime should make one process the initializer and make the others observe or wait for that same initialization generation, rather than each inferring readiness from filesystem presence.

    I would model it explicitly as:

    home identity -> initialization generation -> initializer lease -> committed schema/version -> ready

    Only the committed ready state should authorize normal startup. A process that loses the initializer race should either join that generation or fail with a typed conflict; it should not run a partially initialized state.

    A strong fault-injection test would kill the initializer at several points between DB creation and migration commit, then start another process and prove the new process can distinguish never initialized, initialization in progress, abandoned generation, and committed ready without treating file existence as readiness.

  3. aetherxeg-source commented on Oct 2, 2026

    @aetherxeg-source

    A startup-state invariant here is:

    schema initialization ownership must be singular even when process startup is concurrent

    A fresh shared CODEX_HOME is qualitatively different from an already-initialized shared home: multiple processes are racing not just to open state, but to establish the initial schema/runtime generation.

    I would model bootstrap as an idempotent lease/transaction:

    home identity -> bootstrap generation -> one initializer -> durable schema commit -> many readers/openers

    Other processes may wait or retry against the committed generation, but should not independently perform partially overlapping first-run initialization.

    A useful fault matrix would cover 8 simultaneous starters, initializer crash before commit, crash after schema commit but before success acknowledgement, and two processes observing an empty home at the same instant. After recovery, exactly one valid schema generation should exist and every surviving process should either initialize against it or fail with an explicit retryable bootstrap state.

    The warm-home control in this report is especially valuable: if 24/24 succeeds after one complete initialization, the invariant to test is not generic SQLite concurrency but atomic publication of the first state-runtime generation.

  4. goodman-oai commented on Nov 16, 2026

    @goodman-oai
    Contributor

    The concurrent-startup fix in #59015 shipped in 0.168.0. In a macOS arm64 test, eight app-servers started together against a fresh shared home. Across three rounds, 3 of 24 initialized on 0.160.0 and all 24 initialized on 0.169.0. Both versions passed the separate-home and prewarmed-home controls. Released regression test.

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

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions