You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Name the sync call a stalled main thread is inside in hang reports - #52802
When Orca's main process freezes inside a disk call, its hang watchdog can't tell which call or file it is, so every report says "unknown". Now the main thread writes down which disk call it's inside, in a spot the watchdog can read without the main thread's help. The next freeze will name the file and the call.
Files
Added
Deleted
Net
Test
2
$\color{#1a7f37}{\Huge{\mathbf{+}}}$52
0
$\color{#1a7f37}{\Huge{\mathbf{+}}}$52
Prod
16
$\color{#1a7f37}{\Huge{\mathbf{+}}}$452
$\color{#cf222e}{\Huge{\mathbf{−}}}$28
$\color{#1a7f37}{\Huge{\mathbf{+}}}$424
What Changed
src/main/diagnostics/main-blocking-call-slot.ts: a fixed-size SharedArrayBuffer slot. It holds the sync call the main thread is inside right now: source, label tail, start time. A sequence counter keeps readers from seeing half a write. The watchdog worker inherits it through setEnvironmentData, the same way worker-send-ledger is shared.
enterSyncCall now takes the call's source and label up front and publishes the innermost call. exitSyncCall republishes the caller, or clears the slot once main leaves the outermost call. The existing SQL statement, exec and durable-write annotations pass their labels at entry, and SQLite iterate() steps are annotated like get/all.
src/main/diagnostics/main-sync-fs-annotation.ts: on the main thread only, sync fs calls that touch a path or descriptor are wrapped with the same annotation. These include openSync, readFileSync, writeFileSync, statSync, existsSync, readSync/writeSync/closeSync and realpathSync.native. It is installed with the hang watchdog, so only where the watchdog runs (packaged macOS/Windows with local diagnostics on). Code that kept its own reference to an fs function before startup isn't covered.
The watchdog reads the slot on stall detection and stores it on the observation as blockingCall, redacted: paths keep only their file name, and SQL literals become ?, including one the slot cut short. The next launch's breadcrumb reports activeMainActivity: blocking-call (only when the call is at least half as old as the stall, so a call that began after main stalled doesn't hide the native stacks), blockingCall and blockingCallAgeMs. The recovered-stall span gets stall.blocking_call.
eventLoop.longGapSyncCall now also names sync fs calls, not only SQL and fsync.
Why
Two recent main-thread hangs on macOS, 68 s and 45 s+, have the same native stack: a JS timer calls a sync open() that waits in the kernel on an APFS lock while a SQLite checkpoint write on another thread stalls the volume. In both, the JS frames are unsymbolized and the watchdog wrote nothing useful, so the timer can't be identified. The watchdog's own async writes were queued behind libuv threads stuck on the same lock.
Annotating blocking calls and having the hang watcher read the annotation from another thread is how Chromium names hangs (ScopedBlockingCall and HangWatcher). A JS stack can't be captured once the thread is inside a syscall, so the call has to name itself on entry.
The alternative was moving every main-thread sync fs call off main first. That is a follow-up: the known timer-driven sync fs sites move to async, with a lint ratchet. This PR makes the next stall say which site matters.
Linked Issue
N/A (internal).
Visual Proof
N/A: diagnostics only, no UI or behavior change.
Testing
hang-blocking-call.test.ts drives the real slot and annotation. It checks the outermost call is named while a nested one runs, path and SQL redaction, and that the slot is empty once the call returns.
Ran a dev build on Linux with the main-process inspector and counted main-thread sync fs calls per call site: an idle fresh profile makes only a handful. That run did not exercise the watchdog install path, which is macOS/Windows packaged-only.
I manually tested these changes locally
Automated tests added/updated, or explained why not below
Every added test fails without this change and avoids the test anti-patterns
Performance
Measured with the real modules bundled into one file, as production bundles them (Node 24, Apple Silicon, min of 25 runs):
base
this PR
Cheapest annotated call: in-memory SQLite primary-key get (raw 430 ns)
520 ns
526–543 ns
Slot publish + clear, isolated
n/a
22 ns + 6 ns
Slot setup (once at startup)
n/a
0.05 ms, 512 bytes
That is about 6–20 ns per annotated SQL call. Real statements against on-disk databases cost microseconds, so the overhead stays at or under 1–4% even on the cheapest one.
A wrapped sync fs call adds one small arguments array and about 30 ns of slot work. Each call is a syscall costing 3 µs or more, so the difference is within run-to-run noise on existsSync/statSync.
On worker threads it costs one performance.now() and a depth counter per annotated call. There is no new timer, poll or IPC, and the watchdog reads the slot only when it has already detected a stall.
Risk
Level: Low
The riskiest part is wrapping node:fs sync functions on the main thread. Wrappers forward this and arguments unchanged, inspect the first argument with type checks only, rethrow unchanged, and keep statics such as realpathSync.native. If a wrapper misbehaved, users would see a sync fs call fail on main. Revert is a plain revert; nothing persisted changes shape, because blockingCall is an optional field older builds ignore.
AI Disclosure
Review
Agent skill upstream boundary
Not applicable, or this change copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.
Notes
Cross-platform: the slot and annotation are platform-neutral, path redaction splits on both / and \, and the watchdog already runs on macOS and Windows only. Remote SSH, mobile: unaffected (main process diagnostics only).
Checklist
This PR is small and focused
I explained what changed and why (ELI5, the user-facing before/after, the mechanism, and why over the alternatives)
I stated the risk: what could break, for whom, and how to back it out
Before/after screenshots or videos attached for UI changes, or N/A with reason
Self-reviewed for correctness, security, and performance
Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)
It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.
The change tracks main-thread synchronous calls, including filesystem and SQLite calls, in a shared-memory slot. The hang watchdog can add a validated blocking-call description to live heartbeat-stall observations. Stall classification, recovered-stall messages, and traces now include blocking-call details when available.
Merge Risk: Moderate · previous review 6c64b
The new SQLite iterate() wrapper can leave a statement unreset when a caller stops iterating early, which can hold database locks. Several earlier concerns also remain open, including the redaction of SQL text in hang diagnostics. Fix the iterator cleanup and the open redaction concerns before merging.
Pre-merge checks: 4
Check name
Status
Explanation
Title check
The title names the change a stalled main thread is inside in hang reports: the watchdog now records the main thread's active sync call. The changeset adds a shared-memory slot, annotates sync calls a…
Description check
The description follows the repository template: it includes ELI5, What Changed, Why, Linked Issue (N/A, internal), Visual Proof (N/A with reason), Testing, Performance, Risk with level, Review, Agent…
Linked Issues check
Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check
Check skipped because no linked issues were found for this pull request.
Full details: Title check
Explanation
The title names the change a stalled main thread is inside in hang reports: the watchdog now records the main thread's active sync call. The changeset adds a shared-memory slot, annotates sync calls and sync fs wrappers, and adds blockingCall to hang observations. The title is specific and matches the primary change, though it omits the fs wrapping and the slot mechanism.
Full details: Description check
Explanation
The description follows the repository template: it includes ELI5, What Changed, Why, Linked Issue (N/A, internal), Visual Proof (N/A with reason), Testing, Performance, Risk with level, Review, Agent skill boundary, Notes, and Checklist. The author gave a clear mechanism, rationale, performance numbers, and rollback path. Gaps: the AI Disclosure section is empty, the Risk section does not give a level in the template's expected form beyond 'Low' (it does give one), and the Testing section does not state the platforms tested beyond Linux dev build. The final lint/typecheck/test/build checklist item is unchecked, which is acceptable if CI covers it. The Linked Issue section says N/A (internal), which the template permits for maintainers only, so this should be confirmed.
Resolution
Confirm the Linked Issue exemption applies, since the template requires an issue link for outside contributors. Fill in the empty AI Disclosure section or mark it not applicable. State which platforms were manually tested, since the watchdog path was not exercised on macOS or Windows. Run or confirm pnpm lint, typecheck, test, and build before merge.
Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 11
Note
Due to the large number of review comments, Critical, Major severity comments were prioritized as inline comments.
Caution
Some comments are outside the diff and can’t be posted inline due to GitHub limitations.
⚠️ Outside diff range comments (2)
Major · Abort the snapshot if an existing registry key cannot be… · registry-shortcut-backup.mjs:112-114
tests/tools/win-update-e2e/registry-shortcut-backup.mjs:112-114 Major · Data Integrity & Integration · Quick win
Abort the snapshot if an existing registry key cannot be exported.
If regExport fails, this branch leaves manifest.uninstall as null and returns a usable manifest. The app-key branch has the same behavior.
With the registry refusal removed, installation can now overwrite a real installation's key after its export failed. restoreInstallState cannot restore that key and treats a null manifest entry as evidence that the key was originally absent.
Require a successful export for every discovered key before returning the manifest. Abort before installation if any export fails.
Major · Retain the registry backups when restoration fails. · run.mjs:485
tests/tools/win-update-e2e/run.mjs:485 Major · Data Integrity & Integration · Quick win
Retain the registry backups when restoration fails.
If regImport fails, restoreInstallState returns verified: false and prints manual recovery commands. If restoration throws, the catch block also directs the user to the backups. Both paths then reach this unconditional deletion of runDir.
This deletes the .reg files required by those recovery instructions. Removing the preflight registry refusal now exposes a real installation's registration to this failure path.
Remove runDir only after restoration succeeds. If restoration fails or throws, retain the directory and report its path.
Minor comments: 10
mobile/src/i18n/locales/fr.json: 1
3713-3713: Minor · Functional Correctness · Quick win
Translate the steer action as steering.
“Envoyer maintenant” means “Send now.” It does not tell French-speaking users that this action steers the current model turn. Use a label that conveys steering, distinct from “Envoyer.”
mobile/src/i18n/locales/ja.json: 1
3585-3585: Minor · Functional Correctness · Quick win
Translate the steer action as steering.
“今すぐ送信” means “Send now.” It does not tell Japanese-speaking users that this action steers the current model turn. Use a label that conveys steering, distinct from “送信.”
mobile/src/i18n/locales/ko.json: 1
3595-3595: Minor · Functional Correctness · Quick win
Translate the steer action as steering.
“지금 보내기” means “Send now.” It does not tell Korean-speaking users that this action steers the current model turn. Use a label that conveys steering, distinct from “보내기.”
168-168: Minor · Functional Correctness · Quick win
Restore workspace state after a failed switch.
If the server rejects workspace B, Lines 159-160 have already selected B and cleared the selected teams. The removed context reload restored the server's workspace on a healthy connection. This catch now leaves the picker on B while the server still uses A.
Restore a best-effort loadLinearContext() in the failure path, or roll back both optimistic fields. Keep the original switch error visible if recovery also fails.
A late refusal for a denied request can cancel a later request with the same token.
When admit denies request A, the main process removes A from pending and reindexes the page. The renderer then sends refuseGuestIdleDiscard for A from the finally block in browser-guest-page-retention.ts. That message is asynchronous. If the policy returns to a shorter idle period before it arrives, pump can dispatch request B with the same { rendererId, generation } token.
The late refusal for A then matches B. matches no longer compares an attempt number, so refuse removes B from pending. B's later admit fails, and refuse does not clear consumed. The page stays consumed and out of the deadline index until its visibility changes. Memory Saver does not discard that hidden page in the meantime. No data is lost.
A refusal must settle only the dispatch it answers. The attempt counter removed in this change provided that identity. Add an equivalent per-dispatch identity to the token and to matches.
tests/tools/win-update-e2e/cli-args.mjs: 1
46-47: Minor · Functional Correctness · Quick win
Keep the isolated-target overwrite flag in the help text.
--allow-existing-install is not ignored in isolated mode. main passes it to preflight, which refuses an existing isolated target unless the flag is set.
Restore the explanation that this flag permits overwriting a prior harness installation in the target directory. Otherwise, users who reuse that directory receive instructions that contradict the refusal they must resolve.
123-126: Minor · Functional Correctness · Quick win
Do not restore activation errors after a stop.
If ensure is waiting for artifact resolution when deactivate clears activationErrors, a later lookup rejection now restores the obsolete error. activationError(pluginKey) then returns that error even though the plugin was explicitly stopped. Changed-spec reconciliation has the same problem.
Restore a per-plugin invalidation check around this write. Preserve error recording for activation attempts that have not been superseded.
68-68: Minor · Performance & Scalability · Quick win
Reclamation-triggered checkpoints add main-thread WAL restarts below the 1000-frame threshold.
reclaimed makes the worker run PASSIVE even when fewer than CHECKPOINT_FRAMES frames are pending. A completed checkpoint lets the next foreground write restart the WAL. With synchronous = NORMAL, that restart syncs the WAL header. The foreground connections run on the main thread. The comment at lines 11-12 sets the 1000-frame threshold to avoid this cost.
Each successful reclamation can now trigger one more restart, which adds main-thread syncs. The added count depends on how often reclamation runs. Reclamation needs at least 64 free pages, but the request cadence is not established.
The reclamation-triggered checkpoint either stays within the threshold design, or the extra main-thread restart syncs are accepted and lines 11-12 are updated to say so. The choice between these two options is open.
52-64: Minor · Performance & Scalability · Heavy lift
Incremental vacuum on the checkpoint worker can block foreground commits.
The worker's incremental_vacuum(512) holds the database write lock. A main-thread BEGIN IMMEDIATE that starts during that time waits on the lock for up to 25 ms, then fails with SQLITE_BUSY. Before this change, the worker only ran wal_checkpoint, which does not take the write lock, so this contention is new. The failed save rolls back and throws, and callers must retry it. Keep main-thread commits from waiting on the worker's reclaim step, or bound that step so it does not overlap foreground commits.
src/main/ghostty/parser.ts: 1
36-36: Minor · Functional Correctness · Quick win
Preserve hashes inside unquoted values.
Ghostty permits comments only on separate lines. A whitespace-preceded hash remains part of a value. (ghostty.org)
For font-family = Example #1, this call changes the returned value from Example #1 to Example. Quoting the same value preserves it, so equivalent representations now produce different results. Remove inline-comment stripping and retain the existing whole-line comment check.
themeFields constructs schemas when this module loads. The baseline change increases this file's allowance from 1 to 2.
Keep these schemas lazy and restore the previous baseline allowance. Preserve both strict and tolerant validation when updating the consumers. The baseline explicitly states: “counts may only go DOWN. Wrap schemas in lazyZodSchema(() => ...) instead.”
Additional comments: 1
mobile/src/i18n/locales/es.json-3713-3713: 1
3713-3713: Minor · Functional Correctness · Quick win
Unverified finding
Verification ran but could not confirm this finding. It is shown for review, not as a verified issue.
Translate the steer action as steering.
“Enviar ahora” means “Send now.” It does not tell Spanish-speaking users that this action steers the current model turn. Use a label that conveys steering, distinct from “Enviar.”
Review info
Run configuration
Source mode: Auto
Repository: Unavailable
Branch: Unavailable
File: No configuration file from this repository applied
Commit: Unavailable
Layers: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: 936db0e0-6595-4cce-8d39-9378e41fffdd
Commits
Reviewing files that changed from the base of the PR and between 13c4886 and b51b235.
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 0 remain after this review.
The PR lets the watchdog name the synchronous disk call holding the main thread.
Hang reports can name the sync call that stopped main.
Long event-loop gaps can name sync filesystem calls.
Diagram
%%{init: {'theme': 'neutral'}}%%
flowchart LR
A[Main enters sync call] --> B[Publish outermost call in shared memory]
B --> C[Run disk call]
C --> D[Clear slot on exit]
B --> E[Watchdog detects live stall]
E --> F[Read and redact call]
F --> G[Save hang observation]
G --> H[Next-launch breadcrumb]
G --> I[Recovered-stall trace]
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 2
Review info
Run configuration
Source mode: Auto
Repository: Unavailable
Branch: Unavailable
File: No configuration file from this repository applied
Commit: Unavailable
Layers: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: 7082e49d-1701-4bc0-84f2-a934c2b17f68
Commits
Reviewing files that changed from the base of the PR and between b51b235 and 6a59ebe.
Files selected for processing: 4
src/main/diagnostics/main-blocking-call-slot.ts
src/main/diagnostics/main-sync-calls.ts
src/main/diagnostics/main-sync-fs-annotation.ts
src/main/hang-watchdog/hang-blocking-call.test.ts
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 0 remain after this review.
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 2
Review info
Run configuration
Source mode: Auto
Repository: Unavailable
Branch: Unavailable
File: No configuration file from this repository applied
Commit: Unavailable
Layers: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: 82bd87e8-85dc-4371-95ef-20ce0a2f0963
Commits
Reviewing files that changed from the base of the PR and between 9284e65 and 6c64b6e.
Files selected for processing: 7
src/main/diagnostics/event-loop-delay-probe.ts
src/main/diagnostics/main-blocking-call-slot.ts
src/main/diagnostics/main-sync-calls.ts
src/main/diagnostics/main-sync-fs-annotation.ts
src/main/hang-watchdog/hang-blocking-call.test.ts
src/main/hang-watchdog/previous-hang-detection.ts
src/main/sqlite/node-sqlite-statement.ts
Files with no reviewable changes: 1
src/main/diagnostics/event-loop-delay-probe.ts
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 0 remain after this review.
Perf review (fresh reviewer, perf-scan) on 443eda6
Findings: no confirmed P0 or P1 performance regression. The added work is bounded metadata needed to identify the blocking call. I found no added native I/O, fleet scan, per-call IPC, timer, or accumulating queue.
Reviewed 0050f4ac3283...443eda65237ff639f464570517fbd1186b615d8b. The checkout remains unchanged.
Coverage and measurements. I covered all 18 changed files, including the two tests, and traced startup installation, SQLite execution and iteration, fs nesting, worker callers, observation persistence, recovery reporting, and teardown.
I bundled the real base/head modules with esbuild and measured interleaved runs on macOS arm64. Primary results below use Electron 45.4.1’s Node 24.22.3, running with ELECTRON_RUN_AS_NODE=1 ORCA_BACKGROUND_LAUNCH=1; no desktop window was created. Thread CPU time separates execution cost from substantial scheduling noise on this host. Standalone Node 26 measurements provided a second control.
Operation
Base → head CPU time
Added cost
Main enter/exit, repeated label, watchdog active
0.067 → 0.085 µs
0.018 µs/call
Main enter/exit, alternating labels filling the slot
0.067 → 0.249 µs
0.182 µs/call
Main SQLite get
0.524 → 0.568 µs
0.044 µs/call
Main SQLite run
0.333 → 0.356 µs
0.023 µs/call
Main SQLite exec
0.477 → 0.509 µs
0.032 µs/call
Main SQLite iterator
0.422 → 0.510 µs/row
0.088 µs/row
Recording enabled, watchdog absent: enter/exit
0.074 → 0.083 µs
0.009 µs/call
Neither consumer active: enter/exit
0.035 → 0.040 µs
0.005 µs/call
all() receives one annotation around the statement, independent of returned row count.
For fs, I measured both real syscalls and the actual annotation wrapper around a no-op original to isolate wrapper cost. The latter added 0.061 µs with repeated paths, 0.287 µs with alternating long paths, and 0.006 µs after both consumers were disabled. Real fd reads added 0.078 µs; small UTF-8 reads added approximately 1.04 µs. Other syscall comparisons had overlapping distributions and do not establish a reliable slowdown.
Reproduction and raw results: [benchmark driver](local scratch), [base/head results](local scratch), [wrapper measurements](local scratch), [runtime controls](local scratch).
Added work, bounds, and fleet price. For concrete arithmetic, the reference workload uses 750 worktrees, 300 terminals, 100 agents delivering two status events/s, 12 CLI callers every three seconds, and 50,000 transcripts. The growth workload multiplies each population by ten. These are pricing scenarios, not measured production call rates.
Added work and production trigger
Owner, per-call work, and bound
Reference fleet → 10× price
Every existing main-thread SQLite get/all/run/exec
One process-local recorder. Timestamp, stack bookkeeping, two atomic stores per publication; changed text copies at most 31 source and 223 label characters. Same labels skip copying. Implementation.
Pessimistically treating all 200 status events/s as separate urgent commits with two changed rows gives roughly 1,400 statements/s. Using 0.30 µs metadata/call: 0.42 → 4.2 ms/s. Actual persistence coalesces turn edges and batches routine changes.
Every main-thread iterator step
One annotation per native next(), including the final done step. No additional query or row visit.
Measured 50,000 and 500,000 rows produced exactly 50,001 and 500,001 annotations. At the measured added CPU cost: 4.4 → 44.1 ms per complete scan. A 600-row status hydration costs approximately 0.053 → 0.53 ms.
SQLite execution and iterator steps on workers/daemon/relay threads
With recording and local writer slot inactive, entry returns before clock reads, stack writes, text copies, or atomics. Inherited shared memory does not activate publishing.
Isolated guard difference approximately 0.005–0.006 µs/call: 0.3 → 3 ms for 50,000/500,000 calls. End-to-end inactive iterator measurements showed no resolved regression.
Every intercepted main-thread sync fs call
All 33 listed exports, plus realpathSync.native, use the same wrapper. It examines argument type, forwards arguments, and exits in finally. No payload inspection or extra filesystem operation. Nested calls also restore their parent annotation.
At 0.287 µs/wrapper, one existing operation per worktree costs 0.215 → 2.15 ms per pass; per terminal, 0.086 → 0.86 ms. Divide by the existing pass interval for ms/s. Compound calls pay for their actual intercepted nesting.
Sync fs on workers
Installation returns before wrapping anything. Existing explicit durable-write annotations take the inactive recorder path.
Zero new fs wrappers or I/O at either scale.
Durable sync writes and directory fsync
Existing outer annotations now carry labels; intercepted nested calls publish and restore context. The real durable-write control executed ten annotations, including the two existing outer annotations.
Native operation counts stay unchanged. Metadata remains proportional to those calls; multiplying the isolated mixed-path wrapper cost by the control’s 16 publications gives a conservative estimate of roughly 5 µs/write, or 0.5 → 5 ms per 100/1,000 writes.
Startup installation
Existing platform, consent, and packaged/force gates precede installation. One 272-byte SAB, three eight-entry stack arrays per importing isolate, and a fixed wrapper set. No new worker.
First slot/fs installation measured 0.304 ms CPU combined, constant at both fleet sizes. Benchmark bundle grew 8.7 KB; repeated module evaluation added approximately 11 µs. These are module measurements, not whole-app startup timings.
Live watchdog detection
Reads only when constructing a live heartbeat-stall observation, not on healthy ticks. At most four read attempts over fixed fields; redaction happens afterward. Read path.
Full currentHangBlockingCall() measured 1.27 µs. Even pricing one detection every five seconds gives 0.00025 ms/s, unchanged at 10×.
At most four retained observations; each new call label is capped at 200 characters. Existing marker limits remain 32 KiB written/64 KiB read. Adds fields to existing writes/messages, with no additional write or message trigger.
Parsing four records measured 0.424 µs; retaining an update 1.55 µs; recovery-message construction 0.016 µs, all absolute head costs. Added labels total at most 800 characters per collection, constant at 10×.
Failure, shutdown, worker exit
Spawn failure and worker exit retire the writer; finally clears call state. Existing timers/listeners stop through existing teardown. Reinstallation reuses the same SAB.
Retire/re-ensure measured 0.068 µs, constant at both scales. No per-entity retained resource was added.
The eight stack slots and last-label cache retain full input-string references until replaced; their entry count is bounded, rather than their input-string byte length. Normal SQL labels reference existing cached statement text. Bindings, transcript bodies, history bytes, branch counts, refs, and remotes are not serialized into this slot.
Executed controls confirmed:
Worker installation leaves its writer inactive while allowing it to read main’s published call.
Successful reads, failed opens, and durable writes clear the active call.
Iterator early termination releases the statement sufficiently for DROP TABLE to succeed.
Retirement clears the slot and disables publishing.
Buffer reads at 1 MiB and 10 MiB each executed four intercepted calls on this runtime; UTF-8 reads each executed one. Instrumentation added no reads.
The reviewed production callers include changed-row status persistence/hydration, profile document and automation-run reads, journal readers/writers and maintenance pages, orchestration readers, foreign OpenCode/Hermes readers, and search workers. Search posting admission remains capped at 10,000 examined postings; transcript query admission remains capped at 10,000 rows/16 MiB; journal compaction retains its cursor and page limits.
Steady-idle wakeups. Source-derived scheduled callbacks attributable to this audited subsystem, with default timings and optional histogram reporting disabled:
Process/thread
Before → after
Electron main thread: quiet stall probe + watchdog heartbeat
1.0 → 1.0/s
Watchdog worker, inside that process: check timer + heartbeat receipts
0.7 → 0.7/s
Electron main process, combined
1.7 → 1.7/s
Renderer
0 → 0 additional/s
Daemon, relay, and other workers
0 → 0 additional/s
When watchdog installation is gated off, the main-thread probe remains 0.5 → 0.5/s. These are timer/message-source counts, not measured OS wakeups or whole-app totals.
Disproved: iterator annotation is exactly once per step, with no restart or additional traversal.
Hidden or unobserved work
Checked: workers skip clocks/publication; fs installation follows existing gates. After retirement, the existing main stall probe remains a consumer.
Eager startup imports
Matched; fixed module/wrapper installation cost priced above. No heavy dependency or new process.
Fixed-cadence polling / new idle wakeups
Disproved: no added timer or healthy-tick slot read; existing cadence unchanged.
Whole snapshots / notification amplification
Checked: bounded field added to existing four-record collections and existing recovery messages; no extra publication trigger.
Resource retention / teardown
Checked: fixed shared slot and stack count; no growing registry, queue, or per-worktree ownership.
Six scan questions.
Unused work before a gate? Workers return before expensive recording. Watchdog installation gates remain ahead of fs wrapping. Redaction occurs on diagnostic consumption.
Ownership multiplies work? One main writer and fixed wrapper set per process; no owner per row, terminal, agent, or worktree.
Which thread pays? Main pays the measured annotation costs. Workers retain the inactive path. No new I/O or per-call cross-thread message.
What grows; does progress advance? Annotation count follows actual calls/rows. N/10N controls confirmed exact iterator counts; existing cursors, budgets, and early termination remain effective.
Execution-host effects? macOS runtime exercised. Windows gates/path handling and Linux exclusion inspected; worker/remote paths add no transport or filesystem work. Windows/Linux timing and live SSH/WSL were not executed.
Does obsolete work stop? Exception, iterator-break, retirement, and worker-inheritance controls passed. Shutdown retains fixed metadata until worker exit, then stops publication.
The added tests were inspected; the measurements and controls above were executed independently. I did not run the repository gate or claim packaged UI latency, whole-app idle CPU, or cross-platform timing results.
Problem. Electron's main thread hung for 45–68 s twice on macOS. In both, a JS timer had called a synchronous open() that sat in the kernel on a filesystem lock while another thread's SQLite write stalled the disk. The hang watchdog could not say which call or file it was: JS frames are unsymbolized inside a syscall, and its own writes were queued behind the same stall.
User-facing change. None visible. The next main-thread stall report names the sync call and file (file name only) or SQL statement (literals redacted) that main was inside. It appears in the next launch's breadcrumb, the recovered-stall trace span and eventLoop.longGapSyncCall.
Fixed during review
Path labels reduced to the file name only. Keeping parent folders could expose a username or repo name.
SQL literals cut off by the slot's length limit are now redacted too.
The innermost call is published and its caller restored on return. A descriptor call (readSync, fsyncSync) inherits its caller's file name. More fd/link/vector calls and realpathSync.native are covered, and so are SQLite iterate() steps.
Wrappers inspect arguments with typeof only, so they can't throw where the real call wouldn't.
A blocking call is reported over native stacks only when it is at least half as old as the stall.
iterate() resets the native statement when a consumer stops early (a regression introduced and caught within this PR). A regression test fails without the fix.
Worker threads skip the bookkeeping entirely, and main stops publishing once the watchdog has gone.
Deferred (agreed with the reviewer; tracked in Linear STA-19967). Three label inaccuracies with no behavior or performance effect:
A file literally named fd inherits its caller's file name in a nested call.
File-URL arguments are labelled path.
Nesting deeper than 8 shows the 8th call.
Verified
CI green.
Two independent reviews, then two repair checks.
Final regression audit on the change merged onto current main: SAFE.
Fresh perf review: clean (report above). It adds 0.02–0.09 µs per main-thread SQLite call, about 0.005 µs when no consumer is active, and no new timers or idle wakeups.
Unit tests:
hang-blocking-call.test.ts: nested publish and restore, redaction including a truncated literal.
node-sqlite-statement-iterate.test.ts: early exit releases the statement.
Both drive the real modules. No Electron QA run: the watchdog install path is packaged-only, and the behavior is covered by these tests.
Perf review (fresh reviewer, perf-scan) on f050b22
No P0/P1 findings. Verdict: clean for the requested performance scope. The added publication work is necessary to identify an in-flight blocking call, stays bounded per call, and introduces no timer, IPC, filesystem operation, or database query per publication.
Reviewed 0050f4ac3283...f050b22aa52831271b6892d7c66c0094f99ca2d3. The checkout remains unchanged.
Measured evidence
I bundled the real modules from both revisions with esbuild and benchmarked them on Darwin arm64, Node 26.5.0. Alternating base/head batches in the same process reduced substantial host noise. These are warm microbenchmark medians, not packaged Electron or fleet telemetry.
Main-thread operation
Base → head, µs/call
Median paired increase
Enter/exit, reused label
0.050 → 0.088
0.036 µs
Enter/exit, alternating labels filling the slot
0.065 → 0.564
0.499 µs
existsSync
1.433 → 1.694
0.247 µs
statSync
2.475 → 2.595
0.115 µs
readFileSync, 1 KiB
11.666 → 13.050
1.355 µs
realpathSync.native
10.498 → 9.699
0.353 µs
SQLite get / all
—
0.118 / 0.103 µs
SQLite run / exec
—
0.044 / 0.061 µs
SQLite iterate step, 10,000/100,000-row scans
—
0.140 / 0.116 µs
Paired differences and independently calculated medians need not subtract exactly. Filesystem measurements remained noisy; they are estimates, not latency guarantees. Worker SQLite iteration showed no consistent increase. The inactive enter/exit guard measured approximately 0.005–0.007 µs total, without clocks or atomic stores.
Reproduction artifacts: [paired benchmark](local scratch), [deterministic controls](local scratch), [observation benchmark](local scratch). Scratch files were confined to /tmp.
The prices below distinguish explicit audit workloads from observed production rates.
Added work: trigger, population and bound
Reference fleet → 10× price
Publication: every annotated main-thread call. Four atomic stores per enter/exit pair; changed text writes at most 31 source and 223 label characters. Eight nesting slots.
At 750/7,500 worktrees × two calls/s: 0.055–0.75 → 0.55–7.5 ms/s, using reused/full-changing-label measurements.
Sync fs wrappers: all 33 listed functions plus .native; constant argument labeling and forwarding, with publication for nested calls. No additional disk operations.
SQLite get/all/run/exec: one annotation per existing execution; statement caching, query counts and locking policy unchanged.
At 1,500/15,000 executions/s: 0.066–0.178 → 0.66–1.78 ms/s, depending on method.
SQLite iteration: one annotation per next(), including the final done step. Required row traversal remains unchanged.
A 750/7,500-row inventory adds about 0.1 → 0.9 ms. A 30,000/300,000-row history scan extrapolates to 3.6 → 36 ms using 0.12 µs/row.
Worker calls: fs installation returns before wrapping; SQLite execution and iteration take the inactive guard. Existing durable-write annotations also remain inactive.
No publication stores or added fs operations at either scale. Worker iteration differences were within measurement noise.
Main without a watchdog slot: existing stall recording remains active; additional stack bookkeeping measured 0.0033 µs/call.
At 1,500/15,000 calls/s: 0.005 → 0.049 ms/s.
Startup installation: once after existing platform, consent and packaged/force gates. One 272-byte shared buffer and a fixed wrapper set; no new worker.
Measured 0.101 ms once, unchanged at 10× fleet.
Watchdog read: once when observing a live heartbeat stall, not on every check or heartbeat. Two views, bounded text decoding, at most four attempts.
Measured 0.58 µs for a path and approximately 1.86 µs for a long SQL label. Even at 0.2 reads/s: <0.0004 ms/s, unchanged at 10×.
Observation persistence/recovery: existing writes and recovery messages gain bounded text, at most four observations × 200 characters.
Four-record fixture added 964 bytes. Retain/serialize added 0.67 µs/write; parsing added 2.35 µs/collection; recovery-message serialization 0.116 µs/message. These populations remain four, four and one at 10× fleet.
Teardown: clear the slot and stop publication after worker exit or spawn failure.
One clear costs two atomic stores. Executed controls confirmed zero subsequent stores after retirement.
For the agent/CLI dimensions, 100 agents × two updates/s gives 200 events/s; 10× gives 2,000. Per annotated statement/event, publication costs approximately 0.007–0.10 → 0.07–1.0 ms/s. Twelve CLI clients calling every three seconds produce four calls/s, or forty at 10×: 0.00014–0.002 → 0.0014–0.020 ms/s per annotated statement/RPC. Multiply by the actual statement count, not by every worktree again.
I traced the main-thread last-status persistence route: ordinary saves retain their three-minute cadence, turn edges coalesce at one second, and unchanged baselines retain their existing skip behavior. Journal/profile writer and reader workers, scanner paths and identity-worker consumers retain the inactive publication path. Increasing repos, terminals, remotes, refs or history bytes adds no independent diagnostic sweep or payload copying; only actual calls and returned rows incur annotations.
Sixteen stores for this runtime’s nested readFileSync route.
Idempotent fs installation, descriptor-label inheritance, nested restoration and exception cleanup.
Early iterator termination resets the statement and leaves no active annotation.
A real worker reads the inherited slot while its own publication remains inactive.
The changed tests were inspected; the equivalent controls above were executed directly against bundled production modules.
Idle wakeups
Source-counted recurring callbacks attributable to these diagnostics, with ordinary probe settings and the watchdog enabled:
Process/thread
Base → head callbacks/s
Electron main thread: idle probe + heartbeat
1.0 → 1.0
Watchdog worker: check + heartbeat receipt
0.7 → 0.7
Electron main process, combined
1.7 → 1.7
Renderer / daemon / other workers: added by this path
0 → 0
The pre-existing busy probe cadence and opt-in histogram sampling also remain unchanged. These are scheduling counts, not measured OS wakeups. The PR adds zero steady-idle wakeups/s.
Regression classes touched
Class
Disposition
Sync fs/SQLite on Electron main
Matched and disproved as a regression: existing blocking operations gain measured annotation work; no new I/O or queries. Existing disk/lock stalls remain pre-existing.
Unchanged publication / whole snapshots
Matched and disproved: every call needs a new start/clear lifecycle; unchanged text is reused. Zero per-call messages or subscriber fanout.
Hot-path rescans / diagnostics serialization
Matched and disproved: publication copies bounded label text, not rows, bindings, file contents or history. Formatting runs on diagnostic consumption.
Fixed polling / idle and hidden work
Matched and disproved: no added timer or interval; existing gates and cadences remain intact.
SQL preparation / streaming processing
Matched and disproved: no new preparation or whole-result processing. Iteration adds one bounded annotation per step.
Whole-file rewrites
Matched and disproved: existing bounded marker writes gain a bounded field; no additional writes.
Resource lifetime / retained state
Matched and disproved: fixed buffer, wrapper set and eight stack slots; no per-entity registry or queue. Stack/cache entries retain existing string references, so 272 bytes describes the shared buffer, not all retained label storage.
Eager startup imports
Matched and disproved: small local diagnostic modules and fixed initialization; no new SDK, service, worker or storage scan.
Six scan questions
Unused work before a skip gate? Reviewed: workers skip before timing/publication; fs wrapping skips before installation; retired slots perform no stores.
Ownership multiplying work? Reviewed: one writer/slot/watchdog per eligible app installation; no owner per worktree, pane, agent or database.
Which thread/storage pays? Reviewed and measured: main pays annotation costs; worker calls remain inactive; shared-memory publication performs no storage I/O.
What grows; does progress advance? Reviewed: counts grow with calls/required rows, without additional fleet scans. Nesting, read retries and retained observation counts are bounded.
Execution-host effects? Reviewed structurally: installation remains macOS/Windows-only and introduces no SSH/WSL operation. Windows and packaged Electron timings were not measured.
Does obsolete work stop? Reviewed: shutdown clears timers, closes the port after capture cleanup, and retirement disables publication. Retirement and inactive-worker controls passed; full Electron shutdown was source-traced.
Remaining validation limits are packaged Electron timing, Windows timing and physical stalled-disk behavior. No unresolved amplification candidate was found in the inspected paths.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
ELI5
When Orca's main process freezes inside a disk call, its hang watchdog can't tell which call or file it is, so every report says "unknown". Now the main thread writes down which disk call it's inside, in a spot the watchdog can read without the main thread's help. The next freeze will name the file and the call.
What Changed
src/main/diagnostics/main-blocking-call-slot.ts: a fixed-sizeSharedArrayBufferslot. It holds the sync call the main thread is inside right now: source, label tail, start time. A sequence counter keeps readers from seeing half a write. The watchdog worker inherits it throughsetEnvironmentData, the same wayworker-send-ledgeris shared.enterSyncCallnow takes the call's source and label up front and publishes the innermost call.exitSyncCallrepublishes the caller, or clears the slot once main leaves the outermost call. The existing SQL statement,execand durable-write annotations pass their labels at entry, and SQLiteiterate()steps are annotated likeget/all.src/main/diagnostics/main-sync-fs-annotation.ts: on the main thread only, syncfscalls that touch a path or descriptor are wrapped with the same annotation. These includeopenSync,readFileSync,writeFileSync,statSync,existsSync,readSync/writeSync/closeSyncandrealpathSync.native. It is installed with the hang watchdog, so only where the watchdog runs (packaged macOS/Windows with local diagnostics on). Code that kept its own reference to an fs function before startup isn't covered.blockingCall, redacted: paths keep only their file name, and SQL literals become?, including one the slot cut short. The next launch's breadcrumb reportsactiveMainActivity: blocking-call(only when the call is at least half as old as the stall, so a call that began after main stalled doesn't hide the native stacks),blockingCallandblockingCallAgeMs. The recovered-stall span getsstall.blocking_call.eventLoop.longGapSyncCallnow also names sync fs calls, not only SQL and fsync.Why
Two recent main-thread hangs on macOS, 68 s and 45 s+, have the same native stack: a JS timer calls a sync
open()that waits in the kernel on an APFS lock while a SQLite checkpoint write on another thread stalls the volume. In both, the JS frames are unsymbolized and the watchdog wrote nothing useful, so the timer can't be identified. The watchdog's own async writes were queued behind libuv threads stuck on the same lock.Annotating blocking calls and having the hang watcher read the annotation from another thread is how Chromium names hangs (
ScopedBlockingCallandHangWatcher). A JS stack can't be captured once the thread is inside a syscall, so the call has to name itself on entry.The alternative was moving every main-thread sync fs call off main first. That is a follow-up: the known timer-driven sync fs sites move to async, with a lint ratchet. This PR makes the next stall say which site matters.
Linked Issue
N/A (internal).
Visual Proof
N/A: diagnostics only, no UI or behavior change.
Testing
hang-blocking-call.test.tsdrives the real slot and annotation. It checks the outermost call is named while a nested one runs, path and SQL redaction, and that the slot is empty once the call returns.Ran a dev build on Linux with the main-process inspector and counted main-thread sync fs calls per call site: an idle fresh profile makes only a handful. That run did not exercise the watchdog install path, which is macOS/Windows packaged-only.
I manually tested these changes locally
Automated tests added/updated, or explained why not below
Every added test fails without this change and avoids the test anti-patterns
Performance
Measured with the real modules bundled into one file, as production bundles them (Node 24, Apple Silicon, min of 25 runs):
get(raw 430 ns)existsSync/statSync.performance.now()and a depth counter per annotated call. There is no new timer, poll or IPC, and the watchdog reads the slot only when it has already detected a stall.Risk
Level: Low
The riskiest part is wrapping
node:fssync functions on the main thread. Wrappers forwardthisand arguments unchanged, inspect the first argument with type checks only, rethrow unchanged, and keep statics such asrealpathSync.native. If a wrapper misbehaved, users would see a sync fs call fail on main. Revert is a plain revert; nothing persisted changes shape, becauseblockingCallis an optional field older builds ignore.AI Disclosure
Review
Agent skill upstream boundary
Notes
Cross-platform: the slot and annotation are platform-neutral, path redaction splits on both
/and\, and the watchdog already runs on macOS and Windows only. Remote SSH, mobile: unaffected (main process diagnostics only).Checklist
N/Awith reasonpnpm lint,pnpm typecheck,pnpm test, andpnpm buildpass (or CI will cover; local preferred)