Skip to content

process

process

Marianne daemon process.

Long-running orchestration service that manages job execution, resources, and cross-job coordination. Provides core functions for starting, stopping, and checking conductor status.

The entry point is mzt start/stop/restart via cli/commands/conductor.py.

Attributes

Classes

DaemonProcess

DaemonProcess(config, *, start_profile=None)

Long-running Marianne daemon process.

Composes DaemonServer (IPC), JobManager (job tracking), and ResourceMonitor (limits) into a single lifecycle.

Source code in src/marianne/daemon/process.py
def __init__(self, config: DaemonConfig, *, start_profile: str | None = None) -> None:
    self._config = config
    # #408: the start-time operational profile must survive a reload —
    # a daemon started with ``--profile dev`` reloads with the same
    # overlay instead of silently dropping it.
    self._start_profile = start_profile
    self._signal_received = asyncio.Event()
    self._pgroup = ProcessGroupManager()
    self._start_time = time.monotonic()
    self._signal_tasks: list[asyncio.Task[Any]] = []
    self._profiler: Any = None  # Set in run() step 8.5
    self._correlation: Any = None  # Set in run() step 8.6
    self._config_watcher: Any = None  # Set in run() step 8.7
Methods:
run async
run()

Main daemon lifecycle: boot, serve, shutdown.

Source code in src/marianne/daemon/process.py
async def run(self) -> None:
    """Main daemon lifecycle: boot, serve, shutdown."""
    # 1. Write PID file
    _write_pid(self._config.pid_file)

    try:
        # 2. Set up process group (fixes issue #38 — orphan prevention)
        self._pgroup.setup()

        # 2.5. Reap orphaned backend children from previous runs.
        # Claude CLI spawns LSP/MCP servers that outlive it; if a
        # previous daemon or CLI session crashed, these accumulate.
        startup_reaped = self._pgroup.reap_orphaned_backends()
        if startup_reaped:
            _logger.info(
                "daemon.startup_orphan_reap",
                count=len(startup_reaped),
                pids=startup_reaped,
            )

        # 3. Create components — single ResourceMonitor shared
        #    between periodic monitoring and backpressure checks.
        from marianne.daemon.ipc.handler import RequestHandler
        from marianne.daemon.ipc.server import DaemonServer
        from marianne.daemon.manager import JobManager
        from marianne.daemon.monitor import ResourceMonitor

        # Create monitor first (without manager ref — set after).
        self._monitor = ResourceMonitor(
            self._config.resource_limits,
            pgroup=self._pgroup,
        )
        # Pass the single monitor into JobManager for backpressure.
        self._manager = JobManager(
            self._config,
            start_time=self._start_time,
            monitor=self._monitor,
            pgroup=self._pgroup,
        )
        # Now wire the manager back into the monitor for job counts.
        self._monitor.set_manager(self._manager)
        await self._manager.start()

        # Warn about unenforced / reserved config fields.
        # Each entry: (field, current_value, default, event, message)
        _unenforced_fields: list[tuple[str, object, object, str, str]] = [
            (
                "max_api_calls_per_minute",
                self._config.resource_limits.max_api_calls_per_minute,
                60,
                "config.unenforced_rate_limit",
                "max_api_calls_per_minute is set but NOT YET ENFORCED. "
                "Rate limiting currently works through externally-reported "
                "events via RateLimitCoordinator.",
            ),
            (
                "state_backend_type",
                self._config.state_backend_type,
                "sqlite",
                "config.reserved_field_ignored",
                "state_backend_type is fixed to SQLite; alternative state "
                "backends are not supported.",
            ),
        ]
        for field_name, current, default, event, msg in _unenforced_fields:
            if current != default:
                _logger.warning(event, field=field_name, value=current, message=msg)

        handler = RequestHandler()

        # 4. Create health checker
        from marianne.daemon.health import HealthChecker

        health = HealthChecker(
            self._manager,
            self._monitor,
            start_time=self._start_time,
            learning_store=(
                self._manager._learning_hub.store if self._manager._learning_hub else None
            ),
        )

        # 5. Register RPC methods (adapt JobManager to handler signature)
        self._register_methods(handler, self._manager, health)

        # 6. Start server
        server = DaemonServer(
            self._config.socket.path,
            handler,
            permissions=self._config.socket.permissions,
            backlog=self._config.socket.backlog,
            max_connections=self._config.socket.max_connections,
            max_concurrent_requests=self._config.socket.max_concurrent_requests,
            max_streams=self._config.socket.max_streams,
            request_timeout=self._config.socket.request_timeout,
            write_timeout=self._config.socket.write_timeout,
            enforce_peer_uid=self._config.socket.enforce_peer_uid,
        )
        await server.start()

        # 7. Install signal handlers (tracked to surface exceptions)
        loop = asyncio.get_running_loop()

        from collections.abc import Callable

        def _make_signal_callback(
            signum: signal.Signals,
        ) -> Callable[[], None]:
            """Create a signal callback that captures ``signum`` by value."""

            def _cb() -> None:
                self._track_signal_task(
                    asyncio.create_task(
                        self._handle_signal(signum, self._manager, server),
                    ),
                )

            return _cb

        for sig in (signal.SIGTERM, signal.SIGINT):
            loop.add_signal_handler(sig, _make_signal_callback(sig))

        def _sighup_callback() -> None:
            self._track_signal_task(
                asyncio.create_task(self._handle_sighup()),
            )

        loop.add_signal_handler(signal.SIGHUP, _sighup_callback)

        # 8. Start resource monitor
        interval = self._config.monitor_interval_seconds
        await self._monitor.start(interval_seconds=interval)

        # 8.4. Start entropy monitoring (v25 evolution)
        # Wire health checker callback into manager for job completion tracking
        self._manager._entropy_check_callback = health.on_job_completed
        await health.start_periodic_checks()

        # 8.5. Start profiler collector (after monitor, needs event bus)
        if self._config.profiler.enabled:
            from marianne.daemon.profiler.collector import ProfilerCollector

            self._profiler = ProfilerCollector(
                config=self._config.profiler,
                monitor=self._monitor,
                pgroup=self._pgroup,
                event_bus=self._manager.event_bus,
                manager=self._manager,
            )
            await self._profiler.start()

        # 8.6. Start correlation analyzer (after profiler, needs storage + learning hub)
        if self._config.profiler.enabled and self._profiler is not None:
            from marianne.daemon.profiler.correlation import CorrelationAnalyzer

            self._correlation = CorrelationAnalyzer(
                storage=self._profiler._storage,
                learning_hub=self._manager.learning_hub,
                config=self._config.profiler.correlation,
            )
            await self._correlation.start(self._manager.event_bus)

        # 8.7. Start the config hot-reload watcher (#408) — watches the
        # config file and the instrument profile source dirs (the same
        # dirs the manager loaded from) and funnels changes into the
        # single reload path. Opt-in via hot_reload.enabled (default on).
        if self._config.hot_reload.enabled:
            from marianne.daemon.hot_reload import ConfigWatcher
            from marianne.instruments.classes import class_source_paths

            self._config_watcher = ConfigWatcher(
                config_file=self._config.config_file,
                profile_dirs=list(self._manager.profile_source_paths),
                class_files=list(class_source_paths()),
                reload_fn=self.reload_configuration,
                enabled_fn=lambda: self._config.hot_reload.enabled,
                debounce_fn=lambda: self._config.hot_reload.debounce_seconds,
            )
            await self._config_watcher.start()
            _logger.info(
                "daemon.config_watcher_started",
                config_file=str(self._config.config_file),
            )

        # 9. Run until shutdown
        _logger.info(
            "daemon.started",
            pid=os.getpid(),
            socket=str(self._config.socket.path),
        )
        await self._manager.wait_for_shutdown()

        # 10. Cleanup — watcher, correlation, profiler, entropy, monitor
        if self._config_watcher is not None:
            await self._config_watcher.stop()
            self._config_watcher = None
        if self._correlation is not None:
            await self._correlation.stop()
        if self._profiler is not None:
            await self._profiler.stop()
        await health.stop_periodic_checks()
        await self._monitor.stop()
        await server.stop()

        # 11. Kill remaining children in process group (issue #38)
        self._pgroup.kill_all_children()
        orphans = self._pgroup.cleanup_orphans()
        if orphans:
            _logger.info(
                "daemon.shutdown_orphans_cleaned",
                count=len(orphans),
            )

        _logger.info("daemon.stopped")
    finally:
        # Always remove PID file, even on crash
        self._config.pid_file.unlink(missing_ok=True)
reload_configuration async
reload_configuration(reason)

Single process-level reload entry (#408).

SIGHUP, the daemon.reload IPC method, and the config file watcher all call this. It delegates the actual reload to JobManager.reload_configuration (the one owner of config and profile re-reading) and then applies the two process-owned effects: syncing this process's config view and reconfiguring the log level when the reload says it changed.

Source code in src/marianne/daemon/process.py
async def reload_configuration(self, reason: str) -> ConfigReloadResult:
    """Single process-level reload entry (#408).

    SIGHUP, the ``daemon.reload`` IPC method, and the config file
    watcher all call this. It delegates the actual reload to
    ``JobManager.reload_configuration`` (the one owner of config and
    profile re-reading) and then applies the two process-owned effects:
    syncing this process's config view and reconfiguring the log level
    when the reload says it changed.
    """
    if not hasattr(self, "_manager") or self._manager is None:
        from marianne.daemon.types import ConfigReloadResult

        result = ConfigReloadResult(
            success=False,
            reason=reason,
            config_generation=0,
            error="manager not initialized",
        )
        return result

    result = await self._manager.reload_configuration(
        reason, profile=self._start_profile
    )
    if result.success:
        self._config = self._manager.config
        if "log_level" in result.applied:
            _configure_daemon_logging(
                self._config,
                format="json" if self._config.log_file is not None else "console",
            )
    return result

Functions:

start_conductor

start_conductor(config_file=None, foreground=False, log_level='info', profile=None, clone_name=None)

Start the Marianne conductor process.

Called by mzt start via cli/commands/conductor.py.

A live conductor that is serving is reported as already running (exit 0, GH #459). A live conductor that is draining (graceful shutdown) is superseded (GH #115): this waits up to CONDUCTOR_SUPERSEDE_TIMEOUT for the old process to exit, then starts a fresh conductor; it never spawns a second daemon beside a draining one, which holds the PID-file flock and socket lock.

When clone_name is provided, the conductor runs with isolated paths (socket, PID file, state DB, log) so it can coexist with the production conductor. The base config is loaded normally, then clone-specific paths are applied on top.

Source code in src/marianne/daemon/process.py
def start_conductor(
    config_file: Path | None = None,
    foreground: bool = False,
    log_level: str = "info",
    profile: str | None = None,
    clone_name: str | None = None,
) -> None:
    """Start the Marianne conductor process.

    Called by ``mzt start`` via ``cli/commands/conductor.py``.

    A live conductor that is *serving* is reported as already running
    (exit 0, GH #459). A live conductor that is *draining* (graceful
    shutdown) is superseded (GH #115): this waits up to
    ``CONDUCTOR_SUPERSEDE_TIMEOUT`` for the old process to exit, then
    starts a fresh conductor; it never spawns a second daemon beside a
    draining one, which holds the PID-file flock and socket lock.

    When *clone_name* is provided, the conductor runs with isolated
    paths (socket, PID file, state DB, log) so it can coexist with the
    production conductor.  The base config is loaded normally, then
    clone-specific paths are applied on top.
    """
    config = _load_config(config_file, profile=profile)
    config.log_level = cast(Any, log_level)

    # Apply clone path overrides when running as a clone conductor
    if clone_name is not None:
        from marianne.daemon.clone import build_clone_config

        config = build_clone_config(clone_name, base_config=config)
        config.log_level = cast(Any, log_level)

    # #227: probe the legacy /tmp PID too — a conductor started before the
    # path move must block a second `mzt start` (both would share the state
    # DB). Clones keep their own explicit paths.
    pid_probe_file = (
        config.pid_file
        if clone_name is not None
        else _resolve_live_pid_file(config.pid_file)
    )
    pid = _read_pid(pid_probe_file)
    if pid is not None:
        if _pid_alive(pid):
            label = "clone conductor" if clone_name is not None else "Marianne conductor"
            legacy_note = (
                " (on legacy /tmp paths — `mzt stop && mzt start` to migrate)"
                if pid_probe_file != config.pid_file
                else ""
            )
            # A live PID may be a conductor that is *serving* or one that is
            # *draining* (graceful shutdown can take up to
            # shutdown_timeout_seconds, default 300s). Only a serving one is
            # "already running" — a draining one must be superseded (GH #115).
            # Probe before deciding; on a silent probe be conservative and
            # treat it as running (GH #455: slow is not dead).
            # The #227 legacy PID fallback must probe that daemon's socket,
            # rather than an explicit modern path that bypasses IPC fallback.
            socket_probe_path = (
                LEGACY_SOCKET_PATH
                if pid_probe_file != config.pid_file
                else config.socket.path
            )
            shutting_down = _probe_shutting_down(socket_probe_path)
            if shutting_down is not True:
                # Serving (False) or silent (None): treat as running.
                #
                # Exit 0, not 1: a conductor being up is the state `mzt start`
                # exists to reach. A supervisor with Restart=on-failure (the
                # shipped systemd user unit) read exit 1 as a crash and
                # restarted every 30 s for three days against a hand-started
                # conductor (Pallas, GH #459). Exit 0 ends that loop; the
                # message still names the PID so a human sees what happened.
                typer.echo(f"{label} is already running (PID {pid}){legacy_note}")
                raise typer.Exit(0)
            # Draining conductor: wait (bounded) for it to exit, then start.
            # Never spawn a second daemon beside it — the dying one holds the
            # PID-file flock and socket lock for its whole life.
            typer.echo(
                f"{label} is shutting down (PID {pid}); "
                f"superseding it (waiting up to {CONDUCTOR_SUPERSEDE_TIMEOUT:.0f}s)"
            )
            if not wait_for_conductor_exit(
                pid_probe_file, timeout=CONDUCTOR_SUPERSEDE_TIMEOUT
            ):
                typer.echo(
                    f"Cannot start: {label} (PID {pid}) did not exit within "
                    f"{CONDUCTOR_SUPERSEDE_TIMEOUT:.0f}s. It may still be draining "
                    "active work. Check active scores: mzt status; retry later; "
                    "or use mzt stop --force only when you accept orphaning "
                    "active work."
                )
                raise typer.Exit(1)
            typer.echo("Drained conductor exited; starting a new one")
            # Fall through to a normal start below.
        else:
            # Stale PID file — process is dead, clean up before starting
            typer.echo(f"Cleaned up stale PID file (PID {pid} is no longer running)")
            pid_probe_file.unlink(missing_ok=True)

    # Detect concurrent start race via advisory lock
    if config.pid_file.exists() and not config.pid_file.is_symlink():
        try:
            probe_fd = os.open(str(config.pid_file), os.O_RDONLY)
            try:
                fcntl.flock(probe_fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
                fcntl.flock(probe_fd, fcntl.LOCK_UN)
            finally:
                os.close(probe_fd)
        except OSError:
            typer.echo("Marianne conductor is starting up (PID file locked)")
            raise typer.Exit(1) from None

    log_fmt = "console" if foreground else "json"
    _configure_daemon_logging(config, format=log_fmt)

    if not foreground:
        _daemonize(config)
    else:
        _logger.info(
            "daemon.starting",
            pid=os.getpid(),
            foreground=True,
            clone=clone_name,
        )

    daemon = DaemonProcess(config, start_profile=profile)
    asyncio.run(daemon.run())

stop_conductor

stop_conductor(pid_file=None, force=False, socket_path=None, wait=None)

Stop the running Marianne conductor (daemon) process.

Called by mzt stop via cli/commands/conductor.py.

Non-blocking by default: sends the signal and returns without waiting for the process to exit. Pass wait (seconds) to block until the conductor exits; wait=0 keeps the default signal-and-return behavior.

When jobs are actively running and --force is not set, warns the user and asks for confirmation before proceeding (#94). Force mode (--force) skips the safety check entirely.

Source code in src/marianne/daemon/process.py
def stop_conductor(
    pid_file: Path | None = None,
    force: bool = False,
    socket_path: Path | None = None,
    wait: float | None = None,
) -> None:
    """Stop the running Marianne conductor (daemon) process.

    Called by ``mzt stop`` via ``cli/commands/conductor.py``.

    Non-blocking by default: sends the signal and returns without
    waiting for the process to exit. Pass *wait* (seconds) to block
    until the conductor exits; ``wait=0`` keeps the default
    signal-and-return behavior.

    When jobs are actively running and ``--force`` is not set, warns
    the user and asks for confirmation before proceeding (#94).
    Force mode (``--force``) skips the safety check entirely.
    """
    if wait is not None and (not math.isfinite(wait) or wait < 0):
        raise ValueError("wait must be finite and >= 0")

    # Explicit pid_file always wins; only the default probes legacy (#227).
    resolved_pid_file = (
        pid_file
        if pid_file is not None
        else _resolve_live_pid_file(DaemonConfig().pid_file)
    )
    pid = _read_pid(resolved_pid_file)
    if pid is None or not _pid_alive(pid):
        typer.echo("Marianne conductor is not running")
        resolved_pid_file.unlink(missing_ok=True)
        raise typer.Exit(1)

    # Safety guard: check for running jobs unless --force (#94)
    in_flight: list[dict[str, Any]] = []
    if not force:
        running_info = _check_running_jobs(socket_path)
        if running_info is None:
            typer.echo(
                "Cannot determine active work: conductor is unresponsive. "
                "Stop refused; verify work independently before using --force."
            )
            raise typer.Exit(1)
        if running_info is not None and running_info["running_jobs"] > 0:
            count = running_info["running_jobs"]
            typer.echo(
                f"⚠ Warning: {count} job(s) currently running. "
                "Stopping the conductor will orphan active agents and "
                "may corrupt job state.",
            )
            if not typer.confirm("Proceed with stop?", default=False):
                typer.echo("Aborted.")
                raise typer.Exit(1)
        in_flight = running_info.get("in_flight", [])

    sig = signal.SIGKILL if force else signal.SIGTERM
    os.kill(pid, sig)
    typer.echo(
        f"Sent {'SIGKILL' if force else 'SIGTERM'} to Marianne conductor (PID {pid})",
    )
    if in_flight and not force:
        # A paused job whose pause is still pending keeps its sheet in
        # flight; the drain waits for it (up to shutdown_timeout_seconds)
        # even though running_jobs is 0. Say so before the wait (GH #476).
        typer.echo(
            f"Graceful drain is waiting on {len(in_flight)} in-flight sheet(s):"
        )
        for line in _format_in_flight(in_flight):
            typer.echo(line)
        typer.echo(
            "A boundary-paused job's in-flight sheet is ended at once and "
            "re-runs on resume; only RUNNING jobs hold the drain."
        )

    if wait is not None and wait > 0:
        if wait_for_conductor_exit(resolved_pid_file, timeout=wait):
            typer.echo("Marianne conductor stopped")
        else:
            # Re-probe: during the drain the socket still answers, so the
            # timeout can name what it is waiting on rather than guess.
            late = _check_running_jobs(socket_path)
            still_waiting = late.get("in_flight", []) if late is not None else []
            typer.echo(
                f"Marianne conductor (PID {pid}) did not exit within "
                f"{wait:.0f}s. It is still draining."
                + (
                    f" Waiting on {len(still_waiting)} in-flight sheet(s):"
                    if still_waiting
                    else ""
                )
            )
            for line in _format_in_flight(still_waiting):
                typer.echo(line)
            typer.echo(
                "The drain runs up to the conductor's shutdown_timeout_seconds "
                "(default 300s) and then a few seconds of teardown; a --wait "
                "budget at or below that is a bounded poll, not the drain's "
                "length. Check active scores: mzt status; retry later; or use "
                "mzt stop --force only when you accept orphaning active work."
            )
            raise typer.Exit(1)

get_conductor_status

get_conductor_status(pid_file=None, socket_path=None, as_json=False)

Check Marianne conductor (daemon) status via health probes.

Called by mzt conductor-status via cli/commands/conductor.py. With as_json, stdout carries ONLY the JSON document (human commentary goes to stderr) so mzt conductor-status --json | jq . works. With an explicit socket_path, no PID file is read, asserted, or unlinked — the daemon's own payload is the pid authority (#408 landing fixes).

Source code in src/marianne/daemon/process.py
def get_conductor_status(
    pid_file: Path | None = None,
    socket_path: Path | None = None,
    as_json: bool = False,
) -> None:
    """Check Marianne conductor (daemon) status via health probes.

    Called by ``mzt conductor-status`` via ``cli/commands/conductor.py``.
    With ``as_json``, stdout carries ONLY the JSON document (human
    commentary goes to stderr) so ``mzt conductor-status --json | jq .``
    works. With an explicit ``socket_path``, no PID file is read,
    asserted, or unlinked — the daemon's own payload is the pid
    authority (#408 landing fixes).
    """
    _defaults = DaemonConfig()
    # #408 landing P2: explicit --socket means socket-only probing — the
    # default pid file must never be read, asserted, or UNLINKED as a
    # side effect of inspecting a clone.
    socket_only = socket_path is not None
    resolved_socket: Path = (
        socket_path if socket_path is not None else _defaults.socket.path
    )

    def _note(message: str) -> None:
        # In --json mode stdout is reserved for the JSON document alone;
        # human commentary goes to stderr so pipes stay parseable.
        if as_json:
            typer.secho(message, err=True)
        else:
            typer.echo(message)

    pid: int | None = None
    pid_alive: bool | None = None
    if socket_only and pid_file is not None:
        # A clone's own PID file was named explicitly (conductor.py resolves
        # both clone paths). Reading it is not the #408 hazard, which was the
        # DEFAULT file being read or unlinked while inspecting a clone. It is
        # the evidence that tells busy from dead when the socket is silent
        # (GH #455); it is never asserted or unlinked here.
        pid = _read_pid(pid_file)
        pid_alive = _pid_alive(pid) if pid is not None else None
    if not socket_only:
        # Explicit pid_file always wins; only the default probes legacy (#227).
        resolved_pid_file = (
            pid_file
            if pid_file is not None
            else _resolve_live_pid_file(_defaults.pid_file)
        )
        # #227 transitional: a pre-move conductor serves on the legacy socket.
        if not resolved_socket.exists():
            from marianne.daemon.config import LEGACY_SOCKET_PATH

            if LEGACY_SOCKET_PATH.exists():
                resolved_socket = LEGACY_SOCKET_PATH

        pid = _read_pid(resolved_pid_file)
        if pid is None or not _pid_alive(pid):
            _note("Marianne conductor is not running")
            resolved_pid_file.unlink(missing_ok=True)
            raise typer.Exit(1)
        pid_alive = True

        _note(f"Marianne conductor is running (PID {pid})")

    from marianne.daemon.ipc.client import DaemonClient

    client = DaemonClient(resolved_socket, timeout=CONDUCTOR_PROBE_TIMEOUT)

    from marianne.daemon.exceptions import DaemonError

    async def _probe(method: str) -> dict[str, Any] | None:
        try:
            result: dict[str, Any] = await asyncio.wait_for(
                client.call(method), CONDUCTOR_PROBE_TIMEOUT,
            )
            return result
        except (OSError, DaemonError) as e:
            _logger.info(f"probe.{method.split('.')[-1]}_failed", error=str(e))
            return None

    async def _get_health() -> tuple[
        dict[str, Any] | None,
        dict[str, Any] | None,
        dict[str, Any] | None,
    ]:
        try:
            health, ready, daemon_info = await asyncio.gather(
                _probe("daemon.health"), _probe("daemon.ready"), _probe("daemon.status"),
            )
            return health, ready, daemon_info
        finally:
            await client.close()

    def _silent_socket() -> None:
        """The socket did not answer. Say what the PID file and the host prove
        (GH #455): a live PID under I/O pressure is busy, not dead, and the
        remedy is to wait, never `mzt start`/`mzt restart`.
        """
        from marianne.daemon.system_probe import read_io_pressure

        pressure = read_io_pressure()
        if pid is not None and pid_alive:
            _note(
                f"Marianne conductor PID {pid} is alive but its socket "
                f"{resolved_socket} did not answer: busy or unresponsive"
            )
            if pressure is not None:
                _note(
                    f"  Host I/O pressure (avg10): some {pressure.get('some_avg10', 0.0)}% "
                    f"full {pressure.get('full_avg10', 0.0)}%"
                )
            _note("  Do not start or restart it; wait for pressure to clear and retry")
            if as_json:
                import json as _json

                typer.echo(_json.dumps({
                    "pid": pid,
                    "alive": True,
                    "socket_answered": False,
                    "running_state": "unknown",
                    "io_pressure": pressure,
                }, indent=2, sort_keys=True))
        elif pid is not None:
            _note(f"Marianne conductor PID {pid} from the PID file is not alive")
            _note("  (Could not connect to conductor socket for details)")
        else:
            _note("  (Could not connect to conductor socket for details)")

    try:
        health, ready, daemon_info = asyncio.run(_get_health())
    except (OSError, DaemonError):
        _silent_socket()
        if as_json or socket_only:
            # Machine consumers never get a half-valid full document (the
            # live-PID case above emits its own small one); socket-only mode
            # has no further authority to consult.
            raise typer.Exit(1) from None
        return

    if socket_only and daemon_info is None:
        # The daemon itself did not answer — with an explicit --socket it
        # is the only authority for the full payload, so fail honestly
        # instead of printing one with a foreign or missing pid.
        _silent_socket()
        raise typer.Exit(1)

    if as_json:
        import json

        payload: dict[str, Any] = {"pid": pid}
        if daemon_info is not None:
            payload.update(daemon_info)
        typer.echo(json.dumps(payload, indent=2, sort_keys=True))
        return

    from rich.console import Console
    from rich.panel import Panel

    con = Console()

    # Socket-only mode has no pid-file pid; the daemon payload is
    # authoritative wherever it answered.
    display_pid: Any = (
        pid if pid is not None
        else (daemon_info or {}).get("pid", "unknown")
    )
    if socket_only:
        typer.echo(f"Marianne conductor is running (PID {display_pid})")

    # Build uptime string
    uptime_str = ""
    if health:
        uptime = health.get("uptime_seconds", 0)
        hours, remainder = divmod(int(uptime), 3600)
        minutes, seconds = divmod(remainder, 60)
        if hours >= 24:
            days = hours // 24
            remaining_hours = hours % 24
            uptime_str = f"{days}d {remaining_hours}h {minutes}m"
        else:
            uptime_str = f"{hours}h {minutes}m {seconds}s"

    # Build panel content
    lines: list[str] = []
    lines.append(
        f"PID {display_pid} [dim]\u00b7[/dim] Up {uptime_str}"
        if uptime_str else f"PID {display_pid}"
    )

    if ready:
        status_str = ready.get("status", "unknown")
        accepting = ready.get("accepting_work", False)
        if status_str == "ready" and accepting:
            lines.append("[green]Ready[/green] [dim]\u00b7[/dim] Accepting work")
        elif status_str == "ready":
            lines.append("[yellow]Ready[/yellow] [dim]\u00b7[/dim] Not accepting work")
        else:
            lines.append(f"Status: {status_str}")

        running_jobs = ready.get("running_jobs", 0)
        lines.append("")
        if running_jobs > 0:
            lines.append(f"Jobs: [bold]{running_jobs}[/bold] running")
        else:
            lines.append("[dim]No active jobs[/dim]")
        in_flight_rows = ready.get("in_flight") or []
        if in_flight_rows:
            # Musicians still executing — including those of boundary-paused
            # jobs, which a graceful drain waits on (GH #476).
            lines.append(f"In flight: [bold]{len(in_flight_rows)}[/bold] sheet(s)")
            lines.extend(_format_in_flight(in_flight_rows))

        # Resources with context
        lines.append("")
        lines.append("[bold]Resources[/bold]")
        memory_mb = ready.get("memory_mb", 0)
        memory_limit = ready.get("memory_limit_mb", 0)
        child_procs = ready.get("child_processes", 0)
        process_limit = ready.get("process_limit", 0)

        if memory_limit and memory_limit > 0:
            pct = int(memory_mb / memory_limit * 100)
            lines.append(f"  Memory: {memory_mb} MB ({pct}% of {memory_limit} MB)")
        else:
            lines.append(f"  Memory: {memory_mb} MB")

        if process_limit and process_limit > 0:
            lines.append(f"  Processes: {child_procs} / {process_limit}")
        else:
            lines.append(f"  Processes: {child_procs}")

        # Pressure indicator
        pressure = ready.get("pressure", "NONE")
        if isinstance(pressure, str) and pressure.upper() != "NONE":
            lines.append(f"  Pressure: [yellow]{pressure}[/yellow]")
        else:
            lines.append("  Pressure: [green]NONE[/green]")

        # GH #455: how late the loop wakes (accept() runs there) and whether
        # the host is stalled on I/O. Slow is told apart from dead here.
        lag = ready.get("event_loop_lag_ms")
        peak = ready.get("event_loop_lag_peak_ms")
        if isinstance(lag, (int, float)):
            colour = "red" if lag >= 1000 else "yellow" if lag >= 100 else "green"
            peak_text = f" (peak {peak} ms / 60 s)" if isinstance(peak, (int, float)) else ""
            lines.append(f"  Event loop lag: [{colour}]{lag} ms[/{colour}]{peak_text}")
        io_pressure = ready.get("io_pressure")
        if isinstance(io_pressure, dict):
            some = io_pressure.get("some_avg10", 0.0)
            full = io_pressure.get("full_avg10", 0.0)
            colour = "red" if full >= 20 else "yellow" if some >= 20 else "green"
            lines.append(
                f"  Host I/O pressure: [{colour}]some {some}% full {full}%[/{colour}] (avg10)"
            )

    # Hot-reload observability (GH #408, #450): the last reload's outcome is
    # the only place an operator learns a profile on disk is not the one the
    # conductor runs, and whether the remedy is an edit or a restart.
    if daemon_info:
        lines.append("")
        lines.append("[bold]Config[/bold]")
        generation = daemon_info.get("config_generation")
        loaded_at = daemon_info.get("config_loaded_at")
        lines.append(
            f"  Generation: {generation}"
            + (f" [dim]\u00b7[/dim] loaded {loaded_at}" if loaded_at else "")
        )
        last = daemon_info.get("last_config_reload")
        if isinstance(last, dict):
            state = (
                "failed" if not last.get("success")
                else "partial" if last.get("partial")
                else "applied"
            )
            lines.append(f"  Last reload: {state} ({last.get('reason', '?')})")
            for failed in last.get("failed_profiles") or []:
                retained = failed.get("retained") or ""
                keep = f" — previous entry '{retained}' retained" if retained else ""
                lines.append(
                    f"  [yellow]![/yellow] {failed.get('path')}: "
                    f"{failed.get('reason_code')}{keep}"
                )
            if last.get("schema_stale"):
                lines.append(
                    "  [yellow]![/yellow] conductor predates a profile's schema: "
                    "the file is valid for newer code; restart at a job-free boundary"
                )

    border_style = "green" if ready and ready.get("status") == "ready" else "yellow"
    con.print(Panel("\n".join(lines), title="Conductor", border_style=border_style))

    if daemon_info:
        version = daemon_info.get("version", "?")
        con.print(f"[dim]Version: {version}[/dim]")

wait_for_conductor_exit

wait_for_conductor_exit(pid_file=None, timeout=30.0)

Wait for the conductor process to exit.

Polls _pid_alive until the process is gone or timeout elapses. Cleans up the stale PID file once the process is confirmed dead.

Returns True if the process exited within the timeout.

Source code in src/marianne/daemon/process.py
def wait_for_conductor_exit(
    pid_file: Path | None = None,
    timeout: float = 30.0,
) -> bool:
    """Wait for the conductor process to exit.

    Polls ``_pid_alive`` until the process is gone or *timeout* elapses.
    Cleans up the stale PID file once the process is confirmed dead.

    Returns ``True`` if the process exited within the timeout.
    """
    # Explicit pid_file always wins; only the default probes legacy (#227).
    resolved = (
        pid_file
        if pid_file is not None
        else _resolve_live_pid_file(DaemonConfig().pid_file)
    )
    pid = _read_pid(resolved)
    if pid is None:
        return True

    deadline = time.monotonic() + timeout
    while time.monotonic() < deadline:
        if not _pid_alive(pid):
            resolved.unlink(missing_ok=True)
            return True
        time.sleep(0.1)
    return False