Skip to content

fix(gateway): launchd double-spawn triggers infinite restart death spiral (exit code 1 on instance detection) #21549

Closed

Description

@dramjadj

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:

  1. macOS display wake → launchd enters "on-demand-only mode" → kills existing gateway
  2. KeepAlive triggers restart → launchd spawns two instances simultaneously (intermittent race)
  3. Instance B detects Instance A via PID file at line 14855 → return False → sys.exit(1)
  4. 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.log at 23:19:50 confirm two instances started at the same millisecond
  • macOS log show confirms 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:

  1. Have 2+ launchd plists with KeepAlive.SuccessfulExit=false
  2. Trigger a display wake while gateway is running
  3. 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
  • --replace flag is set in plists but only runs at the first PID check (line 14626), not the second (line 14855)

Activity

  1. added
    type/bugSomething isn't working
    comp/gatewayGateway runner, session dispatch, delivery
    P1High — major feature broken, no workaround
    on May 7, 2026
  2. ValyouHustlin commented on May 13, 2026

    @ValyouHustlin

    Additional field report from an always-on macOS AI hub.

    Environment:

    • Hermes Agent v0.13.0, updated on 2026-05-13
    • macOS launchd user agent: ai.hermes.gateway
    • Gateway used for cron execution, no messaging platforms enabled

    Observed sequence:

    1. Overnight digest warned: Service definition is stale relative to the current Hermes install.
    2. hermes gateway start refreshed ~/Library/LaunchAgents/ai.hermes.gateway.plist and loaded launchd.
    3. The generated plist combined gateway run --replace with KeepAlive.SuccessfulExit=false.
    4. Gateway entered the same restart race described here: one process started, another launchd/replacement process appeared, logs repeatedly showed 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:

    • Remove the generated launchd KeepAlive block while keeping RunAtLoad.
    • Regenerate/reload the plist.
    • Result: one stable gateway process, Hermes cron healthy, overnight digest green.

    I source-retained the local workaround in our ops repo as a reapply/check helper because hermes update can overwrite the installed checkout. This is not meant as a preferred upstream design, but it supports the issue's root cause: macOS launchd KeepAlive.SuccessfulExit=false and gateway run --replace should not be combined unless planned replacement exits are guaranteed not to trigger respawn loops.

  3. daniellsh commented on May 14, 2026

    @daniellsh

    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}.plist

    Each 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.

  4. brucecbi commented on May 26, 2026

    @brucecbi

    +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

    • macOS 26.x (M-series)
    • Hermes Agent at tag v2026.5.7 (commit e19fc91)
    • Two launchd user agent labels coexisting, both invoking hermes_cli.main gateway run --replace without --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)
    • A separate set of profile-aware plists (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---profile labels.

    Observation 1 — oscillation period

    When either of the two no---profile gateways is kickstarted (manual launchctl kickstart -k, or restart triggered by other means), the death spiral kicks in. Measured oscillation period was 6–10 seconds per cycle:

    00:49:04  default gateway A starts -> Replacing existing gateway instance (PID 54286) with --replace
    00:49:08  Exiting with code 1
    00:49:16  default gateway B starts -> Another gateway instance (PID 54295) started during our startup. Exiting to avoid double-running.
    00:49:27  Replacing existing gateway instance (PID 54295) with --replace
    00:49:39  Another gateway instance (PID 54343) started during our startup.
    00:51:21  Replacing existing gateway instance (PID 54703) with --replace
    

    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 — --replace appears to be an active killer, not just exit-1 feedback

    In our case the cycle did not require display-wake or a stale PID file to start. It was triggered by --replace behavior: every fresh gateway start emitted a Replacing existing gateway instance (PID xxx) with --replace log line, after which the named PID exited and was respawned by its own KeepAlive. In this incident, both the killer and the killed were no---profile instances, while the 5 profile-aware gateways (running with --profile <name>) did not appear in the kill/respawn cycle during the same window.

    Whether --replace actually 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---profile labels 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:

    1. (Already discussed in the issue) Exit code 1 on instance detection combined with KeepAlive.SuccessfulExit=false → launchd loop. Option A fix (return True / exit 0) does address this.
    2. (Possibly not yet covered) Whatever rule --replace uses to identify "other gateway instances" treats two no---profile plists 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 --replace identification rule profile/label-aware

    If --replace identifies "other gateway instances" by walking the process list (which is what the Replacing existing gateway instance (PID xxx) log line suggests), it should — if it does not already do so — narrow the match to:

    • Processes with the same --profile value (or both lacking it AND matching some other identifier such as launchd label)
    • Or, alternatively, only processes started by the same launchd label (e.g. via parent PID lineage or an env var injected by the plist)

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

    # Pick which label to keep running. Bootout + disable the other.
    launchctl bootout gui/$(id -u)/com.bruce.birkin.gateway
    launchctl disable gui/$(id -u)/com.bruce.birkin.gateway

    disable is persistent across reboots and reload — the killed label will not RunAtLoad until you launchctl enable it 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.* to ai.hermes.* naming over the past few weeks. Both plists were generated by hermes 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 start could 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

    • Adjacent TencentDB-side issue we filed describing EADDRINUSE + gateway lifecycle when this restart cycle interacts with the Tencent/TencentDB-Agent-Memory Hermes integration: Tencent/TencentDB-Agent-Memory#94.
    • The replacement flow may also have a race window where the new instance can race with the dying one on file locks / IM bot tokens. We did not see this hit us in practice; mentioning only as a thing worth covering if someone is writing tests.

    Happy to provide more data (full agent.log slices, lsof output, launchctl print output) if any maintainer wants a deeper repro.

  5. kylin19860916 commented on Jun 9, 2026

    @kylin19860916

    Additional confirmation on the latest build — bug persists.

    Environment

    • macOS 26.5 (Darwin 25.5.0, arm64 / Apple Silicon)
    • Hermes Agent v0.16.0 (build 2026.6.5) · upstream c3055d6
    • Gateway used for Feishu (Lark) WebSocket bridge + internal cron

    Reproduction (2026-06-08)

    1. Ran hermes update to pull 3 new commits (clean update, no errors).
    2. The update reinstalled ~/Library/LaunchAgents/ai.hermes.gateway.plist with KeepAlive=true and gateway run --replace.
    3. Within minutes the gateway entered SIGTERM-restart loop:
      • Boot → "Starting Hermes Gateway..."
      • 10-30s later → "Received SIGTERM as a planned --replace takeover — exiting cleanly"
      • launchd respawns → next instance again sees a peer and SIGTERMs → loop
    4. At peak observed 6 starts in 2 minutes, with 2 PIDs alive simultaneously.

    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 ~25s agent response was killed mid-turn by the next takeover SIGTERM).

    Workaround (matches ValyouHustlin's fix)

    1. launchctl bootout gui/<uid> ~/Library/LaunchAgents/ai.hermes.gateway.plist
    2. pkill -9 -f "hermes.*gateway run"
    3. Manually rewrite the plist:
      • Remove <key>KeepAlive</key><true/>
      • Keep <key>RunAtLoad</key><true/> (boot-time start)
      • Add <key>ThrottleInterval</key><integer>60</integer> (defense against any residual respawn)
      • Keep all other fields (ProgramArguments with --replace, EnvironmentVariables, etc.)
    4. launchctl load ~/Library/LaunchAgents/ai.hermes.gateway.plist

    Result: stable gateway, single PID, Feishu WS healthy, no SIGTERM loop.

    Note for maintainers

    • hermes update overwrites the plist back to KeepAlive=true, so the workaround has to be re-applied after every upgrade. A --no-keepalive install flag (or making KeepAlive=false the macOS default since --replace already handles the "process disappeared" case via fresh boot) would help long-term.
    • For crash recovery without KeepAlive, users can pair this with a periodic launchctl kickstart -k cron 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.

  6. teknium1 commented on Jun 28, 2026

    @teknium1
    Collaborator

    Closing — see PR #21555. The exit-code premise here was reworked on main after 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 -k racing KeepAlive) is tracked separately in #42446.

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

    P1High — major feature broken, no workaroundcomp/gatewayGateway runner, session dispatch, deliverytype/bugSomething isn't working

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions