Skip to content

core

core

Baton core — event inbox, main loop, and sheet registry.

The baton core is the event-driven execution heart of the conductor. It processes events from five sources (musicians, timers, external commands, observer, internal dispatch), maintains per-sheet execution state, resolves ready sheets, and coordinates dispatch.

The main loop is simple by design::

while not shutting_down:
    event = await inbox.get()
    handle(event)        # updates state
    dispatch_ready()     # dispatches sheets if state changed
    persist()            # save if dirty

Everything else — retry logic, rate limit management, cost enforcement — is done inside event handlers, not in separate subsystems.

See: docs/plans/2026-03-26-baton-design.md for the full architecture.

Attributes

Classes

BatonCore

BatonCore(*, timer=None, inbox=None, cron_handler=None)

The baton's event-driven execution core.

Manages the event inbox, processes events, tracks sheet state across all jobs, resolves ready sheets, and coordinates dispatch.

The baton does NOT own backend execution — it decides WHEN to dispatch, not HOW. Sheet execution is delegated to the musician (via dispatch callbacks registered by the conductor).

Usage::

baton = BatonCore()
baton.register_job("j1", sheets, deps)

# Run the main loop (blocks until shutdown)
await baton.run()

# Or process events manually (for testing)
await baton.handle_event(some_event)

Initialize the baton core.

Parameters:

Name Type Description Default
timer Any | None

Optional TimerWheel for scheduling retry delays. When None, retries are set to RETRY_SCHEDULED without actual timer events (tests or manual event injection).

None
inbox Queue[BatonEvent] | None

Optional pre-created event queue. When provided, allows the caller to share the queue with other components (e.g., TimerWheel) before BatonCore is constructed. When None, a new queue is created.

None
Source code in src/marianne/daemon/baton/core.py
def __init__(
    self,
    *,
    timer: Any | None = None,
    inbox: asyncio.Queue[BatonEvent] | None = None,
    cron_handler: CronHandler | None = None,
) -> None:
    """Initialize the baton core.

    Args:
        timer: Optional TimerWheel for scheduling retry delays.
            When None, retries are set to RETRY_SCHEDULED without
            actual timer events (tests or manual event injection).
        inbox: Optional pre-created event queue. When provided, allows
            the caller to share the queue with other components (e.g.,
            TimerWheel) before BatonCore is constructed. When None,
            a new queue is created.
    """
    self._inbox: asyncio.Queue[BatonEvent] = inbox or asyncio.Queue()
    self._jobs: dict[str, _JobRecord] = {}
    self._registration_token_counter: int = 0
    # Adapter-owned physical task authority. The core keeps this as an
    # injected probe so logical state transitions (notably fallback to
    # PENDING) cannot make a still-running musician look unstarted.
    self._active_execution_probe: Callable[[str, int], bool] | None = None
    self._instruments: dict[str, InstrumentState] = {}
    self._job_cost_limits: dict[str, float] = {}
    self._sheet_cost_limits: dict[tuple[str, int], float] = {}
    self._shutting_down = False
    self._running = False
    self._state_dirty = False
    self._timer = timer
    self._cron_handler = cron_handler

    # Active rate-limit timer handles per instrument. When a new
    # RateLimitHit arrives for an instrument that already has a pending
    # timer, the old timer is cancelled before scheduling the new one.
    # Without this, stale timers fire prematurely and cause wasted
    # dispatch→rate_limit→WAITING cycles.
    self._rate_limit_timers: dict[str, Any] = {}

    # Active circuit breaker recovery timer handles per instrument.
    # When a circuit breaker trips OPEN, a recovery timer is scheduled.
    # On fire, the instrument transitions OPEN→HALF_OPEN for a probe.
    # GH#169: Without this, sheets blocked by all-OPEN fallback chains
    # stay PENDING forever.
    self._circuit_breaker_timers: dict[str, Any] = {}

    # Fallback event collection — side effects of event processing.
    # The adapter drains these after each event cycle and publishes
    # them to the EventBus for observability (dashboard, learning hub).
    self._fallback_events: list[InstrumentFallback] = []
    # Canonical skip transitions use the same drain-and-publish pattern,
    # including scheduler-created dependency/fail-fast skips.
    self._skip_events: list[SheetSkipped] = []

    # Per-model concurrency limits from instrument profiles.
    # Keys: "instrument:model", values: max_concurrent.
    # Populated by set_model_concurrency() from instrument profiles.
    self._model_concurrency: dict[str, int] = {}

    # #201: shared self-healing remedy registry, created lazily on the first
    # healing attempt (cheap, but only needed when self_healing is enabled).
    self._healing_registry: Any = None

    # Retry backoff configuration. These match RetryConfig's field defaults;
    # the manager overrides them via configure_retry() once per job/recovery
    # so score-level `retry:` settings are honored (#196). Jitter defaults
    # OFF here (= the historical no-jitter behavior, so bare-BatonCore tests
    # stay deterministic); production turns it ON by threading
    # RetryConfig.jitter (default True). _jitter_fn is injectable for
    # deterministic boundary tests.
    self._base_retry_delay: float = 10.0
    self._retry_exponential_base: float = 2.0
    self._max_retry_delay: float = 3600.0
    self._jitter: bool = False
    self._jitter_fn: Callable[[float, float], float] = random.uniform
    # Startup-failure floor (GH #470): a fast non-zero exit did no work.
    self._startup_failure_floor: float = 120.0
    self._startup_failure_window: float = 60.0

    # DispatchRetry coalescing (#222). DispatchRetry is a pure wake signal:
    # the loop runs dispatch_ready + completion checks after EVERY event, so
    # multiple queued copies are redundant. A failure cascade that wants to
    # wake the loop N times only needs one. This flag keeps at most one
    # DispatchRetry pending; it is cleared when the loop handles it.
    self._dispatch_retry_pending: bool = False

    # #340: one owned TimerHandle per job (plus the legacy scalar key).
    # Handles are cancelled on deregistration and guarded by registration
    # generation so stale timer events cannot affect a reused job ID.
    self._stagger_wake_handles: dict[str, Any] = {}
    # Per-job stagger custody. A shared InstrumentState timestamp would let
    # one score delay another score using the same provider.
    self._job_last_dispatch_at: dict[tuple[str, str], float] = {}

    # Inbox-depth observability (#222). The inbox is intentionally UNBOUNDED
    # — dropping a baton event (a completion, rate-limit hit, retry-due,
    # control command, ...) would strand a sheet or corrupt state, and the
    # self-enqueue sites run on the consumer task so a blocking bounded put
    # would deadlock. Instead of a hard cap we track the high-water mark so
    # a consumer stall (the only way the queue grows without bound) is
    # diagnosable before it can trend toward OOM.
    self._inbox_high_water: int = 0
Attributes
inbox property
inbox

The event inbox — put events here for the baton to process.

is_running property
is_running

Whether the main loop is currently running.

job_count property
job_count

Number of registered jobs.

running_sheet_count property
running_sheet_count

Number of sheets currently in 'dispatched' status.

Methods:
set_cron_handler
set_cron_handler(handler)

Configure the async callback that receives recurring score ticks.

Source code in src/marianne/daemon/baton/core.py
def set_cron_handler(self, handler: CronHandler) -> None:
    """Configure the async callback that receives recurring score ticks."""
    self._cron_handler = handler
enqueue_dispatch_retry
enqueue_dispatch_retry()

Wake the event loop to run a dispatch / completion cycle.

Coalesced (#222): at most one DispatchRetry is ever pending. When the loop is idle (blocked on inbox.get()) the flag is clear, so this enqueues a fresh wake; while one is already queued, additional calls are no-ops because the pending wake already triggers a full dispatch + completion pass. Bounds cascade-driven wake accumulation to O(1).

Source code in src/marianne/daemon/baton/core.py
def enqueue_dispatch_retry(self) -> None:
    """Wake the event loop to run a dispatch / completion cycle.

    Coalesced (#222): at most one ``DispatchRetry`` is ever pending. When
    the loop is idle (blocked on ``inbox.get()``) the flag is clear, so this
    enqueues a fresh wake; while one is already queued, additional calls are
    no-ops because the pending wake already triggers a full dispatch +
    completion pass. Bounds cascade-driven wake accumulation to O(1).
    """
    if self._dispatch_retry_pending:
        return
    self._dispatch_retry_pending = True
    self._inbox.put_nowait(DispatchRetry())
observe_inbox_depth
observe_inbox_depth(depth)

Record the inbox depth seen by the consumer (#222 high-water mark).

Source code in src/marianne/daemon/baton/core.py
def observe_inbox_depth(self, depth: int) -> None:
    """Record the inbox depth seen by the consumer (#222 high-water mark)."""
    if depth > self._inbox_high_water:
        self._inbox_high_water = depth
drain_fallback_events
drain_fallback_events()

Return and clear collected InstrumentFallback events.

Called by the adapter after each event cycle to publish fallback events to the EventBus for observability.

Source code in src/marianne/daemon/baton/core.py
def drain_fallback_events(self) -> list[InstrumentFallback]:
    """Return and clear collected InstrumentFallback events.

    Called by the adapter after each event cycle to publish
    fallback events to the EventBus for observability.
    """
    events = list(self._fallback_events)
    self._fallback_events.clear()
    return events
drain_skip_events
drain_skip_events()

Return and clear canonical sheet-skip observer events.

Source code in src/marianne/daemon/baton/core.py
def drain_skip_events(self) -> list[SheetSkipped]:
    """Return and clear canonical sheet-skip observer events."""
    events = list(self._skip_events)
    self._skip_events.clear()
    return events
drain_flow_events
drain_flow_events()

Drain flow transitions after checkpoint persistence.

Source code in src/marianne/daemon/baton/core.py
def drain_flow_events(self) -> list[BatonEvent]:
    """Drain flow transitions after checkpoint persistence."""
    events: list[BatonEvent] = []
    for job in self._jobs.values():
        if job.flow is not None:
            events.extend(job.flow.drain_events())
    return events
register_instrument
register_instrument(name, *, max_concurrent=4)

Register an instrument for tracking.

If already registered, returns the existing state (idempotent).

Parameters:

Name Type Description Default
name str

Instrument name (matches InstrumentProfile.name).

required
max_concurrent int

Maximum concurrent sheets on this instrument.

4

Returns:

Type Description
InstrumentState

The InstrumentState for the instrument.

Source code in src/marianne/daemon/baton/core.py
def register_instrument(self, name: str, *, max_concurrent: int = 4) -> InstrumentState:
    """Register an instrument for tracking.

    If already registered, returns the existing state (idempotent).

    Args:
        name: Instrument name (matches InstrumentProfile.name).
        max_concurrent: Maximum concurrent sheets on this instrument.

    Returns:
        The InstrumentState for the instrument.
    """
    if name in self._instruments:
        return self._instruments[name]

    state = InstrumentState(name=name, max_concurrent=max_concurrent)
    self._instruments[name] = state
    _logger.debug(
        "baton.instrument_registered",
        extra={"instrument": name, "max_concurrent": max_concurrent},
    )
    return state
set_model_concurrency
set_model_concurrency(instrument, model, max_concurrent)

Set per-model concurrency limit from instrument profile data.

Called during adapter initialization from loaded InstrumentProfiles.

Source code in src/marianne/daemon/baton/core.py
def set_model_concurrency(
    self,
    instrument: str,
    model: str,
    max_concurrent: int,
) -> None:
    """Set per-model concurrency limit from instrument profile data.

    Called during adapter initialization from loaded InstrumentProfiles.
    """
    key = f"{instrument}:{model}"
    self._model_concurrency[key] = max_concurrent
sync_model_concurrency
sync_model_concurrency(caps)

Atomically replace the whole per-model cap map (#408).

Boot-time population used per-key set_model_concurrency; a config reload needs the full lifecycle: changed caps updated AND entries for profiles that disappeared REMOVED. The new map is built fully and the reference swapped in one step — dispatch reads a per-cycle snapshot copy (build_dispatch_config), so it never iterates a dict that is mutating under it.

Parameters:

Name Type Description Default
caps dict[str, int]

Complete desired map {"instrument:model": max_concurrent} from the fresh profile set. Empty dict removes all caps.

required

Returns:

Type Description
dict[str, list[str]]

Diff actually applied: ``{"added": [...], "changed": [...],

dict[str, list[str]]

"removed": [...]}`` of "instrument:model" keys.

Source code in src/marianne/daemon/baton/core.py
def sync_model_concurrency(self, caps: dict[str, int]) -> dict[str, list[str]]:
    """Atomically replace the whole per-model cap map (#408).

    Boot-time population used per-key ``set_model_concurrency``; a config
    reload needs the full lifecycle: changed caps updated AND entries for
    profiles that disappeared REMOVED. The new map is built fully and the
    reference swapped in one step — dispatch reads a per-cycle snapshot
    copy (``build_dispatch_config``), so it never iterates a dict that is
    mutating under it.

    Args:
        caps: Complete desired map ``{"instrument:model": max_concurrent}``
            from the fresh profile set. Empty dict removes all caps.

    Returns:
        Diff actually applied: ``{"added": [...], "changed": [...],
        "removed": [...]}`` of "instrument:model" keys.
    """
    added = [k for k in caps if k not in self._model_concurrency]
    changed = [
        k
        for k, v in caps.items()
        if k in self._model_concurrency and self._model_concurrency[k] != v
    ]
    removed = [k for k in self._model_concurrency if k not in caps]
    self._model_concurrency = dict(caps)
    return {"added": added, "changed": changed, "removed": removed}
model_concurrency_snapshot
model_concurrency_snapshot()

Copy of the live per-model cap map (for status exposure, #408).

Source code in src/marianne/daemon/baton/core.py
def model_concurrency_snapshot(self) -> dict[str, int]:
    """Copy of the live per-model cap map (for status exposure, #408)."""
    return dict(self._model_concurrency)
get_instrument_state
get_instrument_state(name)

Get the tracking state for a specific instrument.

Source code in src/marianne/daemon/baton/core.py
def get_instrument_state(self, name: str) -> InstrumentState | None:
    """Get the tracking state for a specific instrument."""
    return self._instruments.get(name)
set_active_execution_probe
set_active_execution_probe(probe)

Set the physical musician-liveness authority used by transitions.

Source code in src/marianne/daemon/baton/core.py
def set_active_execution_probe(
    self,
    probe: Callable[[str, int], bool] | None,
) -> None:
    """Set the physical musician-liveness authority used by transitions."""
    self._active_execution_probe = probe
get_job_generation
get_job_generation(job_id)

Return the public event generation for a live managed job.

Source code in src/marianne/daemon/baton/core.py
def get_job_generation(self, job_id: str) -> int | None:
    """Return the public event generation for a live managed job."""
    job = self._jobs.get(job_id)
    return job.event_generation if job is not None else None
get_job_registration_token
get_job_registration_token(job_id)

Return the always-unique private identity of a live registration.

Source code in src/marianne/daemon/baton/core.py
def get_job_registration_token(self, job_id: str) -> int | None:
    """Return the always-unique private identity of a live registration."""
    job = self._jobs.get(job_id)
    return job.registration_token if job is not None else None
is_job_registration_current
is_job_registration_current(job_id, token)

Whether job_id still denotes the captured private identity.

Source code in src/marianne/daemon/baton/core.py
def is_job_registration_current(self, job_id: str, token: int) -> bool:
    """Whether ``job_id`` still denotes the captured private identity."""
    job = self._jobs.get(job_id)
    return job is not None and job.registration_token == token
build_dispatch_config
build_dispatch_config(*, max_concurrent_sheets=10, stagger_delay_ms=0, active_executions=None)

Build a DispatchConfig from the current instrument state.

This bridges the gap between the baton's instrument tracking and the dispatch logic's configuration needs. Called before each dispatch cycle.

Parameters:

Name Type Description Default
max_concurrent_sheets int

Global concurrency ceiling.

10

Returns:

Type Description
DispatchConfig

DispatchConfig with rate-limited instruments, open circuit

DispatchConfig

breakers, and per-instrument concurrency limits derived

DispatchConfig

from the current InstrumentState.

Source code in src/marianne/daemon/baton/core.py
def build_dispatch_config(
    self,
    *,
    max_concurrent_sheets: int = 10,
    stagger_delay_ms: int = 0,
    active_executions: dict[tuple[str, int], tuple[str, str | None]] | None = None,
) -> DispatchConfig:
    """Build a DispatchConfig from the current instrument state.

    This bridges the gap between the baton's instrument tracking
    and the dispatch logic's configuration needs. Called before
    each dispatch cycle.

    Args:
        max_concurrent_sheets: Global concurrency ceiling.

    Returns:
        DispatchConfig with rate-limited instruments, open circuit
        breakers, and per-instrument concurrency limits derived
        from the current InstrumentState.
    """
    # Deferred import to break circular dependency
    # (dispatch.py imports BatonCore at runtime)
    from marianne.daemon.baton.dispatch import DispatchConfig  # noqa: N814

    rate_limited: set[str] = set()
    open_breakers: set[str] = set()
    concurrency: dict[str, int] = {}

    for name, inst in self._instruments.items():
        if inst.rate_limited:
            rate_limited.add(name)
        if inst.circuit_breaker == CircuitBreakerState.OPEN:
            open_breakers.add(name)
        concurrency[name] = inst.max_concurrent

    return DispatchConfig(
        max_concurrent_sheets=max_concurrent_sheets,
        instrument_concurrency=concurrency,
        model_concurrency=dict(self._model_concurrency),
        rate_limited_instruments=rate_limited,
        open_circuit_breakers=open_breakers,
        stagger_delay_ms=stagger_delay_ms,
        active_executions=active_executions,
        job_max_concurrent={
            job_id: job.max_concurrent
            for job_id, job in self._jobs.items()
            if job.max_concurrent is not None
        },
        job_stagger_delay_ms={
            job_id: job.stagger_delay_ms
            for job_id, job in self._jobs.items()
            if job.stagger_delay_ms > 0
        },
    )
set_job_cost_limit
set_job_cost_limit(job_id, max_cost_usd)

Set a per-job cost limit. The baton pauses the job when exceeded.

Parameters:

Name Type Description Default
job_id str

The job to set the limit for.

required
max_cost_usd float

Maximum total cost in USD.

required
Source code in src/marianne/daemon/baton/core.py
def set_job_cost_limit(self, job_id: str, max_cost_usd: float) -> None:
    """Set a per-job cost limit. The baton pauses the job when exceeded.

    Args:
        job_id: The job to set the limit for.
        max_cost_usd: Maximum total cost in USD.
    """
    self._job_cost_limits[job_id] = max_cost_usd
get_job_pause_reason
get_job_pause_reason(job_id)

Return a human-readable reason why a job is paused.

Returns "not_paused" if the job isn't paused or isn't registered.

Source code in src/marianne/daemon/baton/core.py
def get_job_pause_reason(self, job_id: str) -> str:
    """Return a human-readable reason why a job is paused.

    Returns "not_paused" if the job isn't paused or isn't registered.
    """
    job = self._jobs.get(job_id)
    if job is None or not job.paused:
        return "not_paused"
    if job.user_paused:
        return "user_initiated"
    limit = self._job_cost_limits.get(job_id)
    if limit is not None:
        total_cost = sum(s.total_cost_usd for s in job.sheets.values())
        if total_cost >= limit:
            return "cost_limit_exceeded"
    if any(s.status == BatonSheetStatus.FERMATA for s in job.sheets.values()):
        return "escalation_needed"
    return "internal"
get_rate_limited_instruments
get_rate_limited_instruments()

Get the set of currently rate-limited instrument names.

Used by dispatch logic to skip rate-limited instruments.

Source code in src/marianne/daemon/baton/core.py
def get_rate_limited_instruments(self) -> set[str]:
    """Get the set of currently rate-limited instrument names.

    Used by dispatch logic to skip rate-limited instruments.
    """
    return {name for name, inst in self._instruments.items() if inst.rate_limited}
clear_instrument_rate_limit
clear_instrument_rate_limit(instrument=None)

Clear rate limit state on one or all instruments.

Resets rate_limited to False and rate_limit_expires_at to None. Also moves any WAITING sheets on the cleared instrument(s) back to PENDING so they can be re-dispatched.

Parameters:

Name Type Description Default
instrument str | None

Instrument name to clear, or None for all.

None

Returns:

Type Description
int

Number of instruments whose rate limit was cleared.

Source code in src/marianne/daemon/baton/core.py
def clear_instrument_rate_limit(
    self,
    instrument: str | None = None,
) -> int:
    """Clear rate limit state on one or all instruments.

    Resets ``rate_limited`` to ``False`` and ``rate_limit_expires_at``
    to ``None``.  Also moves any WAITING sheets on the cleared
    instrument(s) back to PENDING so they can be re-dispatched.

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

    Returns:
        Number of instruments whose rate limit was cleared.
    """
    cleared = 0
    if instrument is not None:
        # Specific instrument — look it up. If not found, targets is
        # empty (return 0). Previously, missing instruments fell through
        # to clear-all — F-200 bug found by Breakpoint M3.
        # Uses `is not None` (not truthiness) to prevent empty string
        # from falling through to clear-all — F-201 (same bug class).
        inst = self._instruments.get(instrument)
        targets = [inst] if inst is not None else []
    else:
        # None → clear all instruments
        targets = list(self._instruments.values())
    for inst in targets:
        if inst.rate_limited:
            inst.rate_limited = False
            inst.rate_limit_expires_at = None
            cleared += 1
            # Move WAITING sheets on this instrument back to PENDING
            for job in self._jobs.values():
                for sheet in job.sheets.values():
                    if (
                        sheet.status == BatonSheetStatus.WAITING
                        and sheet.instrument_name == inst.name
                    ):
                        sheet.status = BatonSheetStatus.PENDING
    if cleared > 0:
        self._state_dirty = True
    # An operator clearing ALL limits expects every rate-limit WAITING
    # sheet to move, including one stranded on a never-limited instrument
    # by an older conductor's fallback race.
    if instrument is None:
        self._release_stranded_waiting_sheets()
    return cleared
get_open_circuit_breakers
get_open_circuit_breakers()

Get the set of instruments with open circuit breakers.

Used by dispatch logic to skip unhealthy instruments.

Source code in src/marianne/daemon/baton/core.py
def get_open_circuit_breakers(self) -> set[str]:
    """Get the set of instruments with open circuit breakers.

    Used by dispatch logic to skip unhealthy instruments.
    """
    return {
        name
        for name, inst in self._instruments.items()
        if inst.circuit_breaker == CircuitBreakerState.OPEN
    }
set_sheet_cost_limit
set_sheet_cost_limit(job_id, sheet_num, max_cost_usd)

Set a per-sheet cost limit. The baton fails the sheet when exceeded.

Parameters:

Name Type Description Default
job_id str

The job containing the sheet.

required
sheet_num int

The sheet number.

required
max_cost_usd float

Maximum cost in USD for this sheet.

required
Source code in src/marianne/daemon/baton/core.py
def set_sheet_cost_limit(self, job_id: str, sheet_num: int, max_cost_usd: float) -> None:
    """Set a per-sheet cost limit. The baton fails the sheet when exceeded.

    Args:
        job_id: The job containing the sheet.
        sheet_num: The sheet number.
        max_cost_usd: Maximum cost in USD for this sheet.
    """
    self._sheet_cost_limits[(job_id, sheet_num)] = max_cost_usd
configure_retry
configure_retry(*, base_delay=None, exponential_base=None, max_delay=None, jitter=None, jitter_fn=None, startup_failure_floor=None, startup_failure_window=None)

Configure per-job retry backoff (#196).

Threaded once from the manager out of the score's RetryConfig (at registration and recovery) so score-level retry: settings reach the scheduler instead of the hardcoded defaults. Backoff params are BatonCore-level (one set per active job) — distinct from the per-sheet max_retries. Only non-None args override, so partial reconfiguration and the constructor defaults both work. jitter_fn is injectable for deterministic boundary tests; production uses random.uniform.

Source code in src/marianne/daemon/baton/core.py
def configure_retry(
    self,
    *,
    base_delay: float | None = None,
    exponential_base: float | None = None,
    max_delay: float | None = None,
    jitter: bool | None = None,
    jitter_fn: Callable[[float, float], float] | None = None,
    startup_failure_floor: float | None = None,
    startup_failure_window: float | None = None,
) -> None:
    """Configure per-job retry backoff (#196).

    Threaded once from the manager out of the score's ``RetryConfig`` (at
    registration and recovery) so score-level ``retry:`` settings reach the
    scheduler instead of the hardcoded defaults. Backoff params are
    BatonCore-level (one set per active job) — distinct from the per-sheet
    ``max_retries``. Only non-None args override, so partial reconfiguration
    and the constructor defaults both work. ``jitter_fn`` is injectable for
    deterministic boundary tests; production uses ``random.uniform``.
    """
    if base_delay is not None:
        self._base_retry_delay = base_delay
    if exponential_base is not None:
        self._retry_exponential_base = exponential_base
    if max_delay is not None:
        self._max_retry_delay = max_delay
    if jitter is not None:
        self._jitter = jitter
    if jitter_fn is not None:
        self._jitter_fn = jitter_fn
    if startup_failure_floor is not None:
        self._startup_failure_floor = startup_failure_floor
    if startup_failure_window is not None:
        self._startup_failure_window = startup_failure_window
calculate_retry_delay
calculate_retry_delay(attempt)

Calculate retry delay using exponential backoff (#196: optional jitter).

Parameters:

Name Type Description Default
attempt int

0-based attempt index (0 = first retry).

required

Returns:

Type Description
float

Delay in seconds, clamped to _max_retry_delay. When jitter is

float

enabled, EQUAL jitter is applied: raw/2 + U(0, raw/2) — the floor

float

of raw/2 preserves at least half the exponential backoff (unlike

float

full jitter, which can collapse to ~0 and hammer a recovering API),

float

while the spread across [raw/2, raw] desynchronizes a thundering

float

herd of simultaneously-failing fan-out sheets. This is the ONLY

float

backoff path; authoritative rate-limit waits are scheduled

float

separately and never jittered.

Source code in src/marianne/daemon/baton/core.py
def calculate_retry_delay(self, attempt: int) -> float:
    """Calculate retry delay using exponential backoff (#196: optional jitter).

    Args:
        attempt: 0-based attempt index (0 = first retry).

    Returns:
        Delay in seconds, clamped to ``_max_retry_delay``. When jitter is
        enabled, EQUAL jitter is applied: ``raw/2 + U(0, raw/2)`` — the floor
        of ``raw/2`` preserves at least half the exponential backoff (unlike
        full jitter, which can collapse to ~0 and hammer a recovering API),
        while the spread across ``[raw/2, raw]`` desynchronizes a thundering
        herd of simultaneously-failing fan-out sheets. This is the ONLY
        backoff path; authoritative rate-limit waits are scheduled
        separately and never jittered.
    """
    delay = self._base_retry_delay * (self._retry_exponential_base**attempt)
    delay = min(delay, self._max_retry_delay)
    if self._jitter:
        half = delay / 2
        delay = half + self._jitter_fn(0, half)
    return delay
register_job
register_job(job_id, sheets, dependencies, *, escalation_enabled=False, self_healing_enabled=False, pacing_seconds=0.0, max_concurrent=None, fail_fast=False, stagger_delay_ms=0, completion_threshold_percent=0.0, event_generation=None, workspace=None, config_path=None, loops=None, triggers=None, flow_state=None, flow_variables=None)

Register a job's sheets with the baton for scheduling.

Parameters:

Name Type Description Default
job_id str

Unique job identifier.

required
sheets dict[int, SheetExecutionState]

Map of sheet_num → SheetExecutionState.

required
dependencies dict[int, list[int]]

Map of sheet_num → list of dependency sheet_nums. Sheets not in this map have no dependencies.

required
escalation_enabled bool

Whether to enter fermata on exhaustion.

False
self_healing_enabled bool

Whether to try healing on exhaustion.

False
pacing_seconds float

Inter-sheet delay after each completion (from pause_between_sheets_seconds). 0 = no delay.

0.0
max_concurrent int | None

Per-job ceiling, or None for serial/legacy jobs.

None
fail_fast bool

Terminalize unstarted work after the first failure.

False
stagger_delay_ms int

Per-job spacing between same-instrument launches.

0
event_generation int | None

Public custody identity for adapter-managed jobs. Direct low-level callers omit it for legacy events.

None
Source code in src/marianne/daemon/baton/core.py
def register_job(
    self,
    job_id: str,
    sheets: dict[int, SheetExecutionState],
    dependencies: dict[int, list[int]],
    *,
    escalation_enabled: bool = False,
    self_healing_enabled: bool = False,
    pacing_seconds: float = 0.0,
    max_concurrent: int | None = None,
    fail_fast: bool = False,
    stagger_delay_ms: int = 0,
    completion_threshold_percent: float = 0.0,
    event_generation: int | None = None,
    workspace: Path | None = None,
    config_path: Path | None = None,
    loops: dict[str, LoopConfig] | None = None,
    triggers: dict[str, SheetTriggerConfig] | None = None,
    flow_state: FlowState | None = None,
    flow_variables: dict[str, Any] | None = None,
) -> None:
    """Register a job's sheets with the baton for scheduling.

    Args:
        job_id: Unique job identifier.
        sheets: Map of sheet_num → SheetExecutionState.
        dependencies: Map of sheet_num → list of dependency sheet_nums.
            Sheets not in this map have no dependencies.
        escalation_enabled: Whether to enter fermata on exhaustion.
        self_healing_enabled: Whether to try healing on exhaustion.
        pacing_seconds: Inter-sheet delay after each completion (from
            ``pause_between_sheets_seconds``). 0 = no delay.
        max_concurrent: Per-job ceiling, or None for serial/legacy jobs.
        fail_fast: Terminalize unstarted work after the first failure.
        stagger_delay_ms: Per-job spacing between same-instrument launches.
        event_generation: Public custody identity for adapter-managed jobs.
            Direct low-level callers omit it for legacy events.
    """
    if job_id in self._jobs:
        _logger.warning(
            "baton.register_job.duplicate",
            extra={"job_id": job_id},
        )
        return

    # Auto-register any instruments used by the job's sheets
    self._auto_register_instruments(sheets)

    self._registration_token_counter = getattr(self, "_registration_token_counter", 0) + 1
    flow = (
        FlowEngine(
            job_id,
            FlowPlan(loops or {}, triggers or {}, flow_variables or {}),
            flow_state if flow_state is not None else FlowState(),
            event_generation=event_generation,
        )
        if loops or triggers
        else None
    )
    if flow is not None and flow.state.pause_reason and not flow.state.escalation_pause_owners:
        # A checkpoint from before escalation ownership was persisted still
        # carries FERMATA sheets and a flow pause reason.
        flow.state.escalation_pause_owners.update(
            num
            for num, sheet in sheets.items()
            if sheet.status == BatonSheetStatus.FERMATA and sheet.fermata_reason
        )
        if (
            not flow.state.escalation_pause_owners
            and flow.state.trigger_pause_reason is None
        ):
            # No FERMATA sheet owns it: the pre-field checkpoint's pause
            # was a trigger `pause`. Re-own it so a later escalation
            # release cannot clear it.
            flow.state.trigger_pause_reason = flow.state.pause_reason
    self._jobs[job_id] = _JobRecord(
        job_id=job_id,
        sheets=sheets,
        dependencies=dependencies,
        escalation_enabled=escalation_enabled,
        self_healing_enabled=self_healing_enabled,
        workspace=workspace,
        config_path=config_path,
        pacing_seconds=pacing_seconds,
        max_concurrent=max_concurrent,
        fail_fast=fail_fast,
        stagger_delay_ms=stagger_delay_ms,
        completion_threshold_percent=completion_threshold_percent,
        registration_token=self._registration_token_counter,
        event_generation=event_generation,
        flow=flow,
    )
    if flow is not None and flow.state.pause_reason is not None:
        self._jobs[job_id].paused = True
    self._state_dirty = True

    # F-440: Re-propagate failure for any sheet that's already FAILED.
    # During normal execution, _propagate_failure_to_dependents() cascades
    # failure to downstream sheets. But _sync_sheet_status() only fires
    # for SheetAttemptResult/SheetSkipped events, so cascaded failures
    # are NOT synced to the checkpoint. On restart recovery, dependents
    # revert to PENDING while their upstream is FAILED → zombie job.
    # Re-running propagation here is idempotent (only touches non-terminal
    # sheets) and fixes the sync gap for both fresh registration and
    # recovery.
    for sheet_num, sheet in sheets.items():
        if sheet.status == BatonSheetStatus.FAILED and not (flow and flow.state.chains):
            self._propagate_failure_to_dependents(job_id, sheet_num)

    if flow is not None and flow.settle(sheets):
        self._state_dirty = True

    _logger.info(
        "baton.job_registered",
        extra={
            "job_id": job_id,
            "sheet_count": len(sheets),
            "dependency_count": len(dependencies),
        },
    )
deregister_job
deregister_job(job_id)

Remove a job from the baton's tracking.

Cleans up all per-job state including cost limit entries to prevent memory leaks in long-running conductors (F-062).

Source code in src/marianne/daemon/baton/core.py
def deregister_job(self, job_id: str) -> None:
    """Remove a job from the baton's tracking.

    Cleans up all per-job state including cost limit entries to
    prevent memory leaks in long-running conductors (F-062).
    """
    if job_id in self._jobs:
        del self._jobs[job_id]
        # F-062: Clean up cost limit dicts to prevent memory leaks
        self._job_cost_limits.pop(job_id, None)
        # Remove sheet cost limits for this job
        sheet_keys_to_remove = [key for key in self._sheet_cost_limits if key[0] == job_id]
        for key in sheet_keys_to_remove:
            del self._sheet_cost_limits[key]
        for dispatch_key in [key for key in self._job_last_dispatch_at if key[0] == job_id]:
            del self._job_last_dispatch_at[dispatch_key]
        stagger_handle = self._stagger_wake_handles.pop(job_id, None)
        if stagger_handle is not None and self._timer is not None:
            self._timer.cancel(stagger_handle)
        self._skip_events = [event for event in self._skip_events if event.job_id != job_id]
        self._state_dirty = True
        _logger.info("baton.job_deregistered", extra={"job_id": job_id})
get_sheet_state
get_sheet_state(job_id, sheet_num)

Get the scheduling state for a specific sheet.

Source code in src/marianne/daemon/baton/core.py
def get_sheet_state(self, job_id: str, sheet_num: int) -> SheetExecutionState | None:
    """Get the scheduling state for a specific sheet."""
    job = self._jobs.get(job_id)
    if job is None:
        return None
    return job.sheets.get(sheet_num)
is_job_paused
is_job_paused(job_id)

Check if a job's dispatch is paused.

Source code in src/marianne/daemon/baton/core.py
def is_job_paused(self, job_id: str) -> bool:
    """Check if a job's dispatch is paused."""
    job = self._jobs.get(job_id)
    return job.paused if job is not None else False
is_job_complete
is_job_complete(job_id)

Check if all sheets in a job are in terminal state.

Source code in src/marianne/daemon/baton/core.py
def is_job_complete(self, job_id: str) -> bool:
    """Check if all sheets in a job are in terminal state."""
    job = self._jobs.get(job_id)
    if job is None:
        return False
    if job.user_paused:
        return False
    if job.flow is not None and (
        job.flow.busy()
        or job.flow.boundary_pending(job.sheets)
        or job.flow.state.pause_reason is not None
    ):
        return False
    return all(sheet.status in _TERMINAL_BATON_STATUSES for sheet in job.sheets.values())
has_job
has_job(job_id)

Whether the baton is currently tracking this job.

The presence predicate for jobs running in the baton event loop, including auto-recovered jobs that have no manager wrapper task. Used by cancel/pause to tell a genuinely-stale "running" status (no live work anywhere) from a live baton job.

Source code in src/marianne/daemon/baton/core.py
def has_job(self, job_id: str) -> bool:
    """Whether the baton is currently tracking this job.

    The presence predicate for jobs running in the baton event loop,
    including auto-recovered jobs that have no manager wrapper task. Used
    by cancel/pause to tell a genuinely-stale "running" status (no live
    work anywhere) from a live baton job.
    """
    return job_id in self._jobs
get_ready_sheets
get_ready_sheets(job_id)

Find sheets that are ready to dispatch.

A sheet is ready when: 1. Status is 'pending' or 'ready' 2. All dependencies are satisfied (completed or skipped) 3. The job is not paused

Source code in src/marianne/daemon/baton/core.py
def get_ready_sheets(self, job_id: str) -> list[SheetExecutionState]:
    """Find sheets that are ready to dispatch.

    A sheet is ready when:
    1. Status is 'pending' or 'ready'
    2. All dependencies are satisfied (completed or skipped)
    3. The job is not paused
    """
    job = self._jobs.get(job_id)
    if job is None or job.paused or job.pacing_active:
        return []
    if job.flow is not None and job.flow.busy():
        return []

    ready: list[SheetExecutionState] = []
    for sheet_num, sheet in job.sheets.items():
        if sheet.status not in _DISPATCHABLE_BATON_STATUSES:
            continue

        # Check dependencies
        deps = job.dependencies.get(sheet_num, [])
        deps_satisfied = (
            job.flow is not None and sheet_num in job.flow.state.goto_bypass
        ) or all(self._is_dependency_satisfied(job, dep) for dep in deps)
        if deps_satisfied:
            ready.append(sheet)

    return ready
handle_event async
handle_event(event)

Process a single event. Updates state but does NOT dispatch.

This is the core decision-making method. Each event type has a specific handler that updates sheet state.

Per the baton spec: handler exceptions are logged, not re-raised. The baton continues processing subsequent events.

Source code in src/marianne/daemon/baton/core.py
async def handle_event(self, event: BatonEvent) -> None:
    """Process a single event. Updates state but does NOT dispatch.

    This is the core decision-making method. Each event type has
    a specific handler that updates sheet state.

    Per the baton spec: handler exceptions are logged, not re-raised.
    The baton continues processing subsequent events.
    """
    try:
        # Per-job async mutators bind the public generation of their
        # intended managed registration. Direct-core legacy records use
        # None and continue accepting generation-less events while live.
        if hasattr(event, "event_generation"):
            event_job_id = getattr(event, "job_id", None)
            if event_job_id is None or not self._event_generation_is_current(
                event_job_id,
                event.event_generation,
                event_type=type(event).__name__,
            ):
                return
        match event:
            # === Musician events ===
            case SheetAttemptResult():
                await self._handle_attempt_result(event)

            case SheetSkipped():
                self._handle_sheet_skipped(event)

            case SheetDispatched():
                self._handle_sheet_dispatched(event)

            # === Rate limit events ===
            case RateLimitHit():
                self._handle_rate_limit_hit(event)

            case RateLimitExpired():
                self._handle_rate_limit_expired(event)

            # === Timer events ===
            case RetryDue():
                self._handle_retry_due(event)

            case StaleCheck():
                self._handle_stale_check(event)

            case LoopFactsReady():
                job = self._jobs.get(event.job_id)
                if job is not None and job.flow is not None:
                    if job.flow.facts_ready(
                        job.sheets,
                        event.span,
                        event.request_id,
                        event.files,
                        event.error,
                    ):
                        self._state_dirty = True

            case FlowRunFinished():
                job = self._jobs.get(event.job_id)
                if job is not None and job.flow is not None:
                    if job.flow.action_finished(
                        job.sheets,
                        event.chain_id,
                        event.cursor,
                        {
                            "exit_code": event.exit_code,
                            "timed_out": event.timed_out,
                            "log_path": event.log_path,
                            "error": event.error,
                        },
                    ):
                        if event.supervisor_pid is not None:
                            job.flow.state.run_cleanup.append({
                                "supervisor_pid": event.supervisor_pid,
                                "reparented_orphans": event.reparented_orphans,
                            })
                        self._state_dirty = True

            case FlowConcertSubmitted():
                job = self._jobs.get(event.job_id)
                if job is not None and job.flow is not None:
                    if job.flow.action_finished(
                        job.sheets,
                        event.chain_id,
                        event.cursor,
                        {
                            "accepted": event.accepted,
                            "child_job_id": event.child_job_id,
                            "message": event.message,
                        },
                    ):
                        self._state_dirty = True

            case CronTick():
                if self._cron_handler is None:
                    _logger.error(
                        "baton.cron_handler_missing",
                        extra={
                            "entry_name": event.entry_name,
                            "score_path": event.score_path,
                            "due_at": event.due_at,
                        },
                    )
                else:
                    await self._cron_handler(event)

            case JobTimeout():
                self._handle_job_timeout(event)

            case PacingComplete():
                self._handle_pacing_complete(event)

            # === Escalation events ===
            case EscalationNeeded():
                self._handle_escalation_needed(event)

            case EscalationResolved():
                self._handle_escalation_resolved(event)

            case EscalationTimeout():
                self._handle_escalation_timeout(event)

            # === External command events ===
            case PauseJob():
                self._handle_pause_job(event)

            case ResumeJob():
                self._handle_resume_job(event)

            case CancelJob():
                self._handle_cancel_job(event)

            case ConfigReloaded():
                _logger.warning(
                    "baton.event.unimplemented",
                    extra={"event_type": "ConfigReloaded"},
                )

            case ShutdownRequested():
                self._handle_shutdown(event)

            # === Observer events ===
            case ProcessExited():
                await self._handle_process_exited(event)

            case ResourceAnomaly():
                self._handle_resource_anomaly(event)

            # === Instrument fallback events ===
            case InstrumentFallback():
                # InstrumentFallback events are emitted by the baton
                # itself, not received from external sources. They pass
                # through the event bus for observability (dashboard,
                # learning hub, notifications). No handler needed.
                pass

            # === Internal events ===
            case DispatchRetry():
                # Wake signal consumed — clear the coalescing flag so the
                # next cascade can enqueue a fresh wake (#222). Dispatch and
                # completion checks run in the adapter loop after this.
                self._dispatch_retry_pending = False
                # #340: release only the handle belonging to the same job
                # registration. Stale events from a cancelled/replaced
                # timer cannot clear a reused job ID's live handle.
                if event.stagger_job_id is not None:
                    job = self._jobs.get(event.stagger_job_id)
                    if job is not None and event.stagger_generation == job.registration_token:
                        self._stagger_wake_handles.pop(event.stagger_job_id, None)
                elif event.stagger_generation == 0:
                    self._stagger_wake_handles.pop("__legacy__", None)

            case CircuitBreakerRecovery():
                self._handle_circuit_breaker_recovery(event)

            case _:
                _logger.warning(
                    "baton.unknown_event",
                    extra={"event_type": type(event).__name__},
                )

        event_job_id = getattr(event, "job_id", None)
        if isinstance(event_job_id, str):
            self._settle_flow(event_job_id)

    except Exception:
        # #317: include the job/sheet context (when the event carries it)
        # so a handler traceback can be correlated to a specific job in a
        # multi-job conductor without timestamp-based log grepping.
        _logger.error(
            "baton.event_handler_failed",
            extra={
                "event_type": type(event).__name__,
                "job_id": getattr(event, "job_id", None),
                "sheet_num": getattr(event, "sheet_num", None),
            },
            exc_info=True,
        )
request_pause
request_pause(job_id)

Eagerly close the dispatch gate for a job, synchronously (#184).

Called from the producer side (JobManager.pause_job) BEFORE the PauseJob event is enqueued. dispatch_ready gates on job.paused, but that flag was previously set only when the PauseJob event was processed — so a sheet completion queued ahead of the pause would dispatch the next sheet before the pause was seen. Setting the gate here, synchronously, closes the race: on the single-threaded event loop no dispatch can run between this call and the caller's next await.

Sets user_paused too (not just paused): otherwise an escalation timeout — which clears paused only if not user_paused — could unpause a user-paused job in the window before the PauseJob event lands (#326). _handle_pause_job then becomes an idempotent re-set.

Returns True if the job exists in the baton, False otherwise.

Source code in src/marianne/daemon/baton/core.py
def request_pause(self, job_id: str) -> bool:
    """Eagerly close the dispatch gate for a job, synchronously (#184).

    Called from the producer side (``JobManager.pause_job``) BEFORE the
    ``PauseJob`` event is enqueued. ``dispatch_ready`` gates on ``job.paused``,
    but that flag was previously set only when the ``PauseJob`` event was
    *processed* — so a sheet completion queued ahead of the pause would
    dispatch the next sheet before the pause was seen. Setting the gate here,
    synchronously, closes the race: on the single-threaded event loop no
    dispatch can run between this call and the caller's next ``await``.

    Sets ``user_paused`` too (not just ``paused``): otherwise an escalation
    timeout — which clears ``paused`` only ``if not user_paused`` — could
    unpause a user-paused job in the window before the ``PauseJob`` event
    lands (#326). ``_handle_pause_job`` then becomes an idempotent re-set.

    Returns True if the job exists in the baton, False otherwise.
    """
    job = self._jobs.get(job_id)
    if job is None:
        return False
    job.paused = True
    job.user_paused = True
    self._state_dirty = True
    return True
run async
run()

The baton's main event loop.

Processes events from the inbox, updates state, and dispatches ready sheets. Runs until a ShutdownRequested event is received.

Source code in src/marianne/daemon/baton/core.py
async def run(self) -> None:
    """The baton's main event loop.

    Processes events from the inbox, updates state, and dispatches
    ready sheets. Runs until a ShutdownRequested event is received.
    """
    self._running = True
    _logger.info("baton.started")

    try:
        while not self._shutting_down:
            event = await self._inbox.get()
            await self.handle_event(event)
            # dispatch_ready() would be called here when wired to
            # conductor
    except asyncio.CancelledError:
        _logger.info("baton.cancelled")
        raise
    finally:
        self._running = False
        _logger.info("baton.stopped")
get_diagnostics
get_diagnostics(job_id)

Get diagnostic information for a job.

Returns a dict with sheet counts by status, instrument state, and other debugging information. Returns None if job not found.

Source code in src/marianne/daemon/baton/core.py
def get_diagnostics(self, job_id: str) -> dict[str, Any] | None:
    """Get diagnostic information for a job.

    Returns a dict with sheet counts by status, instrument state,
    and other debugging information. Returns None if job not found.
    """
    job = self._jobs.get(job_id)
    if job is None:
        return None

    status_counts: dict[str, int] = {}
    instruments_used: set[str] = set()
    for sheet in job.sheets.values():
        status_key = sheet.status.value
        status_counts[status_key] = status_counts.get(status_key, 0) + 1
        if sheet.instrument_name:
            instruments_used.add(sheet.instrument_name)

    return {
        "job_id": job_id,
        "paused": job.paused,
        "sheets": {
            "total": len(job.sheets),
            **status_counts,
        },
        "instruments_used": sorted(instruments_used),
        "parallel_policy": {
            "max_concurrent": job.max_concurrent,
            "fail_fast": job.fail_fast,
            "stagger_delay_ms": job.stagger_delay_ms,
        },
        # Inbox depth observability (#222) — the inbox is process-wide, not
        # per-job, but surfacing it here makes a consumer stall visible via
        # `mzt diagnose` without a log grep.
        "inbox_depth": self._inbox.qsize(),
        "inbox_high_water": self._inbox_high_water,
    }

Functions: