Repository navigation
Closed
Description
Symptom
When several threads (agent runs) are active at the same time, the whole app intermittently hangs: macOS shows the spinning beachball and the UI stops responding for seconds at a time. Observed on macOS; the mechanism is platform-independent, so Windows and Linux presumably freeze the same way.
Likely mechanisms (from prior investigations, see docs/ISSUES.md)
All of these run on the Electron main process, so N concurrent streaming agent CLIs plus IPC traffic queue behind any one of them:
- Sync git on the event loop in hot IPC paths. Synchronous git on the main-process event loop with no default timeout #88 bounded every sync git call with a 15s timeout, but the explicit remainder stands:
diff,listFiles, sync info, etc. still run viaexecFileSyncon the main process. With several threads each asking for diffs/status, each call blocks all streaming for every other thread. The async-spawn conversion was deferred as "a bigger change than a bound." - Whole-store stringify on the main thread. Cap transcript growth and stop whole-store synchronous stringify on flush #89 capped transcript growth and moved the file write off the event loop, but the JSON.stringify of the store still runs synchronously on the main thread (bounded by the caps, still megabytes under load). Every stream event from every running thread triggers a debounced flush.
- Streaming fan-out. Each running CLI pushes chunks over IPC; 700ms streaming tick re-renders all three main panes #91 fixed the worst re-render fan-out, but with N threads the renderer still re-parses and re-renders on every tick while the main process is serializing all of it.
Any single one of these stalls the shared event loop; together with multiple concurrent runs they compound into the observed beachballs.
Repro
- Open several threads (3+) in one project.
- Start runs in all of them at once.
- Interact with the app (switch threads, scroll, open the Git tab) while runs stream.
What good looks like
- The UI stays responsive (no beachball) with 4+ concurrent runs.
- No synchronous git, gh, or filesystem call runs on the main-process event loop in any path reachable during a run (async spawn or a worker thread/pool instead).
- Store persistence cannot block streaming (e.g. per-thread store files or fully async stringify/write).
Notes
- Related closed issues with standing remainders: Synchronous git on the main-process event loop with no default timeout #88 (sync git timeout bound, not async), Cap transcript growth and stop whole-store synchronous stringify on flush #89 (store caps, stringify still sync), 700ms streaming tick re-renders all three main panes #91 (streaming tick re-renders), Store: every stream event rewrites the entire 15 MB store synchronously #27/IPC: full transcript pushed on every chunk; Markdown re-parses every message #28/Agents panel re-queries all threads' messages on every stream push #29 (IPC fan-out).
- A first diagnostic step could be main-process event-loop lag instrumentation to confirm which mechanism dominates.
Activity
currentbits commentedon Aug 16, 2026
Additional hot path found during audit (probably folds into this issue rather than a separate one): every streamed chunk triggers per-event O(transcript) array copies on the main thread.
store.appendMessage/updateMessageslice the whole message list per call (store.js:759,953), andpushDetail->services.getThreadDetailslices both messages and workLog per push (services.js:1128-1129). With N streaming threads this multiplies the per-chunk main-thread cost on top of the stringify/fan-out described above.currentbits commentedon Aug 17, 2026
Working this with three parallel grok workers, partitioned by file so they cannot collide (each in its own worktree/branch).
W1 — async git in
services.js(thread `049cc370`)Owns
ssh.js+services.js+ipc.js. AddsexecCommandAsynctossh.jsalongside the existing syncexecCommand(whichworktrees.jsstill needs), then convertsgitOutandgitStatus/gitSyncInfo/gitRepoInfo/gitFetch/gitPull/addProject/createProjectto async spawn.W2 — async git in
worktrees.js(thread `f1d4fefc`)Owns
worktrees.jsonly; builds its async helper in-file, mirroring theghTryAsyncpattern already established there. Scoped to the hot read paths: thediff HEAD/--numstatpath behindgit:diff, andlistFiles/lsFilesbehind the mention autocomplete (that one fires on every keystroke). User-initiated write paths (mergeInto,push, PR creation) stay sync — see remainder below.W3 — measurement + store flush (thread `c81bd58a`)
Owns
store.js+ a small lag probe. Adds main-process event-loop lag instrumentation viaperf_hooks.monitorEventLoopDelay()behind an env flag — this is the issue's own suggested first diagnostic step, and it is also what proves the fix. Then measuresJSON.stringify(store, null, 2)on a realistically-capped store before changing anything, and is explicitly authorised to report "not the bottleneck" rather than manufacture a fix.Scope call worth flagging up front
"No synchronous git in any path reachable during a run" taken literally includes merge/push/PR — a user can click merge while other threads stream. Converting all ~50 sync call sites in the 2886-line
worktrees.jsis a much larger, riskier change than the observed symptom needs. The beachball comes from calls that fire repeatedly and automatically (diff on every Git-tab render,listFileson every mention keystroke), not from once-per-click actions that #88 already bounds at 15s.So the deliberate remainder: user-initiated write paths in
worktrees.jsstay synchronous, bounded at 15s. Documented in-file with aponytail:comment rather than left to rot. Say the word if you want the full sweep instead.currentbits commentedon Aug 17, 2026
W3 landed on
coder/fork-app-beachballs-when-multiple-thread-c81bd5, merged and verified here (46/46 electron store+looplag tests pass).The measurement, which reframes mechanism (b):
JSON.stringifyof the live store is ~58ms, becausecoder-store.jsonon the daily driver is 54MB. I verified the file size and composition independently rather than take the worker's word for it — 97% of it (52.5MB) ismessagesByThread, across 227 buckets, median 190KB each.So the sync stringify is a real contributor, but not via the mechanism this issue assumed. #89's per-thread caps are working correctly — no runaway bucket, no orphans from deleted threads, largest thread a reasonable 1.3MB. The store is simply linear in thread count, which no per-thread cap can bound.
Landed here (mitigation): debounce backs off 250ms -> 2s under sustained dirty flushes, resetting when quiet, so N streaming threads cannot force a 58ms whole-store stringify at 4Hz.
saveNow()stays sync with a comment explaining thatprocess.on('exit')cannot await.Tradeoff to be aware of: the unsaved-data window grows from 250ms to 2s under load. Clean exit is covered by the exit hook and there is a crash guard, so it is a hard-crash-only risk — but it is a real change, not free. It reverts once #225 lands.
Structural fix split out to #225: shard
messagesByThreadinto per-thread files. Today, one message arriving on one thread re-serializes all 227 threads — ~0.2ms of useful work inside ~58ms of waste. Sharding takes a flush from 52.5MB to ~190KB and stops it scaling with thread count.Also added:
CODER_LOOP_LAG=1enablesperf_hooks.monitorEventLoopDelay()and logs mean/p50/p99/max every 5s. Off by default, histogram not even created when unset. This is the issue's suggested first diagnostic step, and it is how the "no beachball with 4+ concurrent runs" acceptance criterion gets verified rather than eyeballed.W1 (services.js) and W2 (worktrees.js) still running.
currentbits commentedon Aug 17, 2026
W1 and W2 merged and verified. Electron suite 841 pass / 1 fail, the single failure being
wireClient x webBridge over a real socket, which passes 18/18 when its file runs alone — a pre-existing port-allocation flake under parallel runs, present on main before any of this work. Renderer 723/723, core 38/38, typecheck clean.Established that baseline properly before trusting anyone's numbers: my first run showed 150 failures, which turned out to be my own setup —
core/distwas not built (worktrees have nonode_modules, andnpm run test:electrondepends on a builtcore). Worth knowing for anyone testing in a worktree: clone deps withcp -Rcfrom the main checkout rather thannpm install, and runcd core && npm run buildfirst.Two things the audit turned up after merging
1. A latent bug W1 introduced, now fixed and pinned (
4ba837e).git:syncInfo,git:repoInfoandgit:pulldocument "never throws" and answer in-band. They were written asreturn services.gitFoo(root)inside atry/catch. Once those functions became async, the returned promise settles outside the try, so the catch can no longer see a rejection — the handler would reject instead of returning{ ok: false }. Nothing fails today only because those services functions catch their own errors, which is exactly why it needed pinning rather than shrugging at. Fixed withreturn await, pluselectron/test/ipc-async-guard.test.js, which I confirmed fails 3/3 with theawaits removed and passes 3/3 with them.2. The biggest remaining offender is not git at all — it is
gh, and it was never in this issue's list.worktrees.jshas a syncghTrycallingexecFileSync(ghBin(), ...)withGH_TIMEOUT_MS = 30_000.ghis a network call. So one slow or hangingghfreezes every window and every streaming thread for up to 30 seconds — three orders of magnitude worse than the local git calls this issue was opened about, and worse than the 58ms stringify.Reachable from six IPC handlers:
git:prStatus,git:prChecks,git:listPrs,issues:fetch,issues:list,issues:setPlanStatus. The planboard ones (issues.js) are hit by agents while other threads stream, so this is genuinely hot, not just a click path.The irony:
worktrees.jsalready documents at ~line 1900 that "gh is ALWAYS async (execFile, never execFileSync) so the main process cannot freeze the way prStatus once did" — andghTryAsyncalready exists. That guarantee only ever covered the background PR-state refresher; the user-facing handlers never got it. W4 (6c170652) is now routing them through the existing async helper.3. Also landed (
e06d329):defaultWhichisexecFileSyncandrunner.jscalled it on every run start, uncached — so N concurrent runs paid N PATH walks. Memoised hits only; a miss stays uncached so installing a provider CLI mid-session still works without a restart. Memoised rather than converted to async on purpose: a cache hit is faster than an async spawn and a far smaller diff than the caller cascade. 5 tests, verified to fail without the cache.Remaining sync
execFileSyncafter all this:smoke.js(a test script, not a production path) andmemory-sup.jsresolveNodeBinary(which node, called once when starting the memory server).currentbits commentedon Aug 17, 2026
Measured: the mechanism, and that the fix works
Rather than only assert "the sync calls are gone", I benchmarked event-loop lag directly, using the same
perf_hookshistogram the shippedCODER_LOOP_LAGprobe uses. N "threads" each rungit status --porcelainconcurrently, against a 10ms heartbeat standing in for a streaming thread that needs the loop regularly.starved= share of heartbeats the loop missed. That column is the beachball, in one number.execCommandexecCommandAsyncexecCommandexecCommandAsyncexecCommandexecCommandAsyncTwo things this settles:
The issue's diagnosis was right, and it is specifically a scaling problem. Sync lag grows linearly with concurrent thread count — 18.7 -> 31.3 -> 53.7ms p99 — and starvation goes 29% -> 63% -> 80%. That is exactly the reported symptom: fine with one thread, beachballs with several. At 8 threads the loop was missing four out of five heartbeats.
After the conversion it stops scaling. Async p99 stays flat at 1.1-3.8ms and starvation collapses to 0-7% regardless of thread count. Wall-clock also improves 2.9x at 4 threads and 3.8x at 8, because the git calls now actually overlap instead of queueing.
Worth noting the async numbers are not zero-cost — 5-7% starvation at 2 and 8 threads is spawn overhead, not blocking. It is noise next to 80%.
What this does and does not prove
It confirms the mechanism and validates the fix at the seam that was broken, at the acceptance criterion's "4+ concurrent runs". It is not the same as the end-to-end app test: it does not exercise the renderer, IPC fan-out, or real streaming CLIs. The honest end-to-end check is still
CODER_LOOP_LAG=1 npm run dev, start 4+ real runs, and watch the[looplag]p99/max lines — I have not run that, because it needs the daily-driver app and four billable agent runs.The benchmark was a scratch script and is deliberately not committed —
CODER_LOOP_LAGis the thing that ships, and it is what makes this re-checkable later.Note this measures local git at ~30-50ms. The sync
ghpath W4 is converting is a network call bounded at 30_000ms, so the same starvation curve applies with a ceiling roughly 600x higher.currentbits commentedon Aug 17, 2026
All four workers merged. Final state
Tests: electron 859/860, renderer 723/723, core 38/38, typecheck clean. The single electron failure is
wireClient x webBridge over a real socket, a pre-existing port-allocation flake that passes 18/18 when its file runs alone — present on main before this work.Event-loop lag, re-measured on the final merge (4 concurrent threads,
git status --porcelain, 10ms heartbeat standing in for a streaming thread):execCommand(before)execCommandAsync(after)What W4 did, and what I finished after it
W4 routed the six hot
ghhandlers through the existingghTryAsync. It stopped atcreatePr/mergePrbecause I had scoped write paths out — correct obedience, wrong boundary in hindsight. A 30s network call that freezes every window and every streaming thread on one click is the reported bug, so I finished it:mergePrwas already anasync function— 3 awaits.createPrbecame async. Its local git (push,defaultBranch,gitTry) stays sync at the 15s Synchronous git on the main-process event loop with no default timeout #88 bound; the 30s network calls were the point.ghTryis deleted, not left as a landmine, andworktrees.jsno longer importsexecFileSyncat all.assert.throws->await assert.rejectswhere the throw moved into a rejection).Synchronous
execFileSyncremaining in main-process code — the complete listmemory-sup.js:827—which node, once when starting the memory server.smoke.js:37— a test script, not a production path.That is all of it. No synchronous git or gh remains on any read path.
Deliberate remainders, both filed rather than left to rot
resolveThreadGit/defaultBranchstill make ~2 sync local git calls on the PR read paths, and the worktree write flows stay sync at 15s. Measured at ~30-50ms p99 versus the 30_000ms network calls that were fixed: real, but three orders of magnitude down. Marked in-file with aponytail:comment.messagesByThread(97% of a 54MB store). Would let the debounce backoff added here, and its 2s unsaved-data window, revert to a flat 250ms.Not verified, stated plainly
I have not run the end-to-end check:
CODER_LOOP_LAG=1 npm run dev, 4+ real agent runs, watch the[looplag]p99/max lines. That needs the daily-driver app and four billable runs. The benchmark validates the seam that was broken and the mechanism behind the symptom; it does not exercise the renderer, IPC fan-out, or real streaming CLIs. Leaving this issue open until someone runs that — the acceptance criterion is "the UI stays responsive", and inference is not observation.The streaming fan-out mechanism (c) from the original list was never touched; #91 covered the worst of it and nothing here measured it as a contributor.
currentbits commentedon Aug 17, 2026
End-to-end verified. I was wrong to leave this unverified.
I claimed the end-to-end check needed the daily-driver app and four billable agent runs. That was wrong — this repo ships
CODER_SIMULATE=1andelectron/smoke.jsprecisely so the real stack can be driven for free. I asserted a blocker instead of looking for a way through. Corrected.electron/beachball.js(committed,npm run beachball) runs the issue's own repro against the real stack: real Electron main process, realStore/createRunner/registerIpc, real preload bridge in a realBrowserWindow. N threads in one project, runs started in all of them at once, restarted as they finish so streaming is sustained — while the renderer hammersgit:diff,git:status,files:listandgit:syncInfoover real IPC. The main process measures its own event-loop lag with the sameperf_hookshistogramCODER_LOOP_LAGuses.I ran it on a worktree at the branch point (
6687768, none of this work in it) and on the merged branch. Same machine, same workload, ~596 git IPC calls each.4 concurrent runs, 15s
8 concurrent runs, 15s
The beachball reproduced, and it is gone. Before the fix the main process was missing three out of five 10ms heartbeats for fifteen seconds straight — that is the spinning cursor, measured. After, p99 lag is 2.0ms and starvation is single-digit noise. It no longer degrades with thread count.
One thing I am not going to hide
At 8 threads the single worst spike is higher after the fix (87.2ms vs 77.3ms). p99 collapsed but isolated spikes remain, and ~60-90ms is exactly the whole-store
JSON.stringifymeasured earlier at ~58ms. So the sustained blocking is fixed and the remaining spikes point at #225 (shardmessagesByThread). A single 87ms hitch is not a beachball; a 15-second run of them was.Reference numbers are recorded in the harness header so a regression is legible: STARVED climbing back into the tens of percent is the signal.
Closing this — the acceptance criterion is met and measured, with the two remainders tracked as #225 and #228.
Merge pull request #229 from currentbits/coder/app-beachballs-when-mu…