Repository navigation
perf(codex): share one launch-prep hook install across a spawn burst - #17669
Conversation
Greptile SummaryThe PR consolidates concurrent Codex launch-preparation work without retaining results between spawn bursts.
Confidence Score: 5/5The PR appears safe to merge. No blocking failure remains.
|
| Filename | Overview |
|---|---|
| src/main/in-flight-run-dedupe.ts | Introduces keyed in-flight promise sharing with identity-checked cleanup after either fulfillment or rejection. |
| src/main/codex/codex-hook-service-implementation.ts | Applies burst-scoped sharing to native Codex launch preparation and reuses the generic helper for WSL serialization. |
| src/main/codex/hook-service-concurrent-launch-install.test.ts | Covers burst deduplication, settlement invalidation, rejection recovery, home and lane isolation, and unshared direct installs. |
| src/main/index.ts | Routes resumed Codex-pane hook preparation through the new launch-scoped shared methods. |
| src/main/github/conflict-summary-cache.ts | Replaces its local in-flight deduplication implementation with the behaviorally compatible shared helper. |
| src/main/ipc/pty/ipc/spawn-env-codex.ts | Adds timing boundaries after Codex resume preparation and Codex home resolution. |
| src/main/ipc/pty/ipc/spawn-env.ts | Adds a pane-environment timing boundary before Codex-specific environment assembly. |
| config/tsconfig.cli.json | Includes the new shared deduplication module in the CLI TypeScript project. |
Flowchart
%%{init: {'theme': 'neutral'}}%%
flowchart TD
A[Concurrent PTY spawn burst] --> B{Runtime lane}
B -->|WSL| C[Serialized WSL install keyed by home and distro]
B -->|Native hooks enabled| D[Shared install keyed by normalized home]
B -->|Native hooks disabled| E[Shared refresh keyed by normalized home]
D --> F[One in-flight hook preparation]
E --> F
C --> F
F --> G[All waiting panes continue]
F --> H[Delete entry immediately on resolve or rejection]
H --> I[Next spawn starts fresh preparation]
Reviews (3): Last reviewed commit: "refactor: extract the shared in-flight r..." | Re-trigger Greptile
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Team Run ID: 📒 Files selected for processing (9)
🚧 Files skipped from review as they are similar to previous changes (4)
Included review availability: Your plan provides up to 10 included reviews per hour; 4 remain after this review. 📝 WalkthroughWalkthroughCodex launch preparation now shares in-flight hook installation and refresh operations by normalized runtime home and operation lane. Runtime and session-resume launch paths use the launch-preparation methods. Tests cover concurrency, retries, path isolation, lane isolation, and direct-install behavior. Spawn timing now records pane environment, Codex resume, and Codex home phases. Merge Risk: 🔵 Low · up to Concurrent launches now share one hook setup, reducing repeated work while preserving per-home isolation and retry behavior after failures. If a setup operation never finishes, later launches for that same runtime home could remain blocked, so merge is appropriate with explicit owner awareness of this bounded recovery risk. 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
Full details: Docstring CoverageExplanation Docstring coverage is 22.22% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 9 functions across 8 files. (1 skipped: 1 unsupported.) Full details: Description checkExplanation The description is comprehensive and covers the change, motivation, measurements, invalidation behavior, cross-platform scope, tests, and verification. It does not include the required Linked Issue entry, Visual Proof section or N/A statement, and template checklist sections are not reproduced, but the core review information is substantially complete.
✨ 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 |
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
shareLaunchPrepsingle-flight —installForLaunchPrepandrefreshRuntimeUserHooksForLaunchPrepdedupe concurrent runs keyed bylane + normalized runtime home, with the shared promise dropped the instant it settles (resolve or reject). Theget/setis synchronous (no await in between), so the first spawn of a burst installs and the rest join it; rejection is not cached.- Lane separation — install and hooks-disabled refresh lanes use distinct keys, so a mid-burst hooks toggle (on→off) still lands in the correct lane and is serialized by the existing trust-config queue rather than wrongly shared.
- Call-site swaps in
src/main/index.ts—prepareCodexRuntimeHomeForLaunchandprepareCodexSessionResumeForLaunchnow use the launch-prep variants;runtimeHomePath ?? undefineddefault resolution is semantically unchanged. - Timing marks —
pane_env/codex_resume/codex_homesplit the previously monolithichost_envspan; opt-in (ORCA_PTY_SPAWN_TIMING=1) and no-op otherwise. - Tests — six focused cases with exact
toHaveBeenCalledTimesassertions that would fail without the fix (burst → 1, post-settle → 2, rejection-not-cached → 2, distinct homes → 2, lane isolation, directinstall()unshared).
The single-flight pattern mirrors the existing installForRuntimeHomeSerialized, invalidation on settle is correct, and per-home/per-lane keying prevents cross-account or cross-setting sharing. Verified the new test file passes locally.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
Since the prior Pullfrog review (e9b35e9981), commit 9b5747990 refactored the duplicated single-flight bookkeeping into one generic helper and extended the sharing to the WSL launch-prep install:
- Extracted a generic
shareInFlight<T>helper — folds the WSL lane's inline map bookkeeping and the launch-prepshareLaunchPrepinto one method; the WSL map keepsPromise<AgentHookInstallStatus | null>and the launch-prep map keepsPromise<AgentHookInstallStatus>, so no cast is needed at the read sites. - Extracted
launchPrepKeyto a module helper — same lane-scoped key (installvsrefresh+ normalized home); semantics unchanged. - Routed the WSL launch-prep install through
installForRuntimeHomeSerialized—prepareCodexRuntimeHomeForLaunchnow reaches the WSL install via the serialized variant instead of the rawinstallForRuntimeHome, closing the same per-spawn serialization gap the native lane already closed.
The refactor is behavior-preserving for both the native lane (already reviewed) and the WSL lane's existing callers, and the one real change adopts an already-tested single-flight method whose !runtimeHomePath early-null and supersedeWslReconciliation semantics are identical to the raw call it replaces.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
Codex launch prep runs a full managed-hook install on every local PTY spawn, and both install lanes serialize globally per Codex home. Opening a multi-pane worktree therefore paid N full installs back to back, and a resumed Codex pane prepares twice. Concurrent spawns for the same runtime home now share one run; the promise is dropped as soon as it settles, so the next launch still re-reads hooks.json and the user's trust state. Also split the `host_env` spawn-timing phase, which spanned the entire Codex preamble and pinned that cost on the env builder that ran last.
Both the WSL and launch-prep lanes now share one generic in-flight helper instead of duplicating the map bookkeeping. Also routes the WSL launch-prep install through the serialized variant, which closes the same per-spawn serialization gap on WSL that the native lane just got.
The codex hook service and the GitHub conflict-summary cache had grown near-identical private copies of the same single-flight helper. Both now use one module, which also keeps the hook service clear of the 300-line budget. The shared copy keeps the identity check on clear so a late settle cannot evict a newer entry for the same key.
9b57479 to
3f4703b
Compare
|
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.
✅ No new issues found.
Reviewed changes
Since the prior Pullfrog review (9b5747990), the two refactor commits extracted the single-flight bookkeeping out of both call sites into one shared module rather than keeping three in-tree copies:
- New
dedupeInFlightRunmodule —src/main/in-flight-run-dedupe.tsnow owns the map-backed in-flight dedupe (get → return existing, elsestart()→ set →then(clear, clear)with an identity guard). It replacesCodexHookService.shareInFlightand the GitHub cache's privatededupeInFlight. The generic signature keeps each caller's map type (Promise<AgentHookInstallStatus | null>for WSL,Promise<AgentHookInstallStatus>for launch-prep) with no cast at the read sites. - GitHub conflict-summary cache adopts the shared helper —
dedupeBaseOidResolve/dedupeSummaryDerivationnow route throughdedupeInFlightRun. The only behavioral delta is that the GitHub copy'sfactory().finally(() => map.delete(key))(unconditional delete) becomes the shared helper's identity-checked clear, which is strictly safer against a late settle evicting a newer entry for the same key. config/tsconfig.cli.jsonadds the new file — required so the CLI composite project lists the module pulled in transitively bycodex-hook-service-implementation.ts(avoids TS6307).
Verified the refactor is behavior-preserving: the WSL installForRuntimeHomeSerialized move matches the prior inline map bookkeeping exactly, start() is still called before the entry is visible (same reentrancy characteristics as before), and both implementations attach a rejection handler so a failed run cannot wedge later callers. No leftover shareInFlight references remain.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
…tablyai#17669) * perf(codex): share one launch-prep hook install across a spawn burst Codex launch prep runs a full managed-hook install on every local PTY spawn, and both install lanes serialize globally per Codex home. Opening a multi-pane worktree therefore paid N full installs back to back, and a resumed Codex pane prepares twice. Concurrent spawns for the same runtime home now share one run; the promise is dropped as soon as it settles, so the next launch still re-reads hooks.json and the user's trust state. Also split the `host_env` spawn-timing phase, which spanned the entire Codex preamble and pinned that cost on the env builder that ran last. * refactor(codex): unify the two hook-install single-flight lanes Both the WSL and launch-prep lanes now share one generic in-flight helper instead of duplicating the map bookkeeping. Also routes the WSL launch-prep install through the serialized variant, which closes the same per-spawn serialization gap on WSL that the native lane just got. * refactor: extract the shared in-flight run dedupe The codex hook service and the GitHub conflict-summary cache had grown near-identical private copies of the same single-flight helper. Both now use one module, which also keeps the hook service clear of the 300-line budget. The shared copy keeps the identity check on clear so a late settle cannot evict a newer entry for the same key.

ELI5
Every time Orca opens a terminal, it first does a bit of setup so the coding agent in that terminal can report its status back to the app. That setup involves rewriting a couple of config files, and Orca is careful to only ever do one of them at a time so two terminals can't scribble over each other.
The problem: when you switch to a worktree that has seven terminals, all seven open at once — and each one insisted on doing that whole setup for itself. Because they have to take turns, they formed a queue, and the last terminal sat waiting for the six ahead of it. That queue was a big chunk of the delay before your terminals appeared.
The fix: terminals opening at the same moment now wait on a single shared setup instead of each running their own. It's the same work, done once, and everyone gets the result. Measured on a real config, seven terminals went from 698 ms to 175 ms of setup. Nothing is cached between openings — the next terminal you open still re-reads your settings, so toggling status hooks or changing your Codex config takes effect immediately.
Two smaller things came along with it. The same fix now also applies on WSL, which had the identical queue. And the timing label that pointed at this problem was misleading — it was named after the last step in a long stretch of work rather than the stretch itself, which is why the slowdown looked like it lived somewhere it didn't. That label is now split into four honest ones.
What you'll notice: switching to a worktree with several terminals feels quicker, and the terminals appear together instead of trickling in one by one. Nothing else changes.
What
Codex launch prep (
prepareCodexRuntimeHomeForLaunch,src/main/index.ts:1195) runs a full managed-hook install on every local PTY spawn — bare shells included — and both install lanes serialize globally per Codex home viarunExclusivelyForRuntimeAndSystemTrustConfig. Opening a multi-pane worktree therefore paid N full installs strictly back to back, and a resumed Codex pane prepares twice (once fromresolveVerifiedResumeHome, once from launch prep).Concurrent launch-prep runs for the same runtime home now share one install.
Root cause, with measurements
All numbers measured on macOS against a fixture copied from this machine's real
~/.codexand managed Codex home (62–64 KBconfig.tomlon both sides), drivingCodexHookServicedirectly.codex app-servertrust-grant session (initialize→hooks/list→hooks/list, codex-cli 0.151.0, real managed home)install()with a warm trust-grant ledger (no session)352, 549, 582, 608, 650, 676, 696175521 … 729658The steady-state (warm-ledger) case — which is what a normal worktree activation hits — improves 4×, and every pane finishes together instead of the last one absorbing the whole serialized chain. A resumed Codex pane pays this twice, so the saving roughly doubles for restored agent panes.
The ledger (
codex-trust-grant-ledger.json) already suppresses repeat app-server sessions, and it works correctly under concurrency because the ledger lookup happens inside the serialized region — the burst only ever spends one session. What it does not suppress is the rest of the install:promoteCodexRuntimeHookApprovalsToSystem,readHooksJson,getRuntimeHooksWithSystemUserHooks,writeCodexHooksJson,syncSystemConfigIntoManagedCodexHome, the trust upsert/stale sweep over a 64 KBconfig.toml, the provenance snapshot, andcleanupLegacyManagedHookRepresentations. That's the ~50–110 ms per pane that the mutex turns into a serial chain.Honest scoping of the reported 2.1 s
The report was
host_env=2100mson a 7-tab activation of a large worktree. Two corrections to how that reads:host_envspansmark('auth')(ipc/spawn-preflight.ts:228) →mark('host_env')(ipc/spawn-env-codex.ts), i.e. all ofassemblePtyIpcSpawnEnv+assemblePtyIpcSpawnCodexEnv.buildPtyHostEnvis one synchronous call near the end of that span; optimizing it would have bought ~0 ms. This PR splits the span intopane_env,codex_resume,codex_homeandhost_envso a re-measure attributes cost to the right stage.codex_resume/codex_homephases (resolveCodexHomeAfterManagedAuthReadiness's polling wait,markCodexProjectTrusted's doubleconfig.tomlmutation,ensureCodexStateDbBackfillRecoveryStarted's lock arbitration) — those now have their own labels, so the nextORCA_PTY_SPAWN_TIMING=1capture will say which.Invalidation rule
Documented in the code: the shared promise is dropped the instant it settles, including on rejection. Nothing is cached across spawns — the next launch re-reads
hooks.json,~/.codexapprovals, the hooks on/off setting and the managed script. The key islane + normalized runtime home, so the install and hooks-disabled refresh lanes never share, and per-account Codex homes never share with the shared managed mirror. Directinstall()(settings toggles, hook repair) is deliberately left unshared.Cross-platform
No platform branches added. The WSL lane (
installForRuntimeHomeSerialized) already had its own single-flight and keeps it; this adds the equivalent for the native fallback that runs when there is no WSL plan. Keys are normalized withnormalizeRuntimePathForComparison, so Windows case/separator variants of the same home share correctly. SSH spawns never reach this path.Tests
New
src/main/codex/hook-service-concurrent-launch-install.test.tscovers the fast path and each invalidation trigger:install()stays unsharedVerification
pnpm tccleanpnpm test src/main/codex src/main/ipc/pty— 2068 passed, 16 skippedpnpm run check:code-quality:changed— 0 new findingscheck:max-lines-ratchet,check:reliability-gatespassReadiness review (self, adversarial)
Ran the repo readiness checklist over this diff. Confirmed findings fixed; everything else recorded below with reasoning rather than left implicit.
Superseded by main — WSL launch prep. My earlier revision also switched the WSL lane at this call site onto
installForRuntimeHomeSerialized, because launch prep was the one caller still using the rawinstallForRuntimeHome. #16854 landed that independently while this PR was open, extracting the whole block intoCodexHookService.prepareRuntimeHomeForLaunch. On rebase I dropped my version and kept main's. The native fallback inside that new method was still un-deduped, which is what this PR now changes.Fixed — §08 duplicated mechanism, three copies. The new dedupe duplicated the map bookkeeping
installForRuntimeHomeSerializedalready had, and a third near-identical private copy already existed insrc/main/github/conflict-summary-cache.ts. All three now use onededupeInFlightRunmodule. Callers keep their own maps so each lane retains its exact result type (including the WSL lane's nullable one) without anascast at every read. The shared copy keeps the identity check on clear, which the GitHub copy lacked.Not real — rejection wedging later callers.
clearis passed as both handlers ofrun.then, so a rejected run is evicted immediately. Covered by a test that asserts the next launch retries rather than re-receiving the failure.Not real — unbounded map growth. Entries are keyed by lane + normalized runtime home and deleted on settle; the map is bounded by the number of homes concurrently spawning. The identity check in
clearmakes the settle-vs-replace race safe.Not real — new permanent-stuck risk from a hung install. These calls were already serialized on the same per-
config.tomlmutex, so a hung install blocked every concurrent spawn before this change too. Sharing strictly reduces the number of pending awaits rather than adding a new stall. The underlying app-server session is separately deadline-bounded (10 s native / 30 s WSL).Not real — sharing clobbers a concurrent project-trust write.
markCodexProjectTrusted(src/main/agent-trust-presets.ts:112) takes the same runtime-before-systemrunExclusivelyForCodexTrustConfiglanes and writes[projects.*], which is disjoint from the[hooks.state.*]the install manages. A joined install can neither lose that write nor need to observe it.Not real — sharing skips work a resumed pane needed. The only thing that runs between a pane's own preconditions and its install is
prepareLegacySharedCodexSessionResume, which touches session rollout files and neverhooks.jsonorconfig.toml, so a joined install's inputs are unchanged.Not real — settings toggles get a stale shared result. Direct
install()is deliberately left unshared, so a toggle always forces a real reinstall. The install and hooks-disabled refresh lanes are keyed separately, so a spawn that readshooksEnabled=falsecan never join an in-flight install started when it was true.§06 backward compatibility: nothing persisted changed. The trust-grant ledger,
hooks.jsonandconfig.tomlformats are untouched; the sharing is in-memory and process-local. No mobile-facing surface touched.§03 security: no new network sinks, no shell/eval, no dependency change. The diff adds no new process spawns — it removes redundant runs of an existing one.
Residual risk. The Windows and WSL lanes are reasoned about but not measured; I only had a macOS host. The WSL change is a call-site swap onto an already-tested method (
hook-service-wsl-runtime.test.tscovers its dedupe, alias-normalization and per-distro keying), so the risk is that WSL launch prep wanted a fresh install per spawn for some reason not visible in the code — nothing in the reconciliation-generation logic suggests it does, and two other callers already share that lane.Rebase note (onto 02a7742)
Two conflicts in
src/main/index.ts, both from #16854 landing the WSL direct-home cutover. That PR extracted the launch-prep hook block out ofindex.tsintoCodexHookService.prepareRuntimeHomeForLaunchand routed the WSL lane throughinstallForRuntimeHomeSerialized— overlapping work with my earlier revision. I resolved both to main's side and re-targeted the dedupe into the new method, soindex.tsnow carries only the two-line resume-path change and the service owns the whole launch-prep decision. That is a better shape than what I had.Re-verified after rebasing rather than assuming the rebase was clean:
pnpm tc, 3654 tests acrosssrc/main/codex,src/main/ipc/pty,src/main/agent-hooksandsrc/main/github, andcheck:code-quality:changed. I also re-confirmed the regression test still fails without the fix (7 installs instead of 1) on the rebased tree, since a silently-neutered test would be the easy way for this rebase to go wrong.One run of the combined suite showed a single failure that did not reproduce across three subsequent full runs and named no test in the reporter output; the GitHub suite alone is green. Recording it as an observed flake rather than claiming it away.