Repository navigation
Closed
Labels
bugSomething isn't working
Description
Summary
Codex 앱을 닫았다가 다시 열면, 스레드/세션 목록이 마지막으로 ocx start를 실행한 시점의 상태로 전부 되돌아간다. 그 사이에 생성/갱신된 세션이 사라지거나 옛 상태로 롤백된다.
Root cause (strong hypothesis, evidence below)
opencodex가 config inject 단계에서 Codex 앱이 라이브로 사용 중인 ~/.codex/state_5.sqlite(스레드/세션 목록 DB)에 별도의 bun:sqlite 쓰기 커넥션을 열고 threads 테이블을 UPDATE한다.
src/codex-history-provider.ts:209/:284/:328에서new Database(stateDbPath)— read-write로 열고PRAGMA busy_timeout도 설정하지 않음.syncCodexHistoryProviderUnsafe()가threads를model_provider='opencodex'등으로 UPDATE하고, 각 rollout JSONL의session_meta첫 줄도 다시 쓴다 (updateSessionMeta,utimesSync로 mtime만 보존).- 이 경로는
injectCodexConfig에서만 호출되고,injectCodexConfig는ocx start(src/cli.ts:64)와ocx init(src/init.ts:135)에서만 실행된다. - 셔임의
ensure는app-server를 내부 커맨드로 제외(CODEX_INTERNAL_COMMANDS,src/codex-shim.ts)하므로, 앱이 띄우는codex app-server로는 동작하지 않는다. 즉 DB write는 명시적ocx start시점에만 일어난다 → 롤백 기준점이 "ocx start 시점"인 증상과 정확히 일치.
state_5.sqlite는 WAL 모드(PRAGMA journal_mode=wal)이고, 앱이 그 DB를 열어 둔 상태에서 외부 프로세스(opencodex)가 동일 DB에 writer 커넥션을 열어 커밋/체크포인트를 건드리는 것은 cross-process WAL race를 만든다. 앱은 자기 커넥션 기준으로 in-memory/WAL 상태를 갖고 있다가, 재시작 시 디스크 상태(외부 writer가 마지막으로 남긴 시점)를 다시 읽으면서 그 시점으로 보이게 된다.
Evidence
lsof ~/.codex/state_5.sqlite→codex(app-server, PID 27795)이 다중 FD로 점유 중 (라이브 owner).ps aux→Codex.app .../codex app-server와opencodex .../src/cli.ts start가 동시에 떠 있음.PRAGMA journal_mode→wal,-wal파일이 ~4MB 미체크포인트 상태.- DB write 진입점:
src/codex-history-provider.ts:196-278(syncCodexHistoryProvider→...Unsafe), 호출처src/codex-inject.ts:279-281. - inject 호출처:
src/cli.ts:64,src/init.ts:135. - 셔임 제외 목록:
src/codex-shim.tsCODEX_INTERNAL_COMMANDS에app-server포함.
Impact
사용자 세션/스레드 목록이 앱 재시작 시 롤백됨. 데이터 유실로 보일 수 있음(실제 rollout 파일은 남아 있을 수 있으나, 앱이 보는 목록이 과거 시점으로 고정).
Proposed fixes (검토 필요)
- 앱이 라이브로 열고 있는
state_5.sqlite에 외부 writer 커넥션을 열지 않는다. provider remap이 필요하면:- 앱이 떠 있지 않을 때만 수행하거나,
- 앱 측 API/IPC를 통해 변경하거나,
- rollout JSONL의
session_meta만 갱신하고 DB는 앱이 자체적으로 재인덱싱하도록 위임.
- 부득이 직접 열어야 한다면 최소한:
PRAGMA busy_timeout설정,- 읽기만 필요한 경로는
{ readonly: true }, - 트랜잭션을 짧게/원자적으로, 체크포인트를 강제하지 않도록.
- inject 시 history sync를 기본 off로 두거나(
syncResumeHistory=false가 이미 존재), 앱 실행 중에는 skip하는 가드 추가.
Verification done / not done
- 확인함: 외부 writer 커넥션 존재, 앱의 라이브 DB 점유, inject 호출 경로가
ocx start/init에만 연결됨, 셔임이app-server를 제외함. - 확인 못함(재현 필요): WAL 프레임 단위에서 정확히 어느 커밋/체크포인트가 롤백을 유발하는지 라이브 재현. 위 메커니즘은 강한 가설이며, fix 전 1회 재현 테스트 권장.
Metadata
Metadata
Assignees
Labels
bugSomething isn't working
Activity
lidge-jun commentedon Jun 29, 2026
Update: codex-rs(앱) 코드까지 교차 검증한 결과 (가설 정정/보강)
~/Developer/codex/121_openai-codex/codex-rs의 앱 측 로직을 직접 읽고 라이브state_5.sqlite로 검증했다. 원래 본문의 핵심 방향(= opencodex가 앱의 라이브 DB에 외부 writer를 여는 것)은 유효하지만, 메커니즘 일부는 정정한다.앱(codex-rs)이
state_5.sqlite를 다루는 방식 (확정)STATE_DB_FILENAME = "state_5.sqlite",journal_mode=WAL,synchronous=NORMAL,busy_timeout=5s, 풀 최대 5커넥션 (state/src/runtime.rsbase_sqlite_options,open_sqlite).use_state_db_only).BackfillStatus::Complete면 즉시 return → 앱을 재시작해도 rollout을 다시 스캔하지 않는다 (rollout/src/state_db.rswait_for_backfill_gate,rollout/src/metadata.rsbackfill_sessions_with_lease). 라이브 DB의backfill_state도complete였다.open_log_file(append)로 경로를 재오픈한다 (rollout/src/recorder.rs).정정된 부분
atomicWriteFile의 temp+rename)도 데이터 유실의 직접 원인은 아니다. 앱이 매 flush마다 경로를 append로 재오픈하므로, rename된 새 inode에 계속 이어 쓴다. (단, opencodex가 rename으로 덮어쓴 그 순간의 내용이 "ocx가 읽어둔 스냅샷"이라는 점은 여전히 위험 요소다.)updated_at이 분 단위로 정상 갱신됨). 롤백은 "앱 종료 후 재오픈"이라는 특정 전이에서만 보고됨.가장 유력한 실제 메커니즘 (cross-process WAL)
state_5.sqlite는 WAL 모드이고, 앱이 그 DB를 연 상태에서 opencodex가 별도 프로세스로 read-write 커넥션을 열었다 닫는다(codex-history-provider.ts:209/284/328,new Database(path),busy_timeout/readonly/journal_mode미설정). bun:sqlite는 마지막 커넥션이 닫힐 때 passive checkpoint를 시도한다. 외부 프로세스가 같은 WAL DB의 체크포인트/락 상태에 개입하면:ocx start)를 기준으로 목록을 보게 될 수 있다.즉 "ocx start 시점 고정"은 opencodex 커넥션이 그 DB에 마지막으로 개입한 시점과 일치한다. inject 호출은
ocx start/ocx init에서만 일어나므로(src/cli.ts:64,src/init.ts:135) 증상의 기준점과 정확히 맞는다.주의: 이 WAL 상호작용 부분은 코드 경로로 강하게 뒷받침되지만, "정확히 어느 체크포인트/프레임에서 유실되는지"는 라이브 재현으로 아직 확정하지 못했다. 강한 가설로 취급하고 fix 전에 1회 재현 테스트를 권장한다.
권장 수정 (우선순위순)
state_5.sqlite에 외부 writer 커넥션을 절대 열지 않는다. provider remap이 필요하면 (a) 앱 미실행 시에만 수행, (b) 앱 IPC/API 경유, (c) rollout JSONL의session_meta만 갱신하고 DB 반영은 앱에 위임.PRAGMA busy_timeout설정, 읽기 경로는{ readonly: true }, 트랜잭션 최소화, 외부 프로세스에서 체크포인트를 유발하지 않도록wal_autocheckpoint/close 동작 점검.syncResumeHistory존재) 또는 "앱 실행 중이면 skip" 가드 추가.검증/미검증
lidge-jun commentedon Jun 30, 2026
Resolved in
a846251(fix(history): non-destructive native restore to prevent session rollback), released in v2.6.11 (npmlatest).The fix targets the exact root cause described in this issue — the proxy opening a writer connection / rewriting live rollouts against the app's live
state_5.sqlite:openStateDb()now setsPRAGMA busy_timeout = 5000on the live state DB, matching how the Codex app expects a secondary writer to behave (no longer slams the app's connection pool into a half-applied checkpoint).appendRolloutLine()usesO_APPENDfor the trailingsession_metainstead of temp+rename, so the app's cached append handle is no longer orphaned (this was what dropped new turns / reverted to theocx startsnapshot).session_metabefore writing.patchFirstLineProviderInPlace()does a length-preserving in-place line-1 provider fix (covers theread_session_meta_lineclone path).Verified: tsc clean, full suite green, live repro keeps post-restore turns, reviewed by gpt-5.5 (APPROVE). All fix commits are ancestors of the released
main/dev.If a session revert still reproduces on v2.6.11, please reopen with the
ocx starttiming andlsof ~/.codex/state_5.sqliteoutput.