Skip to content

Sessions revert to the last ocx start snapshot after closing/reopening Codex app #49

Closed

Description

@lidge-jun

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.ts CODEX_INTERNAL_COMMANDS에 app-server 포함.

Impact

사용자 세션/스레드 목록이 앱 재시작 시 롤백됨. 데이터 유실로 보일 수 있음(실제 rollout 파일은 남아 있을 수 있으나, 앱이 보는 목록이 과거 시점으로 고정).

Proposed fixes (검토 필요)

  1. 앱이 라이브로 열고 있는 state_5.sqlite에 외부 writer 커넥션을 열지 않는다. provider remap이 필요하면:
    • 앱이 떠 있지 않을 때만 수행하거나,
    • 앱 측 API/IPC를 통해 변경하거나,
    • rollout JSONL의 session_meta만 갱신하고 DB는 앱이 자체적으로 재인덱싱하도록 위임.
  2. 부득이 직접 열어야 한다면 최소한:
    • PRAGMA busy_timeout 설정,
    • 읽기만 필요한 경로는 { readonly: true },
    • 트랜잭션을 짧게/원자적으로, 체크포인트를 강제하지 않도록.
  3. inject 시 history sync를 기본 off로 두거나(syncResumeHistory=false가 이미 존재), 앱 실행 중에는 skip하는 가드 추가.

Verification done / not done

  • 확인함: 외부 writer 커넥션 존재, 앱의 라이브 DB 점유, inject 호출 경로가 ocx start/init에만 연결됨, 셔임이 app-server를 제외함.
  • 확인 못함(재현 필요): WAL 프레임 단위에서 정확히 어느 커밋/체크포인트가 롤백을 유발하는지 라이브 재현. 위 메커니즘은 강한 가설이며, fix 전 1회 재현 테스트 권장.

Activity

  1. added
    bug
    on Jun 29, 2026
  2. lidge-jun commented on Jun 29, 2026

    @lidge-jun
    OwnerAuthor

    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.rs base_sqlite_options, open_sqlite).
    • 스레드 목록은 이 DB를 단일 소스로 읽는다(use_state_db_only).
    • rollout→DB 미러(backfill)는 BackfillStatus::Complete면 즉시 return → 앱을 재시작해도 rollout을 다시 스캔하지 않는다 (rollout/src/state_db.rs wait_for_backfill_gate, rollout/src/metadata.rs backfill_sessions_with_lease). 라이브 DB의 backfill_state도 complete였다.
    • 라이브 rollout writer는 파일 핸들을 상시 보유하지 않고, flush마다 open_log_file(append)로 경로를 재오픈한다 (rollout/src/recorder.rs).

    정정된 부분

    1. "앱 재시작 시 backfill 재스캔으로 ocx start 시점으로 롤백"은 아니다. backfill은 일회성이라 재스캔하지 않는다.
    2. inode 교체(opencodex atomicWriteFile의 temp+rename)도 데이터 유실의 직접 원인은 아니다. 앱이 매 flush마다 경로를 append로 재오픈하므로, rename된 새 inode에 계속 이어 쓴다. (단, opencodex가 rename으로 덮어쓴 그 순간의 내용이 "ocx가 읽어둔 스냅샷"이라는 점은 여전히 위험 요소다.)
    3. 평상시 라이브 동작은 정상이었다(DB 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의 체크포인트/락 상태에 개입하면:

    • 앱이 아직 메인 DB로 넘기지 않은(WAL에만 있는) 최신 커밋과의 일관성이 흔들리거나,
    • 앱 종료 시점의 체크포인트 경쟁으로 최신 프레임 일부가 메인 DB에 반영되지 못하고,
    • 다음 앱 기동 시 메인 DB(외부 writer가 마지막으로 정리한 시점 ≈ ocx start)를 기준으로 목록을 보게 될 수 있다.

    즉 "ocx start 시점 고정"은 opencodex 커넥션이 그 DB에 마지막으로 개입한 시점과 일치한다. inject 호출은 ocx start/ocx init에서만 일어나므로(src/cli.ts:64, src/init.ts:135) 증상의 기준점과 정확히 맞는다.

    주의: 이 WAL 상호작용 부분은 코드 경로로 강하게 뒷받침되지만, "정확히 어느 체크포인트/프레임에서 유실되는지"는 라이브 재현으로 아직 확정하지 못했다. 강한 가설로 취급하고 fix 전에 1회 재현 테스트를 권장한다.

    권장 수정 (우선순위순)

    1. 앱이 실행 중일 때는 state_5.sqlite에 외부 writer 커넥션을 절대 열지 않는다. provider remap이 필요하면 (a) 앱 미실행 시에만 수행, (b) 앱 IPC/API 경유, (c) rollout JSONL의 session_meta만 갱신하고 DB 반영은 앱에 위임.
    2. 부득이 직접 열어야 한다면 최소한: PRAGMA busy_timeout 설정, 읽기 경로는 { readonly: true }, 트랜잭션 최소화, 외부 프로세스에서 체크포인트를 유발하지 않도록 wal_autocheckpoint/close 동작 점검.
    3. inject 시 history sync 기본 off(이미 syncResumeHistory 존재) 또는 "앱 실행 중이면 skip" 가드 추가.

    검증/미검증

    • 검증함: 앱의 DB 오픈 모드, 단일 소스 읽기, backfill 일회성, 라이브 append 재오픈, opencodex 외부 writer 경로 및 호출 지점, 라이브 DB 정합성(현재 정상).
    • 미검증: cross-process WAL 체크포인트 경쟁의 정확한 유실 프레임 — 라이브 재현 필요.
  3. lidge-jun commented on Jun 30, 2026

    @lidge-jun
    OwnerAuthor

    Resolved in a846251 (fix(history): non-destructive native restore to prevent session rollback), released in v2.6.11 (npm latest).

    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 sets PRAGMA busy_timeout = 5000 on 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() uses O_APPEND for the trailing session_meta instead of temp+rename, so the app's cached append handle is no longer orphaned (this was what dropped new turns / reverted to the ocx start snapshot).
    • A thread-id guard checks the latest session_meta before writing.
    • patchFirstLineProviderInPlace() does a length-preserving in-place line-1 provider fix (covers the read_session_meta_line clone 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 start timing and lsof ~/.codex/state_5.sqlite output.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions