Skip to content

Index

daemon

Marianne daemon service — long-running orchestration conductor.

Classes

BackpressureController

BackpressureController(monitor, rate_coordinator, learning_hub=None)

Manages system load through adaptive backpressure.

Assesses memory usage (as a fraction of the configured limit) and active rate limits to determine a PressureLevel. The scheduler calls can_start_sheet() before dispatching each sheet and gets back a (allowed, delay) tuple.

No internal lock is needed because: - ResourceMonitor methods are thread/coroutine-safe. - RateLimitCoordinator.active_limits is a property that reads a dict snapshot. - PressureLevel assessment is a pure function of those reads.

Source code in src/marianne/daemon/backpressure.py
def __init__(
    self,
    monitor: ResourceMonitor,
    rate_coordinator: RateLimitCoordinator,
    learning_hub: LearningHub | None = None,
) -> None:
    self._monitor = monitor
    self._rate_coordinator = rate_coordinator
    self._learning_hub = learning_hub
Methods:
current_level
current_level()

Assess current pressure level from resource metrics.

Thresholds (memory as % of ResourceLimitConfig.max_memory_mb): - probe failure or monitor degraded → CRITICAL (fail-closed) - >95% or monitor not accepting work → CRITICAL - >85% or any active rate limit → HIGH - >70% → MEDIUM - >50% → LOW - otherwise → NONE

Note: is_accepting_work() also checks child process count against ResourceLimitConfig.max_processes. When process count exceeds 80% of the configured limit, is_accepting_work() returns False, which triggers the CRITICAL path here. This means high process counts indirectly escalate backpressure to CRITICAL even when memory usage is low.

TOCTOU fix (P007): memory is read once and reused for all threshold checks. is_accepting_work() is still called for its process-count check, but the memory percentage used in threshold comparisons comes from the single snapshot above.

Source code in src/marianne/daemon/backpressure.py
def current_level(self) -> PressureLevel:
    """Assess current pressure level from resource metrics.

    Thresholds (memory as % of ``ResourceLimitConfig.max_memory_mb``):
      - probe failure or monitor degraded  → CRITICAL (fail-closed)
      - >95% or monitor not accepting work → CRITICAL
      - >85% or any active rate limit      → HIGH
      - >70%                               → MEDIUM
      - >50%                               → LOW
      - otherwise                          → NONE

    Note: ``is_accepting_work()`` also checks child process count
    against ``ResourceLimitConfig.max_processes``.  When process
    count exceeds 80% of the configured limit, ``is_accepting_work()``
    returns ``False``, which triggers the CRITICAL path here.  This
    means high process counts indirectly escalate backpressure to
    CRITICAL even when memory usage is low.

    TOCTOU fix (P007): memory is read once and reused for all
    threshold checks.  ``is_accepting_work()`` is still called for
    its process-count check, but the memory percentage used in
    threshold comparisons comes from the single snapshot above.
    """
    # Single snapshot of memory — avoids TOCTOU where memory changes
    # between our percentage check and is_accepting_work()'s check.
    current_mem = self._monitor.current_memory_mb()
    if current_mem is None or self._monitor.is_degraded:
        return PressureLevel.CRITICAL

    max_mem = max(self._monitor.max_memory_mb, 1)
    memory_pct = current_mem / max_mem

    # is_accepting_work() re-reads memory internally, but we use our
    # snapshot for threshold decisions; it's only called for its
    # process-count gate (returns False when procs > 80% of limit).
    accepting_work = self._monitor.is_accepting_work()

    if memory_pct > 0.95 or not accepting_work:
        return PressureLevel.CRITICAL
    # Rate limit escalation: when any instrument is actively rate-limited,
    # escalate to HIGH even if memory is below the 85% threshold.
    # Data flows via the baton adapter's write-through (#206):
    # RateLimitHit → BatonAdapter._report_rate_limit_cross_job →
    # JobManager._on_rate_limit → RateLimitCoordinator.
    if memory_pct > 0.85 or self._rate_coordinator.active_limits:
        return PressureLevel.HIGH
    if memory_pct > 0.70:
        return PressureLevel.MEDIUM
    if memory_pct > 0.50:
        return PressureLevel.LOW
    return PressureLevel.NONE
can_start_sheet async
can_start_sheet()

Whether the scheduler may dispatch a sheet, and any delay.

Satisfies the BackpressureChecker protocol used by GlobalSheetScheduler.next_sheet().

Returns:

Type Description
bool

(allowed, delay_seconds). At CRITICAL level the sheet

float

is rejected (allowed=False). At lower levels a positive

tuple[bool, float]

delay is returned to slow dispatch.

Source code in src/marianne/daemon/backpressure.py
async def can_start_sheet(self) -> tuple[bool, float]:
    """Whether the scheduler may dispatch a sheet, and any delay.

    Satisfies the ``BackpressureChecker`` protocol used by
    ``GlobalSheetScheduler.next_sheet()``.

    Returns:
        ``(allowed, delay_seconds)``.  At CRITICAL level the sheet
        is rejected (``allowed=False``).  At lower levels a positive
        delay is returned to slow dispatch.
    """
    level = self.current_level()
    delay = _LEVEL_DELAYS[level]

    if level == PressureLevel.CRITICAL:
        _logger.warning(
            "backpressure.sheet_rejected",
            level=level.value,
        )
        return False, delay

    if delay > 0:
        _logger.info(
            "backpressure.sheet_delayed",
            level=level.value,
            delay_seconds=delay,
        )

    return True, delay
should_accept_job
should_accept_job()

Whether to accept new job submissions.

Returns False only under high resource pressure (memory or process count). Rate limits do NOT cause job rejection — they are per-instrument and handled at the sheet dispatch level by the baton and scheduler (F-149).

This prevents a rate limit on instrument A from blocking jobs that target instrument B.

Source code in src/marianne/daemon/backpressure.py
def should_accept_job(self) -> bool:
    """Whether to accept new job submissions.

    Returns ``False`` only under high **resource** pressure (memory
    or process count).  Rate limits do NOT cause job rejection —
    they are per-instrument and handled at the sheet dispatch level
    by the baton and scheduler (F-149).

    This prevents a rate limit on instrument A from blocking jobs
    that target instrument B.
    """
    current_mem = self._monitor.current_memory_mb()
    if current_mem is None or self._monitor.is_degraded:
        _logger.info(
            "backpressure.job_rejected",
            level="critical",
            reason="resource",
        )
        return False

    max_mem = max(self._monitor.max_memory_mb, 1)
    memory_pct = current_mem / max_mem
    accepting_work = self._monitor.is_accepting_work()

    if memory_pct > 0.85 or not accepting_work:
        _logger.info(
            "backpressure.job_rejected",
            level="high",
            reason="resource",
            memory_pct=round(memory_pct, 2),
        )
        return False

    return True
rejection_reason
rejection_reason()

Why would a job be rejected right now?

Returns:

Type Description
str | None

None if the system would accept the job.

str | None

"resource" if memory or process pressure is the cause.

Rate limits alone no longer cause rejection (F-149). They are per-instrument concerns handled at the sheet dispatch level. This prevents a rate limit on one instrument from blocking jobs targeting different instruments.

Source code in src/marianne/daemon/backpressure.py
def rejection_reason(self) -> str | None:
    """Why would a job be rejected right now?

    Returns:
        ``None`` if the system would accept the job.
        ``"resource"`` if memory or process pressure is the cause.

    Rate limits alone no longer cause rejection (F-149).  They are
    per-instrument concerns handled at the sheet dispatch level.
    This prevents a rate limit on one instrument from blocking jobs
    targeting different instruments.
    """
    current_mem = self._monitor.current_memory_mb()
    if current_mem is None or self._monitor.is_degraded:
        return "resource"

    max_mem = max(self._monitor.max_memory_mb, 1)
    memory_pct = current_mem / max_mem
    accepting_work = self._monitor.is_accepting_work()

    # Critical resource pressure — always resource
    if memory_pct > 0.95 or not accepting_work:
        return "resource"

    # High memory (>85%) — resource pressure regardless of rate limits
    if memory_pct > 0.85:
        return "resource"

    # No pressure — rate limits handled at sheet dispatch level
    return None
estimate_job_resource_needs async
estimate_job_resource_needs(job_config_hash)

Query learned resource patterns for similar job types.

Looks up RESOURCE_CORRELATION patterns from the learning store that match the given job config hash. Returns a ResourceEstimate if sufficient historical data exists, otherwise None.

This is advisory — the caller uses it to adjust thresholds, not to block jobs outright.

Parameters:

Name Type Description Default
job_config_hash str

Stable hash identifying the job type/config.

required

Returns:

Type Description
ResourceEstimate | None

ResourceEstimate with predicted peak memory, CPU-time,

ResourceEstimate | None

and confidence, or None if no data is available.

Source code in src/marianne/daemon/backpressure.py
async def estimate_job_resource_needs(
    self, job_config_hash: str
) -> ResourceEstimate | None:
    """Query learned resource patterns for similar job types.

    Looks up ``RESOURCE_CORRELATION`` patterns from the learning store
    that match the given job config hash.  Returns a ``ResourceEstimate``
    if sufficient historical data exists, otherwise ``None``.

    This is advisory — the caller uses it to adjust thresholds, not
    to block jobs outright.

    Args:
        job_config_hash: Stable hash identifying the job type/config.

    Returns:
        ``ResourceEstimate`` with predicted peak memory, CPU-time,
        and confidence, or ``None`` if no data is available.
    """
    if self._learning_hub is None or not self._learning_hub.is_running:
        return None

    from marianne.daemon.profiler.models import ResourceEstimate as RE
    from marianne.learning.patterns import PatternType

    try:
        store = self._learning_hub.store
        patterns = store.get_patterns(
            pattern_type=PatternType.RESOURCE_CORRELATION.value,
            limit=10,
            min_priority=0.0,
        )

        if not patterns:
            return None

        # Aggregate resource estimates from matching patterns
        peak_memory_values: list[float] = []
        cpu_values: list[float] = []
        confidence_sum = 0.0

        for pattern in patterns:
            desc = pattern.description or ""
            # Extract memory hints from description
            if "RSS" in desc or "memory" in desc.lower():
                # Use effectiveness_score as a rough confidence
                confidence_sum += pattern.effectiveness_score

            # Look for memory_bin context tags for peak memory hints
            tags = pattern.context_tags or ""
            if isinstance(tags, str):
                tag_str = tags
            elif isinstance(tags, list):
                tag_str = ",".join(tags)
            else:
                tag_str = str(tags)

            # Parse failure_rate from tags for signal strength
            if "memory_bin:" in tag_str:
                # Presence of memory correlation patterns gives us
                # a rough estimate based on bin boundaries
                if "<256MB" in tag_str:
                    peak_memory_values.append(256.0)
                elif "256-512MB" in tag_str:
                    peak_memory_values.append(512.0)
                elif "512MB-1GB" in tag_str:
                    peak_memory_values.append(1024.0)
                elif "1-2GB" in tag_str:
                    peak_memory_values.append(2048.0)
                elif ">2GB" in tag_str:
                    peak_memory_values.append(4096.0)

        if not peak_memory_values and confidence_sum == 0:
            return None

        avg_memory = (
            sum(peak_memory_values) / len(peak_memory_values)
            if peak_memory_values
            else 0.0
        )
        avg_cpu = (
            sum(cpu_values) / len(cpu_values)
            if cpu_values
            else 0.0
        )
        confidence = min(1.0, confidence_sum / max(len(patterns), 1))

        return RE(
            estimated_peak_memory_mb=avg_memory,
            estimated_cpu_seconds=avg_cpu,
            confidence=confidence,
        )

    except Exception:  # noqa: BLE001 — structured logger reports backpressure.resource_estimate_failed
        _logger.debug(
            "backpressure.resource_estimate_failed",
            job_config_hash=job_config_hash,
            exc_info=True,
        )
        return None

PressureLevel

Bases: Enum

Graduated pressure levels for adaptive load management.

DaemonConfig

Bases: BaseModel

Top-level configuration for the Marianne conductor.

Controls socket binding, PID file location, concurrency limits, resource constraints, and state backend selection. Follows the same Field() conventions as marianne.core.config.

Attributes
resolved_snapshot_dir property
resolved_snapshot_dir

Where completion snapshots live: snapshot_dir or beside the state DB.

HealthChecker

HealthChecker(manager, monitor, *, start_time=None, learning_store=None)

Daemon health and readiness probes.

Evolution v25: Entropy Response Activation - added periodic entropy monitoring and automatic diversity injection when collapse is detected.

Parameters

manager: The JobManager instance for job count queries. monitor: The ResourceMonitor instance for resource threshold checks. learning_store: Optional learning store for entropy monitoring. If None, entropy checks are disabled.

Source code in src/marianne/daemon/health.py
def __init__(
    self,
    manager: JobManager,
    monitor: ResourceMonitor,
    *,
    start_time: float | None = None,
    learning_store: GlobalLearningStore | None = None,
) -> None:
    self._manager = manager
    self._monitor = monitor
    self._start_time = start_time or time.monotonic()
    self._learning_store = learning_store
    self._last_entropy_check = 0.0
    self._entropy_check_task: asyncio.Task[None] | None = None
    self._completed_jobs_since_check = 0
Methods:
liveness async
liveness()

Is the daemon process alive and responsive?

This is the cheapest possible check — if the daemon can execute this handler and return a response, it's alive. No resource checks or I/O are performed.

Also advertises the IPC protocol_version (#265) — liveness is the handshake every mzt status performs, so clients detect a CLI/conductor protocol skew here without an extra round trip.

Source code in src/marianne/daemon/health.py
async def liveness(self) -> dict[str, Any]:
    """Is the daemon process alive and responsive?

    This is the cheapest possible check — if the daemon can execute
    this handler and return a response, it's alive.  No resource
    checks or I/O are performed.

    Also advertises the IPC ``protocol_version`` (#265) — liveness is
    the handshake every ``mzt status`` performs, so clients detect a
    CLI/conductor protocol skew here without an extra round trip.
    """
    from marianne.daemon.ipc.protocol import PROTOCOL_VERSION

    return {
        "status": "ok",
        "pid": os.getpid(),
        "uptime_seconds": round(time.monotonic() - self._start_time, 1),
        "shutting_down": self._manager.shutting_down,
        "protocol_version": PROTOCOL_VERSION,
    }
readiness async
readiness()

Is the daemon ready to accept new jobs?

Checks resource thresholds via the monitor, job failure rate via the manager, and notification health. Returns "ready" when resources are within limits, the failure rate is not elevated, and notifications are functional; "not_ready" otherwise.

Source code in src/marianne/daemon/health.py
async def readiness(self) -> dict[str, Any]:
    """Is the daemon ready to accept new jobs?

    Checks resource thresholds via the monitor, job failure rate
    via the manager, and notification health.  Returns ``"ready"``
    when resources are within limits, the failure rate is not
    elevated, and notifications are functional; ``"not_ready"``
    otherwise.
    """
    snapshot = await self._monitor.check_now()
    accepting = self._monitor.is_accepting_work()
    failure_elevated = self._manager.failure_rate_elevated
    notif_degraded = self._manager.notifications_degraded

    shutting_down = self._manager.shutting_down
    is_ready = (
        accepting
        and not shutting_down
        and not failure_elevated
        and not notif_degraded
    )
    return {
        "status": "ready" if is_ready else "not_ready",
        "running_jobs": self._manager.running_count,
        # GH #476: the sheets a drain would wait on, so `mzt stop` and
        # `mzt conductor-status` can name them.
        "in_flight": list(getattr(self._manager, "in_flight_sheets", []) or []),
        "memory_mb": round(snapshot.memory_usage_mb, 1),
        "child_processes": snapshot.child_process_count,
        "accepting_work": is_ready,
        "shutting_down": shutting_down,
        "failure_rate_elevated": failure_elevated,
        "notifications_degraded": notif_degraded,
        "uptime_seconds": round(time.monotonic() - self._start_time, 1),
        # GH #455: slow is not dead. The operator reading conductor-status
        # sees how late this loop wakes and whether the host is stalled on I/O.
        "event_loop_lag_ms": self._monitor.event_loop_lag_ms,
        "event_loop_lag_peak_ms": self._monitor.event_loop_lag_peak_ms,
        "io_pressure": read_io_pressure(),
    }
on_job_completed
on_job_completed()

Called by JobManager when a job completes.

Evolution v25: Entropy Response Activation - tracks completed jobs to trigger entropy checks every 10 completions.

Source code in src/marianne/daemon/health.py
def on_job_completed(self) -> None:
    """Called by JobManager when a job completes.

    Evolution v25: Entropy Response Activation - tracks completed jobs
    to trigger entropy checks every 10 completions.
    """
    self._completed_jobs_since_check += 1

    # Check entropy every 10 completed jobs (in addition to time-based checks)
    if self._completed_jobs_since_check >= 10:
        self._completed_jobs_since_check = 0
        # Schedule async check without blocking
        if self._learning_store is not None:
            asyncio.create_task(self._check_entropy_and_respond())
start_periodic_checks async
start_periodic_checks()

Start background task for periodic entropy checks.

Evolution v25: Entropy Response Activation - runs entropy checks at configured intervals (default 1 hour).

Source code in src/marianne/daemon/health.py
async def start_periodic_checks(self) -> None:
    """Start background task for periodic entropy checks.

    Evolution v25: Entropy Response Activation - runs entropy checks
    at configured intervals (default 1 hour).
    """
    if self._learning_store is None:
        return

    async def _check_loop() -> None:
        config = self._manager._config.learning
        interval = config.entropy_check_interval_seconds

        while not self._manager.shutting_down:
            await asyncio.sleep(interval)
            await self._check_entropy_and_respond()

    self._entropy_check_task = asyncio.create_task(_check_loop())
stop_periodic_checks async
stop_periodic_checks()

Stop the periodic entropy check task.

Evolution v25: Entropy Response Activation - cleanly shuts down the entropy monitoring loop.

Source code in src/marianne/daemon/health.py
async def stop_periodic_checks(self) -> None:
    """Stop the periodic entropy check task.

    Evolution v25: Entropy Response Activation - cleanly shuts down
    the entropy monitoring loop.
    """
    if self._entropy_check_task is not None:
        self._entropy_check_task.cancel()
        try:
            await self._entropy_check_task
        except asyncio.CancelledError:
            pass
        self._entropy_check_task = None

JobService

JobService(*, output=None, global_learning_store=None, event_callback=None, state_publish_callback=None, registry=None, token_warning_threshold=None, token_error_threshold=None, pgroup_manager=None)

Core job execution service.

Encapsulates the logic from CLI run/resume/pause commands into a reusable service that can be called from CLI, daemon, dashboard, or MCP server.

All user-facing output goes through the OutputProtocol abstraction, allowing different frontends (Rich console, structlog, SSE, null) to receive execution events without code changes.

Source code in src/marianne/daemon/job_service.py
def __init__(
    self,
    *,
    output: OutputProtocol | None = None,
    global_learning_store: GlobalLearningStore | None = None,
    event_callback: EventCallback | None = None,
    state_publish_callback: StatePublishCallback | None = None,
    registry: JobRegistry | None = None,
    token_warning_threshold: int | None = None,
    token_error_threshold: int | None = None,
    pgroup_manager: ProcessGroupManager | None = None,
) -> None:
    self._output = output or NullOutput()
    self._learning_store = global_learning_store
    self._event_callback = event_callback
    self._state_publish_callback = state_publish_callback
    self._registry = registry
    self._token_warning_threshold = token_warning_threshold
    self._token_error_threshold = token_error_threshold
    self._pgroup_manager = pgroup_manager
    self._notification_consecutive_failures = 0
    self._notifications_degraded = False
Attributes
notifications_degraded property
notifications_degraded

Whether notification delivery is degraded.

Returns True after _NOTIFICATION_DEGRADED_THRESHOLD consecutive notification failures. Readable by HealthChecker.readiness() to signal degraded notification capability to operators.

Methods:
pause_job async
pause_job(job_id, workspace)

Pause a running job via signal file.

Mirrors the logic in cli/commands/pause.py::_pause_job(): Creates a pause signal file that the baton polls at sheet boundaries.

Parameters:

Name Type Description Default
job_id str

Job identifier to pause.

required
workspace Path

Workspace directory containing job state.

required

Returns:

Type Description
bool

True if pause signal was created successfully.

Raises:

Type Description
JobSubmissionError

If job not found or not in a pausable state.

Source code in src/marianne/daemon/job_service.py
async def pause_job(self, job_id: str, workspace: Path) -> bool:
    """Pause a running job via signal file.

    Mirrors the logic in cli/commands/pause.py::_pause_job():
    Creates a pause signal file that the baton polls at sheet boundaries.

    Args:
        job_id: Job identifier to pause.
        workspace: Workspace directory containing job state.

    Returns:
        True if pause signal was created successfully.

    Raises:
        JobSubmissionError: If job not found or not in a pausable state.
    """
    found_state, found_backend = await self._find_job_state(job_id, workspace)
    await found_backend.close()

    if found_state.status != JobStatus.RUNNING:
        raise JobSubmissionError(
            f"Job '{job_id}' is {found_state.status.value}, not running. "
            "Only running jobs can be paused."
        )

    # Create pause signal file
    signal_file = workspace / f".marianne-pause-{job_id}"
    signal_file.touch()

    self._output.job_event(
        job_id,
        "pause_signal_sent",
        {
            "signal_file": str(signal_file),
        },
    )

    return True
get_status async
get_status(job_id, workspace, backend_type='sqlite')

Get job status from state backend.

Parameters:

Name Type Description Default
job_id str

Job identifier.

required
workspace Path

Workspace directory containing job state.

required
backend_type str

State backend type (default "sqlite" for daemon).

'sqlite'

Returns:

Type Description
CheckpointState | None

CheckpointState if found, None if job doesn't exist.

Source code in src/marianne/daemon/job_service.py
async def get_status(
    self,
    job_id: str,
    workspace: Path,
    backend_type: str = "sqlite",
) -> CheckpointState | None:
    """Get job status from state backend.

    Args:
        job_id: Job identifier.
        workspace: Workspace directory containing job state.
        backend_type: State backend type (default "sqlite" for daemon).

    Returns:
        CheckpointState if found, None if job doesn't exist.
    """
    state_backend = self._create_state_backend(workspace, backend_type)
    try:
        return await state_backend.load(job_id)
    finally:
        await state_backend.close()

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

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

ResourceMonitor

ResourceMonitor(config, manager=None, pgroup=None)

Periodic resource monitoring for the daemon.

Checks memory usage, child process count, and zombie processes on a configurable interval. Emits structured log warnings when approaching limits and can trigger hard actions (job cancellation) when hard limits are exceeded.

Source code in src/marianne/daemon/monitor.py
def __init__(
    self,
    config: ResourceLimitConfig,
    manager: JobManager | None = None,
    pgroup: ProcessGroupManager | None = None,
) -> None:
    self._config = config
    self._manager = manager
    self._pgroup = pgroup
    self._task: asyncio.Task[None] | None = None
    self._running = False
    self._consecutive_failures = 0
    self._degraded = False
    self._prune_consecutive_failures = 0
    self._prune_disabled = False
    self._last_successful_check: float = 0.0
    self._lag_task: asyncio.Task[None] | None = None
    self._lag_samples: deque[float] = deque(maxlen=self.LAG_WINDOW_SAMPLES)
Attributes
event_loop_lag_ms property
event_loop_lag_ms

Most recent event-loop wake-up lag in milliseconds (None before the first sample).

event_loop_lag_peak_ms property
event_loop_lag_peak_ms

Worst event-loop lag over the last LAG_WINDOW_SAMPLES seconds.

seconds_since_last_check property
seconds_since_last_check

Seconds since the last successful monitoring check.

Returns float('inf') if no check has succeeded yet. Consumers can use this to detect stale resource data.

max_memory_mb property
max_memory_mb

Configured maximum memory in MB.

is_degraded property
is_degraded

Whether the monitor has entered degraded mode due to repeated failures.

Methods:
start async
start(interval_seconds=15.0)

Start the periodic monitoring loop.

Source code in src/marianne/daemon/monitor.py
async def start(self, interval_seconds: float = 15.0) -> None:
    """Start the periodic monitoring loop."""
    if self._task is not None:
        return
    self._running = True
    self._task = asyncio.create_task(self._loop(interval_seconds))
    self._task.add_done_callback(self._on_loop_done)
    self._lag_task = asyncio.create_task(self._lag_loop())
    _logger.info("monitor.started", interval=interval_seconds)
stop async
stop()

Stop the monitoring loop.

Source code in src/marianne/daemon/monitor.py
async def stop(self) -> None:
    """Stop the monitoring loop."""
    self._running = False
    for attr in ("_task", "_lag_task"):
        task = getattr(self, attr)
        if task is not None:
            task.cancel()
            try:
                await task
            except asyncio.CancelledError:
                pass
            setattr(self, attr, None)
    _logger.info("monitor.stopped")
check_now async
check_now()

Run an immediate resource check and return snapshot.

Source code in src/marianne/daemon/monitor.py
async def check_now(self) -> ResourceSnapshot:
    """Run an immediate resource check and return snapshot."""
    running_jobs = 0
    active_sheets = 0
    if self._manager is not None:
        running_jobs = self._manager.running_count
        active_sheets = self._manager.active_job_count

    mem = self._get_memory_usage_mb()
    procs = self._get_child_process_count()
    zombie_pids = self._check_for_zombies()
    probe_failed = mem is None or procs is None

    snapshot = ResourceSnapshot(
        timestamp=time.monotonic(),
        memory_usage_mb=mem if mem is not None else 0.0,
        child_process_count=procs if procs is not None else 0,
        running_jobs=running_jobs,
        active_sheets=active_sheets,
        zombie_pids=zombie_pids,
        probe_failed=probe_failed,
    )
    return snapshot
is_accepting_work
is_accepting_work()

Check if resource usage is below warning thresholds.

Returns True when both memory and process counts are below WARN_THRESHOLD percent of their configured limits. Used by HealthChecker.readiness() to signal backpressure.

Fail-closed: returns False when probes fail or monitor is degraded.

Source code in src/marianne/daemon/monitor.py
def is_accepting_work(self) -> bool:
    """Check if resource usage is below warning thresholds.

    Returns True when both memory and process counts are below
    ``WARN_THRESHOLD`` percent of their configured limits.  Used by
    ``HealthChecker.readiness()`` to signal backpressure.

    Fail-closed: returns False when probes fail or monitor is degraded.
    """
    if self._degraded:
        return False
    mem = self._get_memory_usage_mb()
    procs = self._get_child_process_count()
    if mem is None or procs is None:
        return False
    mem_pct = _compute_percent(mem, self._config.max_memory_mb)
    proc_pct = _compute_percent(procs, self._config.max_processes)
    return mem_pct < self.WARN_THRESHOLD and proc_pct < self.WARN_THRESHOLD
current_memory_mb
current_memory_mb()

Current RSS memory in MB, or None if probes fail.

Source code in src/marianne/daemon/monitor.py
def current_memory_mb(self) -> float | None:
    """Current RSS memory in MB, or None if probes fail."""
    return self._get_memory_usage_mb()
update_limits
update_limits(new_limits)

Hot-apply new resource limits from a SIGHUP config reload.

Replaces the internal _config reference. Safe because the monitor only reads _config during periodic checks, and asyncio's single-threaded event loop prevents concurrent access.

Source code in src/marianne/daemon/monitor.py
def update_limits(self, new_limits: ResourceLimitConfig) -> None:
    """Hot-apply new resource limits from a SIGHUP config reload.

    Replaces the internal ``_config`` reference.  Safe because the
    monitor only reads ``_config`` during periodic checks, and
    asyncio's single-threaded event loop prevents concurrent access.
    """
    old = self._config
    if (
        old.max_memory_mb != new_limits.max_memory_mb
        or old.max_processes != new_limits.max_processes
    ):
        _logger.info(
            "monitor.limits_updated",
            old_memory_mb=old.max_memory_mb,
            new_memory_mb=new_limits.max_memory_mb,
            old_max_processes=old.max_processes,
            new_max_processes=new_limits.max_processes,
        )
    self._config = new_limits
set_manager
set_manager(manager)

Wire up the job manager reference after construction.

Called by DaemonProcess after both the monitor and manager are created, avoiding the circular dependency of needing both at init.

Source code in src/marianne/daemon/monitor.py
def set_manager(self, manager: JobManager) -> None:
    """Wire up the job manager reference after construction.

    Called by DaemonProcess after both the monitor and manager are
    created, avoiding the circular dependency of needing both at init.
    """
    self._manager = manager

ResourceSnapshot dataclass

ResourceSnapshot(timestamp, memory_usage_mb, child_process_count, running_jobs, active_sheets, zombie_pids=list(), probe_failed=False)

Point-in-time resource usage reading.

ConsoleOutput

ConsoleOutput(console=None)

Bases: OutputProtocol

Rich Console wrapper for CLI backwards compatibility.

Bridges the OutputProtocol to Rich Console, so the existing CLI can adopt the protocol without changing its visual output.

Source code in src/marianne/daemon/output.py
def __init__(self, console: Any | None = None) -> None:
    if console is None:
        from rich.console import Console

        console = Console()
    self._console = console

NullOutput

Bases: OutputProtocol

No-op output for testing.

OutputProtocol

Bases: ABC

Abstract output for job execution feedback.

Replaces tight coupling to Rich Console. Implementations: - NullOutput: no-op for tests - StructuredOutput: structlog for daemon - ConsoleOutput: wraps Rich for CLI backwards compat

StructuredOutput

StructuredOutput(*, event_bus=None)

Bases: OutputProtocol

Structured logging output for daemon mode.

Routes all output through structlog, producing structured JSON events that daemon consumers (SSE, gRPC, log aggregators) can parse.

Source code in src/marianne/daemon/output.py
def __init__(self, *, event_bus: EventBus | None = None) -> None:
    from marianne.core.logging import get_logger

    self._logger = get_logger("daemon.output")
    self._event_bus = event_bus

ProcessGroupManager

ProcessGroupManager()

Manages the daemon's process group to prevent orphans.

The daemon calls setup() early in its lifecycle to become the process group leader. During shutdown, kill_all_children() sends SIGTERM to the entire group, ensuring no child process (including deeply nested MCP servers) survives the daemon.

An atexit handler provides last-resort cleanup even if the normal shutdown path is skipped.

Source code in src/marianne/daemon/pgroup.py
def __init__(self) -> None:
    self._original_pgid: int = os.getpgrp()
    self._is_leader: bool = False
    self._atexit_registered: bool = False
    # PIDs of processes spawned by backends (claude, etc.).
    # Used to identify orphaned children: if a tracked PID is dead
    # but its children survive, those children are orphans.
    self._tracked_backend_pids: set[int] = set()
Attributes
is_leader property
is_leader

Whether the daemon is the process group leader.

original_pgid property
original_pgid

Process group ID before setup() was called.

Methods:
track_backend_pid
track_backend_pid(pid)

Register a backend process PID for orphan tracking.

When a backend (claude, gemini-cli, etc.) spawns a process, call this with the process PID. On cleanup, any surviving children of dead tracked PIDs are killed as orphans — regardless of what they're called. This replaces cmdline pattern matching with ancestry-based detection.

Source code in src/marianne/daemon/pgroup.py
def track_backend_pid(self, pid: int) -> None:
    """Register a backend process PID for orphan tracking.

    When a backend (claude, gemini-cli, etc.) spawns a process, call
    this with the process PID. On cleanup, any surviving children of
    dead tracked PIDs are killed as orphans — regardless of what
    they're called. This replaces cmdline pattern matching with
    ancestry-based detection.
    """
    self._tracked_backend_pids.add(pid)
    _logger.debug("pgroup.track_backend", pid=pid)
untrack_backend_pid
untrack_backend_pid(pid)

Remove a backend PID from tracking after clean exit.

Source code in src/marianne/daemon/pgroup.py
def untrack_backend_pid(self, pid: int) -> None:
    """Remove a backend PID from tracking after clean exit."""
    self._tracked_backend_pids.discard(pid)
    _logger.debug("pgroup.untrack_backend", pid=pid)
setup
setup()

Create a new process group with the daemon as leader.

Must be called early in daemon startup, before spawning any child processes. Idempotent — safe to call multiple times.

Source code in src/marianne/daemon/pgroup.py
def setup(self) -> None:
    """Create a new process group with the daemon as leader.

    Must be called early in daemon startup, before spawning any
    child processes.  Idempotent — safe to call multiple times.
    """
    if self._is_leader:
        return

    try:
        os.setpgrp()
        self._is_leader = True
        _logger.info(
            "pgroup.setup_complete",
            pid=os.getpid(),
            pgid=os.getpgrp(),
            original_pgid=self._original_pgid,
        )
    except OSError as exc:
        # May fail if already the group leader (e.g. after daemonize)
        if os.getpid() == os.getpgrp():
            self._is_leader = True
            _logger.debug(
                "pgroup.already_leader",
                pid=os.getpid(),
            )
        else:
            _logger.warning(
                "pgroup.setup_failed",
                error=str(exc),
                pid=os.getpid(),
            )

    # Register last-resort atexit cleanup
    if self._is_leader and not self._atexit_registered:
        atexit.register(self._atexit_cleanup)
        self._atexit_registered = True
kill_all_children
kill_all_children(sig=SIGTERM)

Send signal to all processes in our group except ourselves.

Parameters:

Name Type Description Default
sig int

Signal number to send (default SIGTERM for graceful stop).

SIGTERM

Returns:

Type Description
int

The process group ID that was signaled, or 0 if no signal sent.

Source code in src/marianne/daemon/pgroup.py
def kill_all_children(self, sig: int = signal.SIGTERM) -> int:
    """Send signal to all processes in our group except ourselves.

    Args:
        sig: Signal number to send (default SIGTERM for graceful stop).

    Returns:
        The process group ID that was signaled, or 0 if no signal sent.
    """
    if not self._is_leader:
        _logger.debug("pgroup.not_leader_skip_kill")
        return 0

    pgid = os.getpgrp()
    my_pid = os.getpid()

    # Count children before signaling for logging
    child_count = self._count_group_members(pgid, exclude_pid=my_pid)

    if child_count == 0:
        _logger.debug("pgroup.no_children_to_signal")
        return pgid

    try:
        # Temporarily ignore the signal in our own process so killpg
        # doesn't terminate us along with the children.
        old_handler = signal.signal(sig, signal.SIG_IGN)
        try:
            sent = _safe_killpg(pgid, sig, context="pgroup.kill_all_children")
        finally:
            signal.signal(sig, old_handler)

        if sent:
            _logger.info(
                "pgroup.signaled_children",
                signal=signal.Signals(sig).name,
                pgid=pgid,
                child_count=child_count,
            )
        return pgid
    except ProcessLookupError:
        _logger.debug("pgroup.no_processes_in_group", pgid=pgid)
        return 0
    except PermissionError:
        _logger.warning("pgroup.permission_denied", pgid=pgid)
        return 0
cleanup_orphans
cleanup_orphans()

Find and clean up orphaned child processes in the daemon's tree.

Detects two categories: 1. Zombie children — reaped via waitpid 2. Orphaned MCP servers — processes whose parent has died (reparented to init/PID 1) that still match MCP patterns

Note: This only scans the daemon's own child tree. For processes that escaped the tree entirely (reparented to init), use reap_orphaned_backends() which does a system-wide scan.

Returns:

Type Description
list[int]

List of PIDs that were cleaned up.

Source code in src/marianne/daemon/pgroup.py
def cleanup_orphans(self) -> list[int]:
    """Find and clean up orphaned child processes in the daemon's tree.

    Detects two categories:
    1. Zombie children — reaped via waitpid
    2. Orphaned MCP servers — processes whose parent has died
       (reparented to init/PID 1) that still match MCP patterns

    Note: This only scans the daemon's own child tree.  For processes
    that escaped the tree entirely (reparented to init), use
    reap_orphaned_backends() which does a system-wide scan.

    Returns:
        List of PIDs that were cleaned up.
    """
    orphans: list[int] = []

    # Strategy 1: psutil-based deep scan (preferred)
    try:
        import psutil

        current = psutil.Process(os.getpid())

        for child in current.children(recursive=True):
            try:
                if not child.is_running():
                    continue

                status = child.status()

                # Reap zombies
                if status == psutil.STATUS_ZOMBIE:
                    try:
                        os.waitpid(child.pid, os.WNOHANG)
                    except ChildProcessError:
                        pass
                    orphans.append(child.pid)
                    _logger.debug(
                        "pgroup.reaped_zombie",
                        pid=child.pid,
                    )
                    continue

                # NOTE: Ancestry-based orphan killing disabled.
                # The F-481 rewrite removed cmdline filtering, making
                # this kill ANY child not parented by us when dead
                # backends exist — including Chrome, pytest, pyright,
                # and other legitimate processes in the daemon's tree.
                # The per-job PID tracking in the conductor DB will
                # replace this.  Until then, only zombie reaping above
                # is active.  Orphaned MCP servers accumulate but
                # don't crash the system.

            except (psutil.NoSuchProcess, psutil.AccessDenied):
                continue

    except ImportError:
        # Strategy 2: /proc fallback (Linux only)
        orphans.extend(self._cleanup_orphans_proc())

    if orphans:
        _logger.info(
            "pgroup.orphan_cleanup",
            cleaned_count=len(orphans),
            pids=orphans,
        )

    return orphans
reap_orphaned_backends
reap_orphaned_backends()

System-wide scan for orphaned backend child processes.

.. warning:: DISABLED — This method is a no-op.

The F-481 rewrite removed cmdline pattern filtering and replaced it with ancestry-only detection (ppid in {0, 1}). Without filtering, this kills EVERY user-owned process parented by init/systemd — including the user's systemd session manager, terminal emulators, and dbus. On WSL2, killing systemd --user cascades into systemd-poweroff.service and shuts down the entire VM (observed 9 times, exit code 9, all terminals dead).

The replacement is per-job PID tracking in the conductor DB (see composer-notes.yaml "PROCESS CLEANUP SIMPLIFICATION"). Until that's implemented, orphaned MCP/LSP servers from dead backends accumulate but don't crash the system.

Returns:

Type Description
list[int]

Empty list (no-op).

Source code in src/marianne/daemon/pgroup.py
def reap_orphaned_backends(self) -> list[int]:
    """System-wide scan for orphaned backend child processes.

    .. warning:: DISABLED — This method is a no-op.

       The F-481 rewrite removed cmdline pattern filtering and replaced
       it with ancestry-only detection (ppid in {0, 1}).  Without
       filtering, this kills EVERY user-owned process parented by
       init/systemd — including the user's systemd session manager,
       terminal emulators, and dbus.  On WSL2, killing ``systemd
       --user`` cascades into ``systemd-poweroff.service`` and shuts
       down the entire VM (observed 9 times, exit code 9, all
       terminals dead).

       The replacement is per-job PID tracking in the conductor DB
       (see composer-notes.yaml "PROCESS CLEANUP SIMPLIFICATION").
       Until that's implemented, orphaned MCP/LSP servers from dead
       backends accumulate but don't crash the system.

    Returns:
        Empty list (no-op).
    """
    # Drain dead PIDs from the tracking set so it doesn't grow
    # unboundedly — but do NOT act on them.
    if self._tracked_backend_pids:
        dead: set[int] = set()
        for bpid in self._tracked_backend_pids:
            try:
                os.kill(bpid, 0)
            except OSError:
                dead.add(bpid)
        if dead:
            self._tracked_backend_pids -= dead
            _logger.debug(
                "pgroup.drained_dead_backend_pids",
                count=len(dead),
                pids=list(dead),
            )
    return []

DaemonProcess

DaemonProcess(config, *, start_profile=None)

Long-running Marianne daemon process.

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

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

Main daemon lifecycle: boot, serve, shutdown.

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

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

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

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

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

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

        handler = RequestHandler()

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

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

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

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

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

        from collections.abc import Callable

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

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

            return _cb

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

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

        loop.add_signal_handler(signal.SIGHUP, _sighup_callback)

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

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

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

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

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

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

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

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

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

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

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

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

Single process-level reload entry (#408).

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

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

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

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

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

GlobalSheetScheduler

GlobalSheetScheduler(config)

Cross-job sheet-level scheduler using a priority min-heap.

Status: Phase 3 infrastructure — built and tested, not yet wired into the execution path.

Manages a global priority queue of sheets from all active jobs. Enforces: - max_concurrent_sheets from DaemonConfig - Per-job fair-share limits (penalty-based, not hard-block) - Per-job hard cap at fair_share * max_per_job_multiplier - DAG dependency awareness via completed-set tracking

The scheduler does NOT own sheet execution — it decides which sheet should run next and the JobManager performs the actual execution.

Integration plan (future): 1. JobManager._run_job_task() calls register_job() with all sheets parsed from the JobConfig. 2. A dispatch loop calls next_sheet() and spawns per-sheet tasks instead of calling JobService.start_job() monolithically. 3. Each per-sheet task calls mark_complete() on finish. 4. cancel_job() / shutdown calls deregister_job() for cleanup.

Source code in src/marianne/daemon/scheduler.py
def __init__(self, config: DaemonConfig) -> None:
    self._config = config
    self._max_concurrent = config.max_concurrent_sheets

    # Priority heap
    self._queue: list[SheetEntry] = []

    # Tracking
    self._running: dict[str, set[int]] = {}  # job_id → running sheet_nums
    self._active_count = 0

    # Per-job DAG tracking
    self._job_completed: dict[str, set[int]] = {}
    self._job_deps: dict[str, dict[int, set[int]]] = {}  # job_id → {sheet → {deps}}
    self._job_all_sheets: dict[str, list[SheetInfo]] = {}  # for re-enqueue

    # Fair-share tuning
    self._fair_share_overage_penalty = 20.0
    self._max_per_job_multiplier = 2.0

    # Rate-limiter error tolerance: after this many consecutive
    # rate-limiter errors, a sheet is dropped from the queue to
    # prevent infinite cycling.
    self._max_rate_limit_skips = 10

    # Optional downstream integrations (set via setters)
    self._rate_limiter: RateLimitChecker | None = None
    self._backpressure: BackpressureChecker | None = None

    # Concurrency control
    self._lock = asyncio.Lock()
Attributes
active_count property
active_count

Number of sheets currently executing.

queued_count property
queued_count

Number of sheets waiting in the queue.

Methods:
set_rate_limiter
set_rate_limiter(rate_limiter)

Wire up the rate limit coordinator (called once during init).

Source code in src/marianne/daemon/scheduler.py
def set_rate_limiter(self, rate_limiter: RateLimitChecker) -> None:
    """Wire up the rate limit coordinator (called once during init)."""
    self._rate_limiter = rate_limiter
set_backpressure
set_backpressure(backpressure)

Wire up the backpressure controller (called once during init).

Source code in src/marianne/daemon/scheduler.py
def set_backpressure(self, backpressure: BackpressureChecker) -> None:
    """Wire up the backpressure controller (called once during init)."""
    self._backpressure = backpressure
set_max_concurrent
set_max_concurrent(limit)

Live-resize the sheet ceiling (#408, #231 in-place pattern).

The constructor snapshots max_concurrent_sheets from the config; a config hot-reload must reach this live object rather than rely on the manager's config reference being rebound. In-flight sheets are never cancelled — a lowered limit takes effect as running sheets drain (next_sheet admits below the new ceiling only).

Source code in src/marianne/daemon/scheduler.py
def set_max_concurrent(self, limit: int) -> None:
    """Live-resize the sheet ceiling (#408, #231 in-place pattern).

    The constructor snapshots ``max_concurrent_sheets`` from the config;
    a config hot-reload must reach this live object rather than rely on
    the manager's config reference being rebound. In-flight sheets are
    never cancelled — a lowered limit takes effect as running sheets
    drain (``next_sheet`` admits below the new ceiling only).
    """
    self._max_concurrent = limit
register_job async
register_job(job_id, sheets, dependencies=None)

Register a job's sheets with the scheduler.

Enqueues sheets whose dependencies are already satisfied (or have no dependencies). Remaining sheets are enqueued as their deps complete via mark_complete().

Parameters:

Name Type Description Default
job_id str

Unique job identifier.

required
sheets list[SheetInfo]

All sheets for this job.

required
dependencies dict[int, set[int]] | None

Optional DAG — {sheet_num: {dependency_sheet_nums}}. If None, all sheets are independent.

None

Raises:

Type Description
ValueError

If dependencies contain a cycle (would deadlock).

Source code in src/marianne/daemon/scheduler.py
async def register_job(
    self,
    job_id: str,
    sheets: list[SheetInfo],
    dependencies: dict[int, set[int]] | None = None,
) -> None:
    """Register a job's sheets with the scheduler.

    Enqueues sheets whose dependencies are already satisfied (or have
    no dependencies).  Remaining sheets are enqueued as their deps
    complete via ``mark_complete()``.

    Args:
        job_id: Unique job identifier.
        sheets: All sheets for this job.
        dependencies: Optional DAG — ``{sheet_num: {dependency_sheet_nums}}``.
                      If None, all sheets are independent.

    Raises:
        ValueError: If dependencies contain a cycle (would deadlock).
    """
    if dependencies:
        cycle = self._detect_cycle(dependencies)
        if cycle:
            raise ValueError(
                f"Circular dependency detected in job {job_id}: "
                f"{' → '.join(str(n) for n in cycle)}"
            )

    # Validate sheet_num uniqueness — duplicates would silently corrupt
    # DAG tracking and completion-set logic.
    seen_nums: set[int] = set()
    for info in sheets:
        if info.sheet_num in seen_nums:
            raise ValueError(
                f"Duplicate sheet_num {info.sheet_num} in job {job_id}"
            )
        seen_nums.add(info.sheet_num)

    # Warn on dependencies referencing sheet_nums not in the sheets list.
    # These deps can never be satisfied, so affected sheets will stay
    # blocked forever.  This is a config error, not a hard failure.
    if dependencies:
        for sheet_num, dep_set in dependencies.items():
            phantom_deps = dep_set - seen_nums
            if phantom_deps:
                _logger.warning(
                    "scheduler.phantom_dependencies",
                    job_id=job_id,
                    sheet_num=sheet_num,
                    missing_deps=sorted(phantom_deps),
                    msg="Dependencies reference non-existent sheet_nums; "
                        "affected sheet will never become ready",
                )

    async with self._lock:
        # Guard against duplicate registration: remove stale heap
        # entries from any prior registration of this job_id.
        if job_id in self._job_all_sheets:
            self._queue = [
                e for e in self._queue if e.info.job_id != job_id
            ]
            heapq.heapify(self._queue)
            # Adjust active count for any running sheets being discarded
            old_running = self._running.pop(job_id, set())
            self._active_count = max(0, self._active_count - len(old_running))
            _logger.warning(
                "scheduler.duplicate_register",
                job_id=job_id,
                msg="Re-registering job; previous entries purged",
            )

        deps = dependencies or {}
        self._job_deps[job_id] = deps
        self._job_completed[job_id] = set()
        self._running[job_id] = set()
        self._job_all_sheets[job_id] = list(sheets)

        # Enqueue sheets whose deps are already met
        enqueued = 0
        for info in sheets:
            sheet_deps = deps.get(info.sheet_num, set())
            if not sheet_deps:
                entry = self._make_entry(info)
                heapq.heappush(self._queue, entry)
                enqueued += 1

        _logger.info(
            "scheduler.job_registered",
            job_id=job_id,
            total_sheets=len(sheets),
            immediately_ready=enqueued,
        )
deregister_job async
deregister_job(job_id)

Remove all pending sheets for a cancelled/completed job.

Source code in src/marianne/daemon/scheduler.py
async def deregister_job(self, job_id: str) -> None:
    """Remove all pending sheets for a cancelled/completed job."""
    async with self._lock:
        # Early return for unknown job_ids — avoids needless O(n) queue
        # rebuild and ensures the log message reflects real deregistrations.
        if job_id not in self._job_all_sheets:
            _logger.debug(
                "scheduler.deregister_unknown_job",
                job_id=job_id,
            )
            return

        # Rebuild queue without this job's sheets
        self._queue = [
            e for e in self._queue if e.info.job_id != job_id
        ]
        heapq.heapify(self._queue)

        self._running.pop(job_id, None)
        self._job_completed.pop(job_id, None)
        self._job_deps.pop(job_id, None)
        self._job_all_sheets.pop(job_id, None)

        # Recount active
        self._active_count = sum(
            len(s) for s in self._running.values()
        )

        _logger.info("scheduler.job_deregistered", job_id=job_id)
next_sheet async
next_sheet()

Pop the highest-priority ready sheet, respecting limits.

Returns None if no sheet can run (concurrency full, backpressure active, queue empty, or all queued sheets are rate-limited).

Single-caller constraint: The backpressure delay (asyncio.sleep) runs outside the scheduler lock. If multiple coroutines call next_sheet() concurrently, they may all pass the backpressure check before any acquires the lock, effectively bypassing the delay for concurrent callers. The intended usage is a single dispatch loop calling next_sheet() sequentially — the JobManager dispatch loop satisfies this constraint.

Source code in src/marianne/daemon/scheduler.py
async def next_sheet(self) -> SheetEntry | None:
    """Pop the highest-priority ready sheet, respecting limits.

    Returns None if no sheet can run (concurrency full, backpressure
    active, queue empty, or all queued sheets are rate-limited).

    **Single-caller constraint:** The backpressure delay (``asyncio.sleep``)
    runs *outside* the scheduler lock.  If multiple coroutines call
    ``next_sheet()`` concurrently, they may all pass the backpressure
    check before any acquires the lock, effectively bypassing the delay
    for concurrent callers.  The intended usage is a single dispatch
    loop calling ``next_sheet()`` sequentially — the ``JobManager``
    dispatch loop satisfies this constraint.
    """
    # Check backpressure first (outside scheduler lock per lock ordering).
    # TOCTOU note: backpressure state may change between this check and
    # the lock acquisition below, but this is acceptable — backpressure
    # is advisory and the delay is best-effort.
    if self._backpressure is not None:
        allowed, delay = await self._backpressure.can_start_sheet()
        if not allowed:
            return None
        if delay > 0:
            await asyncio.sleep(delay)

    async with self._lock:
        if self._active_count >= self._max_concurrent:
            return None

        # Re-score all queued entries against current running state.
        # Priorities depend on fair-share (which changes as sheets
        # dispatch), so enqueue-time scores go stale.  With typical
        # queue sizes of 10-100 entries, the O(n log n) rebuild is
        # negligible compared to API call latency.
        refreshed: list[SheetEntry] = []
        for entry in self._queue:
            rescored = SheetEntry(
                priority=self._calculate_priority(entry.info),
                submitted_at=entry.submitted_at,
                info=entry.info,
                rate_limit_skip_count=entry.rate_limit_skip_count,
            )
            refreshed.append(rescored)
        heapq.heapify(refreshed)
        self._queue = refreshed

        skipped: list[SheetEntry] = []
        dropped: list[SheetEntry] = []
        result: SheetEntry | None = None

        while self._queue:
            entry = heapq.heappop(self._queue)
            job_id = entry.info.job_id

            # Check per-job hard cap
            job_running = len(self._running.get(job_id, set()))
            registered_job_count = len(self._job_all_sheets)
            fair_share = self._fair_share(registered_job_count)
            hard_cap = int(fair_share * self._max_per_job_multiplier)
            hard_cap = max(1, hard_cap)

            if job_running >= hard_cap:
                skipped.append(entry)
                continue

            # Check rate limiting (outside-lock would violate ordering,
            # but rate_limiter._lock is #2, scheduler._lock is #1 — OK
            # to call while holding #1)
            if self._rate_limiter is not None:
                try:
                    is_limited, _ = await self._rate_limiter.is_rate_limited(
                        entry.info.instrument,
                        model=entry.info.model,
                    )
                except (RuntimeError, ValueError, OSError) as e:
                    entry.rate_limit_skip_count += 1
                    if entry.rate_limit_skip_count >= self._max_rate_limit_skips:
                        _logger.error(
                            "scheduler.rate_limiter_error_exhausted",
                            job_id=job_id,
                            sheet_num=entry.info.sheet_num,
                            skip_count=entry.rate_limit_skip_count,
                            max_skips=self._max_rate_limit_skips,
                            error=str(e),
                            error_type=type(e).__name__,
                        )
                        dropped.append(entry)
                    else:
                        _logger.warning(
                            "scheduler.rate_limiter_error",
                            job_id=job_id,
                            sheet_num=entry.info.sheet_num,
                            skip_count=entry.rate_limit_skip_count,
                            max_skips=self._max_rate_limit_skips,
                            error=str(e),
                            error_type=type(e).__name__,
                        )
                        skipped.append(entry)
                    continue
                if is_limited:
                    skipped.append(entry)
                    continue

            # This sheet can run
            result = entry
            break

        # Put skipped entries back
        for s in skipped:
            heapq.heappush(self._queue, s)

        if result is not None:
            job_id = result.info.job_id
            self._running.setdefault(job_id, set()).add(
                result.info.sheet_num,
            )
            self._active_count += 1

            _logger.debug(
                "scheduler.sheet_dispatched",
                job_id=job_id,
                sheet_num=result.info.sheet_num,
                priority=round(result.priority, 2),
                active=self._active_count,
            )

        return result
mark_complete async
mark_complete(job_id, sheet_num, success)

Mark a sheet as done and enqueue newly-ready dependents.

Parameters:

Name Type Description Default
job_id str

The job that owns this sheet.

required
sheet_num int

Which sheet completed.

required
success bool

Whether execution succeeded.

required
Source code in src/marianne/daemon/scheduler.py
async def mark_complete(
    self, job_id: str, sheet_num: int, success: bool,
) -> None:
    """Mark a sheet as done and enqueue newly-ready dependents.

    Args:
        job_id: The job that owns this sheet.
        sheet_num: Which sheet completed.
        success: Whether execution succeeded.
    """
    async with self._lock:
        # Early-return for unknown job_id to prevent memory leaks
        # from stale or misrouted completion messages.
        if job_id not in self._job_all_sheets:
            _logger.debug(
                "scheduler.mark_complete_unknown_job",
                job_id=job_id,
                sheet_num=sheet_num,
            )
            return

        running = self._running.get(job_id)
        actually_was_running = False
        if running is not None and sheet_num in running:
            running.discard(sheet_num)
            actually_was_running = True

        if actually_was_running:
            self._active_count = max(0, self._active_count - 1)

        completed = self._job_completed.setdefault(job_id, set())
        completed.add(sheet_num)

        _logger.debug(
            "scheduler.sheet_completed",
            job_id=job_id,
            sheet_num=sheet_num,
            success=success,
            active=self._active_count,
        )

        # Enqueue newly-ready dependent sheets
        self._enqueue_ready_dependents(job_id)
get_stats async
get_stats()

Return a snapshot of scheduler state.

Source code in src/marianne/daemon/scheduler.py
async def get_stats(self) -> SchedulerStats:
    """Return a snapshot of scheduler state."""
    async with self._lock:
        per_job_running = {
            jid: len(sheets) for jid, sheets in self._running.items()
        }
        per_job_queued: dict[str, int] = {}
        for entry in self._queue:
            jid = entry.info.job_id
            per_job_queued[jid] = per_job_queued.get(jid, 0) + 1

        return SchedulerStats(
            queued=len(self._queue),
            active=self._active_count,
            max_concurrent=self._max_concurrent,
            per_job_running=per_job_running,
            per_job_queued=per_job_queued,
        )

SchedulerStats dataclass

SchedulerStats(queued, active, max_concurrent, per_job_running, per_job_queued)

Statistics snapshot from the scheduler.

SheetEntry dataclass

SheetEntry(priority, submitted_at, info, rate_limit_skip_count=0)

Priority queue entry for a schedulable sheet.

Ordered by (priority, submitted_at) — lower priority value = higher urgency. The info field is excluded from comparison so that heapq ordering is based solely on the numeric sort keys.

SheetInfo dataclass

SheetInfo(job_id, sheet_num, instrument='', model=None, estimated_cost=0.0, dag_depth=0, job_priority=5, retries_so_far=0)

Metadata about a sheet waiting to be scheduled.

DaemonStatus

Bases: BaseModel

Current status snapshot of the running daemon.

Returned by health check / status queries. Provides a lightweight overview without per-job detail.

JobRequest

Bases: BaseModel

Request to submit a job to the daemon.

Sent by clients (CLI, dashboard) to the daemon over IPC. The daemon validates the config and either accepts or rejects.

JobResponse

Bases: BaseModel

Response from the daemon after a job submission.

Returned immediately — does not wait for job completion. Clients poll status separately via DaemonStatus or job-specific queries.