Repository navigation
fix(codex): recover interrupted state DB backfills - #12617
Conversation
📝 WalkthroughWalkthroughThe 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)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
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. Comment |
|
Managed-home recovery: a stale running backfill with a dead supervisor owner recovered to Actionable failure state: when recovery could not proceed, the Codex pane rendered the background-recovery guidance and retry instructions. |
…ckfill-wedge-11830 # Conflicts: # src/main/ipc/pty.ts
|
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. |
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (4)
src/main/codex/codex-state-db-backfill-recovery.ts (1)
267-272: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueReturn the
readypromise 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
startCodexStateDbBackfillRecoveryInBackgroundruns synchronously up to itsMap.set. That coupling is invisible at the call site and breaks if anyone adds anawaitbefore line 257.Return
readyalongsidetask, or expose a smallstartAndWaitForArbitrationthat awaits thereadypromise it created.src/main/codex/codex-state-db.test.ts (2)
57-68: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winDerive 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 winAdd cases for the
unreadableandnot-trackedstatuses.
runCodexStateDbBackfillRecoverybranches on every status kind. Two kinds drive important decisions and have no test here:
unreadable: recovery returns early and reportsunreadable. Cover it with astate_N.sqlitefile that holds non-SQLite bytes.not-tracked: recovery falls through to the session-count heuristic. Cover both shapes, a database with nobackfill_statetable and abackfill_staterow whosestatusis not a string.A
findNewestCodexStateDbPathcase for a home directory that does not exist would also pin thenullreturn.src/main/agent-hooks/managed-hook-owner-identity.ts (1)
121-121: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winUse the PowerShell 4.0-compatible
MachineGuidquery.
Get-ItemPropertyValuerequires PowerShell 5.0, so Windows hosts with PowerShell 4.0 fall through toruntimeHostIdentityand keep the host scope unverifiable. UseGet-ItemProperty ... | Select-Object -ExpandProperty MachineGuidfor 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
📒 Files selected for processing (23)
.oxlintrc.jsonconfig/scripts/relay-watcher-fault-harness.mjsconfig/tsconfig.cli.jsonsrc/main/agent-hooks/managed-hook-install-lock.tssrc/main/agent-hooks/managed-hook-owner-identity.test.tssrc/main/agent-hooks/managed-hook-owner-identity.tssrc/main/codex/codex-hook-trust-grant.test.tssrc/main/codex/codex-hook-trust-grant.tssrc/main/codex/codex-state-db-backfill-recovery.test.tssrc/main/codex/codex-state-db-backfill-recovery.tssrc/main/codex/codex-state-db.test.tssrc/main/codex/codex-state-db.tssrc/main/index.tssrc/main/ipc/pty.test.tssrc/main/ipc/pty.tssrc/main/rate-limits/codex-fetcher.test.tssrc/main/rate-limits/codex-fetcher.tssrc/main/runtime/orca-runtime.tssrc/renderer/src/components/github/GitHubMarkdownComposerEditorPane.tsxsrc/renderer/src/components/terminal-pane/codex-backfill-error-detector.test.tssrc/renderer/src/components/terminal-pane/codex-backfill-error-detector.tssrc/renderer/src/components/terminal-pane/pty-connection.test.tssrc/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
| if (stopping || !isCodexStateDbBackfillPending(codexHomePath)) { | ||
| return Promise.resolve(null) | ||
| } |
There was a problem hiding this comment.
🚀 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 asynccountCodexSessionFilesUpTobuilt onfs/promisesopendirso 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-L97src/main/codex/codex-state-db.ts#L36-L72
| } catch (error) { | ||
| return { | ||
| kind: 'unreadable', | ||
| stateDbPath, | ||
| error: error instanceof Error ? error.message : String(error) | ||
| } |
There was a problem hiding this comment.
🎯 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:
- 1: https://deverrors.com/errors/sqlite-sqlite-readonly-cantinit-unable-to-initialize-wal-file
- 2: https://sqlite.org/rescode.html
- 3: https://sqlite.org/walformat.html
- 4: https://sqlite.org/wal.html
- 5: https://sqlite.org/forum/info/0667868158167ccb
- 6: https://www.mail-archive.com/[email protected]/msg113627.html
🏁 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 || trueRepository: 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')
}
}
JSRepository: 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:
- 1: https://nodejs.org/api/sqlite.html
- 2: node:sqlite - add "timeout" as an option for initializing DatabaseSync nodejs/node#57597
- 3: [Bug]: SessionStart database is locked — NodeSQLiteAdapter drops busy_timeout on Node ≥22.5 mksglu/context-mode#642
- 4: nodejs/node@0df87e07a0
- 5: https://sqlite.org/wal.html
- 6: https://nodejs.org/docs/latest-v22.x/api/sqlite.html
- 7: sqlite: database is locked nodejs/node#57741
🌐 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:
- 1: https://nodejs.org/api/sqlite.html
- 2: https://github.com/nodejs/node/blob/main/doc/api/sqlite.md
- 3: https://nodejs.org/docs/latest-v23.x/api/sqlite.html
- 4: https://nodejs.org/docs/v22.12.0/api/sqlite.html
- 5: sqlite: memory leak and sqlite API misuse nodejs/node#63831
- 6:
node:sqliteopening DatabaseSync in readOnly mode no longer acquiring shared lock? denoland/deno#31807 - 7: lib,src,test,doc: add node:sqlite module nodejs/node#53752
🌐 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:
- 1: https://sqlite.org/rescode.html
- 2: https://www.sqlite.org/walformat.html
- 3: https://deverrors.com/errors/sqlite-sqlite-readonly-cantinit-unable-to-initialize-wal-file
- 4: https://sqlite.org/wal.html
- 5: https://sqlite.org/forum/info/0667868158167ccb
- 6: https://sqlite.org/tempfiles.html
- 7: https://www.sqlite.org/wal.html
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.
|
Review complete at
Verdict: land after fixes. |
…ckfill-wedge-11830
|
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. |
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (4)
src/main/agent-hooks/managed-hook-owner-identity.ts (1)
248-262: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueOptional: hoist
promisify(execFile)to a module constant. The file now callspromisify(execFile)at four separate call sites. A single module-levelexecFileAsyncremoves the repetition and the per-call wrapper allocation.♻️ Proposed refactor
+const execFileAsync = promisify(execFile)Then replace each
await promisify(execFile)(withawait execFileAsync(.src/main/codex/codex-state-db-backfill-recovery.ts (2)
196-221: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueRename
RECOVERY_OWNER_CHECK_TIMEOUT_MSto match its use. The constant is passed aswaitTimeoutMs, 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_MSstates the actual meaning.
283-288: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value
resetForTestsclearsactiveRecoverieswithout aborting the controllers. A test that starts a recovery and then callsresetForTestsleaves 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 winAdd coverage for the remaining status kinds. The suite covers
incompleteandcomplete. It does not covermissing,not-tracked(a state DB without abackfill_statetable), orunreadable.unreadablematters most, becauserunCodexStateDbBackfillRecoverytreats it as terminal both before spawning and inside the poll loop. A regression there silently disables recovery.A
BACKFILL_PENDING_MIN_SESSION_FILES - 1case 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
📒 Files selected for processing (19)
config/tsconfig.cli.jsonsrc/main/agent-hooks/managed-hook-install-lock.tssrc/main/agent-hooks/managed-hook-owner-identity.test.tssrc/main/agent-hooks/managed-hook-owner-identity.tssrc/main/codex/codex-hook-trust-grant.test.tssrc/main/codex/codex-hook-trust-grant.tssrc/main/codex/codex-state-db-backfill-recovery.test.tssrc/main/codex/codex-state-db-backfill-recovery.tssrc/main/codex/codex-state-db.test.tssrc/main/codex/codex-state-db.tssrc/main/index.tssrc/main/ipc/pty.test.tssrc/main/ipc/pty.tssrc/main/rate-limits/codex-fetcher.test.tssrc/main/rate-limits/codex-fetcher.tssrc/renderer/src/components/terminal-pane/codex-backfill-error-detector.test.tssrc/renderer/src/components/terminal-pane/codex-backfill-error-detector.tssrc/renderer/src/components/terminal-pane/pty-connection.test.tssrc/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
| 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 | ||
| } | ||
| } | ||
| } |
There was a problem hiding this comment.
🎯 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:
- 1: https://stackoverflow.com/questions/63762401/wmic-query-on-creationdate-to-find-old-processes
- 2: https://stackoverflow.com/questions/77124820/powershell-script-failing-on-converttodatetime
- 3: https://learn.microsoft.com/en-us/windows/win32/wmisdk/cim-datetime
- 4: https://learn.microsoft.com/en-sg/answers/questions/151635/win10-wmi-showing-daylight-time-strings
- 5: https://kb.ilves.se/powershell-format-wmi-timestap-to-normal-datetime/
- 6: https://miketerrill.net/2014/10/10/comparing-configmgr-date-formats-in-powershell/
🏁 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 || trueRepository: 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.tsRepository: 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"
fiRepository: 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:
- 1: https://learn.microsoft.com/en-us/dotnet/api/system.datetimeoffset.op_implicit?view=net-10.0
- 2: https://learn.microsoft.com/en-us/dotnet/api/system.datetimeoffset.-ctor?view=netframework-4.8.1
- 3: https://stackoverflow.com/questions/37257964/remove-time-zone-offset-from-datetimeoffset
- 4: ConvertFrom-JSON incorrectly deserializes dates to DateTime PowerShell/PowerShell#13592
- 5: https://github.com/dotnet/docs/blob/main/docs/standard/datetime/converting-between-datetime-and-offset.md
- 6: https://learn.microsoft.com/en-us/dotnet/standard/datetime/converting-between-datetime-and-offset
- 7: Add timezone/offset related parameters to the Get-Date command PowerShell/PowerShell#13312
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)
| 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) | ||
| } |
There was a problem hiding this comment.
🩺 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)
| it('does not call a complete backfill pending', async () => { | ||
| const home = await createHome() | ||
| createBackfillDb(home, 5, 'complete') | ||
|
|
||
| expect(isCodexStateDbBackfillPending(home)).toBe(false) | ||
| }) |
There was a problem hiding this comment.
📐 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.
| 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) | |
| }) |
* 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



Fixes #11830. Related: #11828 and upstream openai/codex#37003.
Summary
codex app-serverclaimant behind an exact process-incarnation lock, recovering dead or PID-reused Orca owners while leaving live owners and concurrent Orca instances untouched.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:
Testing
pnpm lintpnpm typecheckpnpm testpnpm buildFocused validation after the final rebase:
The full local
src/main/ipc/pty.test.tsfile 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_statedoes 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
fileMustExist; Orca never updates, deletes, or recreates Codex-owned state.Caveats
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.