Skip to content

fix: the installed service owns the daemon, so auto-start no longer leaves an unowned daemon with a client's settings - #332

Merged
varun369 merged 9 commits into
mainfrom
fix/daemon-supervisor-owns-autostart
Nov 20, 2026
Merged

varun369 merged 9 commits into
mainfrom
fix/daemon-supervisor-owns-autostart

Conversation

@varun369

Copy link
Copy Markdown
Member

Symptom

On macOS with the daemon installed as a LaunchAgent (KeepAlive {SuccessfulExit: false}, ThrottleInterval 30), the service was unloaded with launchctl bootout and the package upgraded. Within about 30 s, an already-running slm mcp stdio process auto-started a new daemon itself. That daemon was detached (ppid 1), not owned by launchd, ran with the MCP client's environment (SLM_AGENT_ID, SLM_CLIENT_CHANNEL=mcp, SLM_MCP_PROFILE, SLM_SKIP_DEP_CHECK) and without the service's own settings (an SLM_RANKING set only in the plist was silently lost). When the LaunchAgent was loaded again, its daemon found the data folder held, exited 0, and launchd never retried: launchctl list showed - 0. The result was a long-lived daemon with the wrong configuration, attributing work through its embedded MCP endpoint to one agent, while the service manager reported nothing wrong.

Root cause

  1. cli/daemon.py::_start_daemon_subprocess (the one spawn path behind ensure_daemon, every CLI/MCP auto-start and slm restart) always ran Popen with a full copy of os.environ. It never asked whether an installed service owns this data folder and port.
  2. server/unified_daemon.py::start_server returns (exit 0) when another daemon holds the instance lock or the port. That is deliberate to avoid a respawn loop, but it also meant the service's daemon could never take ownership back from an unowned one.

Fix

  • (a) The service starts the daemon. New cli/daemon_supervisor.py finds the service definition that service_inventory already proves belongs to this data folder and port, and asks its manager to start it: macOS launchctl kickstart gui/<uid>/<label> (never -k), or launchctl bootstrap when the plist is installed but not loaded; Linux systemctl --user start; Windows schtasks /Run. The client then waits for owned health as before. Choice for an unloaded LaunchAgent: load it. launchd loads it at the next login anyway, and loading it now keeps one owner; spawning around it reproduces the collision. A direct start remains the fallback when there is no service or the manager refuses (for example no GUI domain in a remote shell, or a disabled job); the fallback is logged with the reason.
  • (b) A direct start is scrubbed. daemon_environment() removes client-scoped variables (agent id, client/channel, session, project, MCP profile and tool lists, SLM_MCP_EMBEDDED, SLM_SKIP_DEP_CHECK, SLM_HOOK_*, and the client's SLM_DAEMON_INSTANCE_ID/CAPABILITY), then overlays the service definition's environment when a service exists, so the fallback still runs with the service's settings. Operator settings such as SLM_RANKING set in the starter's environment are kept when there is no service.
  • (c) A service-started daemon takes over once. New server/supervisor_handover.py runs in start_server before the instance-lock wait. Only when this process is the service's job (its PID is the PID the service manager reports) and the folder is held by a live daemon of this data folder that no installed service runs, it asks that daemon to stop through the same authenticated /stop that slm restart uses (graceful drain), waits for the folder to be free, and then starts normally. A holder it cannot identify, or one run by another service, is never stopped.
  • slm doctor adds "Daemon service owner": WARN when the daemon's PID is not the service's PID, naming the SLM_* settings from the service definition that the running daemon lacks (names only, never values). Fix: slm restart, which now restarts through the service.

Why hand-over for (c), and the tradeoff

Considered: (1) exit non-zero when the folder is held, so launchd/systemd retry every 30 s; (2) the current exit 0; (3) hand-over. (1) loops forever while the unowned daemon is healthy, filling the logs and never resolving: an unowned daemon has no reason to exit. (2) is the bug. (3) resolves it in one step with no loop. The tradeoff is that it stops a running daemon. That is limited to a daemon proven to belong to this data folder, proven not to be run by any installed service, and only when the service itself has been started (at login, by launchctl kickstart, or by a client asking the service to start). The stop is graceful. It is tried once per process; if the holder refuses, the service's daemon exits 0 as before (no loop), logs that it will not retry, and slm doctor reports the unowned daemon.

Reviewer concerns, and how they are handled

  1. Windows/Linux parity. Linux systemd Restart=on-failure has the same exit-0 semantics as KeepAlive SuccessfulExit=false, so (a), (b), (c) and doctor all apply (MainPID). On Windows the logon task is a launcher, not a supervisor: it never restarts the daemon and reports no PID. There, (a) runs the task (so the wrapper's environment applies) and (b) applies; (c) and the doctor check are skipped on purpose, because there is no restart loop to collide with.
  2. TOCTOU between the health check and the start. Clients still serialise on daemon.lock; the per-folder instance lock is the final arbiter. kickstart without -k is a no-op on a running job. A load that fails because another client loaded the job first is re-checked and followed by kickstart (unit-tested). Remaining window: during a hand-over, a client still running pre-fix code can spawn a detached daemon between the old daemon's exit and the service daemon's lock acquisition. The service daemon acquires within milliseconds while a cold spawn takes seconds to import, so this is unlikely. If the spawn wins anyway, the service daemon does not retry (no loop) and doctor reports the unowned daemon.
  3. Two MCP clients racing. Both serialise on daemon.lock. Even without it, both requests resolve to one start, because kickstart is idempotent and a second bootstrap fails with "already loaded" and falls through to kickstart. Only one daemon can take the instance lock.

Out of scope: clients already running pre-fix code keep their old in-memory auto-start until they restart. (c) is what repairs the state those clients leave behind. No CHANGELOG entry here; the release commit writes it.

Tests

TDD: written first, RED before the wiring, GREEN after.

  • tests/test_cli/test_daemon_supervisor_autostart.py (16 tests, every service-manager call mocked): service asked and nothing spawned; failed service start falls back to a scrubbed spawn carrying the service's SLM_RANKING; direct spawn without a service drops client identity but keeps operator settings; exact launchctl / systemctl / schtasks argv including load, kickstart, a concurrent-loader race and a failed load; PID parsing; port matching and definition-environment parsing.
  • tests/test_cli/test_supervised_daemon_handover.py (10 tests): takes over only when supervised; never stops an unknown holder or one run by another service; a refused hand-over is reported, not raised; wiring test that start_server runs the hand-over before the lock wait; doctor PASS/WARN/silent cases, never printing values.
  • tests/test_integration/test_daemon_single_owner_e2e.py (2 tests, real daemons on a pytest data folder and a free port, no real service registered): ensure_daemon from a client environment produces a daemon whose process environment has none of the client-scoped variables; a real unowned daemon started with a client environment is handed over to a real "service" daemon (service-manager queries stubbed to name it). The unowned daemon exits, exactly one daemon remains, and it carries the service setting.

Non-vacuity: with only the daemon.py and unified_daemon.py wiring reverted, 7 failed, 21 passed (both integration tests fail: client variables reached the daemon, and the service daemon never became the owner). Restored: 28 passed.

Regression packs: every test module that references the spawn path, start_server, service inventory/live/installer, doctor, restart or the MCP daemon proxy, plus tests/test_daemon: 1254 passed, 2 failed. Neither failure comes from this change. test_doctor_health_verdicts.py::test_deadline_text_mode_names_check_and_exits_one fails identically on main on this machine; its 1 s doctor deadline expires inside the earlier daemon probe. test_maintenance_acts_on_the_bound_workspace.py::test_observe_buffer_ingests_into_the_routed_workspace passes alone (it is timing-sensitive under -n). tests/test_architecture, tests/test_ci_guards, tests/release: 267 passed. lint-imports: 9 kept, 0 broken. ruff: clean.

🤖 Generated with Claude Code

@varun369

Copy link
Copy Markdown
Member Author

Review findings: reproduced, fixed, and checked by reverting each fix

For each finding, the failing test was written first and run on this branch, then the fix went in, then the source change was reverted on its own to show the test fails again.

# Finding Reproduced? Fix commit Tests
0 New, found while reproducing #1. On a real Mac, launchctl list <label> prints text that plutil rejects (array items and the closing brace end in ;), and it never includes EnvironmentVariables. So every check of a loaded LaunchAgent failed closed. A running service looked foreign: job_pid/job_loaded returned nothing, auto-start never used the service, doctor always warned, and slm serve uninstall/reinstall refused to unload it (this last part is also on main). The older fakes answered list with the plist XML, which hid all of this. Yes. Checked read-only against a real loaded job (no start or stop) and with fakes that use the real output formats. 44a7924 test_launchd_real_record.py: test_loaded_service_is_recognised_from_launchds_real_answers, test_uninstall_unloads_a_loaded_service_on_a_real_mac, test_job_of_another_data_folder_under_the_same_label_is_still_refused
MAJOR-1 job_loaded/job_pid skipped the ownership checks Yes, on macOS (both text formats) and Linux. A stale job was kickstarted, a stale or foreign job's PID was reported as the service's, a unit edited without a reload was started, and doctor said PASS for a stale job. dc37fbc test_daemon_supervisor_ownership.py: test_stale_loaded_job_is_never_started, test_stale_loaded_job_falls_back_to_a_direct_start_with_the_files_settings, test_pid_of_a_stale_job_is_not_the_services, test_job_loaded_under_the_name_by_another_data_folder_is_not_ours, test_linux_unit_edited_without_reload_is_never_started, test_doctor_never_calls_a_stale_jobs_process_owned
MAJOR-2 bootstrap exit 0 was taken as "started", with no fallback Yes. A loaded job that cannot run and a job whose program exits at once both returned False after the wait, with no direct start. bb31f61 test_daemon_supervisor_start_verify.py: test_loaded_job_that_cannot_run_falls_back_to_a_direct_start, test_service_whose_daemon_exits_at_once_falls_back_without_the_full_wait, plus the test_watcher_* tests
MINOR-3 Doctor was inconsistent when no service manager could be reached Partly. On Linux with no user bus, discovery already finds nothing, so doctor was silent, not WARN as reported. On macOS, a launchd that cannot be queried gave a WARN whose fix (slm restart) could never clear it. The same WARN happened on Linux when the bus went away after discovery. Both platforms now skip the check. 573786f test_doctor_skips_when_launchd_cannot_be_asked, test_doctor_skips_when_the_user_bus_goes_away_after_discovery, test_doctor_skips_on_linux_without_a_user_bus (already passed before the fix)
MINOR-4 Hand-over checked one record, then stopped whatever was current Yes. A daemon that replaced the checked one was stopped. 21f4afe test_supervised_daemon_handover.py: test_hand_over_never_stops_a_daemon_that_replaced_the_checked_one
MINOR-5 Thread settings were forced after the service's values Yes. 6547793 test_service_thread_settings_win_over_the_direct_start_defaults

How the fixes could have undone the original split-brain fix, and the tests that guard against it

  1. The stricter ownership check refuses a legitimate job, so every start falls back to a detached daemon. Guarded by test_owned_loaded_job_is_kickstarted (both formats), test_linux_owned_unit_is_started, test_doctor_passes_the_owned_jobs_process and test_a_loaded_and_running_job_is_kickstarted_not_restarted. Also checked read-only on a real Mac: the installed job is now found, verified as running, and its PID matches launchd's. On this branch before these commits, the same query returned no PID.
  2. The "service runs no daemon" detection fires on a slow service daemon and starts a second one. It reports an exit only when the manager answers and shows no process for 5 s. It never does so on Windows, when the manager cannot be asked, or when the job is stale. Guarded by test_service_daemon_that_is_running_but_not_ready_is_never_doubled and test_watcher_never_declares_a_death_it_cannot_observe (running/unknown/stale), plus the Windows and grace-period tests. A mutation that treated a running job as dead failed 3 of them.
  3. The thread-settings change lets a client's own OMP_NUM_THREADS through (the literal setdefault suggestion does this). Guarded by test_client_thread_settings_never_reach_the_daemon, which fails under setdefault.
  4. Binding the stop refuses a legitimate hand-over. Guarded by test_hand_over_stops_exactly_the_checked_daemon and the real-daemon e2e test test_service_daemon_takes_the_folder_from_an_unowned_daemon (still passes).
  5. Skipping the doctor check hides a real unowned daemon. Guarded by test_doctor_still_warns_when_the_manager_answers_and_runs_another_process.

Results

  • Daemon, lifecycle, doctor and service packs plus this PR's files (58 files, including the real-daemon e2e tests on temporary data folders and free ports): 619 passed, 1 skipped.
  • Against this branch's original source, 16 of the new tests fail and the rest error at import, as expected.
  • ruff clean; import contracts 9 kept, 0 broken.
  • No real service manager was started, stopped or changed. Every launchd and systemd call in the tests goes to an in-memory fake.

🤖 Generated with Claude Code

varun369 and others added 9 commits November 20, 2026 19:29
…eaves an unowned daemon with a client's settings

- Auto-start asks the installed service (LaunchAgent, systemd user unit,
  logon task) to start the daemon instead of spawning a detached child;
  an unloaded LaunchAgent is loaded. A direct start is the fallback only
  when no service exists or the service manager refuses.
- A directly started daemon never inherits the client's agent name,
  channel, tool profile or identity material, and carries the service's
  own settings when a service exists.
- A daemon started by its service that finds an unowned daemon holding
  the data folder asks it to hand over once, instead of exiting 0 behind
  it for good.
- slm doctor reports a daemon that is not owned by its installed service
  and names the service settings it is missing.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
launchctl list prints text plutil cannot read and never includes the job's
environment, so every check of a loaded LaunchAgent failed closed: a running
service looked foreign, uninstall and reinstall refused to unload it, and
auto-start never used it. Read launchd's own text and take the environment
from launchctl print. A job of another data folder is still refused.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…s its installed definition

A definition edited without a reload, or an install whose load failed, left
the service manager holding an older job under the same name. Auto-start
asked that job to start, running the old interpreter and settings, and
doctor reported its process as owned. The loaded job is now checked against
the installed file (label, program, data folder, port) before it is started
or trusted; a mismatch falls back to a direct start with the file's
settings, and doctor says to reinstall the service.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ut runs no daemon

A successful launchctl bootstrap was taken as a started daemon. A job that
was loaded but could not run (disabled, or a program that exits at once)
cost the client a 60 s wait and then a failed start with no fallback. The
job is now kicked after loading, and a service that shows no process for a
few seconds is treated as not running, so the daemon starts directly with
the service's settings. A service daemon that is still starting is never
doubled.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… manager cannot be asked

Without a reachable service manager (no user bus, no GUI session in a
remote shell) doctor warned on macOS with a fix, slm restart, that could
never clear it, while Linux skipped the same check. Both now skip it; a
reachable manager that runs another process still warns.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…hecked

The hand-over checked the folder's daemon against the service's jobs, then
stopped whatever daemon the record named at the moment of the stop. If
another daemon replaced the checked one in between, that one was stopped.
The stop is now bound to the checked instance and refused on any change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The serial-thread defaults were forced after the service's settings were
applied, so a service that set its own value lost it. The defaults now sit
under the service's settings and still override the client's own values.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… starts nothing

On Windows a logon task whose wrapper points at a removed Python accepted
the start, launched nothing, and auto-start gave up after 60 s. It now
starts the daemon directly with the service's settings once the wait ends,
but only when no daemon record names a live process, the instance lock is
free and nothing listens on the port.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A deeply nested launchctl answer raised RecursionError through the service
checks. The parser now rejects it as unreadable, and the job checks and the
start request treat any unexpected failure as "cannot ask", so auto-start
falls back to a direct start.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@varun369

Copy link
Copy Markdown
Member Author

Second review: both findings reproduced, fixed, and checked by reverting

Rebased on main (#330, #331, #334 and #335 had merged; no conflicts). Each failing test was written and run first, then the fix went in, then the source change was reverted on its own to show the test fails again.

# Finding Reproduced? Fix commit Tests
MAJOR A Windows logon task that accepts schtasks /Run but launches nothing (wrapper points at a removed Python) made auto-start wait 60 s and return False with no direct start. main started the daemon directly. Yes. The real _start_daemon_subprocess and readiness wait, with only Task Scheduler, the spawn and the 0.5 s sleep faked: False, 0 direct starts. 1279e8b test_daemon_supervisor_fallback.py::test_task_that_starts_nothing_falls_back_to_a_direct_start
MINOR ~1000-level nesting in a launchctl list answer raised RecursionError through job_state ("never raises"), request_start and start_through_service. Yes, all three. 0f7c0ed test_launchd_real_record.py: test_deeply_nested_list_text_is_a_value_error (3 shapes), test_deeply_nested_launchd_answer_never_escapes_the_service_checks, test_any_unexpected_failure_in_the_checks_fails_closed

The fix. After a full wait with no daemon, auto-start now starts the daemon directly (scrubbed environment plus the service's settings) only when all of these hold: the service manager reports no process for the job (always true on Windows), no daemon record names a live process, the instance lock is free, and nothing listens on the port. This applies on every platform, so a macOS or Linux manager that stops answering after accepting the start is covered too. The daemon's own instance lock still stops two daemons if one appears after the check. Every fallback logs the service name and slm serve install as the repair. The parser now caps nesting at 32 levels and turns any RecursionError into ValueError; job_state and request_start treat any unexpected exception as "cannot ask".

Ways the fallback could start a second daemon or hide a broken service, and the tests that guard against each

Each guard was removed on its own, and the listed tests failed:

  1. A service daemon that is still starting holds the instance lock but has no record yet. test_daemon_that_holds_the_instance_lock_is_never_doubled. Removing the folder check fails it and 2 others.
  2. A service daemon that published its record but is not answering yet. test_daemon_that_published_its_record_is_never_doubled.
  3. Something already listening on the port (the service's daemon after binding, or anything else). test_anything_listening_on_the_port_is_never_doubled. Removing the port check fails it.
  4. A live service process (macOS/Linux) that is slow. test_service_process_that_is_alive_is_never_doubled (both platforms) and the existing test_service_daemon_that_is_running_but_not_ready_is_never_doubled. Ignoring the manager's PID fails all 3.
  5. The ownership check itself fails, or a caller cannot supply one. test_ownership_check_that_fails_means_no_fallback and test_callers_that_cannot_check_ownership_never_fall_back. Both default to "no fallback".
  6. A broken service hidden forever. The fallback's warning names the service and the repair command (asserted in the reproduction test). On macOS/Linux, slm doctor still warns that the daemon is not owned by its service. On Windows doctor has no task PID to compare, so the log line is the only signal.

test_service_start_that_never_becomes_healthy_reports_failure now states its premise outright: a daemon owns the folder. Without that, falling back is the correct behaviour.

Open, filed separately

Results

  • This PR's test files plus the daemon, lifecycle, doctor and service packs (111 files, including the real-daemon e2e tests on temporary data folders and free ports): 967 passed, 15 skipped, 1 failed.
  • The one failure, test_doctor_health_verdicts.py::test_deadline_text_mode_names_check_and_exits_one, is timing-bound and already fails on main the same way: on a cold start the "Core deps" check takes longer than the test's 1 s doctor deadline, so the deadline names that check instead of the one the test stalls. It passes when warm (2 of 3 runs in its own file). Not related to this change.
  • Revert checks: with the fix-1 source reverted, the reproduction test fails (0 direct starts) along with 5 others. With the fix-2 source reverted, all 5 new parser and fail-closed tests fail. With only the depth cap reverted, the 3 parser tests still fail, so the cap is not redundant with the broader except.
  • ruff clean on every changed file.

No real service manager was started, stopped or changed. Every launchd, systemd and Task Scheduler call in the tests goes to an in-memory fake.

🤖 Generated with Claude Code

@varun369
varun369 merged commit 790938b into main Nov 20, 2026
7 checks passed
@varun369
varun369 deleted the fix/daemon-supervisor-owns-autostart branch November 20, 2026 14:33
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.

1 participant