Skip to content

App beachballs when multiple threads run concurrently #124

Closed

Description

@currentbits

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 via execFileSync on 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

  1. Open several threads (3+) in one project.
  2. Start runs in all of them at once.
  3. 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

Activity

  1. added
    bug
    plan:todo
    on Aug 16, 2026
  2. currentbits commented on Aug 16, 2026

    @currentbits
    OwnerAuthor

    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/updateMessage slice the whole message list per call (store.js:759,953), and pushDetail -> services.getThreadDetail slices 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.

  3. added
    plan:doing
    and removed
    plan:todo
    on Aug 17, 2026
  4. currentbits commented on Aug 17, 2026

    @currentbits
    OwnerAuthor

    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. Adds execCommandAsync to ssh.js alongside the existing sync execCommand (which worktrees.js still needs), then converts gitOut and gitStatus / gitSyncInfo / gitRepoInfo / gitFetch / gitPull / addProject / createProject to async spawn.

    W2 — async git in worktrees.js (thread `f1d4fefc`)
    Owns worktrees.js only; builds its async helper in-file, mirroring the ghTryAsync pattern already established there. Scoped to the hot read paths: the diff HEAD / --numstat path behind git:diff, and listFiles/lsFiles behind 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 via perf_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 measures JSON.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.js is 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, listFiles on 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.js stay synchronous, bounded at 15s. Documented in-file with a ponytail: comment rather than left to rot. Say the word if you want the full sweep instead.

  5. currentbits commented on Aug 17, 2026

    @currentbits
    OwnerAuthor

    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.stringify of the live store is ~58ms, because coder-store.json on 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) is messagesByThread, 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 that process.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 messagesByThread into 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=1 enables perf_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.

  6. currentbits commented on Aug 17, 2026

    @currentbits
    OwnerAuthor

    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/dist was not built (worktrees have no node_modules, and npm run test:electron depends on a built core). Worth knowing for anyone testing in a worktree: clone deps with cp -Rc from the main checkout rather than npm install, and run cd core && npm run build first.

    Two things the audit turned up after merging

    1. A latent bug W1 introduced, now fixed and pinned (4ba837e). git:syncInfo, git:repoInfo and git:pull document "never throws" and answer in-band. They were written as return services.gitFoo(root) inside a try/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 with return await, plus electron/test/ipc-async-guard.test.js, which I confirmed fails 3/3 with the awaits 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.js has a sync ghTry calling execFileSync(ghBin(), ...) with GH_TIMEOUT_MS = 30_000. gh is a network call. So one slow or hanging gh freezes 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.js already documents at ~line 1900 that "gh is ALWAYS async (execFile, never execFileSync) so the main process cannot freeze the way prStatus once did" — and ghTryAsync already 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): defaultWhich is execFileSync and runner.js called 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 execFileSync after all this: smoke.js (a test script, not a production path) and memory-sup.js resolveNodeBinary (which node, called once when starting the memory server).

  7. currentbits commented on Aug 17, 2026

    @currentbits
    OwnerAuthor

    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_hooks histogram the shipped CODER_LOOP_LAG probe uses. N "threads" each run git status --porcelain concurrently, 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.

    concurrent threads path wall lag p50 lag p99 starved
    2 sync execCommand 212ms 13.1ms 18.7ms 29%
    2 async execCommandAsync 141ms 1.1ms 1.8ms 7%
    4 sync execCommand 417ms 26.6ms 31.3ms 63%
    4 async execCommandAsync 144ms 1.1ms 1.6ms 0%
    8 sync execCommand 766ms 50.7ms 53.7ms 80%
    8 async execCommandAsync 201ms 1.2ms 3.8ms 5%

    Two 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_LAG is the thing that ships, and it is what makes this re-checkable later.

    Note this measures local git at ~30-50ms. The sync gh path W4 is converting is a network call bounded at 30_000ms, so the same starvation curve applies with a ceiling roughly 600x higher.

  8. currentbits commented on Aug 17, 2026

    @currentbits
    OwnerAuthor

    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):

    path wall lag p50 lag p99 heartbeats starved
    sync execCommand (before) 423ms 27.0ms 32.2ms 64%
    async execCommandAsync (after) 145ms 1.1ms 1.7ms 0%

    What W4 did, and what I finished after it

    W4 routed the six hot gh handlers through the existing ghTryAsync. It stopped at createPr / mergePr because 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:

    • mergePr was already an async function — 3 awaits.
    • createPr became 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.
    • With no callers left, sync ghTry is deleted, not left as a landmine, and worktrees.js no longer imports execFileSync at all.
    • 19 test call sites converted (assert.throws -> await assert.rejects where the throw moved into a rejection).

    Synchronous execFileSync remaining in main-process code — the complete list

    1. memory-sup.js:827 — which node, once when starting the memory server.
    2. 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

    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.

  9. currentbits commented on Aug 17, 2026

    @currentbits
    OwnerAuthor

    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=1 and electron/smoke.js precisely 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, real Store / createRunner / registerIpc, real preload bridge in a real BrowserWindow. N threads in one project, runs started in all of them at once, restarted as they finish so streaming is sustained — while the renderer hammers git:diff, git:status, files:list and git:syncInfo over real IPC. The main process measures its own event-loop lag with the same perf_hooks histogram CODER_LOOP_LAG uses.

    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

    lag p50 lag p99 lag max heartbeats starved
    before 1.3ms 63.4ms 149.3ms 595/1503 60.4%
    after 1.3ms 2.0ms 33.6ms 1451/1504 3.5%

    8 concurrent runs, 15s

    lag p99 lag max starved
    before 63.1ms 77.3ms 60.7%
    after 2.0ms 87.2ms 5.0%

    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.stringify measured earlier at ~58ms. So the sustained blocking is fixed and the remaining spikes point at #225 (shard messagesByThread). 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.

  10. added
    plan:done
    and removed
    plan:doing
    on Aug 17, 2026
  11. added a commit that references this issue on Aug 17, 2026
    79a1e52
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugplan:done

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions