Skip to content

daemon start right after daemon stop leaves the worker stopped #1295

Closed

Description

@V3RON

What happened

simlock daemon stop && simlock daemon start often leaves the worker stopped. stop prints Daemon stopping, then start prints {"error":{"code":"DAEMON_CONNECTION_LOST","message":"Daemon connection closed"}} (exit 1) or nothing, and simlock daemon status says Daemon stopped. The next command that needs the daemon starts it again. It happened on almost every restart in the run. The docs tell users to restart this way after simlock config set.

What you expected

daemon start after daemon stop starts a new daemon, and daemon status says running.

How to reproduce

  1. SIMLOCK_HOME=$(mktemp -d) simlock daemon start
  2. simlock daemon stop && simlock daemon start (same home)
  3. simlock daemon status: Daemon stopped. Reproduced 2 runs out of 3 on a Mac with a scratch home.

Environment

Simlock 0.5.0 package at main 14a3f826b, macOS 27.0.1 arm64, Xcode 27.1, Android emulator 37.2.13. Found in the 0.6 release E2E run on 2026-11-05. Not new in 0.6: v0.5.0 has the same stop and start paths.

Logs and evidence

Likely cause, from a read of the code:

  • daemon stop returns as soon as the daemon acknowledges (src/cli/commands/daemon.ts:194-204); it does not wait for the process to exit.
  • The daemon releases its socket last, after it drains and disposes its drivers (src/daemon/server.ts:646-669).
  • daemon start first connects to the socket (src/cli/environment.ts:50-54). It reaches the dying daemon, skips the launch, and its getStatus() fails with DAEMON_CONNECTION_LOST (src/cli/commands/daemon.ts:97-107).
  • stopRunningDaemon (src/cli/daemon-service.ts:10-40) already waits for the endpoint to go away, but only daemon install and uninstall use it.

Written by an agent.

Activity

  1. added
    bug:new
    os:macos
    on Nov 5, 2026
  2. self-assigned this
    on Nov 5, 2026
  3. V3RON commented on Nov 5, 2026

    @V3RON
    ContributorAuthor

    This was generated by AI during triage.

    Not a duplicate. Related: #1155 (the planned daemon restart needs the same wait), #684 and #829 (closed, different causes). The failing test below is local only and was not pushed to bug/1295-repro, because this routine pushes no code. A maintainer can ask for it to be pushed. Label stays bug:new (rule 8).

    Reproduction

    Fast-lane e2e test e2e/daemon-restart.test.ts: "daemon start right after daemon stop returns, while the old daemon is still stopping, starts a new daemon and status says running". It fails on main 14a3f826b:

    import { describe, expect, it } from "vitest";
    
    import { type TestEnv, waitFor, withDaemon } from "./helpers/index.js";
    
    async function waitForReadyDevice(env: TestEnv, model: string): Promise<void> {
      await waitFor(
        async () => {
          const rows = (await env.cli(["list", "--devices"])).json as {
            spec: { model: string };
            state: string;
          }[];
          return rows.some((row) => row.state === "ready" && row.spec.model === model);
        },
        { label: `the warm pool makes a ready ${model}` },
      );
    }
    
    describe("daemon stop then start", () => {
      // why: #1295. A stop that still has an idle device to shut down holds its socket for that time;
      // the 2 s shutdown latency stands in for a real simulator's shutdown.
      it("daemon start right after daemon stop returns, while the old daemon is still stopping, starts a new daemon and status says running", async () => {
        const env = await withDaemon({
          configOverrides: {
            warmPool: {
              targets: [{ count: 1, model: "iPhone 16", osVersion: "18.4", platform: "ios" }],
            },
          },
        });
        await env.driverScript.set({
          ios: { knownModels: ["iPhone 16"], availableOsVersions: ["18.4"] },
        });
        await waitForReadyDevice(env, "iPhone 16");
        await env.driverScript.merge({ ios: { latencyMs: { shutdown: 2_000 } } });
    
        const stop = await env.cli(["daemon", "stop"]);
        expect(stop.code, stop.stderr).toBe(0);
        const start = await env.cli(["daemon", "start", "--json"]);
    
        expect({ code: start.code, stderr: start.stderr, json: start.json }).toEqual({
          code: 0,
          stderr: "",
          json: { status: "running" },
        });
        const status = await env.cli(["daemon", "status", "--json"]);
        expect(status.json).toMatchObject({ daemon: { health: "running", mode: "worker" } });
      }, 60_000);
    });
    -   "code": 0, "json": { "status": "running" }, "stderr": "",
    +   "code": 1, "json": undefined,
    +   "stderr": "{\"error\":{\"code\":\"DAEMON_CONNECTION_LOST\",\"message\":\"Daemon connection closed\"}}
    

    The report's "start prints nothing" case was not seen. Only the DAEMON_CONNECTION_LOST output reproduced.

    Root cause

    Defect. daemon stop (src/cli/commands/daemon.ts:194-204) returns as soon as the daemon acknowledges. The daemon then shuts down idle devices (#1056) and releases its socket last (src/daemon/server.ts:646-669). While it is stopping, #accept (src/daemon/server.ts:740) closes every new connection. So the next daemon start fails in its handshake, not in getStatus() as the report guessed. AutoLaunchAdminConnector.connect (src/cli/environment.ts:53) launches a new daemon only when the endpoint is gone, so it rethrows the error. The symptom shows in start, but the cause is that stop doesn't wait.

    Simplest fix

    After stopDaemon(), make daemon stop wait until daemonEndpointPresent() is false, with the same 300 s cap. Move that loop out of stopRunningDaemon (src/cli/daemon-service.ts:28-39) so both paths share it. Keep daemon stop failing when no daemon is running. Update the stop row in cli.mdx.

    Alternatives rejected

    • Release the socket first in #stop: a new daemon would start while the old one still holds the worker lock and the drivers.
    • Make daemon start wait out a stopping daemon: status right after stop would still be wrong.
    • Retry start on DAEMON_CONNECTION_LOST: this hides real connection failures.

    Risk

    • daemon stop now blocks while idle devices shut down. Maintainer decision: is a 300 s cap acceptable, and should the message become Daemon stopped?
    • A test that expects stop to return at once may break.
    • With launchd/systemd installed, the service manager may restart the daemon during the wait.

    Side findings

    • A second daemon stop while the daemon is stopping fails with DAEMON_CONNECTION_LOST. The comment at src/daemon/server.ts:847-851 says daemon.stop stays reachable while stopping, but #accept (:740) closes new connections first. Not filed. A maintainer can decide whether it needs its own issue.

    Written by an agent.

  4. V3RON commented on Nov 5, 2026

    @V3RON
    ContributorAuthor

    Reproduction

    Defect, confirmed as reported. e2e/daemon-lifecycle.test.ts, "daemon start run right after daemon stop, while the old daemon still shuts down an idle device, starts a new daemon that status reports running" (branch bug/1295-repro). A 5 s fake shutdown latency holds the old daemon on its socket.

    pnpm test:e2e e2e/daemon-lifecycle.test.ts -t "daemon start run right after daemon stop"
    
    AssertionError: {"error":{"code":"DAEMON_CONNECTION_LOST","message":"Daemon connection closed"}}
    : expected 1 to be +0
     ❯ e2e/daemon-lifecycle.test.ts:325:38
        325|     expect(start.code, start.stderr).toBe(0);
    

    Root cause

    src/cli/commands/daemon.ts:194-204: daemon stop returns once the daemon acknowledges, while the daemon keeps its socket until it has shut idle devices down (src/daemon/server.ts:654-666). A new connection to it is closed at once (src/daemon/server.ts:740-743). daemon start's first connect (src/cli/environment.ts:50-53) gets that closed connection, which isUnavailable (:222-226) does not count as "nothing listening", so it never launches and fails with DAEMON_CONNECTION_LOST. The docs' restart recipe (stop, then start) breaks whenever shutdown takes longer than one CLI start.

    Simplest fix

    In daemon stop, after stopDaemon(), poll environment.daemonEndpointPresent() until it is false, bounded, as stopRunningDaemon (src/cli/daemon-service.ts:28-40) does; share that loop. Keep today's error when no daemon runs. Update running-the-daemon.mdx:119,129, configuration.mdx:49 and the stop row in cli.mdx.

    Alternatives rejected

    • Make the auto-launch connect wait out a stopping daemon: every command's connect path changes, and a closed connection carries no code to tell "stopping" from "crashed".
    • Release the socket before draining: a new daemon would start while the old one still holds the drivers.
    • Docs only ("wait, then retry"): the documented recipe stays broken.

    Risk

    • daemon stop now blocks while idle devices shut down (about 15 s on a real simulator, e2e/helpers/env.ts:596); check the bound and its message, which must not say "nothing was changed".
    • With no daemon running, daemon stop must still fail as today, not return stopRunningDaemon's silent false.
    • Under launchd or systemd, check the manager does not relaunch onto the socket during the wait.

    Side findings

    Written by an agent.

  5. removed their assignment
    on Nov 5, 2026
  6. added
    bug:ready
    on Nov 5, 2026
  7. removed
    bug:new
    on Nov 5, 2026
  8. self-assigned this
    on Nov 5, 2026
  9. V3RON commented on Nov 5, 2026

    @V3RON
    ContributorAuthor

    Delivery run

    Merged: #1305 (#1295)
    Parked: none
    Waiting: none
    Decided: none

    Written by an agent.

  10. added a commit that references this issue on Nov 5, 2026
    2cf54f2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

bug:readyos:macos

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions