openai / openai/codex

sqlite lock on ~/.codex/state_5.sqlite `Codex couldn't start because another Codex process is using its local data.`

Open
#46,269 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

app-server bug CLI
Dominant language
Rust
Stars
125k
Forks
19.4k
PR merge metrics
PR metrics pending

Description

What version of Codex CLI is running?

codex-cli 0.154.0

What subscription do you have?

$200

Which model were you using?

No response

What platform is your computer?

MacBook Pro m5

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

Ghostty

Codex doctor report
{
  "schemaVersion": 1,
  "generatedAt": "1789667891s since unix epoch",
  "overallStatus": "warning",
  "codexVersion": "0.154.0",
  "checks": {
    "app_server.status": {
      "id": "app_server.status",
      "category": "app-server",
      "status": "ok",
      "summary": "background server is not running",
      "details": {
        "control socket": "/Users/erg/.codex/app-server-control/app-server-control.sock",
        "daemon state dir": "/Users/erg/.codex/app-server-daemon",
        "mode": "ephemeral",
        "pid file": "/Users/erg/.codex/app-server-daemon/app-server.pid (missing)",
        "settings": "/Users/erg/.codex/app-server-daemon/settings.json (missing)",
        "status": "not running",
        "update-loop pid file": "/Users/erg/.codex/app-server-daemon/app-server-updater.pid (missing)"
      },
      "remediation": null,
      "durationMs": 0
    },
    "auth.credentials": {
      "id": "auth.credentials",
      "category": "auth",
      "status": "ok",
      "summary": "auth is configured",
      "details": {
        "auth file": "/Users/erg/.codex/auth.json",
        "auth storage mode": "File",
        "stored API key": "false",
        "stored ChatGPT tokens": "true",
        "stored agent identity": "false",
        "stored auth mode": "chatgpt"
      },
      "remediation": null,
      "durationMs": 0
    },
    "config.load": {
      "id": "config.load",
      "category": "config",
      "status": "ok",
      "summary": "config loaded",
      "details": {
        "CODEX_HOME": "/Users/erg/.codex",
        "active thread overrides": "not inspected",
        "config.toml": "/Users/erg/.codex/config.toml",
        "config.toml parse": "ok",
        "configuration load ms": "23",
        "configuration scope": "invocation config, including cloud-managed policy",
        "cwd": "/Users/erg/foo",
        "enabled feature flags": "shell_tool, view_image, sleep_tool, unified_exec, unified_exec_tty, unified_exec_zsh_fork, shell_snapshot, content_item_kinds, code_mode_host, terminal_resize_reflow, sqlite, hooks, enable_request_compression, unbounded_connection_retries, multi_agent, apps, tool_search_always_defer_mcp_tools, tool_suggest, plugins, in_app_browser, in_app_chat, in_app_dictation, 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, resize_all_images, item_ids, skill_mcp_dependency_install, skill_search, mentions_v2, steer, guardian_approval, goals, collaboration_modes, tool_call_mcp_elicitation, auth_elicitation, personality, fast_mode, tui_app_server, remote_compaction_v2, compaction_image_budget, workspace_dependencies",
        "feature flag overrides": "none",
        "feature flags enabled": "48",
        "log dir": "/Users/erg/.codex/log",
        "mcp servers": "2",
        "model": "gpt-6-astra",
        "model provider": "openai",
        "sqlite home": "/Users/erg/.codex"
      },
      "remediation": null,
      "durationMs": 0
    },
    "desktop.app.version": {
      "id": "desktop.app.version",
      "category": "desktop",
      "status": "ok",
      "summary": "the desktop application is installed",
      "details": {
        "log directory": "$HOME/Library/Logs/com.openai.codex",
        "running": "false",
        "version": "26.908.70816"
      },
      "remediation": null,
      "durationMs": 0
    },
    "desktop.app_server.handshake": {
      "id": "desktop.app_server.handshake",
      "category": "desktop",
      "status": "ok",
      "summary": "the desktop application is not running",
      "details": {},
      "remediation": null,
      "durationMs": 0
    },
    "desktop.security.enforcement": {
      "id": "desktop.security.enforcement",
      "category": "desktop",
      "status": "warning",
      "summary": "the desktop security assessment was unavailable",
      "details": {},
      "remediation": "check access to macos gatekeeper diagnostics",
      "durationMs": 0
    },
    "git.environment": {
      "id": "git.environment",
      "category": "git",
      "status": "ok",
      "summary": "git executable found; execution not verified",
      "details": {
        ".git entry": "directory",
        "PATH git #1": "/Users/erg/foo/scripts/git-guard/git",
        "PATH git #2": "/usr/bin/git",
        "PATH git entries": "2",
        "git execution": "not inspected (PATH helpers are not executed)",
        "repo detected": "true",
        "repo root": "/Users/erg/foo",
        "selected git": "/Users/erg/foo/scripts/git-guard/git"
      },
      "remediation": null,
      "durationMs": 0
    },
    "installation": {
      "id": "installation",
      "category": "install",
      "status": "ok",
      "summary": "installation looks consistent",
      "details": {
        "PATH codex #1": "/Users/erg/.bun/bin/codex",
        "current executable": "/Users/erg/.bun/install/global/node_modules/@openai/codex-darwin-arm64/vendor/aarch64-apple-darwin/bin/codex",
        "install context": "bun (package /Users/erg/.bun/install/global/node_modules/@openai/codex-darwin-arm64/vendor/aarch64-apple-darwin, bin /Users/erg/.bun/install/global/node_modules/@openai/codex-darwin-arm64/vendor/aarch64-apple-darwin/bin, resources /Users/erg/.bun/install/global/node_modules/@openai/codex-darwin-arm64/vendor/aarch64-apple-darwin/codex-resources, path /Users/erg/.bun/install/global/node_modules/@openai/codex-darwin-arm64/vendor/aarch64-apple-darwin/codex-path)",
        "managed by Vite+": "false",
        "managed by bun": "true",
        "managed by npm": "false",
        "managed by pnpm": "false",
        "managed package root": "/Users/erg/.bun/install/global/node_modules/@openai/codex"
      },
      "remediation": null,
      "durationMs": 2
    },
    "mcp.config": {
      "id": "mcp.config",
      "category": "mcp",
      "status": "ok",
      "summary": "MCP configuration is locally consistent",
      "details": {
        "configured servers": "2",
        "disabled servers": "1",
        "stdio servers": "2"
      },
      "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",
        "system proxy": "direct"
      },
      "remediation": null,
      "durationMs": 2
    },
    "network.provider_reachability": {
      "id": "network.provider_reachability",
      "category": "reachability",
      "status": "ok",
      "summary": "active provider endpoints are reachable over HTTP",
      "details": {
        "ChatGPT inference URL": "https://chatgpt.com/backend-api/<redacted> reachable (HTTP 405)",
        "desktop assets CDN": "https://chatgpt.com/backend-api/<redacted> reachable (HTTP 200)",
        "reachability mode": "ChatGPT auth"
      },
      "remediation": null,
      "durationMs": 609
    },
    "network.websocket_reachability": {
      "id": "network.websocket_reachability",
      "category": "websocket",
      "status": "ok",
      "summary": "Responses WebSocket handshake succeeded",
      "details": {
        "DNS": "2 IPv4, 2 IPv6, first IPv6",
        "auth mode": "chatgpt",
        "connect timeout": "15000 ms",
        "endpoint": "wss://chatgpt.com/backend-api/<redacted>",
        "handshake result": "HTTP 101 Switching Protocols",
        "model provider": "openai",
        "provider name": "OpenAI",
        "proxy env vars": "none",
        "reasoning header": "false",
        "server model present": "false",
        "supports websockets": "true",
        "wire API": "responses"
      },
      "remediation": null,
      "durationMs": 907
    },
    "runtime.provenance": {
      "id": "runtime.provenance",
      "category": "runtime",
      "status": "ok",
      "summary": "running bun on macos-aarch64",
      "details": {
        "commit": "unknown",
        "current executable": "/Users/erg/.bun/install/global/node_modules/@openai/codex-darwin-arm64/vendor/aarch64-apple-darwin/bin/codex",
        "install method": "bun (package /Users/erg/.bun/install/global/node_modules/@openai/codex-darwin-arm64/vendor/aarch64-apple-darwin, bin /Users/erg/.bun/install/global/node_modules/@openai/codex-darwin-arm64/vendor/aarch64-apple-darwin/bin, resources /Users/erg/.bun/install/global/node_modules/@openai/codex-darwin-arm64/vendor/aarch64-apple-darwin/codex-resources, path /Users/erg/.bun/install/global/node_modules/@openai/codex-darwin-arm64/vendor/aarch64-apple-darwin/codex-path)",
        "platform": "macos-aarch64",
        "version": "0.154.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": "/Users/erg/.bun/install/global/node_modules/@openai/codex-darwin-arm64/vendor/aarch64-apple-darwin/codex-path/rg",
        "search command readiness": "file exists",
        "search provider": "bundled"
      },
      "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": "none",
        "denied-read glob rules": "0",
        "denied-read rules": "0",
        "execve wrapper helper": "/Users/erg/.codex/tmp/arg0/codex-arg0WaTzXH/codex-execve-wrapper",
        "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": "no supported endpoint protection detected",
      "details": {
        "endpoint products": "none detected"
      },
      "remediation": null,
      "durationMs": 41
    },
    "state.paths": {
      "id": "state.paths",
      "category": "state",
      "status": "ok",
      "summary": "state paths and databases are inspectable",
      "details": {
        "CODEX_HOME": "/Users/erg/.codex (dir)",
        "active rollout files": "727 files, 9564375275 total bytes, 13155949 average bytes",
        "archived rollout files": "0 files, 0 total bytes, 0 average bytes",
        "goals DB": "/Users/erg/.codex/goals_1.sqlite (file)",
        "goals DB integrity": "ok",
        "log DB": "/Users/erg/.codex/logs_2.sqlite (file)",
        "log DB integrity": "ok",
        "log dir": "/Users/erg/.codex/log (missing)",
        "memories DB": "/Users/erg/.codex/memories_1.sqlite (file)",
        "memories DB integrity": "ok",
        "queue DB": "/Users/erg/.codex/queue_1.sqlite (file)",
        "queue DB integrity": "ok",
        "sqlite home": "/Users/erg/.codex (dir)",
        "state DB": "/Users/erg/.codex/state_5.sqlite (file)",
        "state DB integrity": "ok",
        "thread history DB": "/Users/erg/.codex/thread_history_1.sqlite (file)",
        "thread history DB integrity": "ok"
      },
      "remediation": null,
      "durationMs": 36135
    },
    "state.rollout_db_parity": {
      "id": "state.rollout_db_parity",
      "category": "threads",
      "status": "ok",
      "summary": "rollout files and state DB thread inventory agree",
      "details": {
        "default model provider": "openai",
        "rollout DB active files": "727",
        "rollout DB active rows": "727",
        "rollout DB archive mismatches": "0",
        "rollout DB archived files": "0",
        "rollout DB archived rows": "0",
        "rollout DB duplicate DB paths": "0",
        "rollout DB duplicate rollout thread ids": "0",
        "rollout DB malformed file names": "0",
        "rollout DB missing active rows": "0",
        "rollout DB missing archived rows": "0",
        "rollout DB model providers": "openai=727",
        "rollout DB rows": "727",
        "rollout DB scan cap reached": "false",
        "rollout DB scan errors": "0",
        "rollout DB sources": "subagent:thread_spawn=506, cli=210, vscode=11",
        "rollout DB stale rows": "0"
      },
      "remediation": null,
      "durationMs": 1259
    },
    "system.disk": {
      "id": "system.disk",
      "category": "disk",
      "status": "ok",
      "summary": "sufficient free disk space (94.1 GiB)",
      "details": {
        "CODEX_HOME available": "94.1 GiB",
        "failure threshold": "1.0 GiB",
        "warning threshold": "5.0 GiB",
        "worktree available": "94.1 GiB"
      },
      "remediation": null,
      "durationMs": 0
    },
    "system.environment": {
      "id": "system.environment",
      "category": "system",
      "status": "ok",
      "summary": "OS language en-US",
      "details": {
        "EDITOR": "not set",
        "LANG": "en_US.UTF-8",
        "VISUAL": "not set",
        "os": "Mac OS 26.6.2 [64-bit]",
        "os language": "en-US",
        "os type": "Mac OS",
        "os version": "26.6.2"
      },
      "remediation": null,
      "durationMs": 10
    },
    "terminal.env": {
      "id": "terminal.env",
      "category": "terminal",
      "status": "ok",
      "summary": "terminal metadata was detected",
      "details": {
        "COLORTERM": "truecolor",
        "TERMINFO": "/Applications/Ghostty.app/Contents/Resources/terminfo (dir)",
        "TERM_PROGRAM": "ghostty",
        "color output": "enabled",
        "effective locale": "en_US.UTF-8",
        "stderr is terminal": "true",
        "stdin is terminal": "true",
        "stdout is terminal": "true",
        "terminal": "Ghostty",
        "terminal size": "215x54",
        "terminal version": "1.3.2-main-+661e1e77f"
      },
      "remediation": null,
      "durationMs": 1
    },
    "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": "git repo root",
        "terminal title project value": "foo",
        "terminal title source": "default"
      },
      "remediation": null,
      "durationMs": 0
    },
    "updates.status": {
      "id": "updates.status",
      "category": "updates",
      "status": "ok",
      "summary": "update configuration is locally consistent",
      "details": {
        "cached latest version": "0.154.0",
        "check for update on startup": "true",
        "last checked at": "2026-09-17T14:06:17.498322Z",
        "latest version": "0.154.0",
        "latest version status": "current version is not older",
        "update action": "bun install -g @openai/codex",
        "version cache": "/Users/erg/.codex/version.json"
      },
      "remediation": null,
      "durationMs": 694
    }
  }
}
What issue are you seeing?

Can't start for up to five minutes at a time -- sqlite lock woes.

% codex --dangerously-bypass-approvals-and-sandbox
╭─────────────────────────────────────────╮
│ >_ OpenAI Codex (v0.154.0)              │
│                                         │
│ model:       loading   /model to change │
│ directory:   ~/foo                      │
│ permissions: YOLO mode                  │
╰─────────────────────────────────────────╯


› Codex couldn't start because another Codex process is using its local data.
Quit any other copies of Codex that may still be running, then try again.
Technical details:
  Location: /Users/erg/.codex/state_5.sqlite
  Cause: failed to initialize state runtime at /Users/erg/.codex: failed to open log DB at /Users/erg/.codex/logs_2.sqlite: error returned from database: (code: 5) database is locked: error returned from database: (code: 5) database is locked: (code: 5) database is locked
ERROR: failed to initialize sqlite local db at /Users/erg/.codex/state_5.sqlite: failed to initialize state runtime at /Users/erg/.codex: failed to open log DB at /Users/erg/.codex/logs_2.sqlite: error returned from database: (code: 5) database is locked: error returned from database: (code: 5) database is locked: (code: 5) database is locked
% codex --dangerously-bypass-approvals-and-sandbox
╭─────────────────────────────────────────╮
│ >_ OpenAI Codex (v0.154.0)              │
│                                         │
│ model:       loading   /model to change │
│ directory:   ~/foo                      │
│ permissions: YOLO mode                  │
╰─────────────────────────────────────────╯


› Codex couldn't start because another Codex process is using its local data.
Quit any other copies of Codex that may still be running, then try again.
Technical details:
  Location: /Users/erg/.codex/state_5.sqlite
  Cause: failed to initialize state runtime at /Users/erg/.codex: failed to open log DB at /Users/erg/.codex/logs_2.sqlite: error returned from database: (code: 5) database is locked: error returned from database: (code: 5) database is locked: (code: 5) database is locked
ERROR: failed to initialize sqlite local db at /Users/erg/.codex/state_5.sqlite: failed to initialize state runtime at /Users/erg/.codex: failed to open log DB at /Users/erg/.codex/logs_2.sqlite: error returned from database: (code: 5) database is locked: error returned from database: (code: 5) database is locked: (code: 5) database is locked
% codex --dangerously-bypass-approvals-and-sandbox
╭─────────────────────────────────────────╮
│ >_ OpenAI Codex (v0.154.0)              │
│                                         │
│ model:       loading   /model to change │
│ directory:   ~/foo                      │
│ permissions: YOLO mode                  │
╰─────────────────────────────────────────╯


› Codex couldn't start because another Codex process is using its local data.
Quit any other copies of Codex that may still be running, then try again.
Technical details:
  Location: /Users/erg/.codex/state_5.sqlite
  Cause: failed to initialize state runtime at /Users/erg/.codex: failed to open log DB at /Users/erg/.codex/logs_2.sqlite: error returned from database: (code: 5) database is locked: error returned from database: (code: 5) database is locked: (code: 5) database is locked
ERROR: failed to initialize sqlite local db at /Users/erg/.codex/state_5.sqlite: failed to initialize state runtime at /Users/erg/.codex: failed to open log DB at /Users/erg/.codex/logs_2.sqlite: error returned from database: (code: 5) database is locked: error returned from database: (code: 5) database is locked: (code: 5) database is locked
What steps can reproduce the bug?

It's not easy to repro--just run a bunch of agents til you can't start agents anymore.

What is the expected behavior?

Codex should load.

Additional information

Here's a potential patch. all rights to you

diff --git a/codex-rs/app-server/src/lib.rs b/codex-rs/app-server/src/lib.rs
index a7cdee38f2..24f4b3f714 100644
--- a/codex-rs/app-server/src/lib.rs
+++ b/codex-rs/app-server/src/lib.rs
@@ -1280,7 +1280,7 @@ async fn init_sqlite_state_db_with_fresh_start_on_corruption(
             }
             Err(err) => err,
         };
-        let database_path = codex_state::runtime_db_path_for_corruption_error(&err)
+        let database_path = codex_state::runtime_db_path_for_error(&err)
             .unwrap_or_else(|| config.sqlite_config().state_db_path());
         if !codex_state::is_sqlite_corruption_error(&err)
             && !sqlite_home_is_blocking_file(database_path.as_path())
diff --git a/codex-rs/state/src/lib.rs b/codex-rs/state/src/lib.rs
index c9a82df965..46170fcaac 100644
--- a/codex-rs/state/src/lib.rs
+++ b/codex-rs/state/src/lib.rs
@@ -86,6 +86,7 @@ pub use runtime::backup_runtime_db_for_fresh_start;
 pub use runtime::is_sqlite_corruption_error;
 pub use runtime::open_thread_history_db;
 pub use runtime::runtime_db_path_for_corruption_error;
+pub use runtime::runtime_db_path_for_error;
 pub use runtime::sqlite_error_detail_is_corruption;
 pub use runtime::sqlite_error_detail_is_lock;
 pub use runtime::sqlite_integrity_check;
diff --git a/codex-rs/state/src/runtime.rs b/codex-rs/state/src/runtime.rs
index e7fa3cffef..42c36781c5 100644
--- a/codex-rs/state/src/runtime.rs
+++ b/codex-rs/state/src/runtime.rs
@@ -70,6 +70,7 @@ pub(super) use recovery::RuntimeDbInitError;
 pub use recovery::backup_runtime_db_for_fresh_start;
 pub use recovery::is_sqlite_corruption_error;
 pub use recovery::runtime_db_path_for_corruption_error;
+pub use recovery::runtime_db_path_for_error;
 pub use recovery::sqlite_error_detail_is_corruption;
 pub use recovery::sqlite_error_detail_is_lock;
 pub use remote_control::RemoteControlEnrollmentRecord;
@@ -589,6 +590,52 @@ mod tests {
         let _ = tokio::fs::remove_dir_all(codex_home).await;
     }

+    #[tokio::test]
+    async fn open_read_write_pool_does_not_wait_for_another_writer_on_existing_db() {
+        let codex_home = unique_temp_dir();
+        let sqlite = crate::SqliteConfig::new_for_testing(codex_home.as_path().abs());
+        let runtime = StateRuntime::init(sqlite.clone(), "test-provider".to_string())
+            .await
+            .expect("initialize runtime");
+        let logs_path = sqlite.logs_db_path();
+
+        // Hold the WAL writer lock the way a concurrent Codex process does while
+        // flushing a log batch. Opening the same database must not wait on it.
+        let writer_pool = sqlite
+            .open_read_write_pool(&logs_path)
+            .await
+            .expect("open writer pool");
+        let mut writer = writer_pool.acquire().await.expect("acquire writer");
+        sqlx::query("BEGIN IMMEDIATE")
+            .execute(&mut *writer)
+            .await
+            .expect("hold the writer lock");
+
+        let started = Instant::now();
+        let pool = sqlite
+            .open_read_write_pool(&logs_path)
+            .await
+            .expect("open existing db while another writer is active");
+        let one = sqlx::query_scalar::<_, i64>("SELECT 1")
+            .fetch_one(&pool)
+            .await
+            .expect("read while another writer is active");
+        let elapsed = started.elapsed();
+        assert_eq!(one, 1);
+        assert!(elapsed < Duration::from_secs(1), "open waited: {elapsed:?}");
+
+        sqlx::query("ROLLBACK")
+            .execute(&mut *writer)
+            .await
+            .expect("release the writer lock");
+        drop(writer);
+        pool.close().await;
+        writer_pool.close().await;
+        runtime.close().await;
+
+        let _ = tokio::fs::remove_dir_all(codex_home).await;
+    }
+
     #[tokio::test]
     async fn open_state_sqlite_tolerates_newer_applied_migrations() {
         let codex_home = unique_temp_dir();
diff --git a/codex-rs/state/src/runtime/recovery.rs b/codex-rs/state/src/runtime/recovery.rs
index d9cf0bcdc9..af02b3c65c 100644
--- a/codex-rs/state/src/runtime/recovery.rs
+++ b/codex-rs/state/src/runtime/recovery.rs
@@ -91,13 +91,18 @@ pub async fn backup_runtime_db_for_fresh_start(
     }
 }

+/// Path of the runtime database whose open or migration failed, for any error kind.
+pub fn runtime_db_path_for_error(err: &anyhow::Error) -> Option<PathBuf> {
+    err.chain()
+        .find_map(|source| source.downcast_ref::<RuntimeDbInitError>())
+        .map(|err| err.path().to_path_buf())
+}
+
 pub fn runtime_db_path_for_corruption_error(err: &anyhow::Error) -> Option<PathBuf> {
     if !is_sqlite_corruption_error(err) {
         return None;
     }
-    err.chain()
-        .find_map(|source| source.downcast_ref::<RuntimeDbInitError>())
-        .map(|err| err.path().to_path_buf())
+    runtime_db_path_for_error(err)
 }

 pub fn is_sqlite_corruption_error(err: &anyhow::Error) -> bool {
diff --git a/codex-rs/state/src/runtime/recovery_tests.rs b/codex-rs/state/src/runtime/recovery_tests.rs
index 3861000dd3..0e92edcfe9 100644
--- a/codex-rs/state/src/runtime/recovery_tests.rs
+++ b/codex-rs/state/src/runtime/recovery_tests.rs
@@ -100,6 +100,27 @@ async fn runtime_db_path_for_corruption_error_returns_failed_database_path() ->
     Ok(())
 }

+#[tokio::test]
+async fn runtime_db_path_for_error_returns_failed_database_path_for_non_corruption_errors()
+-> std::io::Result<()> {
+    let sqlite_home = unique_temp_dir();
+    tokio::fs::create_dir_all(sqlite_home.as_path()).await?;
+    let sqlite = crate::SqliteConfig::new_for_testing(sqlite_home.as_path().abs());
+    let logs_path = sqlite.logs_db_path();
+    // A directory at the database path makes SQLite fail to open it without
+    // reporting corruption.
+    tokio::fs::create_dir_all(logs_path.as_path()).await?;
+
+    let err = match super::super::StateRuntime::init(sqlite, "openai".to_string()).await {
+        Ok(_) => panic!("unopenable logs db should fail to initialize"),
+        Err(err) => err,
+    };
+
+    assert_eq!(runtime_db_path_for_error(&err), Some(logs_path));
+    assert_eq!(runtime_db_path_for_corruption_error(&err), None);
+    Ok(())
+}
+
 #[test]
 fn runtime_db_path_for_corruption_error_ignores_corrupt_word_in_path() {
     let path = PathBuf::from("/tmp/sqlite_corrupt/state_5.sqlite");
diff --git a/codex-rs/state/src/sqlite.rs b/codex-rs/state/src/sqlite.rs
index 536d56befa..9e711b9df8 100644
--- a/codex-rs/state/src/sqlite.rs
+++ b/codex-rs/state/src/sqlite.rs
@@ -176,9 +176,10 @@ impl SqliteConfig {
         migrator: &Migrator,
         telemetry_override: Option<&dyn DbTelemetry>,
     ) -> anyhow::Result<SqlitePool> {
-        // New state DBs should use incremental auto-vacuum, but retrofitting an
-        // existing DB requires a full VACUUM. Do not attempt that during process
-        // startup: it is maintenance work that can contend with foreground writers.
+        // New state DBs get incremental auto-vacuum from `open_read_write_pool`,
+        // but retrofitting an existing DB requires a full VACUUM. Do not attempt
+        // that during process startup: it is maintenance work that can contend
+        // with foreground writers.
         self.open_runtime_db(STATE_DB, migrator, telemetry_override)
             .await
     }
@@ -276,14 +277,26 @@ impl SqliteConfig {

     /// Open a writable Codex SQLite database, creating it if necessary.
     pub async fn open_read_write_pool(&self, path: &Path) -> Result<SqlitePool, Error> {
-        let options = SqliteConnectOptions::new()
+        // `PRAGMA auto_vacuum` always opens a write transaction, even when the
+        // value is unchanged, and it only takes effect before the first table
+        // is created. Send it only for databases we are about to create so
+        // opening an existing DB never waits on another process's writer.
+        let is_new_database = match tokio::fs::metadata(path).await {
+            Ok(metadata) => metadata.len() == 0,
+            Err(err) if err.kind() == std::io::ErrorKind::NotFound => true,
+            // Let SQLite report the real open error.
+            Err(_) => false,
+        };
+        let mut options = SqliteConnectOptions::new()
             .filename(path)
             .create_if_missing(true)
             .journal_mode(SqliteJournalMode::Wal)
             .synchronous(SqliteSynchronous::Normal)
-            .auto_vacuum(SqliteAutoVacuum::Incremental)
             .busy_timeout(Duration::from_secs(5))
             .log_statements(LevelFilter::Off);
+        if is_new_database {
+            options = options.auto_vacuum(SqliteAutoVacuum::Incremental);
+        }
         SqlitePoolOptions::new()
             .max_connections(5)
             .connect_with(options)
diff --git a/codex-rs/tui/src/lib.rs b/codex-rs/tui/src/lib.rs
index 5514c66907..2cd73b7da2 100644
--- a/codex-rs/tui/src/lib.rs
+++ b/codex-rs/tui/src/lib.rs
@@ -330,7 +330,7 @@ async fn init_state_db_for_app_server_target(
 ) -> std::io::Result<Option<StateDbHandle>> {
     match app_server_target {
         AppServerTarget::Embedded => state_db::try_init(config).await.map(Some).map_err(|err| {
-            let database_path = codex_state::runtime_db_path_for_corruption_error(&err)
+            let database_path = codex_state::runtime_db_path_for_error(&err)
                 .unwrap_or_else(|| config.sqlite_config().state_db_path());
             std::io::Error::other(LocalStateDbStartupError::new(
                 database_path,
@@ -3671,6 +3671,39 @@ requires_openai_auth = {requires_openai_auth}
         Ok(())
     }

+    #[tokio::test]
+    async fn embedded_state_db_open_failure_preserves_failed_database_for_cli_recovery()
+    -> color_eyre::Result<()> {
+        let temp_dir = TempDir::new()?;
+        let mut config = build_config(&temp_dir).await?;
+        let sqlite_home = temp_dir.path().join("sqlite-home");
+        std::fs::create_dir_all(&sqlite_home)?;
+        let sqlite = codex_state::SqliteConfig::new_for_testing(sqlite_home.as_path().abs());
+        let logs_db_path = sqlite.logs_db_path();
+        // A directory at the database path fails to open without being corrupt,
+        // like a lock held by another process would.
+        std::fs::create_dir_all(&logs_db_path)?;
+        config.sqlite = sqlite;
+
+        let err =
+            match init_state_db_for_app_server_target(&config, &AppServerTarget::Embedded).await {
+                Ok(_) => panic!("embedded startup should surface state db init failures"),
+                Err(err) => err,
+            };
+        let startup_error = err
+            .get_ref()
+            .and_then(|err| err.downcast_ref::<LocalStateDbStartupError>())
+            .expect("state db startup failure should retain its typed context");
+
+        assert_eq!(startup_error.database_path(), logs_db_path.as_path());
+        assert!(
+            !codex_state::sqlite_error_detail_is_corruption(startup_error.detail()),
+            "open failure should not be classified as corruption, got: {}",
+            startup_error.detail()
+        );
+        Ok(())
+    }
+
     #[tokio::test]
     #[serial]
     async fn windows_shows_trust_prompt_with_sandbox() -> std::io::Result<()> {

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the reported lock on ~/.codex/state_5.sqlite and the state.paths section of the Codex doctor report; reproduce startup while another Codex process is active and inspect the state database's locking behavior. Done means Codex starts without the reported lock error while the state database still passes its integrity check.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust, sqlite
Domain
cli, databases
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Active
Clarity
Needs clarification
Newbie friendliness
42/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.