Skip to content

[Windows] "Organization settings could not be loaded" caused by state DB backfill stuck in running after crash — app-server times out after 30s #52836

Closed as duplicate

Description

@allvegetable

Environment

  • Codex Desktop (MSIX): OpenAI.Codex 26.1007.2314.0
  • Bundled CLI: codex-cli 0.162.0-alpha.17.2
  • Windows 11 x64 (build 26200), non-ASCII user profile, CODEX_HOME=D:\codex-data
  • Large history (~1 GB thread_history_1.sqlite)

Symptom

After the app quit/crashed (likely during auto-update), every launch showed
"Organization settings could not be loaded". Reboot, Retry, sign out, moving
config.toml aside, restarting CodexSandboxService did not help. No new desktop
log file was written.

Root cause

Running the bundled app-server manually showed:

state db backfill is running at D:\codex-data; waiting up to 30s before retrying startup initialization
Error: failed to initialize sqlite state runtime under D:\codex-data: timed out waiting for state db backfill at D:\codex-data after 30s (status: running)

state_5.sqlite -> backfill_state row was (1, 'running', NULL, NULL, ...)
and never completed. Each desktop launch restarts the backfill, but it takes
longer than the desktop startup deadline, so the app-server is killed and the
row is left in running again. Subsequent launches see running, wait 30s,
and fail -> the generic network-flavoured dialog. A dead loop.

Workaround that fixed it

  1. Quit the app, back up state_5.sqlite (+ -wal, -shm)
  2. UPDATE backfill_state SET status='pending' WHERE id=1;
  3. Run codex.exe app-server standalone (no desktop) and let it finish the
    backfill (~90s here) until status becomes complete
  4. Launch the desktop app normally -> works

Suggestions

  • Detect a stale running backfill (owner process gone) and reset/resume it
    instead of waiting
  • Don't let the desktop startup deadline kill an in-progress backfill
  • Surface the real error instead of "network/proxy/firewall"

Activity

  1. added
    bug
    app
    windows-os
    app-server
    on Oct 10, 2026
  2. github-actions commented on Oct 10, 2026

    @github-actions
    Contributor

    Potential duplicates detected. Please review them and close your issue if it is a duplicate.

    Powered by Codex Action

  3. TBaltensperger commented on Oct 12, 2026

    @TBaltensperger

    Identity: TBaltensperger @ nuitio/devcontainer

    An independent Linux reproduction adds evidence for the abandoned-backfill failure described here. With Codex CLI 0.159.3 on Linux x86_64 and an isolated temporary home, I generated 64 synthetic rollouts (about 60 MB), started the native app-server, and sent SIGINT only after a read-only probe observed its native backfill claim as running. The next native startup reproduced the 30-second timeout with status: running after 30.30 seconds; SQLite integrity remained ok. The experiment did not edit database rows or use customer history.

    The steps and exact output are documented in nuitio/devcontainer#297. This confirms the stale-claim startup failure on Linux as well as the Windows report here; it does not establish what interrupted the customer's original worker. The same timestamp-lease mechanics are present in the 0.159.3 backfill startup code and worker lease code.

  4. TBaltensperger commented on Oct 12, 2026

    @TBaltensperger

    Identity: TBaltensperger @ nuitio/devcontainer

    Customer-report addendum to the earlier Linux reproduction: nuitio/devcontainer#297, updated 2026-10-12, now reports Codex CLI 0.159.3 on Linux x86_64 recovering without SQLite edits. In the failing write-mode home, a later read-only diagnostic found a running claim (updated_at=1791784367) aged 3,015 seconds; the supplied process snapshot reported no Codex worker. The matching shim's doctor reported a healthy database with rollouts missing from its index. A subsequent codex-write resume in the same terminal started successfully, with no database-row modification reported.

    This is the customer's report recorded in that issue, not my independent first-hand verification. The later age exceeds the 900-second native lease and is consistent with native expiry/reclaim; it does not establish the lease age at the earlier 30-second failure or trace the reclaim transaction. It also does not establish what interrupted the original worker. This adds a real-consumer, no-SQL recovery sequence alongside the existing isolated reproduction; no SQL workaround is proposed.

  5. TBaltensperger commented on Oct 13, 2026

    @TBaltensperger

    Identity: TBaltensperger @ nuitio/devcontainer

    This evidence comes from nuitio/devcontainer, a private repository that ships a dev-container image running the pinned Codex CLI 0.159.3. This comment replaces the private links in my two earlier comments here: all the evidence is below. The customer report summarized in my second comment is not relied on here.

    Rerun on 0.159.3 and on 0.162.1, the latest release, on Linux x86_64 with the native binaries from npm. Both runs used throwaway homes and only synthetic history: 64 generated rollouts of about 1 MB each, no real sessions and no credentials. The database was only ever opened read-only (mode=ro); no row was edited.

    Result, identical on both versions

    Step 0.159.3 0.162.1
    1. app-server + initialize, SIGINT once the claim reads running claim at 1.72 s; killed by signal 2 after 1.78 s; row stays status=running, last_watermark=None claim at 1.38 s; killed by signal 2 after 1.56 s; row stays status=running, last_watermark=None
    2. Restart right away exit code 1 after 31.51 s: timed out waiting for state db backfill … after 30s (status: running); updated_at unchanged exit code 1 after 31.42 s, same error; updated_at unchanged
    3. Restart ~937 s after the claim, once the 900 s lease has expired initialize answered after 2.15 s; status=complete, threads=64 initialize answered after 2.24 s; status=complete, threads=64

    Output from 0.162.1 (0.159.3 is the same apart from the timings and timestamps):

    codex: codex-cli 0.162.1
    == 1: start, interrupt after claim
    claim observed after 1.38s: status=running updated_at=1791909033; sending SIGINT
    exited after 1.56s: killed by signal 2
    backfill_state: status=running updated_at=1791909033 last_watermark=None threads=1; age 0s
    == 2: restart
    exited after 31.42s: exit code 1
    stderr: state db backfill is running at $CODEX_HOME; waiting up to 30s before retrying startup initialization
    stderr: Error: failed to initialize sqlite state runtime under $CODEX_HOME: timed out waiting for state db backfill at $CODEX_HOME after 30s (status: running)
    backfill_state: status=running updated_at=1791909033 last_watermark=None threads=1; age 32s
    == 3: restart after the 900 s lease expires
    initialize answered after 2.24s; stopping server
    exited after 2.47s: exit code 0
    backfill_state: status=complete updated_at=1791909972 last_watermark=sessions/2026/01/01/rollout-2026-01-01T01-03-00-<uuid>.jsonl threads=64; age 1s
    

    Once the lease had expired, the whole backfill and initialize together took about 2 s. One interruption had locked the home for 15 minutes, and the only thing that freed it was the lease expiring. Two points stand out. The interrupted process didn't release anything: SIGINT killed it with the default signal action, so it got no chance to clean up. And the failing restart doesn't touch the claim either, so every startup within the 900 s window fails the same way and recovery depends on wall-clock time alone. That matches the dead loop in the report: a desktop deadline that kills each new worker after it has claimed renews the lease every launch.

    Where it comes from (main at cb7091b)

    • The claim is a timestamp only. try_claim_backfill sets status='running', updated_at=now. A running row is taken over only once updated_at <= now - lease. The runtime has functions to claim, checkpoint and complete, but none that releases a claim back to pending (backfill.rs#L46-L103).
    • The table has no owner column. 0008_backfill_state.sql holds id, status, last_watermark, last_success_at, updated_at and nothing more, and no later migration changes backfill_state.
    • The lease is 900 s, and it's refreshed only once per 200-rollout batch. BACKFILL_LEASE_SECONDS = 900, BACKFILL_BATCH_SIZE = 200. The claim is taken in metadata.rs#L222-L238. updated_at moves again only at the per-batch checkpoint_backfill. There is no heartbeat, so a live worker whose batch takes longer than 900 s also loses its lease, and with fewer than 200 rollouts the watermark is never checkpointed before completion (last_watermark=None above).
    • The startup gate waits 30 s, then fails. STARTUP_BACKFILL_WAIT_TIMEOUT = 30 s. wait_for_backfill_gate runs the backfill inline, retries the claim every second, and then returns timed out waiting for state db backfill … (status: running). That message names neither the owner nor the claim's age.
    • The backfill runs before app-server sets up its transport and signal handling. State init (which runs the backfill gate inline) comes before the stdio transport setup, which takes the signal-handler option, and before the main loop's shutdown_signal(). That matches what was observed: SIGINT during backfill kills the process outright (signal 2 above).

    Fix direction

    Recording the owner is what #37003 asks for (host or PID namespace, PID, process start identity, and taking over a confirmed-dead owner); this reproduction is evidence for it. The parts below go beyond that issue:

    1. Record the owner and keep a heartbeat. Store a boot id, PID and process start time with the claim, and refresh updated_at on a timer instead of once per batch. A starting process takes over at once when the recorded owner is provably dead: the same boot id and the PID is gone or its start time differs. When it can't prove that (another host, another namespace), it falls back to the lease.
    2. Release on graceful shutdown or cancellation. On SIGINT, SIGTERM or a cancelled startup, set the row back to pending and keep last_watermark, so the next start resumes instead of waiting. That needs the backfill to be cancellable, or the signal handler installed before state init.
    3. Name the owner and the claim's age in the startup error, for example state db backfill claimed by pid 1234 (started …, boot …) 37 s ago; lease expires in 863 s. Then the desktop and other embedders can show something more accurate than a network-flavoured dialog.

    A fix shouldn't require editing SQLite by hand: once the owner is recorded and the claim is released on shutdown, no manual repair is needed.

    Reproduction script

    Run it as bash repro-backfill-lease.sh [codex-binary] [1 to also wait out the lease]. It needs bash and python3. It creates its own mktemp -d home and opens the database read-only.

    #!/usr/bin/env bash
    # Reproduce: an interrupted state-DB backfill keeps its `running` claim, and the
    # next startup fails after ~30 s until the 900 s lease expires.
    # Synthetic history only, throwaway CODEX_HOME, no credentials; the database is only read.
    # Usage: repro-backfill-lease.sh [codex-binary] [wait-for-expiry: 0|1]
    set -euo pipefail
    CODEX=${1:-codex}; WAIT_EXPIRY=${2:-0}
    T=$(mktemp -d); export CODEX_HOME="$T/codex-home"; mkdir -p "$CODEX_HOME" "$T/work"
    echo "codex: $("$CODEX" --version 2>/dev/null)"
    
    # 64 synthetic rollouts (~1 MB each) from a minimal session_meta + user-message shape.
    python3 - "$CODEX_HOME" <<'PY'
    import json, os, sys, uuid, datetime
    home = sys.argv[1]
    for i in range(64):
        ts = datetime.datetime(2026, 1, 1, tzinfo=datetime.timezone.utc) + datetime.timedelta(minutes=i)
        tid, iso = str(uuid.uuid4()), ts.strftime("%Y-%m-%dT%H:%M:%S.000Z")
        d = os.path.join(home, "sessions", ts.strftime("%Y/%m/%d")); os.makedirs(d, exist_ok=True)
        with open(os.path.join(d, f"rollout-{ts.strftime('%Y-%m-%dT%H-%M-%S')}-{tid}.jsonl"), "w") as f:
            f.write(json.dumps({"timestamp": iso, "type": "session_meta", "payload": {
                "id": tid, "timestamp": iso, "cwd": "/tmp", "originator": "repro",
                "cli_version": "0.0.0", "source": "cli", "model_provider": "openai"}}) + "\n")
            for _ in range(250):
                f.write(json.dumps({"timestamp": iso, "type": "response_item", "payload": {
                    "type": "message", "role": "user",
                    "content": [{"type": "input_text", "text": "x" * 4000}]}}) + "\n")
    PY
    
    # Run app-server, send initialize; optionally SIGINT it once the claim reads `running`.
    run() {  # $1 = interrupt|plain
    python3 - "$CODEX" "$CODEX_HOME/state_5.sqlite" "$1" "$T/work" <<'PY'
    import json, os, select, signal, sqlite3, subprocess, sys, time
    codex, db, mode, cwd = sys.argv[1:]
    def state():
        try:
            c = sqlite3.connect(f"file:{db}?mode=ro", uri=True, timeout=1)
            r = c.execute("SELECT status, updated_at, last_watermark, (SELECT COUNT(*) FROM threads)"
                          " FROM backfill_state WHERE id=1").fetchone(); c.close()
            return r
        except sqlite3.Error:
            return None
    err = open(os.path.join(cwd, "stderr.log"), "w+")
    t0 = time.time()
    p = subprocess.Popen([codex, "app-server"], cwd=cwd, stdin=subprocess.PIPE,
                         stdout=subprocess.PIPE, stderr=err, text=True)
    p.stdin.write(json.dumps({"id": 1, "method": "initialize", "params": {
        "clientInfo": {"name": "repro", "title": None, "version": "0"}}}) + "\n"); p.stdin.flush()
    if mode == "interrupt":
        while (s := state()) is None or s[0] != "running":
            if p.poll() is not None: sys.exit(f"exited before claiming backfill: {s}")
            time.sleep(0.05)
        print(f"claim observed after {time.time()-t0:.2f}s: status={s[0]} updated_at={s[1]}; sending SIGINT")
        p.send_signal(signal.SIGINT)
        try: p.wait(60)
        except subprocess.TimeoutExpired: p.kill(); p.wait()
    else:
        while time.time() < t0 + 120:
            if select.select([p.stdout], [], [], 0.5)[0]:
                line = p.stdout.readline()
                if not line: break
                if json.loads(line).get("id") == 1:
                    print(f"initialize answered after {time.time()-t0:.2f}s; stopping server"); break
        if p.poll() is None: p.stdin.close(); p.terminate(); p.wait(10)
    rc = p.returncode
    print(f"exited after {time.time()-t0:.2f}s: " + (f"killed by signal {-rc}" if rc < 0 else f"exit code {rc}"))
    err.seek(0)
    for line in err.read().splitlines():
        if "backfill" in line: print("stderr:", line.replace(os.path.dirname(db), "$CODEX_HOME"))
    s = state(); print(f"backfill_state: status={s[0]} updated_at={s[1]} last_watermark={s[2]} threads={s[3]}; age {int(time.time()) - s[1]}s")
    PY
    }
    echo "== 1: start, interrupt after claim"; run interrupt
    echo "== 2: restart";                     run plain
    if [ "$WAIT_EXPIRY" = 1 ]; then
      echo "== 3: restart after the 900 s lease expires"; sleep 905; run plain
    fi

    Not verified

    • Only Linux x86_64 was tested; the Windows and desktop path in the report wasn't.
    • SIGKILL and power loss weren't tried. They would leave the row in the same state, because nothing can release a claim then, which is why recording the owner matters.
    • The 0.163.0 alpha pre-releases weren't tested.
    • No patch was built.
  6. goodman-oai commented on Nov 16, 2026

    @goodman-oai
    Contributor

    Tracking this in #37003. An interrupted SQLite backfill leaves a running claim, and the next app-server start times out after 30 seconds. A controlled reproduction on this issue confirmed the immediate retry left the claim unchanged and a later retry succeeded after the lease expired. Reproduction.

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

    appapp-serverbugwindows-os

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions