Skip to content

fix(codex): index a new account home before bridging history into it - #22971

Merged
brennanb2025 merged 5 commits into
stablyai:mainfrom
AmoabaKelvin:fix-codex-new-account-first-launch-timeout
Sep 29, 2026
Merged

brennanb2025 merged 5 commits into
stablyai:mainfrom
AmoabaKelvin:fix-codex-new-account-first-launch-timeout

Conversation

@AmoabaKelvin

@AmoabaKelvin AmoabaKelvin commented Sep 26, 2026 •

Copy link
Copy Markdown
Collaborator
Files Added Deleted Net
Test 6 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​540 $\color{#cf222e}{\Huge{\mathbf{−}}}$​35 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​505
Prod 7 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​402 $\color{#cf222e}{\Huge{\mathbf{−}}}$​90 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​312

ELI5

Each Codex account in Orca gets its own folder. The first time Codex runs in a folder, it reads every old conversation in it to build its list for /resume, and a launching Codex gives up if that takes more than 30 seconds. Orca was copying all your old conversations into a new account's folder before Codex had ever run there, so that first read covered your whole history (19 GB for the reporter) and every launch failed. Now Codex runs on the empty folder first, and your history is added afterwards.

What Changed

Before: adding a Codex account with a large history made every Codex pane in that account fail for minutes with timed out waiting for state db backfill ... after 30s (status: running).

After: the new account's first launch starts immediately, however big the history is. Old conversations still appear in /resume. They're indexed in the background, so they show up gradually on very large histories.

Mechanism, in the account history bridge (codex-account-session-bridge.ts):

  1. If the account folder has no Codex database and no conversations yet, Orca starts codex app-server on it once, in read-only mode. App-server finishes creating its database before it answers the first request, so Codex indexes an empty folder in about 100 ms.
  2. Orca then links the history in, as before.
  3. Codex doesn't pick up files added after that first index by itself, and /resume reads only its database. So Orca asks Codex to read each newly linked conversation (thread/read) in small background batches. This goes through the same batch loop Orca already uses for the default Codex folder (codex-session-index-heal.ts), so it has the same limits and stops when the app quits.

Linking waits for the next launch in two cases:

  • Codex is still indexing the folder.
  • The database can't be read (this case is logged).

A folder that already has conversations but no database inside it gets history linked on every launch, as on main. That happens when Codex keeps its database elsewhere (sqlite_home, which Orca points at the same place for every account folder) or runs a version with no database. Either way there is nothing in the folder for a launch to wait on.

Why

The timeout is only where the problem shows up. The cause is the order: history was added before Codex's first index. Orca can't make Codex's first index cheaper or skip it, and it never writes to Codex's database, so running that index before history arrives is the only thing that removes the wait.

Alternatives considered:

  • Wait for the pane's own Codex to create the database, polling up to 10 minutes. A Codex with no database would never get history. Every launch would also sit in a 10-minute loop, and selecting an account without launching it would leave one running.
  • Link history later without indexing it. Codex's /resume picker reads only its database. It checks the conversation files on disk only when the database is empty. So linked history would be invisible. I confirmed this against codex 0.156.1.
  • Only link a limited number of recent conversations. Whether that fits in 30 seconds depends on disk speed and file sizes, so there's no safe number.

Linked Issue

Fixes #20669

Visual Proof

N/A. This is main-process ordering with no UI change. The evidence is in Testing: startup time and what /resume can see, measured with the real Codex binary.

Testing

Checked against the real codex 0.156.1 binary on scratch CODEX_HOME folders (never the real ~/.codex):

  • Old order: with 300 conversations (752 MB) linked before Codex's first start, startup took 3.9 s, and that grows with history size. With history linked after the first start and no indexing, /resume's database listing showed 1 of 300 conversations.
  • New order: Codex indexed an empty folder, all 300 linked conversations were then indexed, the next start took 57 ms, and /resume lists the history.

The real-binary contract test (codex-index-heal-binary-contract.test.ts) now also checks that an empty first run leaves the index marked complete, and that thread/read indexes a compressed .jsonl.zst conversation. It passes on both 0.150.1 (the version CI pins) and 0.156.1.

The 30-second timeout the reporter hit is in Codex's source: codex-rs/rollout/src/state_db.rs.

  • I manually tested these changes locally
  • Automated tests added/updated, or explained why not below

Review

Agent skill upstream boundary

  • Not applicable, or this change follows docs/reference/agent-skill-sharing-upstream-boundary.md and copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Checklist

  • This PR is small and focused
  • I explained what changed and why (ELI5, the user-facing before/after, the mechanism, and why over the alternatives)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)

@coderabbitai

coderabbitai Bot commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

The account bridge checks the target Codex state DB and backfill status before it links rollout files. When eligible, it can create a state DB. The bridge records thread IDs and timestamps for linked and already-existing rollouts, then calls index healing. The healer reads missing threads in bounded batches and reports outcomes. Tests cover DB creation, readiness checks, rollout linking, index healing, and migration history bridging.

Priority: ➖ Normal

Severity of issue fixed: Medium

Merge Risk: 🟡 Moderate · up to 278d8

Bridging large history into an account home that already has some conversations but no Codex database can still slow or time out the first launch. Some bridged conversations may also stay missing from /resume until the app restarts. Resolve the database-readiness gap before merging.

Security Architecture Review

Security architecture risk: 🟡 Moderate · up to 278d8

History from one Codex account can now become searchable in another account’s home more reliably. This appears intentional, and no direct external disclosure was established, but the account boundary and failure-recovery behavior merit review.

Retained concerns

  • Medium · security · inferred: Automatic index healing makes history linked from sibling accounts discoverable in the selected account’s session database. Bridging across those accounts is intentional and predates this PR, but the new indexing step increases effective visibility without a source-specific account policy at the bridge. Disclosure to another service is not established and would require a further use of that history.
Security review details

Security Blast Radius

  • inferred — The relevant exposure is across locally managed Codex account identities: history from configured and sibling homes is linked into the selected home and can now be indexed there. The examined production path does not establish remote reachability or an independently attacker-controlled source-home caller.

Security Findings and Attack Paths

  • inferred — The new indexing step increases the chance that a user resumes a sibling account’s linked conversation while operating under the selected account. No evidence establishes that indexing alone transmits conversation contents outside the local home.

Trust Boundaries and Controls

  • observed — Production launch checks ownership of the destination managed home and collects trusted managed source homes. The lower-level bridge relies on its caller for source authorization; its own path check only excludes the target and duplicates.

Resilience and Maintainability Implications

  • observed — The readiness gate avoids feeding a known running backfill, and stopped or aborted read batches leave unprocessed IDs unreported for a later pass. Per-thread missing or failed outcomes instead enter a process-lifetime skip cache.

Hardening Proposals

  • proposed — Make the intended cross-account history-sharing policy explicit before indexing sibling-account threads, and consider validating an existing target rollout’s type and provenance before treating it as successfully bridged.
🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Linked Issues check ⚠️ Warning The PR implements the main ordering fix for [#20669]. It creates the state DB before linking history and heals the target index after linking. It also defers unreadable and incomplete homes. Two codin… Update the readiness logic to poll the backfill status every second for up to 10 minutes. Permit linking when the status is complete or not-tracked. Defer other incomplete or unreadable statuses.
Docstring Coverage ⚠️ Warning Docstring coverage is 64.52% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 31 functions across 13 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the primary change: indexing a new Codex account home before bridging history.
Description check ✅ Passed The description is complete and relevant. It includes the user impact, implementation details, rationale, linked issue, testing evidence, visual-proof rationale, and completed checklist items. Optiona…
Out of Scope Changes check ✅ Passed The changes remain connected to [#20669]. State-DB creation, bridge gating, post-link index healing, compressed-rollout support, quit handling, and their tests support prompt first launches and `/resu…
Full details: Linked Issues check

Explanation

The PR implements the main ordering fix for [#20669]. It creates the state DB before linking history and heals the target index after linking. It also defers unreadable and incomplete homes. Two coding requirements remain unmet. isReadyForBridgedHistory reads the backfill status once; it does not poll every second for up to 10 minutes. It returns false for not-tracked, although [#20669] requires linking for that status. The tests and current implementation preserve this behavior.

  • Fix all pre-merge checks with AI

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.

@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: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: f260924b-c89e-4de0-80a8-b1e5b9650f8b

📥 Commits

Reviewing files that changed from the base of the PR and between 8d21fdb and 4bcc1903e93fca1c79aa3ac1b6df9064783e0864.

📒 Files selected for processing (10)
  • src/main/codex-accounts/runtime-home-service-per-account-migration.test.ts
  • src/main/codex/codex-account-session-bridge.test.ts
  • src/main/codex/codex-account-session-bridge.ts
  • src/main/codex/codex-account-session-index-heal.test.ts
  • src/main/codex/codex-account-session-index-heal.ts
  • src/main/codex/codex-session-index-heal-state.ts
  • src/main/codex/codex-session-index-heal.ts
  • src/main/codex/codex-state-db-test-fixture.ts
  • src/main/codex/codex-state-db.test.ts
  • src/main/codex/codex-state-db.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 8 remain after this review.

@pullfrog pullfrog 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.

Important

The new gate has two fail-open paths: it ignores compressed (.jsonl.zst) history, and it treats a state DB without backfill_state as safe to link into even though Codex will then run a blocking backfill over it.

Reviewed changes

  • Bridge gate — isReadyForBridgedHistory now runs codex app-server on an empty home so Codex creates and stamps its state DB before any history is linked, then links and lazily indexes via thread/read.
  • New per-account heal — codex-account-session-index-heal.ts adds createCodexAccountStateDb and healCodexAccountSessionIndex, reusing the system-home heal's launch settings and batch limits.
  • State DB read — readIndexedCodexThreadIds reads indexed thread ids read-only from the newest state_N.sqlite.
  • Rollout parsing — extracted parseCodexRolloutThreadId and exported the heal constants/invocation builder for reuse.
  • Tests — stub-driven coverage of the gate branches, the heal diff/retry/abort paths, and a new state-DB test fixture.

ℹ️ The gate's core Codex assumption is not pinned by the real-binary contract test

The new gate depends on "an app-server session that sends no RPC still leaves the state DB stamped complete before initialize returns." That holds for Codex 0.156.1, but the repo's codex-index-heal-binary-contract.test.ts exists specifically to catch Codex drift, and it does not assert it. Every new test for the gate stubs createStateDb, so a Codex release that changed this ordering would keep them all green while the gate silently stopped linking.

Technical details
# Pin the empty-session state-DB contract

## Affected sites
- `src/main/codex/codex-index-heal-binary-contract.test.ts:80-88` — `createBackfilledCodexHome` asserts only `readThreadRows(home) === []`, which passes vacuously when `findNewestCodexStateDbPath` returns null (no DB created); it never calls `readCodexStateDbBackfillStatus`.
- `src/main/codex/codex-account-session-index-heal.ts:62-66` — `createCodexAccountStateDb` relies on that contract.
- `src/main/codex/codex-account-session-bridge.ts:71-81` — the gate relies on the resulting `complete` status.

## Required outcome
- The real binary must prove that a no-RPC app-server session on an empty home leaves `readCodexStateDbBackfillStatus(home).kind === 'complete'`, so the gate's ordering assumption is guarded rather than hand-verified.

## Open questions for the human
- The contract job pins `CODEX_CLI_VERSION: 0.150.1` while this change was verified on 0.156.1; is the gate's behavior the same on the CI version?

ℹ️ Nitpicks

  • parseCodexRolloutThreadId matches only \.jsonl$, so .jsonl.zst rollouts that the bridge links never enter bridgedThreadIds and are never healed. If /resume is DB-driven, that compressed history stays invisible — worth confirming against the real binary.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@AmoabaKelvin
AmoabaKelvin force-pushed the fix-codex-new-account-first-launch-timeout branch from 4bcc190 to ec0b6a0 Compare September 26, 2026 02:26

@pullfrog pullfrog 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.

ℹ️ No critical issues — prior review feedback is addressed. One optional test-coverage note below.

Reviewed changes

Re-reviewed the increment since the prior pullfrog review at 4bcc1903e9.

  • Compressed rollouts recognized — countCodexSessionFilesUpTo counts .jsonl.zst, and the rollout-id regex accepts the .zst suffix, so compressed history is both bridged and added to bridgedThreadIds for healing.
  • not-tracked gate tightened — a state DB without backfill_state (which Codex migrates to pending before a blocking backfill) no longer counts as ready to link history into, matching isCodexStateDbBackfillPending.
  • Contract test extended — the real-binary test now asserts an empty no-RPC app-server session leaves readCodexStateDbBackfillStatus(home).kind === 'complete'.
  • Tests added — compressed-only bridge + heal, skip-linking on a pre-backfill DB, and compressed-rollout counting.

ℹ️ Compressed thread/read read-repair is a new Codex dependency the contract test doesn't pin

The real-binary contract test exists specifically to catch Codex drift, and this change makes Orca depend on Codex's thread/read read-repair supporting compressed rollouts. A Codex release that dropped compressed repair would leave the stub-driven bridge test green while compressed history silently stopped appearing in /resume. I traced Codex rust-v0.156.1 and the repair path is compression-aware, so this is a coverage gap rather than a defect.

Technical details
# Pin compressed `thread/read` read-repair in the contract test

## Affected sites
- `src/main/codex/codex-session-index-heal-state.ts:25` — regex now accepts `.jsonl.zst`, so compressed threads enter `bridgedThreadIds`.
- `src/main/codex/codex-account-session-index-heal.ts:148` — heals via `thread/read`; correctness of compressed indexing lives in the Codex binary.
- `src/main/codex/codex-index-heal-binary-contract.test.ts:92-121` — `writeRollout` only ever writes `.jsonl`; no arm exercises a compressed rollout.
- `src/main/codex/codex-account-session-bridge.test.ts:284-302` — asserts only that `healIndexStub` was called with the thread id (a double), not that Codex indexes the compressed file.

## Required outcome
- A real-binary arm proving `thread/read` on a `.jsonl.zst`-only rollout inserts the `threads` row, so the new compressed dependency is guarded rather than hand-verified.

## Suggested approach (optional)
- Node 24 exposes `zlib.zstdCompressSync`, so a fixture can write a real `.jsonl.zst` alongside the existing `writeRollout` shape. Codex's own `rollout/compress` RPC could also produce it. Keep it as one narrow arm, consistent with the file's stated "keep it narrow" intent.

## Open questions for the human
- The contract job pins `CODEX_CLI_VERSION: 0.150.1` while the change was verified on 0.156.1; is compressed repair present on the CI version?

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@AmoabaKelvin
AmoabaKelvin force-pushed the fix-codex-new-account-first-launch-timeout branch from ec0b6a0 to cfebdde Compare September 27, 2026 06:03

@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: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 89ffe8ce-6b99-4ce4-8e4c-aecf645b6940

📥 Commits

Reviewing files that changed from the base of the PR and between ec0b6a0e63c31b68b3f64b7b841b4b9bd8eaea91 and cfebddecb4eb3b7a62362fc4d238871a06bd483a.

📒 Files selected for processing (8)
  • src/main/codex/codex-account-session-bridge.test.ts
  • src/main/codex/codex-account-session-bridge.ts
  • src/main/codex/codex-account-session-index-heal.test.ts
  • src/main/codex/codex-account-session-index-heal.ts
  • src/main/codex/codex-index-heal-binary-contract.test.ts
  • src/main/codex/codex-session-index-heal.test.ts
  • src/main/codex/codex-session-index-heal.ts
  • src/main/startup/main-process-quit.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 7 remain after this review.

Comment on lines +96 to +103
({ threadId }, outcome) => {
if (outcome === 'healed') {
summary.healedThreads += 1
return
}
failed.add(threadId)
summary.failedThreads += 1
},

@coderabbitai coderabbitai Bot Sep 27, 2026 •

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

Do not write off missing threads for the whole process lifetime.

The callback adds every non-healed outcome to failed, including missing. A thread read can return missing when the rollout is not present yet or the link was replaced. After that, the thread is never read again until Orca restarts, even after the rollout becomes available. Only this failure is permanent: a thread that stays in the bridge set but is excluded from /resume. Count missing separately and keep it out of the process-wide skip set. As an alternative, keep the skip set only for failed.

Proposed fix
       if (outcome === 'healed') {
         summary.healedThreads += 1
         return
       }
-      failed.add(threadId)
+      if (outcome === 'failed') {
+        failed.add(threadId)
+      }
       summary.failedThreads += 1
📝 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
({ threadId }, outcome) => {
if (outcome === 'healed') {
summary.healedThreads += 1
return
}
failed.add(threadId)
summary.failedThreads += 1
},
({ threadId }, outcome) => {
if (outcome === 'healed') {
summary.healedThreads += 1
return
}
if (outcome === 'failed') {
failed.add(threadId)
}
summary.failedThreads += 1
},

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

A "no rollout found" read is now reported as missingThreads instead of a failure (a29d8b0)

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.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail
git rev-parse --short HEAD
ast-grep outline src/main/codex/codex-account-session-index-heal.ts --match 'healCodexAccountSessionIndex|failedThreadIdsByHome' || true
sed -n '60,145p' src/main/codex/codex-account-session-index-heal.ts
ast-grep outline src/main/codex/codex-account-session-index-heal.test.ts --match 'missing|failed|healCodexAccountSessionIndex' || true
rg -n -C 5 'missingThreads|failedThreads|resetFailedThreads|missing.*retr|failedThreadIdsByHome' src/main/codex/codex-account-session-index-heal.test.ts src/main/codex/codex-session-index-heal.ts

Length of output: 11982


@AmoabaKelvin, missingThreads now reports “no rollout found” separately. The retry issue remains: healCodexAccountSessionIndex still calls failed.add(threadId) before it checks for missing. The next pass therefore excludes that thread ID, even if its rollout becomes available. Please add only failed outcomes to the skip set.

You are interacting with an AI system.

@pullfrog pullfrog 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.

✅ No new issues found.

Reviewed changes

Re-reviewed the increment since the prior pullfrog review at ec0b6a0e63 (the branch was rebased onto f5f537ef; 630d59ec5e carries the previously reviewed content and cfebddecb4 is the new commit).

  • Kept linking history into homes whose state DB lives elsewhere — isReadyForBridgedHistory now runs createStateDb only for an empty home (!findNewestCodexStateDbPath && !hasSessionRollouts). A home holding history without a home-local DB (shared sqlite_home, or a Codex with none) links on every launch instead of being skipped after the first, fixing the post-first-launch stall the prior gate introduced.
  • Shared the system-home read pass — healCodexAccountSessionIndex now delegates to the newly exported readCodexThreadsForIndexHeal/CodexSessionIndexHealOptions instead of duplicating the batching loop; the HEAL_* constants became module-private and readOneThread returns an outcome rather than mutating counts.
  • Stop at quit — a stopping flag plus stopCodexAccountSessionBridges() wired into main-process-quit.ts, refusing new bridges and passing shouldStop into the heal.
  • Read-only app-servers — buildNativeHealInvocation now launches with CODEX_READ_ONLY_APP_SERVER_ARGS (-s read-only -a never), so every background index app-server is read-only.
  • Contract coverage — the real-binary test now has a compressed-only thread/read read-repair arm and asserts an empty no-request session leaves the backfill complete.

All prior pullfrog threads are resolved. The system-home heal refactor is behavior-preserving (counts, ledger records, marker writes, and abort/unsupported/stopped semantics all carry over), the read-only launch args are exercised by the contract test, and the new tests pass (70 tests across the six touched suites; pnpm tc:node clean).

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

Codex indexes every rollout present when it first creates its state DB, and
the TUI gives up after 30s, so large histories broke a new account's launch.

Fixes stablyai#20669
@AmoabaKelvin
AmoabaKelvin force-pushed the fix-codex-new-account-first-launch-timeout branch from cfebdde to a29d8b0 Compare September 27, 2026 08:55

@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.

♻️ Duplicate comments (1)
src/main/codex/codex-account-session-index-heal.ts (1)

102-107: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Keep missing threads out of the process-wide skip set.

The callback adds missing outcomes to failed. Every later pass in the same process then skips that thread. A missing result can be transient. For example, the rollout may not be present yet, or the link may have been replaced. After that, the thread stays outside /resume until Orca restarts. Add only failed outcomes to the skip set.

Proposed fix
-      failed.add(threadId)
       if (outcome === 'missing') {
         summary.missingThreads += 1
       } else {
+        failed.add(threadId)
         summary.failedThreads += 1
       }

The test at src/main/codex/codex-account-session-index-heal.test.ts Line 130-147 must also change to expect a reread.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 70c537f2-ce3f-4f9c-82c3-ed8149c111d4

📥 Commits

Reviewing files that changed from the base of the PR and between cfebddecb4eb3b7a62362fc4d238871a06bd483a and a29d8b0.

📒 Files selected for processing (7)
  • src/main/codex/codex-account-session-bridge.test.ts
  • src/main/codex/codex-account-session-bridge.ts
  • src/main/codex/codex-account-session-index-heal.test.ts
  • src/main/codex/codex-account-session-index-heal.ts
  • src/main/codex/codex-index-heal-binary-contract.test.ts
  • src/main/codex/codex-session-index-heal.test.ts
  • src/main/codex/codex-session-index-heal.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.

@pullfrog pullfrog 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.

✅ No new issues found.

Reviewed changes

Re-reviewed the increment since the prior pullfrog review at cfebddecb4 (the branch was rebased onto 0697014; the whole PR now arrives as the single commit a29d8b0). All prior pullfrog threads are resolved.

  • Injected bridge dependencies — startCodexAccountSessionBridgeInBackground takes an optional second dependenciesOverride argument and threads it into isReadyForBridgedHistory; the module-global mutable dependency holder and _internals.setBackgroundBridgeDependencies are removed. Tests inject through a startBridge helper. The only production caller passes no override, so behavior is unchanged.
  • Separated missing-thread accounting — the account heal summary gains missingThreads, counted separately from failedThreads for outcome === 'missing'; both still enter the process-lifetime skip set, so this is accounting-only and mirrors the system heal.
  • Plugin-free background app-servers — buildNativeHealInvocation now uses CODEX_SHORT_LIVED_PROBE_APP_SERVER_ARGS (-c features.plugins=false … -s read-only -a never app-server), avoiding marketplace clones outliving the one-batch session.
  • Contract and rollout coverage — the real-binary contract test pins the plugin-free args and asserts an empty no-request session leaves the backfill complete; a compressed-only thread/read arm and a compressed-rollout count test cover the .jsonl.zst path.

Verified locally: the 5 touched suites pass (62 tests) and pnpm tc:node is clean.

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

…odex binary

Selecting an account starts the history bridge, which spawned codex app-server
on the fixture homes and raced the test's temp-dir cleanup.
Indexing a large history takes minutes, and Codex's /resume hides unindexed
threads once a directory has any indexed one, so recent conversations stayed
missing until the heal reached them in directory-listing order.
…ink guards

Drop the stop check before creating the state DB: it ran in the same tick as
the check at bridge start, so it could never observe a quit.
…ing a real codex

Fake invocations now point at a nonexistent binary and a throwaway CODEX_HOME,
and cover per-home failure memory and a session that fails during quit.
@brennanb2025

Copy link
Copy Markdown
Contributor

Thanks @AmoabaKelvin, the diagnosis and the fix are right. I reproduced the failure on main (a new account with a big history can't start Codex) and confirmed this branch starts right away, with history still reaching /resume.

I pushed four small follow-ups:

  • The indexing pass now reads the newest conversations first, as the default-home pass does. Directory order could leave recent work missing from /resume for minutes on large histories.
  • The migration test no longer starts the real codex, and the account-index tests' fake command now fails closed.
  • Tests cover the bridge's quit, no-history and failed-link paths.

Small description note: the PR also starts the default-home indexer's Codex processes with plugins off and read-only, and counts .jsonl.zst history. Both are good, but worth a line.

@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.

Caution

Some comments are outside the diff and can’t be posted inline due to GitHub limitations.

⚠️ Outside diff range comments (1)

🟠 Major · Do not treat every missing state DB as ready for history. · codex-account-session-bridge.ts:83

src/main/codex/codex-account-session-bridge.ts:83
🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift

Do not treat every missing state DB as ready for history.

If the target already has rollouts but no state DB, the earlier condition skips createStateDb, and this return still permits linking all source history. Codex 0.156.1 can create its DB and backfill those rollouts on its next launch; a large bridge can therefore reproduce the first-launch timeout this change aims to prevent. Defer linking in this state unless the installed Codex version is known not to create a state DB. (raw.githubusercontent.com)


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: ebcb495b-5bb5-4a24-b105-866b8cbcf6cb

📥 Commits

Reviewing files that changed from the base of the PR and between a29d8b0 and 278d851.

📒 Files selected for processing (6)
  • src/main/codex-accounts/runtime-home-service-per-account-migration.test.ts
  • src/main/codex/codex-account-session-bridge.test.ts
  • src/main/codex/codex-account-session-bridge.ts
  • src/main/codex/codex-account-session-index-heal.test.ts
  • src/main/codex/codex-account-session-index-heal.ts
  • src/main/codex/codex-session-index-heal.test.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 4 remain after this review.

@greptile-apps

greptile-apps Bot commented Sep 28, 2026 •

Copy link
Copy Markdown

RetriggerConfidence Score: 4/5

[High risk] Adds state database initialization and indexing to account session bridging.

The PR should not merge until linked history is indexed when Codex stores its state DB in a shared sqlite_home.

Findings

  1. P1 Shared index skips history ▶
  2. P2 Large indexes block startup ▶

Summary

The PR initializes a new account home's Codex index before linking history, then reads linked threads in bounded batches to make them visible in /resume.

  • Adds backfill-status gating, compressed-rollout recognition, account-home index healing, and quit signaling.
  • The shared-sqlite_home path bypasses the new indexing step; large-history main-process work and bridge cancellation also need attention.
Diagram
%%{init: {'theme': 'neutral'}}%%
flowchart LR
  A[Select or launch account] --> B{Home has DB and rollouts?}
  B -- Neither --> C[Start app-server on empty home]
  B -- Otherwise --> D[Check backfill status]
  C --> D
  D -- Complete or missing --> E[Link source rollouts]
  D -- Incomplete or unreadable --> F[Skip this pass]
  E --> G[Read indexed IDs]
  G -- In-home DB found --> H[thread/read missing IDs in batches]
  G -- No in-home DB --> I[Heal skipped]
Loading

Reviews (1) · Last reviewed commit: "test(codex): make the account heal tests..."

Comment on lines +80 to +84
// Why: with no DB in the home, Codex keeps none (older CLI) or uses a
// `sqlite_home` shared by every Orca home, which already indexes these threads.
const indexed = (options.readIndexedThreadIds ?? readIndexedCodexThreadIds)(codexHomePath)
if (!indexed) {
return { ...summary, outcome: 'no-index' }

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Shared index skips history

When an account uses a shared sqlite_home, its state DB is outside the account home. This lookup returns null, so the heal skips every thread/read. If the shared DB was indexed before history was linked into the account home, those conversations remain absent from the DB-backed /resume list. The heal needs to find the active shared index or read the linked threads without requiring an in-home DB.

Comment on lines +85 to +92
db = new SyncDatabase(stateDbPath, { readonly: true, fileMustExist: true })
const ids = new Set<string>()
for (const row of db.prepare('SELECT id FROM threads').all()) {
if (typeof row.id === 'string') {
ids.add(row.id.toLowerCase())
}
}
return ids

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Large indexes block startup

For a large account, this synchronous query loads every thread ID into memory on the main process. The bridge also retains a map of all rollout IDs, so the bounded thread/read batches do not limit this earlier work. Healing a large history can stall the app and increase memory use; avoid taking a full synchronous index snapshot on the main thread.

@greptile-apps

greptile-apps Bot commented Sep 28, 2026

Copy link
Copy Markdown

Comments Outside Diff

These findings could not be posted inline.

  • P2 Quit does not stop linking src/main/codex/codex-account-session-bridge.ts:169 ▶

    The quit hook sets stopping, but an active bridge never checks it inside this file loop. With a large history, the bridge can keep traversing and linking files after shutdown has requested a stop. Checking between files and source homes would let quit cancel that work promptly.

@pullfrog pullfrog 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.

✅ No new issues found.

Reviewed changes

Re-reviewed the increment since the prior pullfrog review at a29d8b0 (4 commits: f43a32c973, 375782e86a, 0482f220f3, 278d8516e9).

  • Index the newest bridged rollouts first — the bridge summary now carries thread id → rollout stamp (bridgedThreads: Map<string, string>), and healCodexAccountSessionIndex sorts the unindexed threads descending by stamp, so recent work appears in /resume before a large history finishes indexing. Mirrors the system heal's existing descending sort.
  • existing hardlinks still get healed — bridgeRolloutIntoAccountHome returns 'linked' | 'existing' | 'failed'; only failed rollouts are excluded from the heal set, so a rollout already hardlinked into the target is still repaired into the index. Failure to link is covered by a new test.
  • Quit guard moved outward — the stopping parameter is gone from isReadyForBridgedHistory; startCodexAccountSessionBridgeInBackground returns early when stopping and re-checks after readiness, so a quit during the 15s createStateDb still links nothing. The production caller passes no dependency override.
  • Tests fail closed — the account-heal suite's buildInvocation points at a nonexistent binary with an isolated CODEX_HOME, and the per-account migration test mocks the heal module so selecting an account never spawns the real codex app-server.
  • New guard coverage — no-source-history skip, failed-link exclusion, per-home failure memory, stop-during-state-DB-creation, no-start-after-quit, no completion marker when stop flips in the last batch, plugin-free invocation, compressed-rollout counting, and readIndexedCodexThreadIds lower-casing / null cases.

Verified locally: the 5 touched suites pass (70 tests) and pnpm tc:node is clean.

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@brennanb2025

Copy link
Copy Markdown
Contributor

Validation status

Every run below used a synthetic managed Codex account (no real credentials), synthetic conversation history, isolated home folders, and the real Codex CLI. "Before" is this PR's parent commit and "after" is this PR.

Platforms

Platform Codex Result
macOS (two machines) 0.157.0, 0.158.0 Before: a new account with a large history fails with "Chat could not be started … initialize exceeded 15000ms". After: the chat starts at once and history reaches /resume, newest first.
Windows 11 0.157.1 Same as macOS. With 16,000 conversations, before: the chat failed, and a retry 4 minutes later failed again with the index stuck at 3,237 of 16,000. After: the chat starts at once and all 16,000 conversations were indexed in about 21 minutes. Account-folder paths and hardlinks work, and .jsonl.zst history is indexed.
Linux — Not tested.
WSL — Not covered. New WSL managed accounts go through a separate history bridge that this PR doesn't touch, so they likely still stall (unverified, pre-existing).

Setups

  • Small history (40 conversations): no regression. Before and after both show all 40 in /resume within seconds.
  • Large history (13,000–16,000 conversations): fixed, as above. Indexing uses about 1.5–1.7 CPU cores in the background for 15–21 minutes, once per new account. Orca itself stays under 1% CPU.
  • Codex can't start its short read-only process: this covers a custom or enterprise Codex command, or a probe that fails. The PR skips linking history for that launch and logs it; nothing hangs, and the next normal launch links and indexes everything. The trade-off: in that setup, a new account's /resume won't show old conversations until Codex can start.
  • Codex hangs on start: chat start fails, but it fails the same way before this PR. It comes from an existing startup check, not this change.
  • Not tested: Codex versions whose app-server lacks thread/read; history on a different drive from the account folder on Windows (hardlinks fail there; this is existing bridge behaviour).

Follow-ups, not blocking

  • On Windows, these short Codex processes are launched through cmd.exe; a large history means hundreds of launches, which endpoint-security tools may flag. Orca's existing probes launch the same way.
  • Chat start waits on an existing short Codex check, which is why a hanging Codex blocks chat before and after this PR.
  • The WSL bridge probably needs the same order-then-index fix.

@brennanb2025
brennanb2025 merged commit b6c2de9 into stablyai:main Sep 29, 2026
43 checks passed
brennanb2025 added a commit that referenced this pull request Sep 29, 2026
…3745, #23783, #22971, #22565, #22846, #23724, #23721, #23693, #23810) into #23059

#23671 (group chat rows by the turn that produced them) is ported onto
#23059's turn-scope model, so there is one grouping mechanism, not two:

- A host that states each row's turn scope groups by that scope, as
  before. #23671's journal-order derivation (rows between one turn record
  and the next belong to it) moves from the timing selector into
  src/shared/native-chat-turn-grouping.ts and runs only for a host that
  states no scope, replacing the positional fallback there.
- #23671's anchor rules live in structuredAgentTurnAnchors, which
  membership, settled timing and the live clock all read: a turn whose
  opener key nothing resolves yet takes the send still in flight ahead of
  its record (Codex before its echo), else its own record.
- The live turn is one key again. #23671 made row liveness follow the
  owning turn, so the bar key and the liveness key are always the same;
  nativeChatTurnMembership now returns only liveTurnKey (barTurnKey,
  activeTurnOpenedBy and turnKeysByItemId are gone).
- A turn with no user bubble draws its bar above its first row
  (nativeChatTurnBarRows, desktop and mobile), and a turn's diff rollup
  goes under its last row.
- The Codex full-history restore writes each record ahead of its items;
  that also fixes the derived turn scope on #23059's journal.

#23026 (Stop from the moment a message is sent) is ported onto #23059's
command turns: the cancel paths ask the translator for a command's
provider turn instead of the removed compaction tracker, and a Stop that
names no turn still ends a running /compact through its child.
performCancel moved to structured-agent-session-turns-cancel.ts to keep
the turns module under the line limit.

#22090's awaitingInput replaces showTurnStatus/showLiveTurnActivity; the
waiting-behind-/compact rows are kept.
brennanb2025 added a commit that referenced this pull request Sep 30, 2026
The WSL history bridge hardlinked every conversation into a new managed
account home before Codex had opened it, so Codex's first open had to index
all of it and every other Codex on that home gave up after 30s. Apply the
native ordering from #22971 inside the distro: Codex brings the home's index
to complete first, history is linked after, and the shared thread/read loop
indexes it newest first. Windows cannot read the guest's Codex sqlite over
9p, so a marker per linked rollout records the pending indexing work and
dies once thread/read settles it.
nwparker pushed a commit that referenced this pull request Oct 25, 2026
The WSL history bridge hardlinked every conversation into a new managed
account home before Codex had opened it, so Codex's first open had to index
all of it and every other Codex on that home gave up after 30s. Apply the
native ordering from #22971 inside the distro: Codex brings the home's index
to complete first, history is linked after, and the shared thread/read loop
indexes it newest first. Windows cannot read the guest's Codex sqlite over
9p, so a marker per linked rollout records the pending indexing work and
dies once thread/read settles it.
nwparker added a commit that referenced this pull request Oct 25, 2026
… it (carries #23843) (#33630)

New WSL Codex managed accounts no longer link all past rollouts before Codex first opens the home (which stalled startup past Codex's 30s backfill gate or left later-linked sessions unindexed): Codex opens the home first, then history is linked and indexed in background batches newest-first, resumable across restarts — matching #22971's non-WSL order.

Supersedes #23843

Co-authored-by: Brennan Benson <79079362+brennanb2025@users.noreply.github.com>
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.

[P1][codex-accounts] New account's first Codex launch fails: session bridge links history before Codex's first index

2 participants