Skip to content

manager

manager

Job manager for the Marianne daemon.

Maps job IDs to asyncio.Tasks, enforces concurrency limits via semaphore, routes IPC requests to JobService, and cancels all tasks on shutdown.

Attributes

Classes

DaemonJobStatus

Bases: str, Enum

Status values for daemon-managed jobs.

Inherits from str so meta.status serializes directly as a plain string in JSON/dict output — no .value calls needed.

Attributes
is_terminal property
is_terminal

Whether the job has finished (completed, failed, or cancelled).

Mirrors JobStatus.is_terminal; both enums share the same three terminal members by name. TERMINAL_DAEMON_JOB_STATUSES is the one set every consumer reads (GH #225).

JobMeta dataclass

JobMeta(job_id, config_path, workspace, submitted_at=time(), started_at=None, status=QUEUED, error_message=None, error_traceback=None, chain_depth=None, schedule_id=None, running_seconds=0.0, running_started_at=None, max_wall_seconds=None, wall_deadline_at=None, terminal_reason=None, cleanup_generation=None, timeout_cleanup_outcome=None, timeout_cleanup_result_ref=None, deadline_diagnostic=None, hook_config=None, failure_hook_config=None, concert_config=None, completed_new_work=False, observer=None, pending_modify=None, held_chain_hook=None)

Metadata tracked per job in the manager.

Methods:
to_dict
to_dict()

Serialize to a dict suitable for JSON-RPC responses.

Source code in src/marianne/daemon/manager.py
def to_dict(self) -> dict[str, Any]:
    """Serialize to a dict suitable for JSON-RPC responses."""
    result: dict[str, Any] = {
        "job_id": self.job_id,
        "status": self.status,
        "config_path": str(self.config_path),
        "workspace": str(self.workspace),
        "submitted_at": self.submitted_at,
        "started_at": self.started_at,
        "running_seconds": self.running_seconds,
        # #253: emit the same always-present keys as JobRecord.to_dict so
        # list_jobs returns one consistent shape for active and registry
        # jobs (consumers can rely on these keys existing). JobMeta doesn't
        # track these in-memory — None here; live progress (current/total
        # sheet) is available from the checkpoint, not this summary dict.
        "pid": None,
        "completed_at": None,
        "current_sheet": None,
        "total_sheets": None,
    }
    if self.error_message:
        result["error_message"] = self.error_message
    if self.error_traceback:
        result["error_traceback"] = self.error_traceback
    if self.chain_depth is not None:
        result["chain_depth"] = self.chain_depth
    if self.max_wall_seconds is not None:
        result["max_wall_seconds"] = self.max_wall_seconds
    if self.wall_deadline_at is not None:
        result["wall_deadline_at"] = self.wall_deadline_at
    if self.terminal_reason is not None:
        result["terminal_reason"] = self.terminal_reason
    return result

DaemonResourceChecker

DaemonResourceChecker(monitor)

Bridges ResourceMonitor to ParallelExecutor's ResourceChecker protocol.

Used by JobManager to provide backpressure hints to the parallel executor during fanout stages.

Source code in src/marianne/daemon/manager.py
def __init__(self, monitor: ResourceMonitor) -> None:
    self._monitor = monitor
Methods:
can_start_parallel_sheet async
can_start_parallel_sheet()

Check if system resource pressure allows another parallel sheet.

Source code in src/marianne/daemon/manager.py
async def can_start_parallel_sheet(self) -> bool:
    """Check if system resource pressure allows another parallel sheet."""
    return self._monitor.is_accepting_work()

JobManager

JobManager(config, *, start_time=None, monitor=None, pgroup=None, wall_clock=time, monotonic_clock=monotonic, recurrence_clock=None, profile_dirs=None)

Manages concurrent job execution within the daemon.

Wraps JobService with task tracking and concurrency control. Each submitted job becomes an asyncio.Task that the manager tracks from start to completion/cancellation.

Source code in src/marianne/daemon/manager.py
def __init__(
    self,
    config: DaemonConfig,
    *,
    start_time: float | None = None,
    monitor: ResourceMonitor | None = None,
    pgroup: ProcessGroupManager | None = None,
    wall_clock: Callable[[], float] = time.time,
    monotonic_clock: Callable[[], float] = time.monotonic,
    recurrence_clock: Callable[[], datetime] | None = None,
    profile_dirs: tuple[Path, Path] | None = None,
) -> None:
    self._config = config
    self._start_time = start_time or time.monotonic()
    self._pgroup = pgroup
    self._wall_clock = wall_clock
    self._monotonic_clock = monotonic_clock
    self._recurrence_clock = recurrence_clock or utc_now
    # #408: instrument-profile source directories (organization, venue).
    # Recorded so boot, reload, and the file watcher all resolve the
    # SAME profile sources — one load path, no drift between boot and
    # reload. None defers to load_all_profiles defaults at use time.
    self._profile_dirs = profile_dirs
    # #408: config generation bookkeeping for hot reload. Generation
    # starts at 1 once a config LOAD has happened (construction counts
    # as the first load); it advances only on successful reloads.
    self._config_generation = 1
    self._config_loaded_at = datetime.now(UTC).isoformat()
    self._last_reload_result: ConfigReloadResult | None = None
    self._reload_lock = asyncio.Lock()

    # Phase 3: Centralized learning hub.
    # Single GlobalLearningStore shared across all jobs — pattern
    # discoveries in Job A are instantly available to Job B.
    self._learning_hub = LearningHub()

    # Deferred to start() where the learning hub's store is available.
    self._service: JobService | None = None
    self._jobs: dict[str, asyncio.Task[Any]] = {}
    self._failure_hook_tasks: dict[str, asyncio.Task[Any]] = {}
    self._job_meta: dict[str, JobMeta] = {}
    self._cleanup_generation_counter = 0
    # Admission is reserved synchronously before recurrence I/O so a
    # rejected same-ID request cannot publish autonomous work.
    self._job_admission_reservations: dict[str, _JobAdmissionReservation] = {}
    # Recurring lifecycle ownership is keyed by the durable schedule ID,
    # not by one presentation anchor or scheduled child job ID.  Like job
    # admission, it is task-owned and reentrant so controller tick calls
    # can submit their child while holding the recurrence lifecycle lock.
    self._schedule_admission_reservations: dict[
        str, _JobAdmissionReservation
    ] = {}
    # Manual scheduled submissions reserve their score-name lineage before
    # recurrence arms a timer and release it only after JobMeta is visible.
    self._schedule_lineage_reservations: dict[str, int] = {}
    # Live CheckpointState per running job — populated by
    # _PublishingBackend on every state_backend.save() so the
    # conductor can serve status from memory, not disk.
    # Keyed by conductor job_id (which may be deduplicated, e.g.
    # "issue-solver-2"), not the config's name field.
    self._live_states: dict[str, CheckpointState] = {}
    # In-process pause events per job — set by pause_job(), checked by
    # the runner at sheet boundaries.  Keyed by conductor job_id.
    self._pause_events: dict[str, asyncio.Event] = {}
    # Explicit config.name → conductor_id mapping.  Populated in
    # _run_job_task when the config is parsed (config.name becomes
    # known).  Used by _on_state_published as a fallback when
    # state.job_id doesn't match any _job_meta key — O(1) lookup
    # instead of the fragile linear scan it replaces.
    self._config_name_to_conductor_id: dict[str, str] = {}
    # Jobs queued as PENDING during rate limit backpressure.
    # Keyed by conductor job_id.  Auto-started when limits clear.
    self._pending_jobs: dict[str, JobRequest] = {}
    # #231: a live-resizable gate, not a raw Semaphore —
    # reload_configuration() adjusts the limit in place so a config
    # reload never orphans in-flight acquisitions (replacing the object
    # over-admits; see ConcurrencyGate).
    self._concurrency_semaphore = ConcurrencyGate(
        config.max_concurrent_jobs,
    )
    self._id_gen_lock = asyncio.Lock()
    self._shutting_down = False
    self._shutdown_event = asyncio.Event()
    self._recent_failures: deque[float] = deque()
    # v25: Optional entropy check callback set by process.py after health checker init
    self._entropy_check_callback: Callable[[], None] | None = None

    # Phase 3: Global sheet scheduler — lazily initialized via property.
    # Infrastructure is built and tested but not yet wired into the
    # execution path.  Currently, jobs run monolithically via
    # JobService.start_job().  Lazy init avoids allocating resources
    # until Phase 3 is actually wired.
    self._scheduler_instance: GlobalSheetScheduler | None = None

    # Phase 3: Cross-job rate limit coordination.
    # Built and tested; wired into the scheduler so next_sheet()
    # skips rate-limited backends.  Not yet active because the
    # scheduler itself is not yet driving execution.
    self._rate_coordinator = RateLimitCoordinator()

    # Fleet management — tracks running fleets for fleet-level operations
    self._fleet_records: dict[str, Any] = {}

    # Phase 3: Backpressure controller.
    # Uses a single ResourceMonitor instance shared with DaemonProcess
    # for both periodic monitoring and point-in-time backpressure checks.
    # When no monitor is injected (e.g. unit tests), a standalone one
    # is created that only does point-in-time reads.
    self._monitor = monitor or ResourceMonitor(config.resource_limits, manager=self)
    self._backpressure = BackpressureController(
        self._monitor,
        self._rate_coordinator,
    )

    # Persistent job registry — survives daemon restarts.
    db_path = config.state_db_path.expanduser()
    self._registry = JobRegistry(db_path)
    self._schedule_registry = ScheduleRegistry(db_path)
    self._recurrence_controller: RecurrenceController | None = None

    # Event bus for routing runner and observer events to consumers.
    self._event_bus = EventBus(
        max_queue_size=config.observer.max_queue_size,
    )

    # Semantic analyzer — LLM-based analysis of sheet completions.
    # Initialized in start() after the event bus is ready.
    self._semantic_analyzer: SemanticAnalyzer | None = None

    # #203: judgment client — automated FERMATA decider. Initialized in
    # start() after the baton adapter exists (it produces decisions via
    # adapter.resolve_fermata).
    self._judgment_client: Any | None = None

    # Phase 4: Completion snapshots — captures workspace artifacts
    # at job completion with TTL-based cleanup.
    self._snapshot_manager = SnapshotManager(base_dir=config.resolved_snapshot_dir)

    # Observer event recorder — persists per-job observer events to JSONL.
    # Initialized eagerly, started in start() after event bus.
    self._observer_recorder: ObserverRecorder | None = None
    self._orchestra: OrchestraRecorder | None = None

    # Baton adapter — the execution engine for all jobs.
    # Initialized in start(). Import deferred to avoid circular import.
    from marianne.daemon.baton.adapter import BatonAdapter

    self._baton_adapter: BatonAdapter | None = None
    self._mcp_pool: Any | None = None
    self._memory_gate: Any | None = None
    # #171: live instrument registry, retained for SIGHUP hot-reload.
    self._instrument_registry: InstrumentRegistry | None = None
    self._class_map: ClassMap | None = None
    # #197: per-job git worktree paths for isolation cleanup.
    self._job_worktrees: dict[str, Path] = {}
    self._baton_loop_task: asyncio.Task[Any] | None = None
    # #111: ordered, acknowledged checkpoint writer. Created in start()
    # (needs the running loop); replaces fire-and-forget save_checkpoint
    # tasks so per-job persists never reorder.
    self._checkpoint_writer: CheckpointWriter | None = None
Attributes
config property
config

The live, effective conductor configuration.

config_generation property
config_generation

Config generation; advances once per successful reload (#408).

config_loaded_at property
config_loaded_at

ISO-8601 UTC timestamp of the last successful config load.

last_reload_result property
last_reload_result

Outcome of the most recent reload attempt, if any.

profile_source_paths property
profile_source_paths

Resolved profile source dirs (builtins, organization, venue).

The same directories boot loaded from and reload re-reads — the file watcher watches exactly these.

output_hub property
output_hub

Live per-sheet output streaming hub (#352 inc-3), or None before the baton adapter exists. Backs job.output.stream.

uptime_seconds property
uptime_seconds

Seconds since the daemon started (monotonic clock).

shutting_down property
shutting_down

Whether the manager is in the process of shutting down.

in_flight_sheets property
in_flight_sheets

Musicians still executing, as the adapter sees them (GH #476).

What a graceful drain waits on. Empty when no baton adapter is up.

running_count property
running_count

Number of currently running jobs.

active_job_count property
active_job_count

Number of concurrently executing jobs (used for fair-share scheduling).

Currently returns running_count (job-level granularity). Phase 3 will replace this with self._scheduler.active_count for sheet-level granularity once per-sheet dispatch is wired.

failure_rate_elevated property
failure_rate_elevated

Whether the recent job failure rate is elevated.

Returns True if more than _FAILURE_RATE_THRESHOLD unexpected exceptions have occurred within the last _FAILURE_RATE_WINDOW seconds. Used by HealthChecker.readiness() to degrade the health signal when systemic failures are occurring.

notifications_degraded property
notifications_degraded

Whether notification delivery is degraded (forwarded from JobService).

scheduler property
scheduler

Access the global sheet scheduler for cross-job coordination.

rate_coordinator property
rate_coordinator

Access the rate limit coordinator for cross-job rate limiting.

backpressure property
backpressure

Access the backpressure controller for load management.

learning_hub property
learning_hub

Access the centralized learning hub.

observer_recorder property
observer_recorder

Access the observer event recorder for IPC.

orchestra property
orchestra

The orchestra view recorder, for IPC readers (GH #468).

event_bus property
event_bus

Access the event bus for subscribing to events.

Methods:
start async
start()

Start daemon subsystems (learning hub, monitor, etc.).

Source code in src/marianne/daemon/manager.py
async def start(self) -> None:
    """Start daemon subsystems (learning hub, monitor, etc.)."""
    # Open the async registry connection (tables + WAL mode)
    await self._registry.open()
    await self._schedule_registry.open()

    # Recover orphaned jobs (left running/queued from previous daemon).
    # Pause-aware: check each orphan's checkpoint to distinguish truly
    # running jobs from those that were mid-pause when the daemon died.
    orphans = await self._registry.get_orphaned_jobs()
    if orphans:
        failed_count = 0
        paused_count = 0
        for orphan in orphans:
            target_status = self._classify_orphan(orphan)
            await self._registry.update_status(
                orphan.job_id,
                target_status,
                error_message=(
                    "Daemon restarted while job was active"
                    if target_status == DaemonJobStatus.FAILED
                    else None
                ),
            )
            if target_status == DaemonJobStatus.PAUSED:
                paused_count += 1
            else:
                failed_count += 1
        _logger.info(
            "manager.orphans_recovered",
            count=len(orphans),
            failed=failed_count,
            paused=paused_count,
        )

    # Restore ALL job metadata from registry into memory so that
    # RPC handlers (status, resume, pause, errors, …) work for
    # jobs from previous daemon sessions without per-method fallback.
    # F-077: Also restore hook_config so on_success hooks fire after restart.
    all_records = await self._registry.list_jobs(limit=10_000)
    for record in all_records:
        if record.job_id not in self._job_meta:
            # Restore hook_config from registry (F-077: was missing,
            # causing on_success hooks to silently stop after restart)
            hook_config: list[dict[str, Any]] | None = None
            hook_json = await self._registry.get_hook_config(
                record.job_id,
            )
            if hook_json:
                hook_config = json.loads(hook_json)

            failure_hook_config: list[dict[str, Any]] | None = None
            failure_hook_json = await self._registry.get_failure_hook_config(
                record.job_id,
            )
            if failure_hook_json:
                failure_hook_config = json.loads(failure_hook_json)

            concert_config: dict[str, Any] | None = None
            concert_json = await self._registry.get_concert_config(record.job_id)
            if concert_json:
                concert_config = json.loads(concert_json)

            max_wall_seconds = record.max_wall_seconds
            wall_deadline_at = record.wall_deadline_at
            terminal_reason = record.terminal_reason
            if wall_deadline_at is None and record.checkpoint_json:
                try:
                    restored_checkpoint = CheckpointState.model_validate_json(
                        record.checkpoint_json
                    )
                except ValueError:
                    restored_checkpoint = None
                if (
                    restored_checkpoint is not None
                    and restored_checkpoint.wall_deadline_at is not None
                ):
                    max_wall_seconds = restored_checkpoint.max_wall_seconds
                    wall_deadline_at = restored_checkpoint.wall_deadline_at
                    terminal_reason = restored_checkpoint.terminal_reason
                    _logger.info(
                        "manager.deadline_restored_from_checkpoint",
                        job_id=record.job_id,
                        wall_deadline_at=wall_deadline_at,
                    )

            self._job_meta[record.job_id] = JobMeta(
                job_id=record.job_id,
                config_path=Path(record.config_path),
                workspace=Path(record.workspace),
                submitted_at=record.submitted_at,
                started_at=record.started_at,
                running_seconds=record.running_seconds,
                status=record.status,
                error_message=record.error_message,
                max_wall_seconds=max_wall_seconds,
                wall_deadline_at=wall_deadline_at,
                terminal_reason=terminal_reason,
                deadline_diagnostic=record.deadline_diagnostic,
                hook_config=hook_config,
                failure_hook_config=failure_hook_config,
                concert_config=concert_config,
                chain_depth=record.chain_depth,
            )
    if all_records:
        _logger.info(
            "manager.registry_restored",
            total=len(all_records),
            loaded=len(self._job_meta),
        )

    await self._learning_hub.start()
    await self._event_bus.start()
    # Create service with shared store now that the hub is initialized
    self._service = JobService(
        output=StructuredOutput(event_bus=self._event_bus),
        global_learning_store=self._learning_hub.store,
        event_callback=self._on_event,
        state_publish_callback=self._on_state_published,
        registry=self._registry,
        token_warning_threshold=self._config.preflight.token_warning_threshold,
        token_error_threshold=self._config.preflight.token_error_threshold,
        pgroup_manager=self._pgroup,
    )
    # Build the instrument registry up-front. After Phase 1 of the
    # backend atlas migration, all non-baton backend creation must
    # route through the registry (Doctrine RULE: "All model invocations
    # must route through the instrument plugin system after Phase 1").
    # The semantic analyzer and the baton adapter share a single
    # registry instance so that both observe the same set of profiles.
    from marianne.daemon.baton.adapter import BatonAdapter
    from marianne.daemon.baton.backend_pool import (
        BackendPool,
        create_backend_for_instrument,
    )
    from marianne.instruments.loader import (
        load_all_profiles,
        profile_source_dirs,
    )
    from marianne.instruments.registry import InstrumentRegistry

    _, org_dir, venue_dir = profile_source_dirs(
        organization_dir=self._profile_dirs[0] if self._profile_dirs else None,
        venue_dir=self._profile_dirs[1] if self._profile_dirs else None,
    )
    profiles = load_all_profiles(
        organization_dir=org_dir, venue_dir=venue_dir,
    )
    registry = InstrumentRegistry()
    for profile in profiles.values():
        registry.register(profile, override=True)
    # #171: retain for hot-reload of instrument profiles.
    self._instrument_registry = registry
    self._class_map = load_class_map(profile_names=set(profiles))

    # Start semantic analyzer after event bus (needs bus for subscription).
    # Failure must not prevent the conductor from starting.
    try:
        semantic_backend = create_backend_for_instrument(
            registry,
            self._config.learning.instrument,
            model=self._config.learning.model,
        )
        self._semantic_analyzer = SemanticAnalyzer(
            config=self._config.learning,
            backend=semantic_backend,
            learning_hub=self._learning_hub,
            live_states=self._live_states,
        )
        await self._semantic_analyzer.start(self._event_bus)
    except (OSError, ValueError, RuntimeError, TypeError):
        _logger.warning(
            "manager.semantic_analyzer_start_failed",
            exc_info=True,
        )
        self._semantic_analyzer = None

    # Start observer recorder after event bus (needs bus for subscription).
    # Guard: observer.enabled, NOT persist_events. The ring buffer serves
    # mzt top even when persistence is off.
    if self._config.observer.enabled:
        self._observer_recorder = ObserverRecorder(
            config=self._config.observer,
        )
        await self._observer_recorder.start(self._event_bus)

    # The orchestra view (GH #468): a public-safe projection of every job
    # and sheet beat, live over IPC and appended to a daily JSONL for
    # replay. Built after the bus, before any job can start.
    if self._config.orchestra.enabled:
        from marianne.daemon.orchestra import OrchestraRecorder

        self._orchestra = OrchestraRecorder(self._config.orchestra)
        await self._orchestra.start(self._event_bus)

    # Initialize the baton execution engine with the shared registry.
    self._baton_adapter = BatonAdapter(
        event_bus=self._event_bus,
        max_concurrent_sheets=self._config.max_concurrent_sheets,
        persist_callback=self._on_baton_persist,
        # #200: feed learned patterns into prompts. The hub is started at
        # the top of this method, so the store is available; guard anyway
        # so a store-less startup keeps the adapter functional (None skips).
        learning_store=(
            self._learning_hub.store
            if self._learning_hub.is_running
            else None
        ),
        # #206: mirror baton rate limits into the daemon coordinator so
        # backpressure / submit-time warnings / the scheduler see them.
        rate_limit_reporter=self._on_rate_limit,
        # #133: runtime diagnostics (observer events + resource state)
        # for retry failure-evidence enrichment.
        diagnostic_snapshot_fn=self._diagnostic_snapshot,
        flow_pause_callback=self._on_flow_pause,
        flow_concert_callback=self._submit_flow_concert,
    )
    self._baton_adapter.set_backend_pool(BackendPool(registry, pgroup=self._pgroup))

    recurrence_controller = RecurrenceController(
        self._schedule_registry,
        self.submit_job,
        self._baton_adapter.schedule_cron_tick,
        self._baton_adapter.cancel_cron_tick,
        self._is_schedule_active,
        now=self._recurrence_clock,
    )
    self._baton_adapter.set_cron_handler(recurrence_controller.handle_tick)
    self._recurrence_controller = recurrence_controller

    if self._config.mcp_pool.servers:
        from marianne.daemon.mcp_pool import McpPoolManager

        self._mcp_pool = McpPoolManager(self._config.mcp_pool)
        try:
            await self._mcp_pool.start_all()
            self._baton_adapter.set_mcp_pool(self._mcp_pool)
        except Exception:  # noqa: BLE001 — structured logger reports manager.mcp_pool_start_failed
            _logger.warning("manager.mcp_pool_start_failed", exc_info=True)
            try:
                await self._mcp_pool.stop_all()
            except Exception:  # noqa: BLE001 — structured logger reports manager.mcp_pool_stop_after_start_failed
                _logger.warning("manager.mcp_pool_stop_after_start_failed", exc_info=True)
            self._mcp_pool = None

    # Memory dispatch gate (GH #496). Construction is cheap and does no I/O: the
    # gateway, endpoint and audit log are created on the first dispatch of a
    # score that declares `memory:`.
    from marianne.daemon.baton.memory_gate import MemoryDispatchGate

    _marianne_home = Path.home() / ".marianne"
    self._memory_gate = MemoryDispatchGate(
        run_dir=_marianne_home / "run",
        memory_root=_marianne_home / "memory" / "files",
        audit_dir=_marianne_home / "memory" / "audit",
        user=_memory_user(),
        cam_endpoints=self._cam_endpoints_from(self._config),
    )
    self._baton_adapter.set_memory_gate(self._memory_gate)
    try:
        await self._memory_gate.sweep_stale()  # sockets a SIGKILLed conductor left behind
    except Exception:  # noqa: BLE001 — housekeeping: a sweep failure must not stop the conductor
        _logger.warning("manager.memory_gate_sweep_failed", exc_info=True)

    # Populate per-model concurrency from instrument profiles. Boot and
    # reload share this exact mechanism (#408) so the caps lifecycle
    # (set/change/remove) has one owner.
    self._baton_adapter.sync_model_concurrency(
        self._model_caps_from_profiles(profiles)
    )

    # #111: start the ordered checkpoint writer BEFORE the baton loop, so
    # every persist callback (which fires from that loop) has a consumer and
    # writes are serialized in order.
    checkpoint_writer = CheckpointWriter(self._registry)
    checkpoint_writer.start()
    self._checkpoint_writer = checkpoint_writer

    # Start the baton's event loop as a background task
    self._baton_loop_task = asyncio.create_task(
        self._baton_adapter.run(),
        name="baton-loop",
    )
    _logger.info("manager.baton_adapter_started")

    # Interactive-mode hygiene: tmux sessions survive a daemon crash
    # (the tmux server is not our child). Nothing has dispatched yet,
    # so every mzt-* session on the marianne socket is residue from a
    # previous daemon life — kill them. Best-effort: a sweep failure
    # must never block conductor startup.
    await self._sweep_orphan_interactive_sessions()

    # Restore recurring work only after stale interactive sessions are
    # gone. An overdue latest-policy tick may submit immediately.
    await recurrence_controller.restore()

    # A persisted PAUSED job is an operator/flow hold, not an invitation
    # to resume on conductor restart (#409). Explicit mzt resume is the
    # only transition back to RUNNING.
    await self._recover_baton_orphans(candidate_ids=set())

    # A conductor may restart after the registry committed FAILED but
    # before the in-process callback claimed its failure hooks. Reconcile
    # those unclaimed terminal failures after all execution services exist.
    for record in all_records:
        if record.status is DaemonJobStatus.FAILED:
            self._schedule_failure_hooks(record.job_id)

    # #203: judgment client — automated FERMATA decider. Started AFTER
    # orphan recovery so its startup reconciliation sees restart-recovered
    # FERMATA sheets. Failure must not prevent the conductor from starting
    # (fail-open: sheets stay composer-resolvable).
    try:
        from marianne.daemon.judgment import JudgmentClient

        adapter = self._baton_adapter

        def _judgment_backend(instrument: str) -> Any:
            return create_backend_for_instrument(registry, instrument)

        judgment_client = JudgmentClient(
            live_states=self._live_states,
            resolve_fn=adapter.resolve_fermata,
            backend_factory=_judgment_backend,
            diagnostic_fn=self._diagnostic_snapshot,
            persist_fn=self._on_baton_persist,  # GH #382: counter is the cap
        )
        await judgment_client.start(self._event_bus)
        self._judgment_client = judgment_client
    except Exception:  # noqa: BLE001 — structured logger reports manager.judgment_client_start_failed
        _logger.warning(
            "manager.judgment_client_start_failed", exc_info=True
        )
        self._judgment_client = None

    _logger.info(
        "manager.started",
        scheduler_status="lazy_not_wired",
        scheduler_note="Phase 3 scheduler is lazily initialized and not "
        "yet driving execution. Jobs run through the baton engine.",
        semantic_analyzer="active" if self._semantic_analyzer else "unavailable",
        observer_recorder="active" if self._observer_recorder else "unavailable",
        baton_adapter="active",
    )
reload_configuration async
reload_configuration(reason, *, profile=None)

The single config/profile hot-reload path (#408).

SIGHUP (via the DaemonProcess delegate), the daemon.reload IPC method, mzt conductor reload, and the file watcher all funnel here — nothing else re-reads config or profiles. Steps:

  1. Re-read the config file (with the start profile overlay) and the instrument profile directories into temporaries. A config-file load or validation error is fail-closed: nothing is applied, the running config/registry/caps are untouched, generation does not advance. A profile FILE that exists but fails to load is NOT fail-closed — its previous registry entry and caps are retained and the file is reported in declined with partial=True (the #397 edit-accident must not silently remove a live instrument).
  2. Build the effective config: fields that cannot change in a running conductor keep their running values and are reported in declined; everything else is applied in place (resize, never replace holding objects — #231 pattern). A changed memory_backends section is applied that way (#573): it replaces the memory gate's cam endpoint table and is reported in applied as memory_backends; the gate itself is kept, so a session that is already open keeps the backend it was opened with.
  3. Swap the live registry (fresh profiles ∪ retained previous entries from broken files; a healthy fresh profile always wins the name), invalidate the backend pool (#171 semantics: in-flight executions finish on their loaded profile), and atomically replace the per-model cap map — including REMOVAL of entries for profiles that disappeared.
  4. Enqueue a dispatch retry so a raised cap releases waiting sheets on the next baton cycle instead of an unrelated event. A lowered cap never cancels in-flight work; new dispatch waits for drain.
  5. Record generation/loaded_at/applied/declined and return.

Parameters:

Name Type Description Default
reason str

Trigger origin ("sighup", "ipc", "cli", "watcher").

required
profile str | None

Start-time operational profile to re-apply as overlay, so a reload does not silently drop --profile settings.

None

Returns:

Type Description
ConfigReloadResult

The typed reload outcome (also exposed via daemon.status).

Source code in src/marianne/daemon/manager.py
async def reload_configuration(
    self, reason: str, *, profile: str | None = None
) -> ConfigReloadResult:
    """The single config/profile hot-reload path (#408).

    SIGHUP (via the DaemonProcess delegate), the ``daemon.reload`` IPC
    method, ``mzt conductor reload``, and the file watcher all funnel
    here — nothing else re-reads config or profiles. Steps:

    1. Re-read the config file (with the start profile overlay) and the
       instrument profile directories into temporaries. A config-file
       load or validation error is fail-closed: nothing is applied,
       the running config/registry/caps are untouched, generation
       does not advance. A profile FILE that exists but fails to
       load is NOT fail-closed — its previous registry entry and
       caps are retained and the file is reported in ``declined``
       with ``partial=True`` (the #397 edit-accident must not
       silently remove a live instrument).
    2. Build the effective config: fields that cannot change in a
       running conductor keep their running values and are reported in
       ``declined``; everything else is applied in place (resize, never
       replace holding objects — #231 pattern). A changed
       ``memory_backends`` section is applied that way (#573): it
       replaces the memory gate's cam endpoint table and is reported in
       ``applied`` as ``memory_backends``; the gate itself is kept, so a
       session that is already open keeps the backend it was opened with.
    3. Swap the live registry (fresh profiles ∪ retained previous
       entries from broken files; a healthy fresh profile always wins
       the name), invalidate the backend pool (#171 semantics:
       in-flight executions finish on their loaded profile), and
       atomically replace the per-model cap map — including REMOVAL
       of entries for profiles that disappeared.
    4. Enqueue a dispatch retry so a raised cap releases waiting sheets
       on the next baton cycle instead of an unrelated event. A lowered
       cap never cancels in-flight work; new dispatch waits for drain.
    5. Record generation/loaded_at/applied/declined and return.

    Args:
        reason: Trigger origin ("sighup", "ipc", "cli", "watcher").
        profile: Start-time operational profile to re-apply as overlay,
            so a reload does not silently drop ``--profile`` settings.

    Returns:
        The typed reload outcome (also exposed via daemon.status).
    """
    from marianne.instruments.loader import load_all_profiles_with_failures

    async with self._reload_lock:
        old = self._config
        fail = self._record_failed_reload
        config_file = old.config_file

        if config_file is None:
            return fail(
                reason,
                "no config file recorded — started with defaults; "
                "reload has no file to re-read",
            )
        if not Path(config_file).exists():
            return fail(
                reason, f"config file missing: {config_file}"
            )

        # ── Load + validate everything BEFORE applying anything ──
        try:
            from marianne.daemon.process import _load_config

            new_config = _load_config(config_file, profile=profile)
            _, org_dir, venue_dir = self.profile_source_paths
            fresh_profiles, failed_profiles = (
                load_all_profiles_with_failures(
                    organization_dir=org_dir, venue_dir=venue_dir,
                )
            )
        except Exception as exc:  # noqa: BLE001 — return failure details through the public result contract
            return fail(
                reason,
                f"reload validation failed — running config kept: "
                f"{type(exc).__name__}: {exc}",
                declined=[
                    f"reload_failed: {type(exc).__name__}: {exc}",
                ],
            )

        # ── Broken profile files: keep previous entries (P1, #397) ──
        # A source file that exists but failed to load must not
        # silently remove its live registry entry and cap keys. Merge
        # key is the profile's recorded _source_path — never the
        # name — so legal name overrides cannot resurrect stale
        # entries. A healthy fresh profile owning the same name wins.
        merged_profiles = dict(fresh_profiles)
        retained_from: dict[Path, str] = {}
        if failed_profiles and self._instrument_registry is not None:
            failed_paths = {failure.path for failure in failed_profiles}
            for previous in self._instrument_registry.list_all():
                source = previous._source_path
                if source is None or source not in failed_paths:
                    continue
                if previous.name in merged_profiles:
                    continue  # a healthy fresh profile owns the name
                merged_profiles[previous.name] = previous
                retained_from[source] = previous.name

        partial_reload = bool(failed_profiles)
        fresh_classes = load_class_map(profile_names=set(merged_profiles))
        if fresh_classes.failures and self._class_map is not None:
            failed_layers = {failure.layer for failure in fresh_classes.failures}
            layer_rank = {"default": 0, "user": 1, "venue": 2}
            retained = dict(fresh_classes.classes)
            for class_name, prior in self._class_map.classes.items():
                if prior.source_layer not in failed_layers:
                    continue
                current = fresh_classes.classes.get(class_name)
                if (
                    current is not None
                    and layer_rank[current.source_layer] > layer_rank[prior.source_layer]
                ):
                    # A healthy higher layer owns the class now; the old
                    # lower-layer chain must not override it (Forge
                    # Inspect P1, reload-overrides-valid-venue).
                    continue
                retained[class_name] = prior
            fresh_classes = ClassMap(
                retained, fresh_classes.layers, fresh_classes.failures,
                fresh_classes.tombstones,
            )
        partial_reload = partial_reload or bool(fresh_classes.failures)

        # ── Classify: restart-only changes keep running values ──
        applied: list[str] = []
        declined: list[str] = [
            # Every failed profile file is reported — even when a
            # healthy fresh profile now owns the name — so the
            # operator always learns the file on disk is broken.
            # Distinguishable prefix; ``partial`` is the machine flag.
            (
                f"profile load failed ({failure.path}): "
                f"{failure.reason_code}: {failure.reason}"
                + (
                    f" — previous entry '{retained_from[failure.path]}' retained"
                    if failure.path in retained_from
                    else ""
                )
            )
            for failure in failed_profiles
        ]
        declined.extend(
            f"class load failed ({failure.path}): {failure.reason}"
            for failure in fresh_classes.failures
        )
        keep_running: dict[str, Any] = {}
        for field_name in self._RESTART_ONLY_FIELDS:
            if getattr(new_config, field_name) != getattr(old, field_name):
                declined.append(
                    f"{field_name}: restart required (running value kept)"
                )
                keep_running[field_name] = getattr(old, field_name)
        effective = (
            new_config.model_copy(update=keep_running)
            if keep_running
            else new_config
        )

        # ── Apply hot fields in place ──
        if effective.max_concurrent_jobs != old.max_concurrent_jobs:
            # #231: resize the live gate, never replace it — replacing
            # orphaned in-flight acquisitions and over-admitted on lower.
            self._concurrency_semaphore.set_limit(
                effective.max_concurrent_jobs,
            )
            applied.append(
                f"max_concurrent_jobs: "
                f"{old.max_concurrent_jobs}→{effective.max_concurrent_jobs}"
            )

        if effective.max_concurrent_sheets != old.max_concurrent_sheets:
            if self._baton_adapter is not None:
                # Adapter attribute is read per dispatch cycle — in-place
                # update; the setter also wakes the loop.
                self._baton_adapter.set_max_concurrent_sheets(
                    effective.max_concurrent_sheets,
                )
            if self._scheduler_instance is not None:
                self._scheduler_instance.set_max_concurrent(
                    effective.max_concurrent_sheets,
                )
            applied.append(
                f"max_concurrent_sheets: "
                f"{old.max_concurrent_sheets}"
                f"→{effective.max_concurrent_sheets}"
            )

        if effective.resource_limits != old.resource_limits:
            if self._monitor is not None:
                self._monitor.update_limits(effective.resource_limits)
            applied.append("resource_limits")

        if effective.preflight != old.preflight:
            if self._service is not None:
                self._service._token_warning_threshold = (
                    effective.preflight.token_warning_threshold
                )
                self._service._token_error_threshold = (
                    effective.preflight.token_error_threshold
                )
            applied.append("preflight")

        if effective.memory_backends != old.memory_backends:
            # #573: the gate exists only after start(); the section is
            # reported applied either way (the live config carries it).
            if self._memory_gate is not None:
                self._memory_gate.set_cam_endpoints(
                    self._cam_endpoints_from(effective)
                )
            applied.append("memory_backends")

        for field_name in self._LIVE_READ_FIELDS:
            if getattr(effective, field_name) != getattr(old, field_name):
                applied.append(field_name)

        self._config = effective
        if self._class_map is not None and fresh_classes != self._class_map:
            applied.append(f"instrument_classes: {len(fresh_classes.classes)}")
        self._class_map = fresh_classes

        # ── Instrument profiles: registry swap + caps diff ──
        if self._instrument_registry is not None:
            self._instrument_registry.replace_all(merged_profiles)
            if (
                self._baton_adapter is not None
                and self._baton_adapter._backend_pool is not None
            ):
                self._baton_adapter._backend_pool.invalidate()
            applied.append(f"instrument_profiles: {len(merged_profiles)}")
            if self._baton_adapter is not None:
                diff = self._baton_adapter.sync_model_concurrency(
                    self._model_caps_from_profiles(merged_profiles)
                )
                if diff["added"] or diff["changed"] or diff["removed"]:
                    applied.append(
                        "model_concurrency: "
                        f"+{len(diff['added'])} "
                        f"~{len(diff['changed'])} "
                        f"-{len(diff['removed'])}"
                    )

        # ── Commit generation ──
        self._config_generation += 1
        self._config_loaded_at = datetime.now(UTC).isoformat()
        result = ConfigReloadResult(
            success=True,
            partial=partial_reload,
            schema_stale=any(
                failure.reason_code == "instrument_schema_stale"
                for failure in failed_profiles
            ),
            failed_profiles=[
                {
                    "path": str(failure.path),
                    "reason_code": failure.reason_code,
                    "reason": failure.reason,
                    "retained": retained_from.get(failure.path, ""),
                }
                for failure in failed_profiles
            ],
            reason=reason,
            config_generation=self._config_generation,
            config_loaded_at=self._config_loaded_at,
            applied=applied,
            declined=declined,
        )
        self._last_reload_result = result
        _logger.info(
            "manager.config_reloaded",
            reason=reason,
            generation=self._config_generation,
            partial=partial_reload,
            applied=applied,
            declined=declined,
        )
        return result
update_job_config_metadata
update_job_config_metadata(job_id, *, config_path=None, workspace=None)

Update config-derived metadata in the in-memory job map.

Source code in src/marianne/daemon/manager.py
def update_job_config_metadata(
    self,
    job_id: str,
    *,
    config_path: Path | None = None,
    workspace: Path | None = None,
) -> None:
    """Update config-derived metadata in the in-memory job map."""
    meta = self._job_meta.get(job_id)
    if meta is None:
        return
    if config_path is not None:
        meta.config_path = config_path
    if workspace is not None:
        meta.workspace = workspace
submit_job async
submit_job(request)

Validate config, create task, return immediately.

Source code in src/marianne/daemon/manager.py
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
async def submit_job(self, request: JobRequest) -> JobResponse:
    """Validate config, create task, return immediately."""
    if self._shutting_down:
        return JobResponse(
            job_id="",
            status="rejected",
            message="Daemon is shutting down",
        )

    if not self._backpressure.should_accept_job():
        # F-149: should_accept_job() only rejects for resource pressure
        # (memory/processes). Rate limits are per-instrument and handled
        # at the sheet dispatch level — they don't block job submission.
        return JobResponse(
            job_id="",
            status="rejected",
            message="System under high resource pressure — try again later",
        )

    job_id = self._get_job_id(request.job_id or request.config_path.stem)

    # A failure hook can still be producing external side effects after
    # the score itself becomes terminal. Reusing the stable job ID during
    # that window would reset its durable claim beneath the live hook.
    failure_hook_task = self._failure_hook_tasks.get(job_id)
    if failure_hook_task is not None and not failure_hook_task.done():
        return JobResponse(
            job_id=job_id,
            status="rejected",
            message=(
                f"Job '{job_id}' is still running terminal failure hooks. "
                "Wait for those hooks to finish before submitting it again."
            ),
        )

    # Validate config exists and resolve workspace BEFORE acquiring the
    # lock. Config parsing is expensive and doesn't need serialization
    # — it's idempotent and job-independent.
    if not request.config_path.exists():
        return JobResponse(
            job_id=job_id,
            status="rejected",
            message=f"Config file not found: {request.config_path}",
        )

    # Pinned-schedule admission: the recurrence tick bound the daemon-
    # owned pin digest into this request. Read the source bytes once,
    # refuse any drift BEFORE fleet routing, parsing, or registration,
    # and parse only from the verified bytes — the submitted child must
    # consume exactly the bytes the pin admitted (W13 check→parse race).
    verified_source_bytes: bytes | None = None
    if request.expected_source_digest is not None:
        try:
            verified_source_bytes = request.config_path.read_bytes()
        except OSError as exc:
            return JobResponse(
                job_id=job_id,
                status="rejected",
                message=(
                    f"Pinned schedule source could not be read: "
                    f"{request.config_path} ({exc})."
                ),
            )
        actual_digest = hashlib.sha256(verified_source_bytes).hexdigest()
        if actual_digest != request.expected_source_digest:
            _logger.error(
                "manager.pinned_source_drift_refused",
                job_id=job_id,
                config_path=str(request.config_path),
                expected_digest=request.expected_source_digest,
                actual_digest=actual_digest,
            )
            return JobResponse(
                job_id=job_id,
                status="rejected",
                message=(
                    f"Pinned schedule source drift: the bytes at "
                    f"{request.config_path} do not match the "
                    f"daemon-pinned digest for job '{job_id}'. "
                    "Refused before execution; re-register the "
                    "schedule to amend the pin."
                ),
            )

    # GH #403: an opt-in composition lock. The caller's release gate
    # wrote a lock over the exact score bytes; admission verifies the
    # bytes it is about to parse against that lock, so shell control
    # flow around a failed gate cannot reach RUNNING. Ordinary scores
    # carry no lock and are unaffected.
    if request.required_lock is not None:
        lock_bytes = verified_source_bytes
        if lock_bytes is None:
            try:
                lock_bytes = request.config_path.read_bytes()
            except OSError as exc:
                return JobResponse(
                    job_id=job_id, status="rejected",
                    message=f"Locked score could not be read: {request.config_path} ({exc}).",
                )
        refusal = _verify_required_lock(request.required_lock, lock_bytes, job_id)
        if refusal is not None:
            return JobResponse(job_id=job_id, status="rejected", message=refusal)
        # The lock becomes the pin for the whole lifetime of this job:
        # the digest it attests rides expected_source_digest, so the
        # execution path (_run_job_task) re-reads and re-verifies the
        # bytes before the first sheet and runs from them, exactly as a
        # pinned schedule does. Without this the lock would guard only
        # the admission-time parse (security review of c20dc6ee).
        locked_digest = hashlib.sha256(lock_bytes).hexdigest()
        if (request.expected_source_digest is not None
                and request.expected_source_digest != locked_digest):
            return JobResponse(
                job_id=job_id, status="rejected",
                message=(
                    f"Required composition lock {request.required_lock} and the "
                    "daemon-pinned schedule digest disagree about the score bytes."
                ),
            )
        request = request.model_copy(update={"expected_source_digest": locked_digest})
        verified_source_bytes = lock_bytes

    # Fleet detection: route fleet configs to the fleet manager
    from marianne.daemon.fleet import is_fleet_config, submit_fleet

    if verified_source_bytes is not None:
        # Route from the verified bytes only — never re-open the path,
        # or a swap between the digest check and this routing decision
        # could redirect a pinned child into hostile fleet bytes. A
        # pinned registration is always a plain score (the tick parsed
        # it as JobConfig), so fleet-shaped verified bytes refuse.
        fleet_raw = yaml.safe_load(verified_source_bytes)
        if isinstance(fleet_raw, dict) and fleet_raw.get("type") == "fleet":
            return JobResponse(
                job_id=job_id,
                status="rejected",
                message=(
                    f"Pinned schedule source must be a plain score, "
                    f"not a fleet config: {request.config_path}."
                ),
            )
    elif is_fleet_config(request.config_path):
        from marianne.core.config.fleet import FleetConfig

        try:
            with open(request.config_path) as f:
                raw = yaml.safe_load(f)
            fleet_config = FleetConfig.model_validate(raw)
        except Exception as exc:  # noqa: BLE001 — return failure details through the public result contract
            return JobResponse(
                job_id=job_id,
                status="rejected",
                message=f"Failed to parse fleet config: {exc}",
            )
        return await submit_fleet(self, request.config_path, fleet_config)

    # Parse config for workspace resolution and hook extraction.
    # When workspace is provided explicitly, parsing is best-effort
    # (hooks won't be available if it fails, but the job still runs).
    from marianne.core.config import JobConfig

    parsed_config: JobConfig | None = None
    if verified_source_bytes is not None:
        # Parse the verified bytes themselves: between this parse and
        # the digest check above the path may change again, and the
        # hooks/workspace admitted here must come from the pinned bytes.
        try:
            parsed_config = JobConfig.from_yaml_bytes(
                verified_source_bytes,
                source_path=request.config_path,
            )
            workspace = parsed_config.workspace
        except (ValueError, OSError, KeyError, yaml.YAMLError) as exc:
            _logger.error(
                "manager.pinned_config_parse_failed",
                job_id=job_id,
                config_path=str(request.config_path),
                exc_info=True,
            )
            return JobResponse(
                job_id=job_id,
                status="rejected",
                message=(
                    f"Failed to parse pinned config file: "
                    f"{request.config_path} ({exc})."
                ),
            )
    elif request.workspace:
        workspace = request.workspace
        try:
            parsed_config = JobConfig.from_yaml(request.config_path)
        except (ValueError, OSError, KeyError, yaml.YAMLError):
            _logger.debug(
                "manager.config_parse_for_hooks_failed",
                job_id=job_id,
                config_path=str(request.config_path),
            )
    else:
        try:
            parsed_config = JobConfig.from_yaml(request.config_path)
            workspace = parsed_config.workspace
        except (ValueError, OSError, KeyError, yaml.YAMLError) as exc:
            _logger.error(
                "manager.config_parse_failed",
                job_id=job_id,
                config_path=str(request.config_path),
                exc_info=True,
            )
            return JobResponse(
                job_id=job_id,
                status="rejected",
                message=(
                    f"Failed to parse config file: "
                    f"{request.config_path} ({exc}). "
                    "Cannot determine workspace. "
                    "Fix the config or pass --workspace explicitly."
                ),
            )

    admitted_classes = None
    if isinstance(parsed_config, ConcreteJobConfig) and isinstance(
        self._instrument_registry, InstrumentRegistry
    ):
        try:
            profile_names = {
                profile.name for profile in self._instrument_registry.list_all()
            }
            class_map = self._class_map or load_class_map(profile_names=profile_names)
            # A venue class file beside the score that this conductor never
            # read (GH #510): under the shipped unit the daemon's working
            # directory is $HOME, so its "venue" layer IS the user file and
            # the checkout's .marianne/classes.yaml reaches `mzt validate`
            # but never dispatch. Refuse at submit, naming both paths, as
            # the venue-profile guard below does.
            unread = unloaded_venue_class_layer(
                class_map,
                request.client_cwd,
                requested_class_names(parsed_config, profile_names, class_map),
            )
            if unread is not None:
                beside, loaded = unread
                return JobResponse(
                    job_id=job_id,
                    status="rejected",
                    message=(
                        f"The score uses a capability class that {beside} "
                        f"redefines, but this conductor's venue class layer is "
                        f"{loaded.resolve()} (resolved from its working directory), "
                        "so dispatch would not use that file. Start the conductor "
                        "from the project directory, or move the definition to "
                        "~/.marianne/classes.yaml and run 'mzt conductor reload'."
                    ),
                )
            admitted_classes = resolve_job_classes(
                parsed_config,
                profile_names,
                class_map,
                expected_route=request.expected_route is not None,
            )
        except ValueError as exc:
            return JobResponse(
                job_id=job_id, status="rejected", message=str(exc),
            )

    # A venue profile beside the score (`<client_cwd>/.marianne/instruments/`)
    # that this conductor did not load is the first-run wall for anyone
    # who wrote a local-server profile where the docs say to: the CLI's
    # validate/check/list saw it from the project directory, the daemon
    # loaded its venue dir from the directory it was started in, and the
    # job failed at sheet 1 with E505 "not found in registry. Available:
    # <every other profile>". Refuse at submit, naming both directories.
    if isinstance(parsed_config, ConcreteJobConfig) and isinstance(
        self._instrument_registry, InstrumentRegistry
    ):
        unloaded = self._unloaded_venue_profiles(parsed_config, request.client_cwd)
        if unloaded and request.client_cwd is not None:
            _, _, daemon_venue = self.profile_source_paths
            names = ", ".join(f"'{n}'" for n in sorted(unloaded))
            return JobResponse(
                job_id=job_id,
                status="rejected",
                message=(
                    f"The score binds {names}, which exists only in "
                    f"{request.client_cwd / '.marianne' / 'instruments'} and is "
                    f"not loaded by this conductor (its venue profiles come from "
                    f"{daemon_venue.resolve()}). Start the conductor from the "
                    "project directory, or move the profile to "
                    "~/.marianne/instruments/ and run 'mzt conductor reload'."
                ),
            )

    # A named run of a score that omits workspace: (GH #505). The loader
    # derived ~/workspaces/<score name>; a run named with --job-id gets
    # ~/workspaces/<job-id> instead, so two commissions of one shipped
    # score never share a workspace. Carried on the request so the job
    # task, the pending queue and resume all use the same path.
    if (
        request.job_id
        and not request.workspace
        and parsed_config is not None
        and parsed_config.workspace_auto_managed
    ):
        workspace = default_workspace_for(job_id)
        workspace.parent.mkdir(parents=True, exist_ok=True)
        request = request.model_copy(update={"workspace": workspace})

    # Resolve relative workspace against client_cwd (working directory fix).
    # When the CLI sends client_cwd, relative workspace paths from the
    # config should resolve against where the user invoked the command,
    # not where the daemon was spawned.
    if request.client_cwd and not workspace.is_absolute():
        workspace = (request.client_cwd / workspace).resolve()
        _logger.debug(
            "manager.workspace_resolved_from_client_cwd",
            job_id=job_id,
            client_cwd=str(request.client_cwd),
            workspace=str(workspace),
        )

    # Extract hook config from parsed config for daemon-owned execution.
    hook_config_list: list[dict[str, Any]] | None = None
    failure_hook_config_list: list[dict[str, Any]] | None = None
    concert_config_dict: dict[str, Any] | None = None
    if parsed_config and parsed_config.on_success:
        hook_config_list = [h.model_dump(mode="json") for h in parsed_config.on_success]
    if parsed_config and parsed_config.on_failure:
        failure_hook_config_list = [h.model_dump(mode="json") for h in parsed_config.on_failure]
    if parsed_config and parsed_config.concert.enabled:
        concert_config_dict = parsed_config.concert.model_dump(mode="json")

    # Early workspace validation: reject jobs whose workspace parent
    # doesn't exist or isn't writable, instead of failing deep in
    # JobService.start_job(). Workspace itself may not exist yet —
    # it gets created by JobService — but the parent must be valid.
    ws_parent = workspace.parent
    if not ws_parent.exists():
        return JobResponse(
            job_id=job_id,
            status="rejected",
            message=(
                f"Workspace parent directory does not exist: {ws_parent}. "
                "Create the parent directory or change the workspace path."
            ),
        )
    if not os.access(ws_parent, os.W_OK):
        return JobResponse(
            job_id=job_id,
            status="rejected",
            message=(
                f"Workspace parent directory is not writable: {ws_parent}. "
                "Fix permissions or change the workspace path."
            ),
        )

    # Claim this job ID without awaiting before recurrence can publish a
    # durable schedule or timer. Contenders reject instead of waiting, so
    # no manager lock is held while recurrence performs I/O.
    if not self._try_reserve_job_admission(job_id):
        existing = self._job_meta.get(job_id)
        if existing is not None and existing.status in {
            DaemonJobStatus.PENDING,
            DaemonJobStatus.QUEUED,
            DaemonJobStatus.RUNNING,
        }:
            detail = f"already {existing.status.value}"
        else:
            detail = "already being submitted"
        return JobResponse(
            job_id=job_id,
            status="rejected",
            message=(
                f"Job '{job_id}' is {detail}. "
                "Use 'mzt pause' or 'mzt cancel' first, or wait for it to finish."
            ),
        )

    schedule_admission_claims: list[tuple[str, ...]] = []

    def _claim_schedule_admission(schedule_ids: tuple[str, ...]) -> None:
        if not self._try_reserve_schedule_admission(schedule_ids):
            joined = ", ".join(repr(value) for value in schedule_ids)
            raise JobSubmissionError(
                f"Schedule lifecycle for {joined} is already active"
            )
        schedule_admission_claims.append(schedule_ids)

    def _probe_schedule_admission(schedule_ids: tuple[str, ...]) -> bool:
        if not self._schedule_admission_available(schedule_ids):
            joined = ", ".join(repr(value) for value in schedule_ids)
            raise JobSubmissionError(
                f"Schedule lifecycle for {joined} is already active"
            )
        return True

    try:
        if request.scheduled_due_at is not None and request.schedule_id is not None:
            try:
                _claim_schedule_admission((request.schedule_id,))
            except JobSubmissionError as exc:
                return JobResponse(
                    job_id=job_id,
                    status="rejected",
                    message=str(exc),
                )

        # A manual submission refreshes the source-owned schedule before
        # its immediate run. This lifecycle lock must be acquired before
        # the manager ID lock; scheduled children skip registration,
        # preserving that one-way lock order.
        reservation_id: str | None = None
        try:
            if (
                request.scheduled_due_at is None
                and parsed_config is not None
                and self._recurrence_controller is not None
            ):
                if parsed_config.schedule is not None:
                    reservation_id = parsed_config.name
                    self._reserve_schedule_lineage(reservation_id)
                    # A lifecycle command may hold the controller's
                    # registration lock while mutating this source. Probe
                    # every currently known source identity before waiting
                    # so manual submission rejects instead of blocking on
                    # the cross-subsystem lock.
                    source_path = request.config_path.resolve(strict=False)
                    known_ids = {
                        parsed_config.name,
                        *(
                            current.schedule_id
                            for current in await self._recurrence_controller.describe()
                            if current.score_path.resolve(strict=False) == source_path
                        ),
                    }
                    _probe_schedule_admission(tuple(sorted(known_ids)))
                registered_schedule = await self._recurrence_controller.register(
                    request.config_path,
                    parsed_config,
                    before_wait=_probe_schedule_admission,
                    before_mutation=_claim_schedule_admission,
                )
                if registered_schedule is None:
                    if reservation_id is not None:
                        self._release_schedule_lineage(reservation_id)
                    reservation_id = None
                else:
                    if registered_schedule.schedule_id != reservation_id:
                        self._reserve_schedule_lineage(
                            registered_schedule.schedule_id
                        )
                        if reservation_id is not None:
                            self._release_schedule_lineage(reservation_id)
                        reservation_id = registered_schedule.schedule_id
                    request = request.model_copy(
                        update={"schedule_id": registered_schedule.schedule_id},
                    )
        except JobSubmissionError as exc:
            if reservation_id is not None:
                self._release_schedule_lineage(reservation_id)
            return JobResponse(
                job_id=job_id,
                status="rejected",
                message=str(exc),
            )
        except BaseException:
            if reservation_id is not None:
                self._release_schedule_lineage(reservation_id)
            raise

        try:
            # Serialize only the duplicate-check → insert window to prevent
            # TOCTOU races between concurrent submissions.
            async with self._id_gen_lock:
                # Recheck active metadata after recurrence I/O. The
                # admission reservation prevents another submitter from
                # reaching this publication window for the same ID.
                existing = self._job_meta.get(job_id)
                if existing and existing.status in (
                    DaemonJobStatus.PENDING,
                    DaemonJobStatus.QUEUED,
                    DaemonJobStatus.RUNNING,
                ):
                    return JobResponse(
                        job_id=job_id,
                        status="rejected",
                        message=(
                            f"Job '{job_id}' is already {existing.status.value}. "
                            "Use 'mzt pause' or 'mzt cancel' first, or wait for it to finish."
                        ),
                    )

                # Auto-detect changed score file on re-run (#103).
                # When a COMPLETED job exists and --fresh wasn't set, check
                # if the score file was modified after the last run completed.
                if not request.fresh:
                    record = await self._registry.get_job(job_id)
                    if (
                        record is not None
                        and record.status == DaemonJobStatus.COMPLETED
                        and _should_auto_fresh(
                            request.config_path,
                            record.completed_at,
                        )
                    ):
                        request = request.model_copy(update={"fresh": True})
                        _logger.info(
                            "auto_fresh.score_changed",
                            job_id=job_id,
                            config_path=str(request.config_path),
                            message=(
                                "Score file modified since last completed run — "
                                "starting fresh"
                            ),
                        )

                registered_at = self._wall_clock()
                max_wall_seconds = (
                    parsed_config.tick_wall_seconds
                    if parsed_config is not None
                    and (
                        request.schedule_id is not None
                        or request.scheduled_due_at is not None
                    )
                    else None
                )
                wall_deadline_at = (
                    registered_at + max_wall_seconds
                    if max_wall_seconds is not None
                    else None
                )
                # Register in DB first — if this fails, no phantom in-memory entry
                log_path = self._ensure_workspace_log_path(workspace)
                try:
                    committed = await self._registry.register_job(
                        job_id,
                        request.config_path,
                        workspace,
                        log_path=log_path,
                        submitted_at=registered_at,
                        max_wall_seconds=max_wall_seconds,
                        wall_deadline_at=wall_deadline_at,
                    )
                except FailureHooksInProgressError as exc:
                    return JobResponse(
                        job_id=job_id,
                        status="rejected",
                        message=str(exc),
                    )
                meta = JobMeta(
                    job_id=committed.job_id,
                    config_path=Path(committed.config_path),
                    workspace=Path(committed.workspace),
                    submitted_at=committed.submitted_at,
                    chain_depth=request.chain_depth,
                    schedule_id=request.schedule_id,
                    max_wall_seconds=committed.max_wall_seconds,
                    wall_deadline_at=committed.wall_deadline_at,
                    deadline_diagnostic=committed.deadline_diagnostic,
                    hook_config=hook_config_list,
                    failure_hook_config=failure_hook_config_list,
                    concert_config=concert_config_dict,
                )
                self._job_meta[job_id] = meta
                self._bind_cleanup_generation(meta, new_execution=True)
                if admitted_classes is not None:
                    admission = CheckpointState(
                        job_id=job_id,
                        job_name=parsed_config.name if parsed_config else job_id,
                        total_sheets=parsed_config.sheet.total_sheets if parsed_config else 0,
                        instrument_classes=admitted_classes,
                    )
                    await self._registry.save_checkpoint(
                        job_id, admission.model_dump_json()
                    )

                if concert_config_dict is not None or request.chain_depth is not None:
                    await self._registry.store_concert_context(
                        job_id,
                        (
                            json.dumps(concert_config_dict)
                            if concert_config_dict is not None
                            else None
                        ),
                        request.chain_depth,
                    )

                # Persist hook config to registry for restart resilience
                if hook_config_list:
                    await self._registry.store_hook_config(
                        job_id,
                        json.dumps(hook_config_list),
                    )
                if failure_hook_config_list:
                    await self._registry.store_failure_hook_config(
                        job_id,
                        json.dumps(failure_hook_config_list),
                    )
        finally:
            if reservation_id is not None:
                self._release_schedule_lineage(reservation_id)

        try:
            task = asyncio.create_task(
                self._run_job_task(job_id, request),
                name=f"job-{job_id}",
            )
        except RuntimeError:
            # Clean up metadata if task creation fails
            # RuntimeError is raised by asyncio when no running event loop
            self._job_meta.pop(job_id, None)
            await self._registry.update_status(
                job_id,
                DaemonJobStatus.FAILED,
                error_message="Task creation failed",
            )
            raise
        self._jobs[job_id] = task
        task.add_done_callback(lambda t: self._on_task_done(job_id, t))

        _logger.info(
            "job.submitted",
            job_id=job_id,
            config_path=str(request.config_path),
        )

        return JobResponse(
            job_id=job_id,
            status="accepted",
            message=(
                f"Job queued (concurrency limit: "
                f"{self._config.max_concurrent_jobs})"
            ),
        )
    finally:
        for schedule_ids in reversed(schedule_admission_claims):
            self._release_schedule_admission(schedule_ids)
        self._release_job_admission(job_id)
get_job_status async
get_job_status(job_id, workspace=None)

Get full status of a specific job.

Resolution order (no workspace/disk fallback): 1. Live in-memory state for active jobs 2. Registry checkpoint (historical jobs — persisted on every save) 3. Terminal live-state fallback if no registry checkpoint is available 4. Basic metadata (jobs that never ran / pre-checkpoint registry)

Source code in src/marianne/daemon/manager.py
async def get_job_status(self, job_id: str, workspace: Path | None = None) -> dict[str, Any]:
    """Get full status of a specific job.

    Resolution order (no workspace/disk fallback):
    1. Live in-memory state for active jobs
    2. Registry checkpoint (historical jobs — persisted on every save)
    3. Terminal live-state fallback if no registry checkpoint is available
    4. Basic metadata (jobs that never ran / pre-checkpoint registry)
    """
    _ = workspace  # Unused — daemon is the single source of truth

    schedule_record = await self._schedule_for_job(job_id)
    meta = self._job_meta.get(job_id)
    record: JobRecord | None = None
    if meta is None:
        # Check the persistent registry for historical jobs
        record = await self._registry.get_job(job_id)
        if record is None:
            if schedule_record is not None:
                return self._schedule_anchor_status(schedule_record)
            raise JobSubmissionError(f"Job '{job_id}' not found")

    # 1. Live in-memory state for active jobs. Terminal live states are a
    # cache: direct recovery and registry reconciliation can update the DB
    # without changing this process' old object, so non-active jobs must
    # read the registry before trusting _live_states.
    live = self._live_states.get(job_id)
    if live is not None and meta is not None and meta.status in _ACTIVE_DAEMON_STATUSES:
        live_data = _normalize_cancelled_checkpoint_status(
            live.model_dump(mode="json"),
        )
        return await self._merge_registry_hook_metadata(
            job_id,
            live_data,
        )

    # 2. Registry checkpoint (historical/terminal jobs)
    #    Skip if meta shows an active status — the checkpoint is stale
    #    between resume acceptance and the first new state save.
    if meta is None or meta.status not in _ACTIVE_DAEMON_STATUSES:
        try:
            if record is None:
                record = await self._registry.get_job(job_id)
            checkpoint_json = await self._registry.load_checkpoint(job_id)
            if checkpoint_json is not None:
                import json

                checkpoint_data: dict[str, Any] = json.loads(checkpoint_json)
                # Override checkpoint status with the registry's
                # authoritative status. The checkpoint may have been
                # persisted before a cancel/fail was recorded in the
                # registry's status column.
                authoritative_status = (
                    record.status.value
                    if record is not None
                    else (meta.status.value if meta is not None else None)
                )
                if (
                    authoritative_status
                    and checkpoint_data.get("status") != authoritative_status
                ):
                    checkpoint_data["status"] = authoritative_status
                checkpoint_data = _normalize_cancelled_checkpoint_status(
                    checkpoint_data,
                )
                return await self._merge_registry_hook_metadata(
                    job_id,
                    checkpoint_data,
                )
        except Exception:  # noqa: BLE001 — structured logger reports get_job_status.registry_checkpoint_failed
            _logger.debug(
                "get_job_status.registry_checkpoint_failed",
                job_id=job_id,
                exc_info=True,
            )

    # 3. Terminal live-state fallback for a known job whose registry has no
    # checkpoint yet.
    if live is not None:
        live_data = _normalize_cancelled_checkpoint_status(
            live.model_dump(mode="json"),
        )
        return await self._merge_registry_hook_metadata(
            job_id,
            live_data,
        )

    # 3b. Detect stale RUNNING status (no live state + no running task).
    #     This happens when meta was restored from the registry after a
    #     daemon restart but the job's process no longer exists.
    if meta is not None and meta.status == DaemonJobStatus.RUNNING:
        task = self._jobs.get(job_id)
        if task is None or task.done():
            _logger.info(
                "get_job_status.stale_running_corrected",
                job_id=job_id,
            )
            await self._set_job_status(
                job_id,
                DaemonJobStatus.FAILED,
            )
            # Now fall through to return the corrected checkpoint
            # or metadata below.
            try:
                checkpoint_json = await self._registry.load_checkpoint(
                    job_id,
                )
                if checkpoint_json is not None:
                    import json as _json

                    failed_data = _json.loads(checkpoint_json)
                    # Override the checkpoint's stale status
                    failed_data["status"] = "failed"
                    failed_data = _normalize_cancelled_checkpoint_status(failed_data)
                    return await self._merge_registry_hook_metadata(
                        job_id,
                        failed_data,
                    )
            except Exception:  # noqa: BLE001 — structured logger reports get_job_status.checkpoint_load_after_fail
                _logger.debug(
                    "get_job_status.checkpoint_load_after_fail",
                    job_id=job_id,
                    exc_info=True,
                )

    # 4. Basic metadata (job never produced a checkpoint, or active job
    #    whose registry checkpoint is stale)
    if meta is not None:
        return await self._merge_registry_hook_metadata(job_id, meta.to_dict())
    assert record is not None  # guaranteed by the check above
    return await self._merge_registry_hook_metadata(job_id, record.to_dict())
pause_job async
pause_job(job_id)

Pause recurring ticks and any currently running work.

Source code in src/marianne/daemon/manager.py
async def pause_job(self, job_id: str) -> bool:
    """Pause recurring ticks and any currently running work."""
    record = await JobManager._schedule_for_job(self, job_id)
    if record is None:
        return await self._pause_active_job(job_id)

    controller = getattr(self, "_recurrence_controller", None)
    assert controller is not None
    claims: list[tuple[str, ...]] = []
    authority: ScheduleRecord | None = None
    pause_mutation_entered = False
    owned_job_ids: list[str] = []
    changed_events: list[asyncio.Event] = []
    created_signals: list[Path] = []
    changed_baton: list[tuple[JobMeta, bool, bool, int | None]] = []
    staged_children: list[tuple[JobMeta, DaemonJobStatus]] = []
    pause_commit_started = False

    def claim(schedule_ids: tuple[str, ...]) -> None:
        self._claim_lifecycle_admission(claims, schedule_ids)

    def capture_authority(current: ScheduleRecord) -> None:
        nonlocal authority
        self._claim_related_job_admissions(current, owned_job_ids)
        authority = current

    def mark_pause_mutation(_current: ScheduleRecord) -> None:
        nonlocal pause_mutation_entered
        pause_mutation_entered = True

    try:
        current = await controller.pause(
            record.schedule_id,
            score_path=record.score_path,
            before_mutation=claim,
            on_authority=capture_authority,
            on_mutation=mark_pause_mutation,
        )
        related = self._schedule_related_meta(current)

        def pause_order(meta: JobMeta) -> int:
            if meta.status is DaemonJobStatus.RUNNING:
                baton_has_job = (
                    self._baton_adapter is not None
                    and self._baton_adapter.has_job(meta.job_id)
                )
                # Fallible filesystem pauses precede local signals. A
                # later failure therefore cannot strand an earlier local
                # dispatch gate in the paused state.
                return 1 if baton_has_job or meta.job_id in self._pause_events else 0
            if meta.status is DaemonJobStatus.QUEUED:
                return 2
            if meta.status is DaemonJobStatus.PENDING:
                return 3
            return 4

        for meta in sorted(related, key=pause_order):
            if meta.status in {
                DaemonJobStatus.PENDING,
                DaemonJobStatus.QUEUED,
            }:
                prior_status = meta.status
                staged_children.append((meta, prior_status))
                await self._set_job_status(meta.job_id, DaemonJobStatus.PAUSED)
                continue
            event = self._pause_events.get(meta.job_id)
            event_was_set = event.is_set() if event is not None else False
            signal_path = meta.workspace / f".marianne-pause-{meta.job_id}"
            signal_existed = signal_path.exists()
            baton_job = (
                self._baton_adapter._baton._jobs.get(meta.job_id)
                if self._baton_adapter is not None
                and meta.status is DaemonJobStatus.RUNNING
                else None
            )
            baton_prior = (
                (
                    baton_job.paused,
                    baton_job.user_paused,
                    baton_job.event_generation,
                )
                if baton_job is not None
                else None
            )
            await self._pause_related_job(
                meta,
                defer_baton_event=baton_prior is not None,
            )
            if baton_prior is not None:
                changed_baton.append((meta, *baton_prior))
            if event is not None and not event_was_set and event.is_set():
                changed_events.append(event)
            if not signal_existed and signal_path.exists():
                created_signals.append(signal_path)

        # Every fallible child status transition has succeeded. Commit
        # pending removal and queued cancellation only now, so an earlier
        # child can always be restored without recreating detached work.
        pause_commit_started = True
        queued_tasks: list[asyncio.Task[Any]] = []
        for meta, prior_status in staged_children:
            if prior_status is DaemonJobStatus.PENDING:
                self._pending_jobs.pop(meta.job_id, None)
                continue
            task = self._jobs.pop(meta.job_id, None)
            if task is not None and not task.done():
                task.cancel(msg=f"schedule pause requested for {meta.job_id}")
                queued_tasks.append(task)
        if queued_tasks:

            async def settle_queued_tasks() -> None:
                await asyncio.gather(*queued_tasks, return_exceptions=True)

            settlement = asyncio.create_task(
                settle_queued_tasks(),
                name=f"schedule-pause-settle-{current.schedule_id}",
            )
            try:
                await asyncio.shield(settlement)
            except asyncio.CancelledError:
                # Cancellation remains loud, but every already-cancelled
                # queued task settles before lifecycle ownership is lost.
                await settlement
                raise
        if changed_baton:
            from marianne.daemon.baton.events import PauseJob

            adapter = self._baton_adapter
            assert adapter is not None
            for meta, _paused, _user_paused, event_generation in changed_baton:
                adapter._baton.inbox.put_nowait(
                    PauseJob(
                        job_id=meta.job_id,
                        event_generation=event_generation,
                    )
                )
        return True
    except BaseException as exc:
        if pause_commit_started:
            # The pause is fully committed and all queued tasks have been
            # joined. Propagate cancellation/failure loudly without
            # pretending the completed lifecycle transition was undone.
            raise
        child_rollback_error: BaseException | None = None
        for meta, prior_status in reversed(staged_children):
            try:
                await self._set_job_status(meta.job_id, prior_status)
            except BaseException as rollback_exc:  # noqa: BLE001 — retain child rollback failure for the aggregate exception below
                if child_rollback_error is None:
                    child_rollback_error = rollback_exc
        baton_rollback_error: BaseException | None = None
        for meta, paused, user_paused, _generation in reversed(changed_baton):
            baton_job = (
                self._baton_adapter._baton._jobs.get(meta.job_id)
                if self._baton_adapter is not None
                else None
            )
            if baton_job is not None:
                baton_job.paused = paused
                baton_job.user_paused = user_paused
                adapter = self._baton_adapter
                assert adapter is not None
                adapter._baton._state_dirty = True
            try:
                await self._set_job_status(meta.job_id, DaemonJobStatus.RUNNING)
            except BaseException as rollback_exc:  # noqa: BLE001 — retain baton rollback failure for the aggregate exception below
                if baton_rollback_error is None:
                    baton_rollback_error = rollback_exc
        for event in changed_events:
            event.clear()
        for signal_path in created_signals:
            try:
                signal_path.unlink(missing_ok=True)
            except OSError:
                _logger.error(
                    "schedule.pause_signal_rollback_failed",
                    path=str(signal_path),
                    exc_info=True,
                )
        if (
            pause_mutation_entered
            and authority is not None
            and authority.enabled
            and claims
        ):
            try:
                await controller.resume(
                    authority.schedule_id,
                    score_path=authority.score_path,
                    before_mutation=claim,
                )
            except BaseException as rollback_exc:  # noqa: BLE001 — report recurrence rollback failure with the original pause error
                raise RuntimeError(
                    f"Failed to pause active job {job_id!r}; recurrence rollback "
                    f"also failed: {rollback_exc}"
                ) from exc
        if baton_rollback_error is not None:
            raise RuntimeError(
                f"Failed to pause active job {job_id!r}; baton rollback "
                f"also failed: {baton_rollback_error}"
            ) from exc
        if child_rollback_error is not None:
            raise RuntimeError(
                f"Failed to pause active job {job_id!r}; child rollback "
                f"also failed: {child_rollback_error}"
            ) from exc
        raise
    finally:
        self._release_lifecycle_admission(claims)
        for owned_job_id in reversed(owned_job_ids):
            self._release_job_admission(owned_job_id)
resume_job async
resume_job(job_id, workspace=None, config_path=None, no_reload=False, from_sheet=None, escalation=False, self_healing=False)

Enable recurring ticks and resume active work when it is paused.

Source code in src/marianne/daemon/manager.py
async def resume_job(
    self,
    job_id: str,
    workspace: Path | None = None,
    config_path: Path | None = None,
    no_reload: bool = False,
    from_sheet: int | None = None,
    escalation: bool = False,
    self_healing: bool = False,
) -> JobResponse:
    """Enable recurring ticks and resume active work when it is paused."""
    # A fleet ID resumes the fleet (GH #515): every paused member, then any
    # dependent group that was dropped when a dependency member failed and
    # whose dependencies are success now (the member resubmitted under its
    # fleet-scoped ID, GH #514). No RPC or CLI word changes: `mzt resume
    # <fleet>` is the re-arm.
    # getattr: tests build the manager as MagicMock(spec=JobManager), which
    # has no instance attributes.
    if job_id in (getattr(self, "_fleet_records", None) or {}):
        from marianne.daemon.fleet import resume_fleet

        outcome = await resume_fleet(self, job_id)
        if "error" in outcome:
            return JobResponse(job_id=job_id, status="rejected", message=str(outcome["error"]))
        rearmed = outcome.get("rearmed") or []
        resumed = outcome.get("resumed") or {}
        return JobResponse(
            job_id=job_id,
            status="accepted",
            message=(
                f"Fleet '{job_id}': resumed {len(resumed)} member(s)"
                + (f"; re-armed dropped group(s) {', '.join(rearmed)}" if rearmed else "")
            ),
        )
    record = await JobManager._schedule_for_job(self, job_id)
    if record is None:
        return await JobManager._resume_active_job(
            self,
            job_id,
            workspace=workspace,
            config_path=config_path,
            no_reload=no_reload,
            from_sheet=from_sheet,
            escalation=escalation,
            self_healing=self_healing,
        )

    controller = getattr(self, "_recurrence_controller", None)
    assert controller is not None
    schedule_id = record.schedule_id
    active_statuses = {
        DaemonJobStatus.PENDING,
        DaemonJobStatus.QUEUED,
        DaemonJobStatus.RUNNING,
    }
    schedule_resumable_statuses = {
        DaemonJobStatus.PAUSED,
        DaemonJobStatus.PAUSED_AT_CHAIN,
    }
    related = self._schedule_related_meta(record)
    resumable = [
        meta for meta in related if meta.status in schedule_resumable_statuses
    ]
    held_chains = [
        meta
        for meta in resumable
        if meta.status is DaemonJobStatus.PAUSED_AT_CHAIN
        and meta.held_chain_hook is not None
    ]
    if len(held_chains) > 1:
        return JobResponse(
            job_id=job_id,
            status="rejected",
            message=(
                "Schedule has multiple held chains; resume each child "
                "explicitly to preserve chain ordering"
            ),
        )
    # A held chain submission is irreversible once accepted. Run ordinary
    # resumptions first and the sole held chain last, so no later child can
    # fail after its chained job has been published.
    resumable.sort(
        key=lambda meta: meta.status is DaemonJobStatus.PAUSED_AT_CHAIN
    )
    requested_meta = self._job_meta.get(job_id)
    if (
        requested_meta is not None
        and requested_meta in related
        and requested_meta.status
        in {DaemonJobStatus.FAILED, DaemonJobStatus.CANCELLED}
    ):
        resumable.append(requested_meta)
    active = [meta for meta in related if meta.status in active_statuses]
    admission_ids = sorted({meta.job_id for meta in resumable})
    if not admission_ids and not active:
        admission_ids = [job_id]
    owned_job_ids: list[str] = []
    for admission_id in admission_ids:
        if not self._try_reserve_job_admission(admission_id):
            for owned_job_id in reversed(owned_job_ids):
                self._release_job_admission(owned_job_id)
            raise JobSubmissionError(
                f"Score '{admission_id}' is already being submitted"
            )
        owned_job_ids.append(admission_id)

    claims: list[tuple[str, ...]] = []
    authority: ScheduleRecord | None = None
    mutation_entered = False
    lineage_ids: list[str] = []
    resumed_meta: list[JobMeta] = []

    def claim(schedule_ids: tuple[str, ...]) -> None:
        self._claim_lifecycle_admission(claims, schedule_ids)

    def capture_authority(current: ScheduleRecord) -> None:
        nonlocal authority, mutation_entered
        authority = current
        mutation_entered = True
        self._reserve_schedule_lineage(current.schedule_id)
        lineage_ids.append(current.schedule_id)

    async def compensate(original_exc: BaseException) -> None:
        """Restore active work and recurrence before surfacing a failed resume."""
        active_rollback_error: BaseException | None = None
        deferred_cancellation: asyncio.CancelledError | None = None
        if resumed_meta:
            rollback_task = asyncio.create_task(
                self._re_pause_resumed_jobs(resumed_meta),
                name=(
                    "schedule-resume-rollback-"
                    f"{authority.schedule_id if authority is not None else schedule_id}"
                ),
            )
            try:
                await asyncio.shield(rollback_task)
            except asyncio.CancelledError as cancel_exc:
                deferred_cancellation = cancel_exc
                try:
                    await rollback_task
                except BaseException as rollback_exc:  # noqa: BLE001 — retain active rollback failure for the aggregate exception below
                    active_rollback_error = rollback_exc
            except BaseException as rollback_exc:  # noqa: BLE001 — retain active rollback failure for the aggregate exception below
                active_rollback_error = rollback_exc

        recurrence_rollback_error: BaseException | None = None
        if mutation_entered and authority is not None and not authority.enabled:
            try:
                await controller.pause(
                    authority.schedule_id,
                    score_path=authority.score_path,
                    before_mutation=claim,
                )
            except BaseException as rollback_exc:  # noqa: BLE001 — retain recurrence rollback failure for the aggregate exception below
                recurrence_rollback_error = rollback_exc

        if (
            active_rollback_error is not None
            or recurrence_rollback_error is not None
        ):
            details: list[str] = []
            if active_rollback_error is not None:
                details.append(f"active rollback failed: {active_rollback_error}")
            if recurrence_rollback_error is not None:
                details.append(
                    f"recurrence rollback failed: {recurrence_rollback_error}"
                )
            raise RuntimeError(
                f"Failed to resume active job {job_id!r}; " + "; ".join(details)
            ) from original_exc
        if deferred_cancellation is not None:
            raise deferred_cancellation

    try:
        try:
            await controller.resume(
                schedule_id,
                score_path=record.score_path,
                before_mutation=claim,
                on_authority=capture_authority,
            )
            if not resumable:
                return JobResponse(
                    job_id=job_id,
                    status="accepted",
                    message="Recurring schedule resumed",
                )
            response: JobResponse | None = None
            for resumable_meta in resumable:
                is_requested = resumable_meta.job_id == job_id
                response = await JobManager._resume_active_job(
                    self,
                    resumable_meta.job_id,
                    workspace=workspace if is_requested else None,
                    config_path=config_path if is_requested else None,
                    no_reload=no_reload,
                    from_sheet=from_sheet if is_requested else None,
                    escalation=escalation if is_requested else False,
                    self_healing=self_healing if is_requested else False,
                )
                if response.status != "accepted":
                    await compensate(
                        JobSubmissionError(
                            response.message
                            or f"Resume of {resumable_meta.job_id!r} was rejected"
                        )
                    )
                    return response
                resumed_meta.append(resumable_meta)
            assert response is not None
            return response
        except BaseException as exc:
            await compensate(exc)
            raise
        finally:
            for lineage_id in reversed(lineage_ids):
                self._release_schedule_lineage(lineage_id)
    finally:
        self._release_lifecycle_admission(claims)
        for owned_job_id in reversed(owned_job_ids):
            self._release_job_admission(owned_job_id)
modify_job async
modify_job(job_id, config_path, workspace=None)

Pause a running job and queue automatic resume with new config.

If the job is already paused/failed/cancelled, resume immediately. If running, send pause signal and store pending_modify — _on_task_done will trigger the resume when the task completes (pauses).

Source code in src/marianne/daemon/manager.py
async def modify_job(
    self,
    job_id: str,
    config_path: Path,
    workspace: Path | None = None,
) -> JobResponse:
    """Pause a running job and queue automatic resume with new config.

    If the job is already paused/failed/cancelled, resume immediately.
    If running, send pause signal and store pending_modify — _on_task_done
    will trigger the resume when the task completes (pauses).
    """
    meta = self._job_meta.get(job_id)
    if meta is None:
        raise JobSubmissionError(f"Job '{job_id}' not found")

    ws = workspace or meta.workspace

    # Already resumable — resume immediately with new config
    _resumable = (
        DaemonJobStatus.PAUSED,
        DaemonJobStatus.FAILED,
        DaemonJobStatus.CANCELLED,
    )
    if meta.status in _resumable:
        meta.config_path = config_path
        return await self.resume_job(job_id, ws)

    if meta.status != DaemonJobStatus.RUNNING:
        raise JobSubmissionError(f"Job '{job_id}' is {meta.status.value}, cannot modify")

    # Send pause signal
    await self.pause_job(job_id)

    # Store pending action — _on_task_done will resume when the job pauses
    meta.pending_modify = (config_path, ws)

    # Baton path: the old task sits on wait_for_completion() and won't
    # exit just because the baton paused dispatch. Cancel the task so
    # _on_task_done fires and triggers the deferred resume.
    if self._baton_adapter is not None:
        old_task = self._jobs.get(job_id)
        if old_task is not None and not old_task.done():
            old_task.cancel(msg=f"modify: paused for config reload on {job_id}")
            _logger.info("job.modify_cancelled_baton_task", job_id=job_id)

    return JobResponse(
        job_id=job_id,
        status="accepted",
        message=f"Pause signal sent. Will resume with {config_path.name} when paused.",
    )
cancel_job async
cancel_job(job_id, *, source='unknown', expected_source_digest=None, expected_registration_id=None, require_schedule=False)

Cancel active work and remove its recurrence, when present.

Source code in src/marianne/daemon/manager.py
async def cancel_job(
    self, job_id: str, *, source: str = "unknown",
    expected_source_digest: str | None = None,
    expected_registration_id: str | None = None,
    require_schedule: bool = False,
) -> bool:
    """Cancel active work and remove its recurrence, when present."""
    record = await JobManager._schedule_for_job(self, job_id)
    if record is None:
        if require_schedule:
            raise JobSubmissionError("Bound schedule disappeared before cancellation")
        if not self._try_reserve_job_admission(job_id, allow_active=True):
            raise JobSubmissionError(
                f"Score '{job_id}' is already being submitted"
            )
        try:
            return await self._cancel_active_job(job_id, source=source)
        finally:
            self._release_job_admission(job_id)

    controller = getattr(self, "_recurrence_controller", None)
    assert controller is not None
    claims: list[tuple[str, ...]] = []
    owned_job_ids: list[str] = []
    removal_entered = False

    def claim(schedule_ids: tuple[str, ...]) -> None:
        self._claim_lifecycle_admission(claims, schedule_ids)

    def capture_authority(current: ScheduleRecord) -> None:
        nonlocal removal_entered
        if (expected_source_digest is not None
                and current.source_digest != expected_source_digest):
            raise JobSubmissionError("Bound schedule digest changed before cancellation")
        if (expected_registration_id is not None
                and current.registration_id != expected_registration_id):
            raise JobSubmissionError("Bound registration changed before cancellation")
        self._claim_related_job_admissions(current, owned_job_ids)
        removal_entered = True

    try:
        removal_error: BaseException | None = None
        try:
            record = await controller.remove(
                record.schedule_id,
                score_path=record.score_path,
                before_mutation=claim,
                on_authority=capture_authority,
            )
        except BaseException as exc:
            if not removal_entered:
                raise
            # Removal failure must never leave future autonomous work enabled.
            # A durable pause is the safe degraded state and the original
            # removal error remains loud to the caller.
            try:
                await controller.pause(
                    record.schedule_id,
                    score_path=record.score_path,
                    before_mutation=claim,
                )
            except BaseException as safety_exc:  # noqa: BLE001 — retain safety-pause failure until shielded cancellation finishes
                removal_error = RuntimeError(
                    f"Failed to remove recurrence for {job_id!r}; safety pause "
                    f"also failed: {safety_exc}"
                )
                removal_error.__cause__ = exc
            else:
                removal_error = exc

        async def finish_cancellation() -> None:
            await self._cancel_schedule_related(record, source=source)
            token = getattr(record, "registration_id", None)
            if removal_error is None and isinstance(token, str) and token:
                await self._schedule_registry.record_terminal(
                    token, record.schedule_id, record.source_digest,
                )

        cleanup = asyncio.create_task(
            finish_cancellation(),
            name=f"schedule-cancel-{record.schedule_id}",
        )
        try:
            await asyncio.shield(cleanup)
        except asyncio.CancelledError:
            # Command cancellation may cancel the waiter, never the safety
            # work: recurrence is already removed/paused and every child
            # must reach CANCELLED before schedule admission is released.
            await cleanup
            raise
        if removal_error is not None:
            raise removal_error
        return True
    finally:
        self._release_lifecycle_admission(claims)
        for owned_job_id in reversed(owned_job_ids):
            self._release_job_admission(owned_job_id)
register_schedule async
register_schedule(config_path, *, registration_id=None)

Register a recurring source and expose its daemon-accepted bytes.

Source code in src/marianne/daemon/manager.py
async def register_schedule(
    self, config_path: Path, *, registration_id: str | None = None,
) -> dict[str, Any]:
    """Register a recurring source and expose its daemon-accepted bytes."""
    try:
        identity = await self._schedule_registry.identity()
    except ScheduleRegistryBusyError:
        return self._schedule_venue_result("", "", "inconclusive", "registry_busy")
    except ScheduleRegistryDataError:
        return self._schedule_venue_result("", "", "inconclusive", "damaged_state")
    controller = self._recurrence_controller
    if controller is None:
        return self._schedule_venue_result(identity, "", "inconclusive", "registry_busy")
    claims: list[tuple[str, ...]] = []
    try:
        record = await controller.register(
            config_path,
            before_wait=self._schedule_admission_available,
            before_mutation=lambda ids: self._claim_lifecycle_admission(claims, ids),
            require_schedule=True,
            registration_id=registration_id,
        )
        if record is None:
            return self._schedule_venue_result(identity, "", "inconclusive", "no_schedule")
        return self._schedule_venue_result(
            identity, record.schedule_id,
            "live" if record.enabled else "disabled",
            source_digest=record.source_digest,
            pinned_source_digest=record.pinned_source_digest,
        )
    except ScheduleRegistryBusyError:
        return self._schedule_venue_result(identity, "", "inconclusive", "registry_busy")
    except ScheduleRegistryDataError:
        return self._schedule_venue_result(identity, "", "inconclusive", "damaged_state")
    finally:
        self._release_lifecycle_admission(claims)
register_schedule_v2 async
register_schedule_v2(config_path)

Mint one durable caller-held receipt in the registration transaction.

Source code in src/marianne/daemon/manager.py
async def register_schedule_v2(self, config_path: Path) -> dict[str, Any]:
    """Mint one durable caller-held receipt in the registration transaction."""
    token = uuid4().hex
    try:
        result = await self.register_schedule(config_path, registration_id=token)
    except ScheduleRegistryError:
        return self._schedule_venue_result("", "", "inconclusive", "damaged_state")
    result["receipt_version"] = 2
    if result["state"] in {"live", "disabled"}:
        result["registration_id"] = token
    return result
current_schedule_v2 async
current_schedule_v2(schedule_id, registry_identity, source_digest, registration_id, receipt_version)

A row or terminal must match the caller's exact v2 receipt.

Source code in src/marianne/daemon/manager.py
async def current_schedule_v2(
    self, schedule_id: str, registry_identity: str, source_digest: str,
    registration_id: str, receipt_version: int,
) -> dict[str, Any]:
    """A row or terminal must match the caller's exact v2 receipt."""
    if receipt_version != 2 or not registration_id:
        return self._schedule_venue_result(
            registry_identity, schedule_id, "inconclusive", "invalid_receipt"
        )
    try:
        result = await self.current_schedule(schedule_id, registry_identity, source_digest)
    except ScheduleRegistryError:
        return self._schedule_venue_result(
            registry_identity, schedule_id, "inconclusive", "damaged_state"
        )
    result["receipt_version"] = 2
    if result["state"] == "inconclusive":
        return result
    try:
        record = await self._schedule_registry.get(schedule_id)
        if record is not None:
            if record.registration_id != registration_id:
                result.update(state="inconclusive", reason="registration_changed")
            else:
                result["registration_id"] = registration_id
            return result
        terminal = await self._schedule_registry.terminal_for(registration_id)
    except ScheduleRegistryBusyError:
        result.update(state="inconclusive", reason="registry_busy")
        return result
    except ScheduleRegistryDataError:
        result.update(state="inconclusive", reason="damaged_state")
        return result
    except ScheduleRegistryError:
        result.update(state="inconclusive", reason="damaged_state")
        return result
    if terminal != (schedule_id, registry_identity, source_digest):
        result.update(state="inconclusive", reason="receipt_not_found")
    else:
        result["registration_id"] = registration_id
    return result
current_schedule async
current_schedule(schedule_id, registry_identity, source_digest)

Read one exact schedule from one durable venue; uncertainty stays typed.

Source code in src/marianne/daemon/manager.py
async def current_schedule(
    self, schedule_id: str, registry_identity: str, source_digest: str,
) -> dict[str, Any]:
    """Read one exact schedule from one durable venue; uncertainty stays typed."""
    try:
        actual = await self._schedule_registry.identity()
    except ScheduleRegistryBusyError:
        return self._schedule_venue_result(
            registry_identity, schedule_id, "inconclusive", "registry_busy"
        )
    except ScheduleRegistryDataError:
        return self._schedule_venue_result(
            registry_identity, schedule_id, "inconclusive", "damaged_state"
        )
    if actual != registry_identity:
        return self._schedule_venue_result(
            actual, schedule_id, "inconclusive", "identity_mismatch"
        )
    if not schedule_id or not source_digest:
        return self._schedule_venue_result(
            actual, schedule_id, "inconclusive", "digest_mismatch"
        )
    try:
        record = await self._schedule_registry.get(schedule_id)
    except ScheduleRegistryBusyError:
        return self._schedule_venue_result(actual, schedule_id, "inconclusive", "registry_busy")
    except ScheduleRegistryDataError:
        return self._schedule_venue_result(actual, schedule_id, "inconclusive", "damaged_state")
    if record is not None and record.source_digest != source_digest:
        return self._schedule_venue_result(
            actual, schedule_id, "inconclusive", "digest_mismatch"
        )
    if self._is_schedule_active(schedule_id):
        state = "running"
    elif record is None:
        state = "not_registered"
    else:
        state = "live" if record.enabled else "disabled"
    return self._schedule_venue_result(
        actual, schedule_id, state, source_digest=source_digest,
        pinned_source_digest=record.pinned_source_digest if record else None,
    )
cancel_schedule async
cancel_schedule(schedule_id, registry_identity, source_digest)

Cancel a bound schedule with a digest check inside lifecycle ownership.

Source code in src/marianne/daemon/manager.py
async def cancel_schedule(
    self, schedule_id: str, registry_identity: str, source_digest: str,
) -> dict[str, Any]:
    """Cancel a bound schedule with a digest check inside lifecycle ownership."""
    before = await self.current_schedule(schedule_id, registry_identity, source_digest)
    if before["state"] == "inconclusive":
        return before
    if before["state"] == "not_registered":
        return before
    try:
        await self.cancel_job(
            schedule_id, source="schedule.cancel",
            expected_source_digest=source_digest, require_schedule=True,
        )
    except ScheduleRegistryDataError:
        return self._schedule_venue_result(
            registry_identity, schedule_id, "inconclusive", "damaged_state"
        )
    except (JobSubmissionError, ScheduleRegistryBusyError):
        return self._schedule_venue_result(
            registry_identity, schedule_id, "inconclusive", "race"
        )
    after = await self.current_schedule(schedule_id, registry_identity, source_digest)
    after["cancelled"] = after["state"] == "not_registered"
    return after
list_jobs async
list_jobs()

List all jobs with live progress data.

In-memory _job_meta is authoritative for active jobs. Live state from _live_states enriches active entries with sheet-level progress so mzt list shows completion counts. The registry fills in historical jobs.

Source code in src/marianne/daemon/manager.py
async def list_jobs(self) -> list[dict[str, Any]]:
    """List all jobs with live progress data.

    In-memory ``_job_meta`` is authoritative for active jobs.
    Live state from ``_live_states`` enriches active entries with
    sheet-level progress so ``mzt list`` shows completion counts.
    The registry fills in historical jobs.
    """
    seen: set[str] = set()
    result: list[dict[str, Any]] = []
    recurrence_controller = getattr(self, "_recurrence_controller", None)
    schedule_records = (
        await recurrence_controller.describe()
        if recurrence_controller is not None
        else []
    )
    schedule_index = self._build_schedule_index(schedule_records)
    represented_schedules: set[str] = set()
    registry_records = {
        record.job_id: record
        for record in await self._registry.list_jobs()
    }

    # Active jobs first — enrich with live progress. Terminal in-memory
    # metadata is only a cache; direct recovery can repair the registry
    # without mutating this process' stale JobMeta (#391).
    for meta in self._job_meta.values():
        if meta.status in _ACTIVE_DAEMON_STATUSES:
            entry = meta.to_dict()
            live = self._live_states.get(meta.job_id)
            if live is not None:
                completed = sum(
                    1 for s in live.sheets.values()
                    if s.status.value == "completed"
                )
                entry["progress_completed"] = completed
                entry["progress_total"] = len(live.sheets)
        elif meta.job_id in registry_records:
            entry = registry_records[meta.job_id].to_dict()
        else:
            entry = meta.to_dict()
        merged = await self._merge_schedule_status(
            meta.job_id,
            entry,
            index=schedule_index,
        )
        result.append(merged)
        matched = await self._schedule_for_job(meta.job_id, index=schedule_index)
        if matched is not None and self._is_stable_schedule_anchor(
            meta.job_id,
            matched,
        ):
            represented_schedules.add(matched.schedule_id)
        seen.add(meta.job_id)

    # Historical jobs from registry
    for record in registry_records.values():
        if record.job_id not in seen:
            merged = await self._merge_schedule_status(
                record.job_id,
                record.to_dict(),
                index=schedule_index,
            )
            result.append(merged)
            matched = await self._schedule_for_job(
                record.job_id,
                config_path=Path(record.config_path),
                index=schedule_index,
            )
            if matched is not None and self._is_stable_schedule_anchor(
                record.job_id,
                matched,
            ):
                represented_schedules.add(matched.schedule_id)

    for schedule_record in schedule_index.records:
        if schedule_record.schedule_id not in represented_schedules:
            result.append(self._schedule_anchor_status(schedule_record))

    return result
clear_jobs async
clear_jobs(statuses=None, older_than_seconds=None, job_ids=None)

Clear terminal jobs from registry and in-memory metadata.

Parameters:

Name Type Description Default
statuses list[str] | None

Status filter (defaults to terminal statuses).

None
older_than_seconds float | None

Age filter in seconds.

None
job_ids list[str] | None

Only clear these specific job IDs.

None

Returns:

Type Description
dict[str, Any]

Dict with "deleted" count.

Source code in src/marianne/daemon/manager.py
async def clear_jobs(
    self,
    statuses: list[str] | None = None,
    older_than_seconds: float | None = None,
    job_ids: list[str] | None = None,
) -> dict[str, Any]:
    """Clear terminal jobs from registry and in-memory metadata.

    Args:
        statuses: Status filter (defaults to terminal statuses).
        older_than_seconds: Age filter in seconds.
        job_ids: Only clear these specific job IDs.

    Returns:
        Dict with "deleted" count.
    """
    safe_statuses = set(statuses or ["completed", "failed", "cancelled"])
    safe_statuses -= {"queued", "running", "pending"}  # Never clear active jobs

    to_remove: list[str] = []
    now = time.time()
    for jid, meta in self._job_meta.items():
        if job_ids is not None and jid not in job_ids:
            continue
        if meta.status.value not in safe_statuses:
            continue
        if older_than_seconds is not None:
            if (now - meta.submitted_at) < older_than_seconds:
                continue
        to_remove.append(jid)

    # #111: capture workspaces BEFORE popping so we can also remove the
    # cleared jobs' workspace state below (the registry row + in-memory
    # entry going away isn't enough — stale workspace state would otherwise
    # be resurrected by a later offline read or re-submit).
    to_clean: list[tuple[str, Path, str]] = []
    for jid in to_remove:
        removed_meta = self._job_meta.get(jid)
        if removed_meta is not None:
            from marianne.daemon.baton.pass_ledger import scope_for

            scope = scope_for(removed_meta.config_path, jid)
            to_clean.append((jid, removed_meta.workspace, scope))
        self._job_meta.pop(jid, None)
        self._live_states.pop(jid, None)

    deleted = await self._registry.delete_jobs(
        job_ids=job_ids,
        statuses=list(safe_statuses),
        older_than_seconds=older_than_seconds,
    )

    # #111: remove each cleared job's workspace state (per job, so a shared
    # workspace keeps other jobs' rows). Best-effort; never fails the clear.
    for jid, ws, scope in to_clean:
        await self._delete_workspace_state(jid, ws, ledger_scope=scope)

    _logger.info(
        "manager.clear_jobs",
        in_memory_removed=len(to_remove),
        registry_deleted=deleted,
    )
    return {"deleted": deleted}
clear_rate_limits async
clear_rate_limits(instrument=None)

Clear active rate limits from the coordinator and baton.

Removes the active rate limit so new sheets can be dispatched immediately. Clears both the RateLimitCoordinator (used by the legacy runner and scheduler) and the baton's per-instrument InstrumentState (used by the baton dispatch loop).

Parameters:

Name Type Description Default
instrument str | None

Instrument name to clear, or None for all.

None

Returns:

Type Description
dict[str, Any]

Dict with cleared count and instrument filter.

Source code in src/marianne/daemon/manager.py
async def clear_rate_limits(
    self,
    instrument: str | None = None,
) -> dict[str, Any]:
    """Clear active rate limits from the coordinator and baton.

    Removes the active rate limit so new sheets can be dispatched
    immediately.  Clears both the ``RateLimitCoordinator`` (used by
    the legacy runner and scheduler) and the baton's per-instrument
    ``InstrumentState`` (used by the baton dispatch loop).

    Args:
        instrument: Instrument name to clear, or ``None`` for all.

    Returns:
        Dict with ``cleared`` count and ``instrument`` filter.
    """
    cleared = await self.rate_coordinator.clear_limits(
        instrument=instrument,
    )
    baton_cleared = 0
    if self._baton_adapter is not None:
        baton_cleared = self._baton_adapter.clear_instrument_rate_limit(
            instrument,
        )
        # Kick the baton event loop so dispatch_ready() runs for the
        # newly-PENDING sheets. Without this, the loop blocks on
        # inbox.get() and cleared sheets sit idle until an unrelated
        # event arrives.
        from marianne.daemon.baton.events import DispatchRetry

        self._baton_adapter._baton.inbox.put_nowait(DispatchRetry())
    _logger.info(
        "manager.clear_rate_limits",
        instrument=instrument,
        coordinator_cleared=cleared,
        baton_cleared=baton_cleared,
    )
    # Start any pending jobs now that limits are cleared
    await self._start_pending_jobs()
    return {
        "cleared": cleared + baton_cleared,
        "instrument": instrument,
    }
get_job_errors async
get_job_errors(job_id, workspace=None)

Get errors for a specific job.

Returns the CheckpointState for the CLI to extract error information. Uses the same resolution as get_job_status: live state first, then registry, never workspace files.

Source code in src/marianne/daemon/manager.py
async def get_job_errors(self, job_id: str, workspace: Path | None = None) -> dict[str, Any]:
    """Get errors for a specific job.

    Returns the CheckpointState for the CLI to extract error information.
    Uses the same resolution as get_job_status: live state first, then
    registry, never workspace files.
    """
    _ = workspace  # Conductor DB is the sole source of truth
    state_dict = await self.get_job_status(job_id)
    return {"state": state_dict}
get_diagnostic_report async
get_diagnostic_report(job_id, workspace=None)

Get diagnostic data for a specific job.

Returns the CheckpointState plus workspace path. Uses the same resolution as get_job_status: live state first, then registry.

Source code in src/marianne/daemon/manager.py
async def get_diagnostic_report(
    self,
    job_id: str,
    workspace: Path | None = None,
) -> dict[str, Any]:
    """Get diagnostic data for a specific job.

    Returns the CheckpointState plus workspace path. Uses the same
    resolution as get_job_status: live state first, then registry.
    """
    ws = await self._resolve_job_workspace(job_id, workspace)
    state_dict = await self.get_job_status(job_id)
    return {
        "state": state_dict,
        "workspace": str(ws),
    }
get_execution_history async
get_execution_history(job_id, workspace=None, sheet_num=None, limit=50)

Per-attempt history for a job, read from its checkpoint (GH #488).

Each sheet's attempt_history is written on every attempt and persisted with the checkpoint, so history needs no second store.

Source code in src/marianne/daemon/manager.py
async def get_execution_history(
    self,
    job_id: str,
    workspace: Path | None = None,
    sheet_num: int | None = None,
    limit: int = 50,
) -> dict[str, Any]:
    """Per-attempt history for a job, read from its checkpoint (GH #488).

    Each sheet's ``attempt_history`` is written on every attempt and
    persisted with the checkpoint, so history needs no second store.
    """
    from marianne.core.checkpoint import (
        CheckpointState,
        execution_history_records,
    )

    status = await self.get_job_status(job_id, workspace)
    records: list[dict[str, Any]] = []
    has_history = False
    if isinstance(status, dict) and isinstance(status.get("sheets"), dict):
        state = CheckpointState.model_validate(status)
        records = execution_history_records(state, sheet_num, limit)
        has_history = True
    return {
        "job_id": job_id,
        "records": records,
        "has_history": has_history,
    }
recover_job async
recover_job(job_id, workspace=None, sheet_num=None, dry_run=False)

Get state for recover operation.

Returns the job state and workspace for the CLI to run validations locally. The actual validation logic stays in the CLI command to avoid duplicating ValidationEngine setup in the daemon.

Source code in src/marianne/daemon/manager.py
async def recover_job(
    self,
    job_id: str,
    workspace: Path | None = None,
    sheet_num: int | None = None,
    dry_run: bool = False,
) -> dict[str, Any]:
    """Get state for recover operation.

    Returns the job state and workspace for the CLI to run
    validations locally. The actual validation logic stays
    in the CLI command to avoid duplicating ValidationEngine
    setup in the daemon.
    """
    ws = await self._resolve_job_workspace(job_id, workspace)
    # #111: read the authoritative daemon DB, not per-workspace state. Baton
    # jobs don't write workspace state, so the old get_status() read empty
    # (and created an empty workspace .marianne-state.db as a side effect).
    state = await self._load_checkpoint(job_id, ws)
    if state is None:
        raise JobSubmissionError(f"No state found for job '{job_id}'")

    return {
        "state": state.model_dump(mode="json"),
        "workspace": str(ws),
        "dry_run": dry_run,
        "sheet_num": sheet_num,
    }
resolve_escalation async
resolve_escalation(job_id, sheet_num, decision)

Resolve a FERMATA sheet via IPC (#361, backs mzt resolve).

Delegates to the baton adapter, which writes the decision marker and triggers immediate consumption through the existing poll path.

Source code in src/marianne/daemon/manager.py
async def resolve_escalation(
    self, job_id: str, sheet_num: int, decision: str
) -> dict[str, Any]:
    """Resolve a FERMATA sheet via IPC (#361, backs ``mzt resolve``).

    Delegates to the baton adapter, which writes the decision marker
    and triggers immediate consumption through the existing poll path.
    """
    if self._baton_adapter is None:
        return {"resolved": False, "message": "Baton adapter not initialized"}
    ok, message = self._baton_adapter.resolve_fermata(
        job_id, sheet_num, decision
    )
    return {"resolved": ok, "message": message}
get_daemon_status async
get_daemon_status()

Build daemon status summary.

Returns all fields required by the DaemonStatus Pydantic model so DaemonClient.status() can deserialize without crashing.

Source code in src/marianne/daemon/manager.py
async def get_daemon_status(self) -> dict[str, Any]:
    """Build daemon status summary.

    Returns all fields required by the ``DaemonStatus`` Pydantic model
    so ``DaemonClient.status()`` can deserialize without crashing.
    """
    from marianne.daemon.ipc.protocol import PROTOCOL_VERSION

    mem = self._monitor.current_memory_mb()
    model_concurrency: dict[str, int] = {}
    if self._baton_adapter is not None:
        model_concurrency = self._baton_adapter.model_concurrency_snapshot()
    return {
        "pid": os.getpid(),
        "uptime_seconds": round(time.monotonic() - self._start_time, 1),
        "running_jobs": self.running_count,
        "total_jobs_active": self.active_job_count,
        "memory_usage_mb": round(mem, 1) if mem is not None else 0.0,
        "version": getattr(marianne, "__version__", "0.1.0"),
        "protocol_version": PROTOCOL_VERSION,
        # #408: hot-reload observability.
        "config_generation": self._config_generation,
        "config_loaded_at": self._config_loaded_at,
        "last_config_reload": (
            self._last_reload_result.model_dump()
            if self._last_reload_result is not None
            else None
        ),
        "model_concurrency": model_concurrency,
    }
shutdown async
shutdown(graceful=True)

Cancel all running jobs, optionally waiting for sheets.

Deregisters all active jobs from the global sheet scheduler to clean up any pending sheets, running-sheet tracking, and dependency data before the daemon exits.

Source code in src/marianne/daemon/manager.py
async def shutdown(self, graceful: bool = True) -> None:
    """Cancel all running jobs, optionally waiting for sheets.

    Deregisters all active jobs from the global sheet scheduler
    to clean up any pending sheets, running-sheet tracking, and
    dependency data before the daemon exits.
    """
    self._shutting_down = True

    # Revoke recurrence-owned handles before waiting for jobs. This blocks
    # new ticks throughout the shutdown window and, critically, before the
    # TimerWheel drains non-cancelled events after ShutdownRequested.
    if self._recurrence_controller is not None:
        try:
            await self._recurrence_controller.shutdown()
        except Exception:  # noqa: BLE001 — structured logger reports manager.recurrence_stop_failed
            _logger.warning(
                "manager.recurrence_stop_failed",
                exc_info=True,
            )

    if graceful:
        timeout = self._config.shutdown_timeout_seconds
        # Name what the drain waits on (GH #476): a PAUSED job whose pause
        # is still pending keeps a musician in flight, and running_jobs=0
        # alone made a 300 s drain look like a hang.
        _logger.info(
            "manager.shutting_down",
            graceful=True,
            timeout=timeout,
            running_jobs=self.running_count,
            in_flight=self.in_flight_sheets,
        )

        # Wait for running tasks to complete (up to timeout). A PAUSED
        # job whose musicians have all settled is already at rest: its
        # task waits for a resume that cannot arrive during shutdown, so
        # waiting on it only burns the whole timeout (Pallas 2026-10-21:
        # two restarts each took exactly 300 s with running_jobs=0). It
        # is cancelled below with the rest and stays PAUSED on disk.
        # GH #476 gap 2: a job paused at a sheet boundary keeps its current
        # sheet in flight until the musician ends, yet that sheet is
        # discarded and re-run on resume by design. Waiting the whole
        # budget for it buys nothing (Pallas 21 Oct and 22 Oct: eight and
        # four boundary-paused jobs each held a 300 s drain). End those
        # musicians now; the pause stays on disk and resume re-runs the
        # sheet. RUNNING jobs still get the full drain.
        ended = self._end_boundary_paused_musicians()
        if ended:
            _logger.info(
                "manager.shutdown_ended_boundary_paused_sheets",
                sheets=ended,
            )
        running = [
            t for job_id, t in self._jobs.items()
            if not t.done() and not self._is_settled_pause(job_id)
        ]
        if running:
            _, pending = await asyncio.wait(
                running,
                timeout=timeout,
            )
            if pending:
                _logger.warning(
                    "manager.shutdown_timeout_exceeded",
                    timeout=timeout,
                    held_by=self.in_flight_sheets,
                )
            for task in pending:
                task.cancel(msg="graceful shutdown timeout exceeded")
            if pending:
                results = await asyncio.gather(*pending, return_exceptions=True)
                for result in results:
                    if isinstance(result, BaseException):
                        _logger.warning(
                            "manager.shutdown_task_exception",
                            error=str(result),
                            error_type=type(result).__name__,
                        )
        settled = [
            t for job_id, t in self._jobs.items()
            if not t.done() and self._is_settled_pause(job_id)
        ]
        for task in settled:
            task.cancel(msg="graceful shutdown: paused job at rest")
        if settled:
            await asyncio.gather(*settled, return_exceptions=True)
            _logger.info("manager.shutdown_settled_pauses", count=len(settled))
    else:
        _logger.info("manager.shutting_down", graceful=False)
        for task in self._jobs.values():
            if not task.done():
                task.cancel(msg="non-graceful shutdown")
        if self._jobs:
            results = await asyncio.gather(
                *self._jobs.values(),
                return_exceptions=True,
            )
            for result in results:
                if isinstance(result, BaseException):
                    _logger.warning(
                        "manager.shutdown_task_exception",
                        error=str(result),
                        error_type=type(result).__name__,
                    )

    await self._settle_failure_hook_tasks(graceful=graceful)

    # Deregister all known jobs from the scheduler to clean up
    # heap entries, running-sheet tracking, and dependency data.
    # Uses _job_meta (not _jobs) because task done-callbacks may
    # have already cleared entries from _jobs during cancellation.
    # Guard: only touch the scheduler if it was ever initialized.
    if self._scheduler_instance is not None:
        for job_id in list(self._job_meta.keys()):
            await self._scheduler_instance.deregister_job(job_id)

    self._jobs.clear()

    # Stop the baton adapter: send ShutdownRequested, wait for the
    # event loop to exit, cancel if it doesn't, close backend pool.
    if self._baton_adapter is not None:
        try:
            from marianne.daemon.baton.events import ShutdownRequested

            self._baton_adapter._baton.inbox.put_nowait(ShutdownRequested(graceful=graceful))
            # Wait for the baton loop to exit (bounded by 5s)
            if self._baton_loop_task is not None and not self._baton_loop_task.done():
                try:
                    await asyncio.wait_for(self._baton_loop_task, timeout=5.0)
                except (TimeoutError, asyncio.CancelledError):
                    self._baton_loop_task.cancel()
                    try:
                        await self._baton_loop_task
                    except (asyncio.CancelledError, Exception):  # noqa: BLE001 — shutdown must finish
                        _logger.warning("manager.baton_loop_shutdown_error", exc_info=True)
            # Cancel any remaining musician tasks
            await self._baton_adapter.shutdown()
            _logger.info("manager.baton_adapter_stopped")
        except Exception:  # noqa: BLE001 — structured logger reports manager.baton_adapter_stop_failed
            _logger.warning(
                "manager.baton_adapter_stop_failed",
                exc_info=True,
            )

    if self._mcp_pool is not None:
        try:
            await self._mcp_pool.stop_all()
        except Exception:  # noqa: BLE001 — structured logger reports manager.mcp_pool_stop_failed
            _logger.warning("manager.mcp_pool_stop_failed", exc_info=True)
        finally:
            self._mcp_pool = None

    if self._memory_gate is not None:
        try:
            await self._memory_gate.shutdown()
        except Exception:  # noqa: BLE001 — structured logger reports manager.memory_gate_stop_failed
            _logger.warning("manager.memory_gate_stop_failed", exc_info=True)
        finally:
            self._memory_gate = None

    # Stop all observers for any remaining jobs
    for jid in list(self._job_meta.keys()):
        await self._stop_observer(jid)

    if self._orchestra is not None:
        try:
            await self._orchestra.stop(self._event_bus)
        except (OSError, RuntimeError):
            _logger.warning("manager.orchestra_stop_failed", exc_info=True)

    # Stop observer recorder before event bus (needs bus for unsubscribe).
    if self._observer_recorder is not None:
        try:
            await self._observer_recorder.stop(self._event_bus)
        except (OSError, RuntimeError):
            _logger.warning(
                "manager.observer_recorder_stop_failed",
                exc_info=True,
            )

    # #203: stop the judgment client before the event bus (unsubscribe);
    # in-flight judgments are cancelled — affected sheets simply remain
    # in composer-resolvable FERMATA.
    if self._judgment_client is not None:
        try:
            await self._judgment_client.stop(self._event_bus)
        except asyncio.CancelledError:
            raise
        except Exception:  # noqa: BLE001 — structured logger reports manager.judgment_client_stop_failed
            _logger.warning(
                "manager.judgment_client_stop_failed", exc_info=True
            )

    # Stop semantic analyzer before event bus (needs bus for unsubscribe,
    # and learning hub for final writes during drain).
    if self._semantic_analyzer is not None:
        try:
            await self._semantic_analyzer.stop(self._event_bus)
        except asyncio.CancelledError:
            raise
        except (OSError, RuntimeError):
            _logger.warning(
                "manager.semantic_analyzer_stop_failed",
                exc_info=True,
            )

    # Shutdown event bus
    await self._event_bus.shutdown()

    # Stop centralized learning hub (final persist + cleanup)
    await self._learning_hub.stop()

    # GH #412: everything from here on must not be able to strand the
    # process. If the final flush or a registry close raises, the event
    # is still set so DaemonProcess.run() proceeds to teardown instead of
    # parking forever on wait_for_shutdown() with the IPC socket still
    # answering (a zombie conductor that only SIGKILL clears).
    try:
        # #111: stop the ordered checkpoint writer BEFORE the final flush,
        # so the synchronous flush below is the authoritative last write.
        # Any snapshots still queued in the writer are superseded by that
        # flush (which serialises the latest in-memory state), so they are
        # dropped rather than drained — preventing an older queued blob
        # from landing after the newest one.
        if self._checkpoint_writer is not None:
            await self._checkpoint_writer.stop()
            self._checkpoint_writer = None

        # Final checkpoint flush: persist live states to registry before
        # closing. Active states preserve progress; terminal states are
        # skipped if direct recovery already wrote a newer registry
        # checkpoint (#391).
        flushed, skipped_newer_registry = (
            await self._flush_live_checkpoints_on_shutdown()
        )
        if flushed:
            _logger.info("manager.shutdown_checkpoint_flush", flushed=flushed)
        if skipped_newer_registry:
            _logger.info(
                "manager.shutdown_checkpoint_flush_skipped_newer_registry",
                skipped=skipped_newer_registry,
            )
    except Exception:
        _logger.error("manager.shutdown_final_flush_failed", exc_info=True)
    finally:
        for name, registry in (
            ("schedule_registry", self._schedule_registry),
            ("registry", self._registry),
        ):
            try:
                await registry.close()
            except Exception:
                _logger.error(
                    "manager.shutdown_registry_close_failed",
                    registry=name,
                    exc_info=True,
                )
        self._shutdown_event.set()
        _logger.info("manager.shutdown_complete")
wait_for_shutdown async
wait_for_shutdown()

Block until shutdown is complete.

Source code in src/marianne/daemon/manager.py
async def wait_for_shutdown(self) -> None:
    """Block until shutdown is complete."""
    await self._shutdown_event.wait()

Functions: