Skip to content

Windows desktop app 26.928.2636.0 fails to start: "failed to initialize sqlite state runtime" #49653

Open

Description

@henrickfrankie

Version: Codex desktop 26.928.2636.0 (Microsoft Store), bundled codex-cli 0.159.2, Windows 11 (10.0.26200)

Since the auto-update today (~12:02) the app fails on every launch on two machines:
"ChatGPT failed to start. (code=1, signal=null). Most recent error: Error: failed to initialize sqlite state runtime under C:\Users<user>.codex: failed to initialize state runtime at C:\Users<user>.codex"

codex-desktop-log-redacted.log

Findings:

  • Restart/reboot does not help (one machine worked once after a restart, the other does not).
  • Moving state_5.sqlite* aside (fresh DB is created and fully migrated, 58/58) does not help.
  • codex doctor reports all DBs healthy (integrity ok), 0 failures.
  • Running the same codex.exe with the app's exact flags (app-server --analytics-default-enabled ...) from a shell stays up without errors. The failure only happens when launched by the desktop app (exits ~190 ms after spawn, code=1).
  • Desktop log shows right before the failure: "Failed to repair missing thread cwd metadata errorName=SqliteError".

Log: %LOCALAPPDATA%\Packages\OpenAI.Codex_2p2nqsd0c76g0\LocalCache\Local\Codex\Logs\2026\09\30\codex-desktop-*.log (attached)

Activity

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

    @github-actions
    Contributor

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

    Powered by Codex Action

  3. medking82 commented on Oct 3, 2026

    @medking82

    Additional Windows recurrence matching this issue, including the warning immediately before failure:

    • Windows 11 Pro for Workstations, 10.0.26300, x64.
    • Microsoft Store package identity: OpenAI.Codex.
    • Two observed failures on 2026-10-03: 02:44:01 UTC on desktop 26.930.3748.0 and 05:19:25 UTC on desktop 26.930.3930.0.
    • The current 26.930.3930.0 bundled executable reports codex-cli 0.160.0.
    • Both launches emit Failed to repair missing thread cwd metadata errorName=SqliteError, followed by app-server exit code 1 and the same generic SQLite state-runtime initialization error.
    • Handshake failure durations: 1081 ms and 893 ms, respectively.
    • A subsequent launch of 26.930.3930.0 at 05:20:17 UTC succeeded (handshake 274 ms). No repair was performed during this investigation; earlier changes between attempts were not audited.

    Read-only checks after the successful launch:

    • PRAGMA quick_check returned ok for state_5.sqlite, logs_2.sqlite, goals_1.sqlite, memories_1.sqlite, queue_1.sqlite, and sqlite/codex-dev.db.
    • The latest eight state_5.sqlite migration records, through version 58, have success=1.
    • C: has approximately 640 GB free.
    • A bounded quick_check of thread_history_1.sqlite was interrupted by the diagnostic time limit; its integrity was not established.

    These checks describe the current state. They do not establish the underlying cause at failure time or rule out a transient lock/mapping/schema problem. The fatal message omits the failing database and leaf SQLite error, so the specific cause remains unknown.

    There is also a secondary recovery failure, relevant to #47138:

    At 05:19:26 and 05:19:34 UTC, automatic/manual startup-recovery update checking failed with net::ERR_BLOCKED_BY_CLIENT. The immediately preceding updater log reports policy=pending.

    Read-only inspection of the installed 26.930.3930.0 app archive shows:

    1. The Store updater fetches the production update manifest using electron.net.fetch.
    2. The session request hook cancels URLs disallowed by the application network policy.
    3. Until that policy is ready, the hook passes a null policy; the policy helper rejects HTTPS requests in that state.

    The configured production manifest is https://persistent.oaistatic.com/codex-app-prod/windows-store-update.json. This is inferred from package configuration; no live request trace was captured.

    This supports an application-internal block while startup policy is pending, rather than attributing the updater error to external network filtering. It also means the offered recovery update check cannot complete in this observed startup-failure state.

    Could startup diagnostics retain the failing database/operation and full SQLite error chain, and could recovery update checks work safely when normal startup policy cannot finish loading? A fix should preserve configured network requirements rather than disable them.

    The failure is intermittent; no deterministic reproduction was attempted against live account/session data. No database reset, configuration edit, process termination, reinstall, or update was performed in this investigation. Full account/session data and full desktop logs are intentionally omitted.

  4. medking82 commented on Oct 3, 2026

    @medking82

    Isolated Windows SHM reproduction and proposed lifecycle repair (CLI 0.160.0)

    Following up with a deterministic reproduction using newly generated Codex data, not my existing sessions or credentials. Related: #49605 and #47138.

    Environment: Windows 11 x64 build 26300; Microsoft Store desktop 26.930.3930.0; its bundled codex-cli 0.160.0; Python 3.12. No desktop binary replacement was performed.

    Reproduction results

    Condition Initialize Exit
    New isolated home, normal first startup Success 0
    SQLite connection closed, independent mapping of state_5.sqlite-shm retained Failure 1
    Mapping released, same file handle still open Success 0
    Mapping and file handle both released Success 0

    The failed case produces exactly the generic error from this issue:

    Error: failed to initialize sqlite state runtime under %ISOLATED_HOME%:
    failed to initialize state runtime at %ISOLATED_HOME%
    

    A separate native Windows check against the isolated mapped SHM file confirmed that SetEndOfFile refuses to reset it with error 1224 (ERROR_USER_MAPPED_FILE). That is a mechanism check, not a trace of the internal SQLite syscall. A Python SQLite read-only-style query can still open this DB while the mapping remains, so a healthy/simple read does not establish that the runtime initialization path can succeed.

    The connection is already closed in the failure case. The open-file-only control succeeds; the retained mapped section is the distinguishing input. Releasing it restores startup without rebuilding or replacing any database.

    This reproduces a Windows state-runtime failure mechanism and matches the visible incident error. It does not retrospectively prove that my two earlier desktop incidents were caused by this mapping race; the incident logs omit the leaf cause, and no process/mapping trace was captured at those times. The initial isolated probe had an invalid transport argument; the results above are from the corrected, independently tested stdio:// reproducer below.

    Proposed upstream changes

    1. Coordinate app-server replacement with confirmed process exit. Retain the original process handle before requesting termination; await its completion before initializing a replacement against the same SQLite home. Do not infer completion solely from a missing PID/path discovery entry. Account for other supported clients sharing the home; do not terminate unrelated clients.
    2. Handle the specific transient mapped-file initialization failure with a bounded retry. Preserve its typed OS/SQLite cause, close partial pools, and retry only when the failure is positively identified as transient. Do not classify it as corruption or invoke DB rebuild merely because the outer initialization error is generic. The appropriate SQLite extended-error mapping and retry bound need an upstream implementation/test, not a catch-all retry.
    3. Expose the full cause chain. The app-server/src/lib.rs fatal formatting currently collapses it with {err}. Prefer {err:#} (including the sibling recovery failure path) so the failing DB, operation and underlying cause survive into logs/dialog diagnostics.
    4. Keep startup update recovery usable under pending requirements policy. Our earlier read-only package inspection showed updater electron.net.fetch going through a session hook that rejects HTTPS while policy is pending. A narrowly approved recovery request path should preserve configured network requirements; globally disabling them is not a repair.

    Suggested upstream regression: generate an isolated home, retain the old SHM mapping after the connection closes, attempt replacement initialization, release the mapping, and verify bounded recovery plus preservation of existing DB data. Also assert that startup diagnostics contain the underlying DB/operation/cause. Separately test update recovery before normal policy readiness.

    Local mitigation already implemented

    Our existing browser native-host maintenance script had a narrower process-exit verification gap: roughly two seconds of path-filtered polling after termination. It now retains the verified process handles and uses a 30-second shared confirmation budget before runtime replacement, failing closed on timeout or a newly detected replacement process. It revalidates path ownership before stopping, disposes handles and preserves backups. The existing scheduled-task configuration is unchanged.

    This passed five regression cases (delayed exit/path disappearance, timeout, replacement process, already-exited target, identity/path change) under Windows PowerShell 5.1 and PowerShell 7, plus a real isolated Windows process-handle check. The updated script is deployed locally and the extension health check remains healthy. This hardens our browser maintenance; it is not a patch to the desktop app's own startup lifecycle and is not a claim that the desktop incidents are permanently resolved.

    Standalone reproducer

    Run on Windows with the installed/bundled codex.exe and Python 3. Choose a new workspace directory. The script never copies or changes an existing Codex home, does not require credentials, and only stops diagnostic processes it creates.

    python reproduce-stale-shm.py --runtime <absolute-path-to-codex.exe> --workspace <new-isolated-directory>
    
    """Windows-only isolated reproducer. Requires Python 3 and a Codex runtime."""
    import argparse
    import json
    import mmap
    import os
    from pathlib import Path
    import queue
    import sqlite3
    import subprocess
    import threading
    import time
    
    parser = argparse.ArgumentParser()
    parser.add_argument("--runtime", type=Path, required=True)
    parser.add_argument("--workspace", type=Path, required=True,
                        help="A new directory for generated test data; must not exist")
    args = parser.parse_args()
    runtime = args.runtime.resolve(strict=True)
    home = args.workspace.resolve()
    home.mkdir(parents=True, exist_ok=False)
    (home / "config.toml").write_text("[analytics]\nenabled=false\n[feedback]\nenabled=false\n", encoding="utf-8")
    
    
    def launch(case):
        env = os.environ.copy()
        env["CODEX_HOME"] = str(home)
        env.pop("CODEX_SQLITE_HOME", None)
        proc = subprocess.Popen([str(runtime), "app-server", "--listen", "stdio://"],
                                cwd=home, env=env, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE, text=True, encoding="utf-8", errors="replace",
                                creationflags=subprocess.CREATE_NO_WINDOW)
        messages, errors = queue.Queue(), []
    
        def stdout_reader():
            for line in proc.stdout:
                messages.put(line)
    
        def stderr_reader():
            for line in proc.stderr:
                errors.append(line.strip())
    
        readers = [threading.Thread(target=stdout_reader, daemon=True), threading.Thread(target=stderr_reader, daemon=True)]
        for reader in readers:
            reader.start()
        started, initialized = time.monotonic(), False
        try:
            proc.stdin.write(json.dumps({"id": 1, "method": "initialize", "params": {
                "clientInfo": {"name": "isolated_shm_repro", "version": "1"},
                "capabilities": {"experimentalApi": True}}}) + "\n")
            proc.stdin.flush()
            while time.monotonic() - started < 40:
                if proc.poll() is not None and messages.empty():
                    break
                try:
                    message = json.loads(messages.get(timeout=0.1))
                except (queue.Empty, json.JSONDecodeError):
                    continue
                if message.get("id") == 1:
                    initialized = "result" in message
                    break
        finally:
            proc.stdin.close()
            try:
                proc.wait(timeout=5)
            except subprocess.TimeoutExpired:
                # Stop only the process created by this test against the new home.
                proc.terminate()
                proc.wait(timeout=10)
            for reader in readers:
                reader.join(timeout=2)
        result = {"case": case, "initialized": initialized, "exit_code": proc.returncode,
                  "errors": [line.replace(str(home), "%ISOLATED_HOME%") for line in errors if "Error:" in line]}
        print(json.dumps(result), flush=True)
        return result
    
    
    baseline = launch("baseline")
    if not baseline["initialized"]:
        raise RuntimeError("Baseline did not initialize; this is not the SHM reproduction")
    connection = sqlite3.connect(home / "state_5.sqlite")
    connection.execute("SELECT name FROM sqlite_master LIMIT 1").fetchall()
    with (home / "state_5.sqlite-shm").open("r+b") as shm_file:
        with mmap.mmap(shm_file.fileno(), 0) as retained_mapping:
            connection.close()  # The connection is gone; its independent mapping remains.
            held = launch("old-shm-mapping-retained")
        released_mapping = launch("mapping-released-file-handle-still-open")
    released = launch("old-shm-mapping-released")
    assert not held["initialized"] and held["exit_code"] == 1, "Expected mapped-SHM startup failure was not reproduced"
    assert released_mapping["initialized"] and released_mapping["exit_code"] == 0, "An open file handle alone still blocked startup"
    assert released["initialized"] and released["exit_code"] == 0, "Startup did not recover after releasing the mapping"
    (home / "results.json").write_text(json.dumps([baseline, held, released_mapping, released], indent=2), encoding="utf-8")
    print("PASS: healthy fresh data -> retained mapping failure -> release recovery; no existing home touched")
  5. Jaws17935 commented on Oct 6, 2026

    @Jaws17935

    Another Windows recurrence, still present on 26.930.7945.0 (bundled codex-cli 0.160.1). Related: #49605.

    Environment: Windows 11 Pro 10.0.26300 x64, Microsoft Store package OpenAI.Codex, auto-update on, sandbox = "elevated". Antivirus: Bitdefender (no Cisco Secure Endpoint).

    Pattern: it only happens on the relaunch right after a Store auto-update.
    Since 2026-09-23 (oldest retained desktop log), 2 of 13 update restarts failed. I found no failures on launches that were not update restarts.

    update_resume_state_saved (UTC) Next launch Version launched Result
    2026-10-03 09:02:10 09:02:39 26.930.3930.0 failed
    2026-10-06 11:43:02 11:43:16 26.930.7945.0 failed
    11 other update restarts, 09-22 to 10-05 1.8 to 50.9 s later various ok

    The gap between the update shutdown and the next launch does not separate failures from successes. Several successful relaunches had shorter gaps.

    Same marker as reported above. In both failures the desktop host's own SQLite step fails about 0.2 s after launch, before the app-server is spawned:

    2026-10-03T09:02:39.425Z warning Failed to repair missing thread cwd metadata errorName=SqliteError
    2026-10-06T11:43:16.602Z warning Failed to repair missing thread cwd metadata errorName=SqliteError
    

    That line is absent from every successful launch in my logs. Then the app-server exits with code 1 about 1.1 s later with the generic failed to initialize sqlite state runtime error. In the failure dialog, "Check for Updates" fails with net::ERR_BLOCKED_BY_CLIENT, which matches the pending-policy analysis above.

    What I checked (read-only or on copies):

    • PRAGMA quick_check returned ok for state_5, logs_2, memories_1, goals_1, queue_1 and thread_history_1 (1.4 GB).
    • No sqlx migration was applied at either failure time. The latest state_5 migration is Crash when asking a question #58 from 2026-09-30.
    • The same copied runtime (%LOCALAPPDATA%\OpenAI\Codex\bin\<hash>\codex.exe app-server) against the same CODEX_HOME initializes normally from a shell a few minutes later. Relaunching the app also succeeds.
    • Teardown timing on this machine: a killed codex.exe app-server disappears from the process list within 10 ms (2 runs). That is the same as a trivial control process. So the slow EDR teardown described in [Windows 26.924] Desktop app fails to start after app-server restart due to lingering SQLite SHM mapping #49605 does not reproduce here in steady state. What held the databases at the failure moment is unknown, because the leaf SQLite error is not logged.

    +1 to the proposals above:

    1. Surface the full cause chain ({err:#}) for both the host-side SqliteError and the app-server init failure.
    2. Wait for confirmed exit of the previous instance before starting a replacement against the same CODEX_HOME, including across the Store update restart, or use a bounded retry for the transient case.
  6. paandayankur commented on Oct 7, 2026

    @paandayankur

    Additional report: this startup failure happens every day and requires manual recovery before the desktop app will start.

    Environment

    • Microsoft Store desktop package: OpenAI.Codex_26.930.7945.0_x64__2p2nqsd0c76g0
    • Bundled runtime: codex-cli 0.160.1
    • Microsoft Windows 11 Enterprise, version 10.0.26200, build 26200, 64-bit
    • Windows-native runtime; Codex home is a local directory under %USERPROFILE%\.codex

    Actual behavior and frequency

    On daily use, launching the desktop app fails with:

    failed to initialize sqlite state runtime under C:\Users\<user>\.codex:
    failed to initialize state runtime at C:\Users\<user>\.codex
    

    The inspected desktop logs contain repeated failures between 1 and 7 October 2026, across multiple desktop builds. The latest inspected failed startup was on 7 October 2026 at 21:48:50 UTC. The app-server exited with code 1 before initialization completed; the initialization handshake logged durationMs=761, outcome=failure.

    Immediately before that failure, the desktop log also recorded:

    Failed to repair missing thread cwd metadata errorName=SqliteError
    

    This is a daily blocker, not a one-off launch failure.

    Reproduction / recovery observed

    1. Launch the installed Windows desktop app during normal daily use.
    2. Startup fails with the SQLite initialization error above.
    3. Force-stop the desktop app and sandbox service, then remove the following leftovers using the existing workaround.
    4. Relaunch the app; it starts, but the problem returns on a later day.

    Existing workaround (paths sanitized):

    Get-Process -Name ChatGPT, codex-windows-sandbox-service -ErrorAction SilentlyContinue | Stop-Process -Force
    Remove-Item -Path "$env:USERPROFILE\.codex\thread-writer-locks\*.lock" -Force -ErrorAction SilentlyContinue
    Remove-Item -Path "$env:USERPROFILE\.codex\..codex-global-state*.tmp*" -Force -ErrorAction SilentlyContinue
    Remove-Item -Path "$env:USERPROFILE\.codex\.codex-provisioning-*.guard" -Force -ErrorAction SilentlyContinue

    The combined workaround does not establish which step restores startup. Its individual steps have not been isolated in controlled tests. The trigger relative to sleep/wake, normal quit, or updates has not yet been established.

    Verified diagnostics after successful recovery

    • Read-only PRAGMA quick_check returned ok for:
      • state_5.sqlite
      • thread_history_1.sqlite
      • logs_2.sqlite
      • sqlite/codex-dev.db
    • No unsuccessful rows were found in _sqlx_migrations in the state and thread-history databases.
    • The user account has FullControl on state_5.sqlite; the Codex home is not a junction or symbolic link.
    • The running-process snapshot after recovery showed one desktop process tree with one app-server and one remote exec-server; it did not demonstrate duplicate desktop instances.
    • Current thread-writer lock files are actively held while the app is running; their mere presence is not proof of orphaned locks.
    • The inspected desktop logs did not expose the underlying SQLite exception. No relevant codex_state / sqlx warning or error was found in the retained internal database logs.

    Expected behavior

    The desktop app should start reliably each day without force-killing processes or manually clearing files. If runtime initialization encounters a transient lock or process-lifecycle race, it should recover safely or provide the underlying SQLite/OS error and an actionable recovery path.

    The databases checked are structurally healthy after recovery. A locking or lifecycle problem is plausible, but the exact root cause has not been confirmed on this machine. No raw session data, credentials, or identifying local paths are attached.

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