Skip to content

fix(codex): recover interrupted state DB backfills - #12617

Merged
brennanb2025 merged 6 commits into
mainfrom
brennanb2025/codex-backfill-wedge-11830
Aug 7, 2026
Merged

brennanb2025 merged 6 commits into
mainfrom
brennanb2025/codex-backfill-wedge-11830

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #11830. Related: #11828 and upstream openai/codex#37003.

Summary

  • Detect incomplete state-DB backfills in managed Codex homes without mutating Codex-owned SQLite.
  • Supervise a durable codex app-server claimant behind an exact process-incarnation lock, recovering dead or PID-reused Orca owners while leaving live owners and concurrent Orca instances untouched.
  • Cover native macOS/Linux/Windows and WSL homes, defer short trust/rate-limit app-server probes that could refresh the stale lease, and reap owned recovery children on app quit.
  • Surface Codex's backfill timeout in the pane as an actionable recovery message instead of silently dropping to a shell.

This branch was implemented fresh from current main; it does not reuse or cherry-pick the closed release-lineage PR #11981.

Screenshots

Electron QA through CDP, showing the recovery message in a Codex-launched pane:

codex-backfill-actionable-toast.png

Testing

  • pnpm lint
  • pnpm typecheck
  • pnpm test
  • pnpm build
  • Added or updated high-quality tests that would catch regressions, or explained why tests were not needed

Focused validation after the final rebase:

  • 73/73 tests across state inspection/recovery, dead and PID-reused owner recovery, live-owner non-interference, Windows creation-time identity, install locking, trust deferral, rate-limit deferral, WSL routing, and renderer detection.
  • Main PTY Codex owner-arbitration integration: 1 passed / 446 skipped.
  • Renderer PTY actionable-error integration: 1 passed / 544 skipped.
  • Electron dev build booted successfully and the exact Codex-pane error path displayed the screenshot above.

The full local src/main/ipc/pty.test.ts file reached 438 passing tests; nine unrelated MiMo/Pi/WSL harness cases failed in this environment. None exercises a Codex launch or the new recovery mock, and the change-owned Codex integration test is green.

AI Review Report

Reviewed the complete delta against origin/main, including recovery lifecycle, lock stealing, child-process exit races, read-only DB inspection, shutdown, and all short-lived Codex app-server call sites. The review explicitly checked native macOS, Linux, and Windows process identity, WSL distro/PID-namespace scoping and shell quoting, SSH/folder-workspace behavior, path normalization, and Electron renderer behavior; no shortcut or label behavior changed.

The central integration risk is that Codex 0.146's backfill_state does not record a verifiable owner. The implementation therefore never guesses from CPU activity or age and never writes Codex schema: Orca arbitrates only its own supervisor with host + PID + process-start identity, while Codex's existing lease/claim transaction arbitrates the actual backfill. The missing upstream owner/repair contract is tracked in openai/codex#37003.

Security Audit

  • SQLite access is read-only with fileMustExist; Orca never updates, deletes, or recreates Codex-owned state.
  • Recovery commands use fixed arguments, existing Windows spawn handling, existing WSL login-shell quoting, and an absolute system PowerShell path. No user-controlled command fragments are introduced.
  • Lock paths hash normalized Codex-home paths under Orca user data, and the existing atomic hard-link claim protocol prevents concurrent ownership or unsafe replacement.
  • Windows liveness uses MachineGuid plus CIM process creation time, not PID alone; Linux includes PID namespace, boot ID, and start ticks; macOS includes boot identity and process start data.
  • No auth material, secrets, dependencies, or new IPC surface are introduced.

Caveats

  • Recovery-only churn can launch roughly one losing app-server every 32 seconds while a foreign Codex backfill lease remains live.
  • Recovery checks Codex's SQLite state read-only every five seconds.
  • The recovery supervisor stops after one hour; tighten that cap if real histories materially exceed the reported six-minute recovery.

Notes

Orca keeps the sanctioned app-server claimant alive until Codex marks the backfill complete, but intentionally does not hold pane startup for the full potentially long index. Pane startup waits only for exact Orca supervisor-owner arbitration; Codex remains the sole authority for its backfill claim.

On quit, Orca terminates and joins only recovery children it owns. Crash recovery remains required and covered because no shutdown path can make an abrupt host/process loss impossible.

@coderabbitai

coderabbitai Bot commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The change adds Codex state-database inspection and supervised backfill recovery. Recovery supports native and WSL Codex processes, polling, retries, cancellation, locking, and shutdown. Codex startup, PTY creation, rate-limit fetching, and trust grants now coordinate with recovery. Terminal PTY output detects split or ANSI-encoded backfill timeout messages and reports a recovery notice. Windows process and host identity probing now use registry and PowerShell data with caching and fallbacks.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 31.03% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the main change: recovering interrupted Codex state database backfills.
Description check ✅ Passed The description includes all required sections, detailed implementation context, testing results, review findings, security risks, screenshots, and platform notes.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Managed-home recovery: a stale running backfill with a dead supervisor owner recovered to complete, and the Codex pane launched with the recovered session-history index ready.

Managed home recovered and Codex pane ready

Actionable failure state: when recovery could not proceed, the Codex pane rendered the background-recovery guidance and retry instructions.

Actionable recovery failure guidance

…ckfill-wedge-11830

# Conflicts:
#	src/main/ipc/pty.ts
@coderabbitai

coderabbitai Bot commented Aug 5, 2026

Copy link
Copy Markdown
Contributor

Note

GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (4)
src/main/codex/codex-state-db-backfill-recovery.ts (1)

267-272: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Return the ready promise from the start call instead of re-reading the map.

Line 271 re-derives the key and looks the entry up again. This works only because startCodexStateDbBackfillRecoveryInBackground runs synchronously up to its Map.set. That coupling is invisible at the call site and breaks if anyone adds an await before line 257.

Return ready alongside task, or expose a small startAndWaitForArbitration that awaits the ready promise it created.

src/main/codex/codex-state-db.test.ts (2)

57-68: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Derive the file count from BACKFILL_PENDING_MIN_SESSION_FILES.

Line 62 hardcodes 100, which duplicates the exported threshold. If the threshold rises, this test writes too few files and reports a false failure. If the threshold drops, the test stops exercising the boundary.

♻️ Proposed change
 import {
+  BACKFILL_PENDING_MIN_SESSION_FILES,
   findNewestCodexStateDbPath,
   isCodexStateDbBackfillPending,
   readCodexStateDbBackfillStatus
 } from './codex-state-db'
     await Promise.all(
-      Array.from({ length: 100 }, (_, index) =>
+      Array.from({ length: BACKFILL_PENDING_MIN_SESSION_FILES }, (_, index) =>
         writeFile(join(sessions, `rollout-${index}.jsonl`), '{}\n')
       )
     )

37-76: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add cases for the unreadable and not-tracked statuses.

runCodexStateDbBackfillRecovery branches on every status kind. Two kinds drive important decisions and have no test here:

  • unreadable: recovery returns early and reports unreadable. Cover it with a state_N.sqlite file that holds non-SQLite bytes.
  • not-tracked: recovery falls through to the session-count heuristic. Cover both shapes, a database with no backfill_state table and a backfill_state row whose status is not a string.

A findNewestCodexStateDbPath case for a home directory that does not exist would also pin the null return.

src/main/agent-hooks/managed-hook-owner-identity.ts (1)

121-121: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Use the PowerShell 4.0-compatible MachineGuid query.

Get-ItemPropertyValue requires PowerShell 5.0, so Windows hosts with PowerShell 4.0 fall through to runtimeHostIdentity and keep the host scope unverifiable. Use Get-ItemProperty ... | Select-Object -ExpandProperty MachineGuid for compatibility with older PowerShell versions.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: d6ef2b1f-ffa4-4f23-b4f3-86927e939bcf

📥 Commits

Reviewing files that changed from the base of the PR and between 4c49989 and 2bbf072.

📒 Files selected for processing (23)
  • .oxlintrc.json
  • config/scripts/relay-watcher-fault-harness.mjs
  • config/tsconfig.cli.json
  • src/main/agent-hooks/managed-hook-install-lock.ts
  • src/main/agent-hooks/managed-hook-owner-identity.test.ts
  • src/main/agent-hooks/managed-hook-owner-identity.ts
  • src/main/codex/codex-hook-trust-grant.test.ts
  • src/main/codex/codex-hook-trust-grant.ts
  • src/main/codex/codex-state-db-backfill-recovery.test.ts
  • src/main/codex/codex-state-db-backfill-recovery.ts
  • src/main/codex/codex-state-db.test.ts
  • src/main/codex/codex-state-db.ts
  • src/main/index.ts
  • src/main/ipc/pty.test.ts
  • src/main/ipc/pty.ts
  • src/main/rate-limits/codex-fetcher.test.ts
  • src/main/rate-limits/codex-fetcher.ts
  • src/main/runtime/orca-runtime.ts
  • src/renderer/src/components/github/GitHubMarkdownComposerEditorPane.tsx
  • src/renderer/src/components/terminal-pane/codex-backfill-error-detector.test.ts
  • src/renderer/src/components/terminal-pane/codex-backfill-error-detector.ts
  • src/renderer/src/components/terminal-pane/pty-connection.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection.ts
🚧 Files skipped from review as they are similar to previous changes (15)
  • config/tsconfig.cli.json
  • src/main/rate-limits/codex-fetcher.test.ts
  • src/renderer/src/components/terminal-pane/codex-backfill-error-detector.test.ts
  • src/main/agent-hooks/managed-hook-owner-identity.test.ts
  • src/main/rate-limits/codex-fetcher.ts
  • src/main/codex/codex-state-db-backfill-recovery.test.ts
  • src/main/agent-hooks/managed-hook-install-lock.ts
  • src/renderer/src/components/terminal-pane/pty-connection.ts
  • src/main/index.ts
  • src/renderer/src/components/terminal-pane/pty-connection.test.ts
  • src/main/codex/codex-hook-trust-grant.ts
  • src/renderer/src/components/terminal-pane/codex-backfill-error-detector.ts
  • src/main/ipc/pty.ts
  • src/main/codex/codex-hook-trust-grant.test.ts
  • src/main/ipc/pty.test.ts

Comment on lines +240 to +242
if (stopping || !isCodexStateDbBackfillPending(codexHomePath)) {
return Promise.resolve(null)
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🚀 Performance & Scalability | 🟠 Major | 🏗️ Heavy lift

Synchronous SQLite and filesystem access runs on the Electron main-process event loop. isCodexStateDbBackfillPending is a synchronous function that opens a SQLite database and walks a directory tree. Per the stack context it runs during PTY creation, rate-limit fetching, and trust grants, so every one of those paths blocks the main-process event loop and stalls IPC and the UI. The cost peaks in exactly the case this PR targets, a large unindexed sessions tree, and a WSL home reached through \\wsl.localhost\... turns each directory read into a 9P round trip.

  • src/main/codex/codex-state-db-backfill-recovery.ts#L240-L242: move the pending probe off the event loop, for example by awaiting an async variant instead of calling the synchronous one inline.
  • src/main/codex/codex-state-db.ts#L74-L97: add an async countCodexSessionFilesUpTo built on fs/promises opendir so the loop yields between directory reads, and keep the synchronous version only if a synchronous caller still needs it.
  • src/main/codex/codex-state-db.ts#L36-L72: expose an async wrapper for the status read so the SQLite open and the two queries do not block the loop either.
🧰 Tools
🪛 ast-grep (0.45.0)

[warning] Importing child_process exposes a command-execution surface; ensure any command/argument built from input is validated, and prefer execFile/spawn with an argument array over exec.
Context: import { spawn, type ChildProcess } from 'node:child_process'
Note: [CWE-78] Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection').

(detect-child-process-typescript)

📍 Affects 2 files
  • src/main/codex/codex-state-db-backfill-recovery.ts#L240-L242 (this comment)
  • src/main/codex/codex-state-db.ts#L74-L97
  • src/main/codex/codex-state-db.ts#L36-L72

Comment on lines +59 to +64
} catch (error) {
return {
kind: 'unreadable',
stateDbPath,
error: error instanceof Error ? error.message : String(error)
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy lift

🧩 Analysis chain

🌐 Web query:

SQLite read-only connection wal file missing shm SQLITE_READONLY_CANTINIT error

💡 Result:

The SQLITE_READONLY_CANTINIT error occurs in SQLite when a database is in Write-Ahead Logging (WAL) mode, and the database connection attempts to initialize the required shared memory (SHM) region but lacks the necessary write permissions to do so [1][2]. In WAL mode, SQLite uses a file with a "-shm" suffix as a memory-mapped shared memory region to coordinate access between processes [3]. By design, SQLite requires write access to this "-shm" file (or the directory containing the database, if the file does not yet exist) to initialize this coordination mechanism, even if the database connection is intended to be read-only [4][5]. Key details regarding this error: - Origin: The error originates in the Virtual File System (VFS) xShmMap method when the system determines the shared memory region is unusable due to insufficient permissions [1][2]. - Behavior: Under normal circumstances, higher-level logic within SQLite intercepts this specific error and falls back to an in-memory shared memory region, allowing the process to read the database despite the permission restriction [1][2]. - Why it persists: If the error persists or is surfaced to the application, it usually indicates that the environment is highly restrictive, such as running on read-only media, within a strictly controlled container, or due to aggressive security policies (like SELinux or AppArmor) preventing the creation or modification of the -shm file [1]. - Prevention and Workarounds: - Immutable databases: If the database files are on read-only media, opening the connection with the immutable query parameter can bypass the need for -shm initialization [4]. - Journal mode: If possible, converting the database to PRAGMA journal_mode=DELETE eliminates the requirement for WAL files and the associated shared memory [4]. - Permissions: Ensure the user process has read and write access to the directory containing the database to allow for file creation, or ensure the -shm and -wal files are pre-created with appropriate permissions [4][1]. Note that while this error is often intercepted internally, it can still appear in logs or be caught by applications in specific configurations or older SQLite versions [4][6][2]. [4][1][5][2]

Citations:


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf 'Repository files matching codex-state-db:\n'
git ls-files | rg 'codex-state-db|codex-state-db-backfill|backfill.*cov|codex.*state.*db' || true

printf '\nTarget file outline and relevant lines:\n'
if [ -f src/main/codex/codex-state-db.ts ]; then
  wc -l src/main/codex/codex-state-db.ts
  ast-grep outline src/main/codex/codex-state-db.ts --view expanded || true
  sed -n '1,140p' src/main/codex/codex-state-db.ts | cat -n
fi

printf '\nRecovery file relevant lines:\n'
files=$(git ls-files | rg 'codex-state-db-backfill-recovery\.ts$')
for f in $files; do
  echo "### $f"
  wc -l "$f"
  ast-grep outline "$f" --view expanded || true
  sed -n '1,240p' "$f" | cat -n
done

printf '\nSearch for unreadable handling and status type definitions:\n'
rg -n "CodexStateDbBackfillStatus|unreadable|SQLITE_BUSY|SQLITE_CANTOPEN|SQLITE_READONLY|status is|kind:" src test tests __tests__ . 2>/dev/null | head -200 || true

Repository: stablyai/orca

Length of output: 35968


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf 'sync-database file outline and implementation:\n'
if [ -f src/main/sqlite/sync-database.ts ]; then
  wc -l src/main/sqlite/sync-database.ts
  ast-grep outline src/main/sqlite/sync-database.ts --view expanded || true
  sed -n '1,220p' src/main/sqlite/sync-database.ts | cat -n
fi

printf '\nSQLite module references:\n'
rg -n "SyncDatabase|import .*(sqlite|better-sqlite|sql|libsql|duckdb)|new Database|from 'better-sqlite3'\"|from \"better-sqlite3\"|from 'libsql'|from \"libsql\"" src/main src/shared src/test test tests 2>/dev/null | head -80 || true

printf '\nSQLite package references in manifests:\n'
for f in package.json pnpm-lock.yaml package-lock.json yarn.lock bun.lockb bun.lock; do
  if [ -f "$f" ]; then
    echo "### $f"
    rg -n "better-sqlite3|sql.js|libsql|duckdb|sqlite3" "$f" | head -100 || true
  fi
done

printf '\nRelevant tests for unreadable status:\n'
sed -n '1,220p' src/main/codex/codex-state-db.test.ts | cat -n
sed -n '1,240p' src/main/codex/codex-state-db-backfill-recovery.test.ts | cat -n

printf '\nCheck installed Sqljs bindings (if no-mods allowed, just inspect if available):\n'
node - <<'JS'
const candidates = ['sql.js', 'better-sqlite3', 'libsql', 'sqlite3']
for (const name of candidates) {
  try {
    const mod = require(name)
    console.log(name, 'present', Object.keys(mod).slice(0, 6))
  } catch (e) {
    if (!/Cannot find module/.test(String(e?.message || e))) throw e
    console.log(name, 'missing')
  }
}
JS

Repository: stablyai/orca

Length of output: 23922


🌐 Web query:

Node.js node::sqlite DatabaseSync read-only locking transaction error code SQLite_BUSY read-only WAL

💡 Result:

The SQLITE_BUSY error in Node.js node:sqlite when using DatabaseSync is primarily caused by the default busy_timeout being set to 0 [1][2][3]. This means that if the database file is locked (e.g., by another process or a concurrent connection), SQLite will return an error immediately rather than waiting for the lock to be released [1][4]. In Write-Ahead Logging (WAL) mode, while writers and readers typically do not block each other, SQLITE_BUSY can still occur under specific conditions, such as during checkpointing, recovery, or when another connection holds an exclusive lock [5]. To resolve or mitigate this issue, you should use the timeout option available in the DatabaseSync constructor [1][6]. How to fix: When initializing DatabaseSync, provide a timeout value (in milliseconds) in the options object [1][4]: const { DatabaseSync } = require('node:sqlite'); const db = new DatabaseSync('./path/to/database.sqlite', { readOnly: true, timeout: 5000 // Wait up to 5 seconds for the lock to be released }); If you are using an older version of Node.js where the timeout option is not supported, or if you prefer to set it manually, you can execute a PRAGMA statement immediately after opening the database [2][7][3]: const db = new DatabaseSync('./path/to/database.sqlite', { readOnly: true }); db.exec('PRAGMA busy_timeout = 5000;'); This ensures that the database connection will wait for the specified duration before returning an SQLITE_BUSY error, which is often sufficient to handle transient lock contention [5][7].

Citations:


🌐 Web query:

Node.js node:sqlite DatabaseSync readOnly true error code readonly cannot initialize sqlite

💡 Result:

In Node.js, the DatabaseSync constructor's readOnly option allows you to open a SQLite database in read-only mode [1][2]. According to official documentation, if readOnly is set to true, the operation will fail if the database file does not already exist [1][3]. If you are encountering an error indicating it "cannot initialize sqlite," ensure the following: 1. Path Existence: Confirm the file path provided to the DatabaseSync constructor is correct and that the file already exists on the disk [1][4]. If you are pointing to a new file, the readOnly: true setting will prevent creation and trigger an error [1][2]. 2. Permissions: Verify that the process running the Node.js script has the necessary filesystem permissions to read the specified SQLite database file. 3. Initialization State: If you are manually managing the database lifecycle by setting open: false in the options object, ensure you call the db.open() method before attempting any operations [3][2]. Attempting to interact with a database handle that failed to open or was not opened can result in internal errors or "sqlite API misuse" scenarios [5]. If you are using an in-memory database, note that readOnly: true is generally not applicable in the same way as file-backed databases, as memory databases are transient and created upon initialization [3][2]. For further troubleshooting of specific error codes, check the stack trace against the latest Node.js release, as updates to the node:sqlite module (such as improvements to lock handling and error reporting) are ongoing [5][6][7].

Citations:


🌐 Web query:

SQLite C API SQLITE_READONLY_CANTINIT read-only database WAL file missing SHM file

💡 Result:

The SQLITE_READONLY_CANTINIT error code (1288) occurs when SQLite is unable to initialize the Write-Ahead Logging (WAL) shared memory region, which is required for database access [1]. In WAL mode, SQLite uses a "shared memory" file (the -shm file) to coordinate access between processes [2]. This error typically arises because the process lacks the necessary write permissions to create or access the -shm and -wal files, which are required for WAL-mode operations [3]. Although the connection may be intended for read-only use, SQLite still requires physical write access to these files (or the directory containing them) to initialize the shared memory mapping [4][5]. Specifically, the error indicates that the shared memory region exists (or is needed) but is unusable because the current process cannot write to it [1]. To resolve or avoid this issue: 1. Ensure the process user has read and write permissions on both the database file and the directory containing it, as SQLite must be able to create or modify the -wal and -shm files [4][3]. 2. If the database is on read-only media, consider switching the database journal mode to DELETE (e.g., PRAGMA journal_mode=DELETE) before making the media read-only [4]. 3. For read-only access to a WAL-mode database where you cannot grant write permissions, you may be able to use the immutable query parameter (e.g., file:test.db?immutable=1) if your SQLite version supports it [4]. 4. If you have exclusive access, using PRAGMA locking_mode=EXCLUSIVE can allow operation without the -shm file, as SQLite will use heap memory instead [2][6][7]. Starting with SQLite 3.22.0, a read-only WAL-mode database can be opened if the -shm and -wal files already exist, if they can be created, or if the database is marked as immutable [4][7].

Citations:


Separate retryable database read failures from permanent unreadable states.

readCodexStateDbBackfillStatus maps all SQLite errors to unreadable, but runCodexStateDbBackfillRecovery treats unreadable as terminal before spawning and again during the poll loop. Add a retryable status kind for lock/open failures such as SQLITE_BUSY, SQLITE_LOCKED, SQLITE_CANTOPEN, and read-only WAL issues, and keep the recovery supervisor waiting while that status is reported.

@brennanb2025

brennanb2025 commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor Author

Review complete at 073afc46ea.

  • Resolved the origin/main conflict first and pushed the merge.
  • Senior review/fix loop returned clean after focused regression and performance fixes.
  • Focused validation passed (654 tests), lifecycle validation passed (27 tests), and full typecheck/lint/format checks passed.
  • Electron QA confirmed the Codex backfill-timeout path presents the actionable recovery notice.
  • Latest PR Checks are green, including Windows packaging and both Node test matrices.

Electron QA — Codex backfill recovery notice

Verdict: land after fixes.

@coderabbitai

coderabbitai Bot commented Aug 7, 2026

Copy link
Copy Markdown
Contributor

Note

GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer.

@brennanb2025
brennanb2025 merged commit f0443c3 into main Aug 7, 2026
43 checks passed

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (4)
src/main/agent-hooks/managed-hook-owner-identity.ts (1)

248-262: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Optional: hoist promisify(execFile) to a module constant. The file now calls promisify(execFile) at four separate call sites. A single module-level execFileAsync removes the repetition and the per-call wrapper allocation.

♻️ Proposed refactor
+const execFileAsync = promisify(execFile)

Then replace each await promisify(execFile)( with await execFileAsync(.

src/main/codex/codex-state-db-backfill-recovery.ts (2)

196-221: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Rename RECOVERY_OWNER_CHECK_TIMEOUT_MS to match its use. The constant is passed as waitTimeoutMs, which bounds how long the caller waits for another holder to release the supervisor lock. The current name describes an owner-liveness probe instead. RECOVERY_LOCK_WAIT_TIMEOUT_MS states the actual meaning.


283-288: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

resetForTests clears activeRecoveries without aborting the controllers. A test that starts a recovery and then calls resetForTests leaves the supervisor task running against the previous temporary Codex home. Abort each controller before clearing the map.

♻️ Proposed fix
   resetForTests(): void {
     stopping = false
+    for (const recovery of activeRecoveries.values()) {
+      recovery.controller.abort()
+    }
     activeRecoveries.clear()
   }
src/main/codex/codex-state-db.test.ts (1)

37-76: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add coverage for the remaining status kinds. The suite covers incomplete and complete. It does not cover missing, not-tracked (a state DB without a backfill_state table), or unreadable. unreadable matters most, because runCodexStateDbBackfillRecovery treats it as terminal both before spawning and inside the poll loop. A regression there silently disables recovery.

A BACKFILL_PENDING_MIN_SESSION_FILES - 1 case would also pin the threshold, which is currently only asserted at the exact boundary.

I can generate these cases if you want.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: fea6b57f-65c3-42e1-b63b-eb82b284c60a

📥 Commits

Reviewing files that changed from the base of the PR and between 8c3e953 and 2e74ae3.

📒 Files selected for processing (19)
  • config/tsconfig.cli.json
  • src/main/agent-hooks/managed-hook-install-lock.ts
  • src/main/agent-hooks/managed-hook-owner-identity.test.ts
  • src/main/agent-hooks/managed-hook-owner-identity.ts
  • src/main/codex/codex-hook-trust-grant.test.ts
  • src/main/codex/codex-hook-trust-grant.ts
  • src/main/codex/codex-state-db-backfill-recovery.test.ts
  • src/main/codex/codex-state-db-backfill-recovery.ts
  • src/main/codex/codex-state-db.test.ts
  • src/main/codex/codex-state-db.ts
  • src/main/index.ts
  • src/main/ipc/pty.test.ts
  • src/main/ipc/pty.ts
  • src/main/rate-limits/codex-fetcher.test.ts
  • src/main/rate-limits/codex-fetcher.ts
  • src/renderer/src/components/terminal-pane/codex-backfill-error-detector.test.ts
  • src/renderer/src/components/terminal-pane/codex-backfill-error-detector.ts
  • src/renderer/src/components/terminal-pane/pty-connection.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection.ts
🚧 Files skipped from review as they are similar to previous changes (14)
  • src/main/rate-limits/codex-fetcher.test.ts
  • src/main/rate-limits/codex-fetcher.ts
  • src/main/codex/codex-hook-trust-grant.ts
  • src/renderer/src/components/terminal-pane/pty-connection.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection.ts
  • src/main/index.ts
  • src/main/agent-hooks/managed-hook-install-lock.ts
  • config/tsconfig.cli.json
  • src/main/ipc/pty.test.ts
  • src/renderer/src/components/terminal-pane/codex-backfill-error-detector.ts
  • src/main/ipc/pty.ts
  • src/main/codex/codex-state-db-backfill-recovery.test.ts
  • src/renderer/src/components/terminal-pane/codex-backfill-error-detector.test.ts
  • src/main/codex/codex-hook-trust-grant.test.ts

Comment on lines +237 to +247
const startedAt = stdout.trim()
return startedAt === 'missing' ? null : startedAt ? `win32:${pid}:${startedAt}` : undefined
} catch {
try {
process.kill(pid, 0)
return pid === process.pid ? runtimeProcessIdentity : undefined
} catch (error) {
return hasCode(error, 'ESRCH') ? null : undefined
}
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🌐 Web query:

PowerShell Get-CimInstance Win32_Process CreationDate DateTimeOffset cast local time offset DST

💡 Result:

When you use Get-CimInstance to retrieve the Win32_Process class, the CreationDate property is automatically converted from the WMI CIM_DATETIME string format into a native.NET DateTime object [1][2]. Unlike the older Get-WmiObject cmdlet, which returned these timestamps as strings, Get-CimInstance handles this conversion for you, simplifying time zone and daylight saving time (DST) calculations [1][2]. Because the resulting object is a standard.NET DateTime, you can work with it directly in PowerShell [1]. How to use the CreationDate as a DateTimeOffset: If you need to ensure the time includes offset information or perform specific time zone conversions, you can cast the resulting DateTime object into a DateTimeOffset: $process = Get-CimInstance Win32_Process | Select-Object -First 1 $creationDate = [DateTimeOffset]$process.CreationDate This cast preserves the local time represented by the CIM object. By default, the CIM_DATETIME format includes the UTC offset (e.g., -300 for UTC-5), which the CIM infrastructure uses to correctly instantiate the local time [3][4]. Key considerations: 1. Automatic Conversion: Get-CimInstance performs the conversion from the WMI DMTF format (yyyymmddHHMMSS.mmmmmmsUUU) to DateTime automatically [3][2]. 2. Daylight Saving Time: Because the CIM_DATETIME string contains the UTC offset, the conversion process typically respects the time zone and DST rules active at the time the process was created [3][4]. 3. Avoid Old Methods: You do not need to use [System.Management.ManagementDateTimeConverter]::ToDateTime or [WMI] type accelerators when using Get-CimInstance, as those were intended for the deprecated WMI infrastructure [5][6][2]. If you find that the CreationDate is returning an unexpected offset, ensure your local system time and time zone settings are configured correctly, as WMI relies on the system's current time zone information to interpret the stored offset [4].

Citations:


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Locate and inspect the relevant file and surrounding logic without executing repository code.
if [ -f src/main/agent-hooks/managed-hook-owner-identity.ts ]; then
  echo "FOUND src/main/agent-hooks/managed-hook-owner-identity.ts"
  wc -l src/main/agent-hooks/managed-hook-owner-identity.ts
  sed -n '200,270p' src/main/agent-hooks/managed-hook-owner-identity.ts
else
  echo "Missing target file"
fi

echo
echo "Search acquireInstallLock usages and lock comparison:"
rg -n "acquireInstallLock|managed-hook-owner-identity|Created|Started|CreationDate|startedAt|process identity" src/main -S || true

Repository: stablyai/orca

Length of output: 50370


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "managed-hook-owner-identity tests around Windows identity:"
sed -n '1,130p' src/main/agent-hooks/managed-hook-owner-identity.test.ts
echo
sed -n '130,340p' src/main/agent-hooks/managed-hook-owner-identity.test.ts

echo
echo "managed-hook-install-lock acquireInstallLock implementation:"
sed -n '1,170p' src/main/agent-hooks/managed-hook-install-lock.ts

echo
echo "Relevant tests around owned live process vs PID reuse:"
sed -n '1,130p' src/main/agent-hooks/managed-hook-install-lock.test.ts
sed -n '130,300p' src/main/agent-hooks/managed-hook-install-lock.test.ts

Repository: stablyai/orca

Length of output: 25367


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Behavioral probe for the PowerShell DateTimeOffset cast across DST transitions using .NET runtime semantics
# if PowerShell/.NET are available in this build/test workspace.
if command -v pwsh >/dev/null 2>&1; then
  echo "pwsh available: $(pwsh -NoProfile -Command '$PSVersionTable.PSVersion')"
  pwsh -NoProfile -Command '
    [System.Enum]::GetNames([System.TimeZoneInfo])
    $utc = [System.TimeZoneInfo]::Utc
    $pst = [System.TimeZoneInfo]::FindSystemTimeZoneById("Pacific Standard Time")
    $downdate = [DateTime]"2026-11-01T01:30:00"
    $upe = [DateTime]"2026-03-08T02:30:00"
    $down = [DateTimeOffset]$downdate
    $up = [DateTimeOffset]$upe
    [string]$down.ToUniversalTime().ToUnixTimeMilliseconds()
    [string]$up.ToUniversalTime().ToUnixTimeMilliseconds()
    $down.ToLocalTime().ToString("o zz:zz")
    $up.ToLocalTime().ToString("o zz:zz")
  '
else
  echo "pwsh not available"
fi

if command -v dotnet >/dev/null 2>&1; then
  echo "dotnet available"
  dotnet --list-runtimes
else
  echo "dotnet not available"
fi

Repository: stablyai/orca

Length of output: 983


🌐 Web query:

PowerShell [DateTimeOffset]$localDateTime local time offset cast local TimeZone UTC offset

💡 Result:

When you cast a PowerShell [DateTime] object to a [DateTimeOffset] type, the resulting offset is determined by the DateTime.Kind property of the source object [1]. 1. If the DateTime.Kind is Utc: The resulting [DateTimeOffset] has an offset of zero (UTC) [1][2]. 2. If the DateTime.Kind is Local or Unspecified: The [DateTimeOffset] will automatically apply the current local system's time zone offset [1][2]. Because PowerShell and.NET use the system's local time zone settings to determine this offset for Local/Unspecified kinds, the cast does not perform a conversion to UTC itself; rather, it attaches the current system's local offset to the existing date and time value [1][3]. If you have an [DateTime] object representing a specific point in time but need to ensure it is treated correctly as local time before casting, you can ensure its Kind is set to Local using the.ToLocalTime method [4]. For example: $dt = Get-Date $dto = [DateTimeOffset]$dt In this case, $dto will possess an offset matching the current local machine's time zone offset at the moment of the cast [1]. Note that [DateTimeOffset] represents a specific point in time, and while it holds the offset information, it does not store the specific time zone ID (e.g., Eastern Standard Time) [5][6]. If you need to manipulate or identify the actual time zone, use the [TimeZoneInfo] class [7].

Citations:


Use a stable Windows process start timestamp. CreationDate comes back as local DateTime; casting to [DateTimeOffset] attaches the current local offset, so DST changes can alter the process identity string and make acquireInstallLock treat a live owner as PID-reused. Use $p.CreationDate.ToUniversalTime() or another offset-independent millisecond value.

🧰 Tools
🪛 ast-grep (0.45.0)

[warning] Importing child_process exposes a command-execution surface; ensure any command/argument built from input is validated, and prefer execFile/spawn with an argument array over exec.
Context: import { execFile } from 'node:child_process'
Note: [CWE-78] Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection').

(detect-child-process-typescript)

Comment on lines +150 to +177
try {
while (!childDown && !signal.aborted && dependencies.now() < deadline) {
await dependencies.sleep(RECOVERY_POLL_INTERVAL_MS, signal)
const status = dependencies.readStatus(codexHomePath)
if (status.kind === 'complete') {
await dependencies.terminate(child)
return finish('completed', spawnCount)
}
if (status.kind === 'unreadable') {
await dependencies.terminate(child)
return finish('unreadable', spawnCount)
}
}
} catch (error) {
if (!signal.aborted) {
await dependencies.terminate(child)
throw error
}
}

if (signal.aborted) {
await dependencies.terminate(child)
return finish('stopped', spawnCount)
}
if (!childDown) {
await dependencies.terminate(child)
return finish('gave-up', spawnCount)
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Guard the terminate calls so a termination failure cannot leak the child.

dependencies.terminate(child) is awaited at lines 155, 159, 165, 171, and 175 without error handling. If termination rejects, the rejection propagates out of runCodexStateDbBackfillRecovery. The spawned codex app-server child then stays alive and holds the Codex home for the rest of the app session. The quit path at stopCodexStateDbBackfillRecoveries cannot reap it, because the recovery task has already ended.

♻️ Proposed fix
+    const stopChild = async (): Promise<void> => {
+      try {
+        await dependencies.terminate(child)
+      } catch (error) {
+        console.warn('[codex-state-db-backfill] failed to terminate recovery child:', error)
+      }
+    }

Then replace each await dependencies.terminate(child) in the loop body with await stopChild().

🧰 Tools
🪛 ast-grep (0.45.0)

[warning] Importing child_process exposes a command-execution surface; ensure any command/argument built from input is validated, and prefer execFile/spawn with an argument array over exec.
Context: import { spawn, type ChildProcess } from 'node:child_process'
Note: [CWE-78] Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection').

(detect-child-process-typescript)

Comment on lines +70 to +75
it('does not call a complete backfill pending', async () => {
const home = await createHome()
createBackfillDb(home, 5, 'complete')

expect(isCodexStateDbBackfillPending(home)).toBe(false)
})

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

This test passes even if the complete status is ignored.

The home has no sessions directory, so countCodexSessionFilesUpTo returns 0 and isCodexStateDbBackfillPending returns false through the session-count branch. The complete status is never the deciding factor. Add the session files so the assertion actually exercises the complete short-circuit.

💚 Proposed fix
   it('does not call a complete backfill pending', async () => {
     const home = await createHome()
     createBackfillDb(home, 5, 'complete')
+    const sessions = join(home, 'sessions', '2026', '08', '04')
+    await mkdir(sessions, { recursive: true })
+    await Promise.all(
+      Array.from({ length: 100 }, (_, index) =>
+        writeFile(join(sessions, `rollout-${index}.jsonl`), '{}\n')
+      )
+    )
 
     expect(isCodexStateDbBackfillPending(home)).toBe(false)
   })
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
it('does not call a complete backfill pending', async () => {
const home = await createHome()
createBackfillDb(home, 5, 'complete')
expect(isCodexStateDbBackfillPending(home)).toBe(false)
})
it('does not call a complete backfill pending', async () => {
const home = await createHome()
createBackfillDb(home, 5, 'complete')
const sessions = join(home, 'sessions', '2026', '08', '04')
await mkdir(sessions, { recursive: true })
await Promise.all(
Array.from({ length: 100 }, (_, index) =>
writeFile(join(sessions, `rollout-${index}.jsonl`), '{}\n')
)
)
expect(isCodexStateDbBackfillPending(home)).toBe(false)
})

enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
* fix(codex): recover interrupted state DB backfills

* fix(codex): detect mixed-case backfill timeout

* fix(codex): harden backfill recovery review findings

* fix(codex): keep process identity retries safe
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Interrupted Codex state-DB index leaves managed CODEX_HOME wedged — every Codex pane fails after a 30s hang with nothing surfaced to the user

1 participant