Repository navigation
Description
Bug Summary
When launchd (macOS) spawns two gateway instances simultaneously (intermittent race on display wake, KeepAlive restart, or update), the second instance detects the first via the PID file at gateway/run.py:14855 and exits with code 1 (return False → sys.exit(1)). Because the plist has KeepAlive.SuccessfulExit=false, launchd interprets exit code 1 as a failure and immediately restarts — creating an infinite loop that spams logs and drains CPU until manually stopped.
Root Cause
Commit cbe29db77 added a second PID check during startup (gateway/run.py:14850-14859) that exits with return False when another instance is detected. This was intended to prevent double-running, but the exit code (1) combined with launchd's SuccessfulExit=false creates a death spiral.
The cascade:
- macOS display wake → launchd enters "on-demand-only mode" → kills existing gateway
KeepAlivetriggers restart → launchd spawns two instances simultaneously (intermittent race)- Instance B detects Instance A via PID file at line 14855 →
return False→sys.exit(1) - launchd
SuccessfulExit=false→ auto-restart → detect other instance → exit 1 → loop
Evidence
- 3 confirmed incidents after May 6 update: May 6 01:37, May 6 02:08, May 7 23:19
- 196 occurrences of "Another gateway instance started during our startup" in
gateway.log - 299 occurrences in
gateway.error.log - Duplicate log lines in
agent.logat 23:19:50 confirm two instances started at the same millisecond - macOS
log showconfirms display wake triggered the cascade at 23:19:33
Reproduction
Hard to reproduce reliably (depends on launchd timing), but on macOS with multiple gateway profile plists:
- Have 2+ launchd plists with
KeepAlive.SuccessfulExit=false - Trigger a display wake while gateway is running
- If launchd double-spawns, the death spiral starts
Current Code (v0.13.0 / v2026.5.7)
# gateway/run.py:14850-14859
_current_pid = get_running_pid()
if _current_pid is not None and _current_pid != os.getpid():
logger.error(
"Another gateway instance (PID %d) started during our startup. "
"Exiting to avoid double-running.", _current_pid
)
return False # → sys.exit(1) in main() — triggers KeepAlive restart loop
# gateway/run.py:14967-14969
success = asyncio.run(start_gateway(config))
if not success:
sys.exit(1)Proposed Fix
Option A (minimal): Change return False to return True (exit 0) when another instance is detected. This tells launchd "clean exit, no restart needed" — the surviving instance continues normally. This is the correct semantics: detecting another healthy instance is not a failure.
Option B (robust): Add a startup lock (flock on the PID file or lock file) with jitter backoff. Only one instance acquires the lock; others wait briefly then exit 0 if another instance won.
Option A is sufficient and matches the intent of SuccessfulExit=false — only exit 1 for genuine failures (no platforms connected, unhandled errors), not for "another instance is already handling this."
Environment
- macOS (launchd service manager)
- Hermes Agent v0.13.0 (v2026.5.7)
- Multiple gateway profile plists with
KeepAlive.SuccessfulExit=false --replaceflag is set in plists but only runs at the first PID check (line 14626), not the second (line 14855)
Activity
ValyouHustlin commentedon May 13, 2026
Additional field report from an always-on macOS AI hub.
Environment:
ai.hermes.gatewayObserved sequence:
Service definition is stale relative to the current Hermes install.hermes gateway startrefreshed~/Library/LaunchAgents/ai.hermes.gateway.plistand loaded launchd.gateway run --replacewithKeepAlive.SuccessfulExit=false.Another gateway instance (PID <pid>) started during our startup. Exiting to avoid double-running., then SIGTERM/shutdown/restart repeated.Local workaround that stabilized this host:
KeepAliveblock while keepingRunAtLoad.I source-retained the local workaround in our ops repo as a reapply/check helper because
hermes updatecan overwrite the installed checkout. This is not meant as a preferred upstream design, but it supports the issue's root cause: macOS launchdKeepAlive.SuccessfulExit=falseandgateway run --replaceshould not be combined unless planned replacement exits are guaranteed not to trigger respawn loops.daniellsh commentedon May 14, 2026
Confirming this on macOS 26.4.1 (Apple M4 Mac mini) with a multi-profile launchd setup. We run 3 independent profiles, each with its own launchd plist:
~/Library/LaunchAgents/ai.hermes.gateway-{profile1,profile2,profile3}.plistEach invokes hermes --profile gateway run --replace. Currently pinned at v0.11.0 because this bug, combined with #19471 and #21596, makes any upgrade a hard no-go.
Happy to test any fix or patch on this exact multi-profile macOS configuration if that would help validation.
brucecbi commentedon May 26, 2026
+1 from another macOS multi-launchd setup. Adding two specific data points and one additional angle that I think is not yet covered in this thread.
Setup
v2026.5.7(commite19fc91)launchduser agent labels coexisting, both invokinghermes_cli.main gateway run --replacewithout--profile:ai.hermes.gateway.plist(new naming, default profile)com.bruce.birkin.gateway.plist(legacy naming, points to a non-default sticky profile via the same root config + profile state)ai.hermes.gateway-{jobs,elon,trump,naval,munger,birkin,taleb}.plist) invoking with--profile <name>— in this incident, these labels were not observed participating in the death spiral. I am not claiming from source inspection that they are impossible to affect; the observation is that the loop involved the two no---profilelabels.Observation 1 — oscillation period
When either of the two no-
--profilegateways is kickstarted (manuallaunchctl kickstart -k, or restart triggered by other means), the death spiral kicks in. Measured oscillation period was 6–10 seconds per cycle:This matches the issue's root cause analysis exactly: exit 1 →
KeepAlive.SuccessfulExit=false→ respawn → detect other instance → exit 1 → loop. Adding the timing in case it helps a maintainer reproduce.Observation 2 —
--replaceappears to be an active killer, not just exit-1 feedbackIn our case the cycle did not require display-wake or a stale PID file to start. It was triggered by
--replacebehavior: every fresh gateway start emitted aReplacing existing gateway instance (PID xxx) with --replacelog line, after which the named PID exited and was respawned by its ownKeepAlive. In this incident, both the killer and the killed were no---profileinstances, while the 5 profile-aware gateways (running with--profile <name>) did not appear in the kill/respawn cycle during the same window.Whether
--replaceactually filters target instances by the presence/value of--profile, by launchd label, by parent PID lineage, or by something else, is a source-level question I have not verified. The observation is just: two no---profilelabels treated each other as "the same instance" and ended up in a kill cycle.So I'd argue there are two stacked surface areas producing this spiral:
KeepAlive.SuccessfulExit=false→ launchd loop. Option A fix (return True / exit 0) does address this.--replaceuses to identify "other gateway instances" treats two no---profileplists as the same target, so they keep clobbering each other. Option A fix does NOT address this — the kill still happens, the new instance still runs, it's just that the killed one now exits cleanly (0) and KeepAlive may or may not restart it depending on the plist.The second surface is what stays even after #21549 lands. For users running multiple no-profile labels intentionally, the new "exit 0 on detected instance" behavior just means one of the two labels silently loses its gateway every time anything is kickstarted.
Suggested additional fix: make
--replaceidentification rule profile/label-awareIf
--replaceidentifies "other gateway instances" by walking the process list (which is what theReplacing existing gateway instance (PID xxx)log line suggests), it should — if it does not already do so — narrow the match to:--profilevalue (or both lacking it AND matching some other identifier such as launchd label)Without one of these (or whatever the current rule is being documented and verified to handle this case), multi-label setups will keep clobbering each other.
User-side workaround that broke the cycle for us
For anyone hitting this right now, the following works on macOS launchd (tested 2026-05-26 00:54):
disableis persistent across reboots and reload — the killed label will not RunAtLoad until youlaunchctl enableit back.This is purely a host-side workaround that doesn't depend on hermes-agent shipping a fix.
Why we ended up here
For context (not a bug report — just explaining why we have two no-profile labels): we've been migrating from
com.bruce.*toai.hermes.*naming over the past few weeks. Both plists were generated byhermes gateway start(or its predecessors) at different points in the migration, and we hadn't decommissioned the old one. Static coexistence was fine — they didn't fight when nobody triggered a restart. The death spiral only manifested when something (manual kickstart in our case) caused a respawn.So in addition to fixing the spiral itself,
hermes gateway startcould potentially detect "another hermes plist already loaded for the default profile" and warn the user. That might prevent a class of accidental dual-label setups.Cross-references
EADDRINUSE+ gateway lifecycle when this restart cycle interacts with theTencent/TencentDB-Agent-MemoryHermes integration: Tencent/TencentDB-Agent-Memory#94.Happy to provide more data (full agent.log slices, lsof output, launchctl print output) if any maintainer wants a deeper repro.
kylin19860916 commentedon Jun 9, 2026
Additional confirmation on the latest build — bug persists.
Environment
Reproduction (2026-06-08)
hermes updateto pull 3 new commits (clean update, no errors).~/Library/LaunchAgents/ai.hermes.gateway.plistwithKeepAlive=trueandgateway run --replace.Effect on messaging platform
Feishu WebSocket reconnected on every restart, so
--replace-driven shutdown notifications spammed the home channel and active sessions could not complete (each~25sagent response was killed mid-turn by the next takeover SIGTERM).Workaround (matches ValyouHustlin's fix)
launchctl bootout gui/<uid> ~/Library/LaunchAgents/ai.hermes.gateway.plistpkill -9 -f "hermes.*gateway run"<key>KeepAlive</key><true/><key>RunAtLoad</key><true/>(boot-time start)<key>ThrottleInterval</key><integer>60</integer>(defense against any residual respawn)--replace, EnvironmentVariables, etc.)launchctl load ~/Library/LaunchAgents/ai.hermes.gateway.plistResult: stable gateway, single PID, Feishu WS healthy, no SIGTERM loop.
Note for maintainers
hermes updateoverwrites the plist back toKeepAlive=true, so the workaround has to be re-applied after every upgrade. A--no-keepaliveinstall flag (or makingKeepAlive=falsethe macOS default since--replacealready handles the "process disappeared" case via fresh boot) would help long-term.launchctl kickstart -kcron as a poor-man's watchdog — works fine in practice.Happy to test patches on this exact macOS 26.5 / v0.16.0 / Feishu-gateway setup.
teknium1 commentedon Jun 28, 2026
Closing — see PR #21555. The exit-code premise here was reworked on
mainafter this was filed (#51734 takeover-marker, #37388/#43475 SuccessfulExit tuning), this exact failure mode has no corroborating reports and was never reliably reproduced, and the real confirmed double-spawn cause (kickstart -kracing KeepAlive) is tracked separately in #42446.