Skip to content

fix(daemon): respawn worker on unexpected exit instead of hanging or quitting - #2725

Open
emanblue wants to merge 1 commit into
espanso:devfrom
emanblue:fix/daemon-worker-respawn
Open

emanblue wants to merge 1 commit into
espanso:devfrom
emanblue:fix/daemon-worker-respawn

Conversation

@emanblue

Copy link
Copy Markdown

Problem

On macOS (service mode), espanso can silently stop expanding for hours: the daemon process stays alive while the worker process is gone and is never respawned. espanso service status reports "not running" even though the daemon PID is alive, and a manual espanso restart is required to recover. Reported in #2530 (the dead-worker symptom also appears in #2576).

Root cause

In espanso/src/cli/daemon/mod.rs:

  1. spawn_worker()'s worker-status-monitor thread only forwarded an exit code to the daemon when the worker exited non-zero (or died by signal → WORKER_ERROR_EXIT_NO_CODE). A worker that exited WORKER_SUCCESS (0) unexpectedly — or a failed child.wait() — was dropped silently, so the daemon's select! loop was never notified and the worker was never respawned (the "half-dead" state).
  2. In the exit_signal arm, any code other than WORKER_EXIT_ALL_PROCESSES / WORKER_RESTART hit _ => { ...; return code; }, so an unexpected worker death made the daemon exit. Combined with the macOS launchd plist having RunAtLoad but no KeepAlive, nothing relaunched espanso.

Fix

  • Forward every worker exit to the daemon (including WORKER_SUCCESS and the wait() error case), so the daemon is always notified.
  • On an unexpected worker exit, respawn the worker with bounded, backing-off retries (MAX_WORKER_AUTO_RESTARTS), giving up only if it dies repeatedly in quick succession (crash-loop protection; the counter resets after a healthy run of WORKER_HEALTHY_RUNTIME).
  • Track daemon-initiated restarts (config / keyboard-layout change) via an expected_worker_exits counter so the deliberately-terminated old worker is not mistaken for an unexpected death and double-spawned. restart_worker now returns whether it actually spawned a replacement.

Testing

Built with --no-default-features --features vendored-tls; clippy clean on the changed file. Manual test on macOS with isolated config/runtime dirs:

  • Kill the worker → daemon logs worker exited unexpectedly with code 90 then respawning worker (attempt 1/5) after 500ms; a new worker starts. (Before this change: the daemon hung with no worker.)
  • Repeated rapid kills → backoff 500ms → 1s → 1.5s → 2s → 2.5s, then worker died 5 times in quick succession; giving up to avoid a crash-loop and the daemon exits cleanly (no infinite spin).
  • Normal config-change restart still works without double-spawning (expected-exit accounting).

Note / open question

This makes the daemon resilient to worker death regardless of cause. On macOS the trigger appears to be the worker being torn down across sleep / secure-input transitions (see #2530). Separately, the macOS launchd plist lacks KeepAlive; I deliberately left that out of this PR because the launchd-managed process is the short-lived launcher, so adding KeepAlive naively would cause a respawn loop — happy to address it properly in a follow-up if maintainers prefer.

@EvanAhern

Copy link
Copy Markdown

Strong +1 on this fix, with field data from macOS confirming the exact failure path this PR addresses.

Environment: espanso 2.3.0 (Homebrew cask), macOS 26.5 (25F71), ARM64 (MacBookPro17,1).

What we observed: five identical crash cascades within three days (accelerating; first occurrence 2026-06-30), each one:

[worker] thread 'engine thread' panicked at 'capacity overflow': .../core/src/iter/traits/iterator.rs:2027
[worker] thread 'detect thread' panicked at 'unable to send to the source channel: "SendError(..)"': espanso/src/cli/worker/engine/funnel/mod.rs:104
[worker] unable to send UIEvent to engine: sending on a disconnected channel
[worker] thread 'main' panicked at 'broken UI->Engine channel': espanso/src/cli/worker/mod.rs:150
[worker] thread 'main' panicked at 'panic in a function that cannot unwind'
thread caused non-unwinding panic. aborting.
[daemon] received unexpected exit code from worker 90, exiting

The engine-thread capacity overflow at iterator.rs:2027 appears to be the same panic reported on Windows in #2606 (there on both 2.2.3 and 2.3.0), so the trigger looks cross-platform; on this machine it now fires every few hours while idle.

Why this PR matters: after each abort, the daemon exits per the code path this PR changes, and since the launchd plist that espanso service register writes has RunAtLoad but no KeepAlive, nothing ever relaunches espanso — every crash became a silent, indefinite, total outage of all expansions until a human noticed. With the bounded respawn in this PR, each of our five outages would have been a sub-second blip instead.

One adjacent observation while debugging (happy to file separately with full details if useful): with a lingering espanso modulo welcome child open, the worker's engine loop appears parked — expansions stop, IPC requests are accepted but queue undrained, and a daemon-initiated worker restart times out ("could not restart worker, as the exit process has timed out"), after which the daemon's restart machinery no longer reacts to config changes. Killing the modulo child immediately unblocks the queued events and the pending exit. That wedge is a different path than the dead-worker respawn fixed here, but it interacts with the same "daemon gives up" outcome.

Full .ips crash reports (two from 2026-07-06 alone) available on request. Thanks for digging into the daemon lifecycle — this fix addresses a real reliability gap.

@AucaCoyan
AucaCoyan removed the request for review from Archigos July 19, 2026 11:52

@AucaCoyan AucaCoyan left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nice job!

…quitting

The daemon's worker-status-monitor only forwarded a worker exit to the
daemon when the worker exited with a non-zero code (or died by signal).
A worker that exited WORKER_SUCCESS (0) unexpectedly — or a failed
`child.wait()` — was dropped silently, leaving the daemon blocked in its
`select!` loop with a dead worker that was never respawned (a "half-dead"
state: daemon alive, worker gone, expansion silently stops). On any other
unexpected exit code the daemon would `return` and quit; combined with the
macOS launchd plist having no `KeepAlive`, nothing relaunched espanso.

This change:
- forwards every worker exit to the daemon (including WORKER_SUCCESS and
  the `wait()` error case), so the daemon is always notified;
- on an unexpected worker exit, respawns the worker with a bounded,
  backing-off retry (up to MAX_WORKER_AUTO_RESTARTS) instead of hanging or
  quitting, giving up only if the worker dies repeatedly in quick
  succession (crash-loop protection; the counter resets after a healthy run);
- tracks daemon-initiated restarts (config / keyboard-layout change) via an
  expected-exit counter so the deliberately-terminated old worker is not
  mistaken for an unexpected death and double-spawned.

restart_worker now returns whether it spawned a replacement, so the caller
only records an expected exit when a replacement actually started.

Tested on macOS: killing the worker now respawns it (was: daemon hung);
repeated rapid kills back off (500ms -> 2.5s) and give up after 5 attempts.

Refs: espanso#2530

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@marcdhansen

Copy link
Copy Markdown

Tested this PR locally on Apple Silicon with macOS 26.6.1 (Darwin 25.6.0). The documented macOS Cargo build completed successfully. I launched the PR binary with isolated configuration and runtime directories, terminated only its worker, and reproduced worker exit code 90. The daemon stayed alive, logged the bounded respawn attempt, spawned a replacement worker, and the replacement worker initialized successfully.

@alvanx

alvanx commented Sep 22, 2026

Copy link
Copy Markdown

Another macOS 26 report, adding it since this PR looks like the fix for the half-dead state.

Environment: espanso 2.4.1, macOS 26.5.2 (25F84), Apple Silicon (MacBookPro18,1).

Two separate failures:

  1. Worker aborts (recovers on its own). Four crash reports between Sep 16 and 17, all with the same stack: panic_cannot_unwind in espanso_ui::mac::MacEventLoop's UIEventLoop::run callback, called from __NSFireTimer. The worker had been running anywhere from 1 minute to 14 hours. Espanso came back by itself each time.

  2. Half-dead state (does not recover). Twice (Sep 18 and Sep 22) the worker disappeared with no crash report, while the daemon stayed alive. espanso status reports "not running", and espanso start shows the "already running" window. Expansion stays dead until you intervene. On Sep 18, the last worker log lines are secure input being taken and released by loginwindow (a screen lock), seconds before the worker vanished. I don't have the log for Sep 22 because the restart overwrote it.

The only way to recover is to kill every espanso process, delete the .sock/.lock files in the runtime dir, then run espanso start.

A worker exit with no crash report plus a daemon that never notices fits the silently dropped WORKER_SUCCESS / failed wait() path this PR fixes. I haven't confirmed the exit code, though. It would be great to see this merged.

@BingJun-You

Copy link
Copy Markdown

This would likely also recover the Windows case in #2850: after a config change the new worker panics with unable to initialize IPC server: Access is denied (os error 5) while the old worker still holds the named pipe, and the daemon exits on worker exit code 101. I have not run this branch on Windows.

This branch has not been deployed

No deployments
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.

6 participants