Skip to content

perf(agents): move Codex launch trust writes off the main thread - #44244

Merged
brennanb2025 merged 3 commits into
mainfrom
brennanb2025/p1-codex-trust-offmain
Nov 19, 2026
Merged

brennanb2025 merged 3 commits into
mainfrom
brennanb2025/p1-codex-trust-offmain

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

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.toml files, 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

  • Off main. The grant is one request to a new dedicated worker thread (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.
  • One ledger publication per grant, written ahead. The worker reads and plans every config, records the tables it is about to create in one ledger read/validate/write, then publishes the configs in order. A worker stopped mid-grant therefore still leaves cleanup records; a record whose table never landed is harmless (removal compares bytes and just forgets it). On the normal path, records for configs that did not land are dropped afterwards. Already-trusted projects write nothing and never read the ledger.
  • Concurrent edits are never overwritten. Some main-thread code replaces these configs without the per-config lock (for example the managed-home settings mirror). Each config is published only while it still holds the exact bytes the grant read; the check runs after the temp write and backup, before every rename attempt (including Windows retry backoff). If another writer changed the file, the grant redoes that config's edit (recording any new table first), up to three times, then gives up and the agent asks. Removal does the same. A main-thread writer can still drop a table the worker just added; the next launch re-grants it.
  • One serialized ledger writer. Worktree-removal cleanup moved onto the same worker (one config lock at a time, as before), so nothing on main touches the Codex ledger anymore and the queue's one-request-at-a-time order is the only writer. No records are lost to async interleaving.
  • Stopped writes can't race installs. If a request fails or hits the 60 s watchdog, the client waits for the old worker to exit before releasing the config locks. The 20 s launch deadline is unchanged, so a slow write still never blocks a launch.
  • Unchanged: trust decisions, fresh reads of external edits, symlink/permission handling, atomic replace and backups, ledger file name and format, exact-byte ownership checks on removal. Antigravity keeps its own ledger file and synchronous path.
  • The worker entry ships in the Electron build and in orcad artifacts.

Tests

codex-project-trust-ownership.test.ts runs 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 KB config.toml files 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:

Scenario Max main-timer overshoot, before after Ledger records after (expected 2,892)
12 concurrent new grants 1,551 / 1,857 / 1,890 ms 0.7 / 0.8 / 0.9 ms 2,892 in every run
12 concurrent already-trusted 751 / 773 / 862 ms 0.8 / 0.8 / 0.9 ms unchanged (no writes)

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)

  • Deleting a worktree through the sidebar (worktrees:remove) does not drop Orca-created Codex trust tables or ledger records; orca worktree rm does.
  • On Windows, after a failed replace of a read-only config.toml, the leftover config.toml.bak stays read-only and later grants to that config fail until it is cleared.

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

Copy link
Copy Markdown
Contributor Author

Perf scan — PR #44244 @ 258761f

Verdict: 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.

Findings

None that block this PR (no P0 or P1 introduced or made worse).

Pre-existing, now moved off main (non-blocking, for follow-up):

  • Unchanged-input reread. codex-project-trust-transaction.ts:56-69: a relaunch in an already-trusted worktree still reads and scans all 2–3 configs (~58 ms of worker CPU per launch at fleet size). There is no write because updated === existing. Base paid this on main. Caching on a stat/mtime fingerprint would remove it.
  • Removal ledger amplification. codex-project-trust-transaction.ts:85-115: each removed worktree costs 1 ledger parse for listOwnedConfigs, then 2 ledger reads and 1 full ledger write per owned config. Measured ~3 ms + 3 × 28 ms ≈ 85 ms of worker time per worktree. The count matches base, which ran it on main. In a bulk removal of more than ~235 worktrees, a launch grant queued behind it in the worker FIFO would miss the 20 s launch deadline. The agent would then show its own trust prompt; nothing is lost. A forgetAll batch, like this PR's recordAll, would remove it.

Evidence

  • Reproduced (local bench, mac, node, bundled production transaction via handleCodexProjectTrustRequest). Workload: 3 × 330 KB config.toml, a 2,856-entry / 878 KB ledger.

    Operation Worker time
    Grant, new worktree (3 config writes + 1 ledger write) 110 ms
    Grant, re-launch (no writes) 58 ms
    listOwnedConfigs 3.3 ms
    removeOwned, per config ~28 ms

    On base, all of this ran on Electron main.

  • Source-proven counts.

    • Ledger per grant: base did up to 3 reads + 3 writes (one record per created table). Head does at most 1 read + 1 write (recordAll). When no table was created it does 0 reads and 0 writes (records.length === 0 early return).
    • Main per grant now does: one join(getOrcaUserDataPath()), one structured clone of ≤3 short path strings, and lock bookkeeping. canonicalize, which uses realpathSync, moved into the worker.
  • Worker bundle. esbuild bundles codex-project-trust-worker-entry.ts to 66 KB from 44 inputs, with 0 electron requires. The ledger no longer imports codex-home-paths; the path is passed in.

  • Tests. codex-project-trust-ownership.test.ts and worktree-removal-agent-trust-cleanup.test.ts pass (9 tests). I inspected their assertions but did not use them as perf evidence.

Census: trigger → owner/thread → work → bound

Work Trigger / rate Thread Work per event Bound
markCodexProjectTrusted → grantCodexProjectTrustOffMain Codex launch via applyWorkspaceTrustOnThisHost (user-driven; bursts of tens at fleet) Main: lock chain + postMessage O(1) small clone 20 s launch deadline; 60 s request timeout
grantCodexProjectTrust Same Worker (one request at a time) 2–3 config read/scan (~330 KB each), ≤3 atomic writes, ≤1 ledger read + ≤1 write Linear in config bytes and ledger entries; off main
listOwnedConfigs Worktree removal Worker 1 ledger parse Once per removed worktree
removeOwned Per owned config (≤3) per removed worktree Worker, one config lock at a time 1 config read, 2 ledger reads, 1 config write, 1 ledger write Pre-existing count (see above)
Worker lifetime First request after 60 s idle Spawned from main One worker spawn idleTeardownMs: 60_000; maxConsecutiveDeaths: 2; awaitRetirement
Publish (response) One per request Worker → main {id, ok, configFiles?} with ≤3 paths 1:1 with requests
Subscribe (listener) port.on('message') Worker One listener per worker lifetime Released with the worker at idle teardown

Regression classes touched

Class Disposition
Sync fs or SQLite on Electron main Fixed. All config and ledger fs moved to the worker. The baselines shrink (agent-trust-presets 14→12 sync-fs, config-toml-trust 30→23 blocking). The 2 lines in agent-trust-path-canonicalization.ts are a move; its only production caller runs in the worker.
Whole-file rewrite per change Improved. Ledger rewrites per grant go from ≤3 to ≤1, with no write when nothing was created and no config write when bytes are equal. Removal's per-config ledger rewrite is pre-existing (see above).
Re-reading unchanged input Matched; pre-existing. The relaunch re-scan is the same count as base and is now off main.
Unbounded fan-out or queues Disproved. There is one serialized worker and no Promise.all. The queue has no cap, but entries hold tiny payloads and are bounded by user launches and removals. Removal takes one lock at a time, which avoids deadlock against installer lock order.
Fixed-cadence poll or loop No timers except the per-request deadline (unref'd) and the 60 s idle teardown, which settles.
Per-entity state outlives the entity Disproved. tailByTomlPath deletes its settled tail. The queue is a module singleton. The worker is released when idle.
Update published when nothing changed / whole snapshot Disproved. One response per request with no change fan-out. listOwnedConfigs returns ≤3 paths, not the ledger.
Eager startup imports Disproved. The new main-side imports are the request queue (already used elsewhere), codex-home-paths, and the mutation queue. TOML and ledger code moved to the worker bundle.
Subprocess per item No matching code. A worker thread is not a child process, and there is one per app.

Six questions

  1. Unused work before the skip gate: checked. A no-create grant skips the ledger entirely. Equal content skips the config write. The relaunch re-read is pre-existing (see above).
  2. Ownership multiplying work: checked. There is one module-level queue and one worker per process (Electron main or orcad), not one per pane or worktree.
  3. Thread and storage layer: checked. All TOML and ledger I/O now runs on the worker. Main keeps only O(1) clone and lock work. A spawn after idle costs one worker spawn on main, at most once per 60 s of idle.
  4. Growth and progress: checked. Worker cost grows with config bytes and ledger entries (priced above). Grant batching keeps ledger rewrites at ≤1 per grant. Failed removals keep their record for a later pass, so they make progress. The bulk-removal head-of-line risk is pre-existing and was worse on main.
  5. Execution host: checked statically. WSL/UNC config reads now block a worker instead of main, which is better on slow 9P. orcad ships the entry (orcad-entry-build.mjs, orcad-artifacts.ts), so remote/orcad hosts run the same path. Windows rename retries are unchanged. Not measured on Windows/WSL/Linux.
  6. Obsolete work stops: checked. A timeout destroys the worker. awaitRetirement, plus callers awaiting retired() while holding config locks, prevents a second ledger writer. A missed launch deadline lets the launch proceed while the grant finishes safely. The idle worker is torn down.

Fleet pricing

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

Copy link
Copy Markdown
Contributor Author

Perf scan: PR #44244 at 59bee33190a

Verdict: clean. I found no perf regression that this PR introduces or amplifies. It moves the Codex launch trust grant and the ownership ledger off Electron main, and off orcad's event loop. Electron main now does a constant small amount of work per grant.

Findings

None that block (P0/P1).

Evidence

I bundled codex-project-trust-transaction.ts and ran it with node. Fixture: three config.toml files of 269 KB each (3,300 [projects] tables) and a 538 KB ledger with 2,856 entries. I counted the fs calls and timed them. All of this runs on the worker thread.

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.ts on origin/main): for each config, upsertOrcaCreatedProjectTrustLevel read and rewrote the config, then ledger.record did 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 second apply returns 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.ts passes, 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

  1. 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 postMessage with 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.
  2. Worktree removal (worktree-removal-agent-trust-cleanup.ts:27 → removeOrcaCreatedProjectTrustEntries)
    • Main does: one listOwnedConfigs round trip, then one removeOwned round 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.
  3. 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.
  4. 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.

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

  1. 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).
  2. Ownership multiplication: checked. There is one worker per process and one request per launch or removal. Nothing is held per row or per pane.
  3. 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.
  4. 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.
  5. 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.
  6. 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. removeOwned reads 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. readAgentStateJsonFileSync caps 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.
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Perf scan: PR #44244 at 80b52eb

Verdict: clean. This PR adds no perf regression. It removes the Codex launch-trust transaction from Electron main. It also cuts ledger work per new-worktree grant from 3 reads + 3 writes to 1 read + 1 write. Three older problems in this area are listed at the end. This PR doesn't cause them, and none of them blocks it.

Scope: git diff origin/main...80b52eb (29 files, production plus build config). I traced the callers from the launch path (applyWorkspaceTrustOnThisHost → writePreset('codex') → markCodexProjectTrusted) and from worktree removal (worktree-removal-agent-trust-cleanup). I read all code at the pinned head, so none of this rests on the PR description.

Work census (trigger → owner/thread → work × repeats → bound)

Reference fleet: about 2,856 ledger entries (~624 KB, measured with a synthetic ledger of the same shape), config.toml ~330 KB × 3, and 100+ agents launching in bursts.

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

  1. 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.
  2. 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.
  3. 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.
  4. 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).
  5. 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-check stillCurrent before each attempt: at most about 5 × 330 KB reads per publish, on the worker. Windows/WSL was not run.
  6. 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. readAgentStateJsonFileSync caps 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 next apply overwrites 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.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Review status: ready

Problem. Every Codex launch that pre-trusts its workspace edited two or three ~330 KB config.toml files and read, validated and rewrote the whole ~666 KB ownership ledger once per config, all synchronously on Electron main (and orcad's loop). A field capture tied ~288 ms of those calls to an 850 ms main-timer stall.

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

  • The whole grant runs as one request on a new worker thread while main holds every config's lock in hook-installer order; the worker is the ownership ledger's only writer (worktree-removal cleanup moved onto it too).
  • One ledger read/validate/write per grant, written before any config is published, so a worker stopped mid-grant still leaves cleanup records; records for configs that didn't land are dropped afterwards. Already-trusted projects write nothing.
  • Each config is published only while it still holds the bytes the grant read (checked before every rename attempt), so a concurrent main-thread edit is redone around, never overwritten.

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

  • remote-check (pnpm check:changed, 39 checks) PASS on 80b52eb.
  • Benchmark: head=80b52ebcdb1ec3c1840db97930ebda3a17557f73 gate=PASS corpus="3x330 KB config.toml + 2,856-entry 715 KB ledger, 12 concurrent launches, Omarchy Node 26" max main-timer overshoot before→after: new grants 1,551–1,890 ms → 0.7–0.9 ms; already trusted 751–862 ms → 0.8–0.9 ms; ledger 2,892/2,892 records in every run.
  • Perf scan (separate reviewer) clean on 80b52eb (comment above).
  • QA, Windows low spec, ~1,900 worktrees, on 80b52eb: PASS. Bursts of new and already-trusted grants, under CPU load with concurrent removals, after restart, external edit plus cleanup ownership, read-only config, held config (rename retry), a writer rewriting the config every 50/250 ms (its edits always survive; at 50 ms the grants give up and Codex asks), write-ahead timeline. CPU profiles show no trust code on main. Same-machine trust-related stall removed (A burst worst stall 1,540 → 636 ms; the remaining ~600 ms is the hook installer, below).
  • QA, Windows high spec, ~1,900 worktrees, on the first head: worst main stall 674 → 61 ms (new grants), 367 → 54 ms (already trusted), 308 → 33 ms (under load), 840–881 → 21–30 ms (failing/retrying write).

Deferred / found, not caused by this PR (same on main)

  • The Codex hook installer still scans and republishes the 330 KB managed config on main (~0.5–0.75 s per burst on a low-spec Windows machine, longer while the file is locked). Separate follow-up.
  • Sidebar worktree delete (worktrees:remove) skips Codex trust cleanup; orca worktree rm does it.
  • On Windows a read-only config.toml leaves a read-only config.toml.bak that blocks later grants until cleared.
  • P2s noted by reviewers: removal still reads the ledger twice per config (now on the worker); a record can outlive a table that never landed if the worker is killed (harmless; removal compares bytes).

@brennanb2025
brennanb2025 marked this pull request as ready for review November 19, 2026 03:58
@brennanb2025

Copy link
Copy Markdown
Contributor Author

QA screenshots

Windows low spec, head 80b52eb, ~1,900-worktree fleet with three ~330 KB configs and a 2,856-entry ledger: a Codex agent launched into a never-trusted worktree (r01/w015, part of a 5-launch burst after a restart) reaches its ready prompt with no trust dialog; the grant was written by the new worker.

Codex ready with no trust prompt, Windows low spec, 80b52eb

Windows high spec, first QA round on the same fleet size: the same result for r12/w015 in a burst.

Codex ready with no trust prompt, Windows high spec

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.

1 participant