Repository navigation
perf(agents): move Codex launch trust writes off the main thread - #44244
Conversation
Codex launch trust edited two or three ~330 KB config.toml files and read, validated and rewrote the whole ownership ledger once per config, all synchronously on Electron main (and orcad's loop). The grant now runs as one request on a dedicated worker thread while main still holds every config's mutation lock in hook-installer order. The worker reads the ledger once per grant, records every table it created in a single publication (also for configs that landed before a later one failed), and is the ledger's only writer: worktree-removal cleanup moved onto the same worker, one config lock at a time. A worker that fails or times out must exit before the locks are released, so a stopped write can never race a hook install.
Perf scan — PR #44244 @ 258761fVerdict: clean. No perf regression found. The PR removes a 58–110 ms synchronous stall from Electron main on every Codex agent launch. That work now runs serialized on a dedicated worker thread. FindingsNone that block this PR (no P0 or P1 introduced or made worse). Pre-existing, now moved off main (non-blocking, for follow-up):
Evidence
Census: trigger → owner/thread → work → bound
Regression classes touched
Six questions
Fleet pricingReference fleet: 100+ agents, launch bursts of tens. A burst of 20 Codex launches into new worktrees costs ~2.2 s of serialized worker time and ~0 ms of main time per launch. Base cost was ~1.2–2.2 s on main, i.e. 58–110 ms of stall per launch. At 10× fleet, config and ledger bytes would raise worker time roughly linearly. Main cost stays constant. Residual gaps: no packaged-build or Windows timing. Worker spawn cost on main was not measured; it is one spawn per 60 s idle window. |
…ped trust grant Some main-thread writers replace the Codex configs without the per-config lock. Now that the grant runs on a worker it could publish a stale snapshot over their edit, so each config is published only while it still holds the bytes the grant read (checked after the backup, right before the rename); on a change the grant redoes that config's edit. The grant now records the tables it is about to create before it publishes any config, so a worker stopped by the watchdog mid-grant still leaves cleanup evidence. Records for configs that did not land are dropped afterwards on the normal path, still one ledger write per grant.
Perf scan: PR #44244 at
|
| Operation | Worker time | Config I/O | Ledger I/O |
|---|---|---|---|
| First grant (3 configs) | 112–118 ms | 6 reads (plan + stillCurrent), 3 temp writes, 3 backups, 3 renames |
1 read, 1 write |
| Repeat grant (already trusted) | 53–58 ms | 3 reads, 0 writes | 0 |
listOwnedConfigs |
2.7 ms | 0 | 1 read |
removeOwned × 3 configs |
75–85 ms | 6 reads, 3 writes | 6 reads, 3 writes |
- Cold worker: the bundled entry is 68 KB.
new Worker()takes 0.8 ms on the spawning thread. The first response arrives 30 ms later, and that time is spent on the worker thread. - Base for comparison (from source,
config-toml-trust.tsonorigin/main): for each config,upsertOrcaCreatedProjectTrustLevelread and rewrote the config, thenledger.recorddid a full ledger read and rewrite. A 3-config grant therefore did up to 3 ledger reads and 3 rewrites on Electron main. This head does 1 read and 1 write on the worker. The secondapplyreturns early without I/O when there is nothing to record or forget (counted above). - Tests:
pnpm test codex-project-trust-ownership.test.ts agent-trust-presets.test.tspasses, 13/13. The tests use an in-process worker fixture, so they cover correctness and not the thread move.
Work census
Format: trigger → owner/thread → work → bound
- Codex agent launch (
execution-host-workspace-trust.ts:105→markCodexProjectTrusted,agent-trust-presets.ts:138)- Owner: Electron main or orcad.
- Main does: nested per-config mutation locks, plus one
postMessagewith about 3 short paths. - The worker does:
realpath, 2–3 config reads and scans, at most 1 ledger read/write, and conditional config publishes. - Bound: one request per launch. Requests are serialized by the per-config locks and the one-at-a-time queue.
- Worktree removal (
worktree-removal-agent-trust-cleanup.ts:27→removeOrcaCreatedProjectTrustEntries)- Main does: one
listOwnedConfigsround trip, then oneremoveOwnedround trip per owned config, each under that config's lock. - The worker does: the same reads and writes that ran on main at base.
- Bound: one list per removal, plus requests for at most the ~3 configs that list returns.
- Main does: one
- Worker lifetime (
codex-project-trust-worker-client.ts)- One lazy worker per process, torn down after 60 s idle.
- Request timeout 60 s,
awaitRetirement, and at most 2 consecutive deaths before the queue fails. - No poll and no timer while idle.
- Publish/subscribe surfaces (
codex-project-trust-worker-entry.ts, worker client)- One
port.on('message')per worker lifetime and exactly one response per request. - Responses are
{id, ok, configFiles?}and carry no config or ledger content. - No store writes, version bumps or broadcasts.
- One
Pricing at the reference fleet
- Electron main per launch: about 0.1 ms of clone and post. A 100-agent launch burst costs well under 10 ms of main time in total. It is constant per launch and does not grow with worktrees or ledger size.
- Worker during that burst: 100 × ~55 ms (repeat grants) is about 5.5 s of serialized worker time, all off main. The last launch in the burst gets its trust within the 20 s launch deadline. At base, this same serial work ran on main and stalled the UI.
- Bulk removal of 100 worktrees: 100 × ~85 ms is about 8.5 s on the worker. At base this ran on main.
- Cold spawn: 0.8 ms on main. It happens at most once per burst separated by more than 60 s idle.
Regression classes screened
| Class | Disposition |
|---|---|
| Sync fs on Electron main | Matched and resolved. The config and ledger *Sync calls moved onto the worker entry, which is registered in main-blocking-worker-entries.json. What remains on main per launch is lock bookkeeping and postMessage. The baseline counts in main-sync-fs-baseline / main-blocking-helper-baseline only went down or moved file. |
| Whole-file rewrite per change | Improved. The ledger now gets 1 write per grant instead of one per config. A repeat grant does 0 writes. A config write is skipped when its content is equal. The added stillCurrent re-read (+1 config read per publish) is the necessary compare-and-swap check against unlocked main-thread writers. |
| Re-reading unchanged input | Matched, pre-existing (see below). |
| Unbounded fan-out or queues | Disproved. The queue has no cap, but grants are serialized by the per-config locks. Removal sends one list request per removal plus one locked request per config. Pending requests are bounded by concurrent callers, and payloads are paths only. |
| Fixed-cadence poll that never settles | No matching code. The only timer is the idle-teardown timeout. |
| Per-entity state outlives the entity | Disproved. The module holds a single queue singleton. Nothing is keyed per worktree. |
| Eager startup imports | Disproved. The client imports only the existing queue and spawn modules. The transaction code is loaded only by the worker entry. |
| Update published when nothing changed / whole-snapshot publish | Disproved. There is exactly one small response per request and no other publication. |
Six questions
- Unused work before the skip gate: checked. A repeat grant skips the ledger entirely and publishes nothing; this was counted. The config scan still runs on every launch (pre-existing, see below).
- Ownership multiplication: checked. There is one worker per process and one request per launch or removal. Nothing is held per row or per pane.
- Thread and storage layer: checked. Config and ledger reads, scans and writes, including the Windows rename retry, now run on the worker. Main pays about 0.1 ms per request and 0.8 ms per cold spawn. No SQLite is involved.
- Growth and progress: checked. The publish retry loop is capped at 3 attempts and rereads each time, so every attempt makes progress. The ledger grows with live granted worktrees × configs, and removal forgets entries.
- Execution host: checked. orcad bundles the same entry (
orcad-entry-build.mjs,orcad-artifacts.ts), so remote hosts keep their event loop free. No SSH round trips are added per item. Windows rename retries now block the worker instead of main. Not run on Windows/WSL/Linux. - Obsolete work stops: checked. A timed-out worker is terminated, and callers keep the config locks until it exits (
awaitRetirement), so a second ledger writer never runs beside it. The worker is released after 60 s idle.
Pre-existing, not introduced (does not block)
- Config scan on every launch. Each launch reads and scans every config (~55 ms of worker time for 3 × 269 KB) even when it is already trusted. There is no stat or content key. This is now off main, but it does not scale: a burst of about 1,000 agents (10× fleet) would serialize past the 20 s launch deadline, and those launches would continue without pre-trust.
- Per-config ledger rewrites on removal.
removeOwnedreads the ledger twice and rewrites it once per config, so 3 full 538 KB rewrites per worktree removal. It could be batched the same way grants now are. - Ledger size cap.
readAgentStateJsonFileSynccaps reads at 4 MB. At 10× fleet the ledger would reach about 5.4 MB. The read would then throw and degrade to an empty ledger, and the next write would drop every ownership record. That loses cleanup, so stale[projects]tables would build up in the configs.
Not covered
No packaged-build profile of Electron main. The thread placement is proven from source and the build-entry registration, not by tracing a live launch. Not run on Windows/WSL.
…rename retry A grant that redoes a config after another writer changed it now records the redone table in the ledger before publishing it, swapping out the record it added for the earlier bytes; a ledger write that failed is retried rather than treated as recorded. The sync Windows rename retry takes the same isCurrent check as its async twin, so a config replaced during a retry backoff is never overwritten with the grant's older snapshot.
Perf scan: PR #44244 at
|
| Work | Trigger | Thread | Per event | Bound |
|---|---|---|---|---|
| Main side of grant | Each Codex launch (local host, and orcad on remote hosts) | Electron main / orcad loop | Takes the per-config mutex, posts a small request (paths only), waits on a promise | Constant; no fs on main. canonicalize (existsSync/realpath) moved to the worker |
planGrant × configs |
Each grant | Worker | 1 × readFileSync (330 KB, ~1.5 ms measured), plus upsert/has/find scans of that text |
C = 2–3 configs; same count as base, now off main |
Ledger apply (ahead) |
Grant that creates ≥1 table | Worker | 1 read + validate + parse + stringify + atomic write | 1 per grant (base: 1 per created config, so 3). Skipped entirely when nothing is created (relaunch in a trusted worktree = 0 ledger I/O) |
| Config publish | Each config whose content changes | Worker | temp write + rolling backup copy + stillCurrent re-read (330 KB) + rename |
1 per changed config. Redo capped at PUBLISH_ATTEMPTS=3. The re-read repeats on each Windows rename retry (bounded, ~750 ms total) |
Ledger apply (final) |
Only if what landed differs from what was recorded ahead | Worker | 1 read + 1 write | 0 in the normal case |
| Removal | Worktree delete | Worker (main only awaits) | listOwnedConfigs 1 ledger read, then per config removeOwned: getWritten read + forget read/write + 330 KB config read/publish |
Same counts as base. Moved off main |
| Worker lifetime | First request after 60 s idle | Worker thread | Spawns a worker isolate | Released after IDLE_TEARDOWN_MS=60_000. One spawn per burst, not per launch |
Measured on this machine (Node, synthetic ledger of the same shape): ledger read + parse + validate + stringify + write + rename averaged 2.8 ms at 2,856 entries (624 KB) and 45.5 ms at 28,560 entries (6.3 MB). A new-worktree grant therefore costs roughly 15–30 ms of worker time at fleet size and about 0 ms on main. A burst of 100 new-worktree launches costs about 1.5–3 s total. It runs serially on the worker, which the per-config locks already forced on base, where the same time went to main. That is well inside the 20 s launch deadline. The worker-side figures are partly estimated (unit costs above × counts), not end-to-end measured.
Regression classes the diff touches
| Class | Disposition |
|---|---|
| Sync fs on Electron main | Matched, disproved. The grant's readFileSync/writeFileSync/renameSync, ledger read/write and realpath now run only in codex-project-trust-worker-entry, which main does not import (git grep shows the transaction imported only by the worker entry). main-sync-fs-baseline and main-blocking-helper-baseline both go down. The other writeTomlConfigAtomically / renameFileWithWindowsRetry callers use the default isCurrent, so their cost is unchanged |
| Whole-file rewrite per change | Matched, disproved. Ledger writes per grant dropped from C to 1. The equal-content skip holds for configs (updated === raw → no publish) and for the ledger (changed gate) |
| Re-reading unchanged input | Matched, disproved. The extra stillCurrent re-read is needed for the compare-before-rename that keeps unlocked main writers from being overwritten. It runs once per publish, not per launch, and an unchanged relaunch publishes nothing |
| Unbounded fan-out / queues | Matched, disproved. Reuses WorkerThreadRequestQueue: one request at a time, a 60 s timeout, and awaitRetirement so a timed-out worker can never run beside a second ledger writer. Grants hold every config lock, so at most one grant is in flight. Removals are serialized per config lock |
| Hot-path rescans | Matched, disproved. The recorded/added .some/.filter loops cover ≤ C (3) records. Ledger find is O(entries per config) × C, the same as base, now on the worker |
| Per-entity state outlives entity | Matched, disproved. The only new state is one module-level queue. No maps keyed by worktree or host |
| Fixed-cadence poll | No match. The only timer is the queue's idle teardown, which settles |
| Eager startup imports | Matched, disproved. Main gains only the worker client and spawn shim, built on the existing queue. smol-toml and the transaction load only in the worker |
| Publish (config/ledger publication, observation) | Reviewed. observeFilePublication inside the worker has no AsyncLocalStorage scope, so it does nothing. It never ran inside a main observation scope for this path, so main loses no cache key and re-reads nothing |
| Subscribe (worker message/exit listeners) | Reviewed. One port.on('message') per worker lifetime. Queue listeners are tied to the worker and torn down with it. Nothing is added per launch |
Six questions
- Unused work before the skip gate? Reviewed. An already-trusted relaunch reads the configs (needed to decide) but skips all ledger I/O and every publish. The ledger is read only when the grant creates a table.
- Does ownership multiply work? Reviewed. There is one worker singleton per process (main, or orcad on remote hosts). The number of grants is still one per launch, as on base, with no added fanout.
- Which thread pays? Reviewed. All config and ledger I/O moved to the worker thread. Main pays a structured clone of a few paths. The worker's CPU time is off the main event loop and the renderer.
- What grows, and does the next attempt make progress? Reviewed. Redo is capped at 3 and re-reads fresh each time. A ledger publish failure only loses cleanup (logged), with no retry loop. Ledger size grows with worktrees × configs, which is older behavior (see below).
- What does the execution host change? Reviewed by reading only. The orcad bundle ships the worker entry (
ORCAD_CHILD_ENTRY_POINTS,ORCAD_ARTIFACTS), so remote hosts run the grant locally on the host with no per-item SSH round trips. Windows rename retries now re-checkstillCurrentbefore each attempt: at most about 5 × 330 KB reads per publish, on the worker. Windows/WSL was not run. - Does obsolete work stop? Reviewed. Past the launch deadline the launch goes ahead while the grant finishes holding its locks. That is intended: a timed-out worker is retired before callers release their locks. The idle worker is torn down after 60 s.
Older issues, not caused by this PR
These were present on base and keep the same counts; the PR moved the work off main:
- The ledger hits its read cap at about 10× fleet.
readAgentStateJsonFileSynccaps at 4 MiB. At ~220 B per entry that is ~19k entries, and 10× fleet gives 28,560 entries / 6.3 MB.read()then degrades to an empty ledger, and the nextapplyoverwrites it with only the new records, so cleanup ownership is lost silently. This is a correctness and growth problem rather than a speed one. - Removal is not batched. Per worktree it costs 1 + 2·C ledger reads and C writes. A bulk delete of 100 worktrees is about 700 parses + 300 writes ≈ 2–3 s of worker time, and launch grants can wait behind it in the same worker queue.
- Stale ledger entries persist. Entries for worktrees deleted outside Orca are never forgotten, so the ledger keeps growing with history.
Evidence and gaps
- Reproduced: the touched tests pass (
codex-project-trust-ownership,agent-trust-presets,worktree-removal-agent-trust-cleanup: 16/16). The ledger and config I/O timings above come from synthetic files at N and 10N. - Source-proven: every count in the census.
- Not measured: an end-to-end packaged-build launch trace, worker spawn time and bundle size, and Windows/WSL runs. Main-thread impact is stated as proven counts (0 fs calls per launch), not as a profile.
Review status: readyProblem. Every Codex launch that pre-trusts its workspace edited two or three ~330 KB What changes for users. Launching Codex agents no longer freezes the app while trust is written. Trust decisions, config bytes and worktree-removal cleanup are the same as before. If the trust write can't finish, Codex shows its own trust prompt, as it already did. What this PR does
Fixed during review (three passes, council + tie-break for the design): lost updates against main-thread config writers that don't take the lock; ownership lost when the watchdog stops the worker mid-grant; redone edits published before their record; Windows rename retries that could overwrite a newer config; a failed write-ahead ledger write treated as recorded. Verified
Deferred / found, not caused by this PR (same on main)
|
QA screenshotsWindows low spec, head Windows high spec, first QA round on the same fleet size: the same result for |


Problem
Every Codex launch that pre-trusts its workspace ran the whole trust transaction synchronously on Electron main (and on orcad's loop on remote hosts): read and line-scan two or three ~330 KB
config.tomlfiles, atomically replace the changed ones (symlink resolve, mode, temp write,.bak, rename), and for every newly created[projects."<path>"]table read, validate and rewrite the whole ownership ledger (~666 KB, ~2,856 entries). A three-config new grant meant three whole-ledger reads and three rewrites. A field capture attributed ~288 ms of sync calls inside an 850 ms main-timer stall to this path.Fix
orca-codex-project-trust) on the existing worker request queue. Main still takes every config's mutation lock in hook-installer order (managed runtime home before system home) and holds them for the whole request, so hook installs keep their ordering guarantee ([Bug][Windows]: Codex trust-grant blocks the Electron main thread during cold start and pane launch #16441). Canonicalizing the workspace path, parsing, transforming and publishing all happen on the worker.Tests
codex-project-trust-ownership.test.tsruns the real handler behind an in-process worker boundary: already-trusted (no writes, no.bak, no ledger), a new grant beside a 2,856-entry ledger and three ~330 KB configs, concurrent launches and removals with no lost records, a config that fails to publish after an earlier one landed, and the existing external-edit and cleanup-ownership cases. The bots DB test fixture now shares the generic in-process worker fixture.Measurements
Omarchy (Linux, 28 cores, Node 26), built PR head
80b52ebcdb1, Jinjing's fixture size: three 330 KBconfig.tomlfiles and a 715 KB, 2,856-entry ledger. 12 concurrent launches into new projects, then the same 12 again (already trusted). "Before" runs the same transaction one config at a time on the main thread, which is the old call pattern: one ledger read and rewrite per config. "After" runs through the real worker thread. Three runs each:Finishing the whole burst takes longer off main (new grants 2.3–2.6 s vs 1.6–1.9 s; already-trusted 0.84–0.93 s vs 0.75–0.87 s) because each publication re-reads the config before replacing it. All of that time is on the worker; launch never waits past the existing 20 s trust deadline.
Windows QA at ~1,900 worktrees (first QA round, head
258761f): worst main stall for a 10-launch burst of new grants dropped from 674 ms to 61 ms, already-trusted from 367 ms to 54 ms, under CPU load with concurrent removals from 308 ms to 33 ms, and a failing or retrying config write from 840–881 ms to 21–30 ms. Ledger counts matched exactly after every flow.Found during QA, not caused by this PR (same on main)
worktrees:remove) does not drop Orca-created Codex trust tables or ledger records;orca worktree rmdoes.config.toml, the leftoverconfig.toml.bakstays read-only and later grants to that config fail until it is cleared.