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
¶
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
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 | |
Attributes¶
running_sheet_count
property
¶
Number of sheets currently in 'dispatched' status.
Methods:¶
set_cron_handler
¶
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
observe_inbox_depth
¶
Record the inbox depth seen by the consumer (#222 high-water mark).
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
drain_skip_events
¶
Return and clear canonical sheet-skip observer events.
drain_flow_events
¶
Drain flow transitions after checkpoint persistence.
Source code in src/marianne/daemon/baton/core.py
register_instrument
¶
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
set_model_concurrency
¶
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
sync_model_concurrency
¶
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 |
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
model_concurrency_snapshot
¶
get_instrument_state
¶
set_active_execution_probe
¶
Set the physical musician-liveness authority used by transitions.
get_job_generation
¶
Return the public event generation for a live managed job.
get_job_registration_token
¶
Return the always-unique private identity of a live registration.
is_job_registration_current
¶
Whether job_id still denotes the captured private identity.
build_dispatch_config
¶
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
set_job_cost_limit
¶
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
get_job_pause_reason
¶
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
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
clear_instrument_rate_limit
¶
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
|
Returns:
| Type | Description |
|---|---|
int
|
Number of instruments whose rate limit was cleared. |
Source code in src/marianne/daemon/baton/core.py
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
set_sheet_cost_limit
¶
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
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
calculate_retry_delay
¶
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 |
float
|
enabled, EQUAL jitter is applied: |
float
|
of |
float
|
full jitter, which can collapse to ~0 and hammer a recovering API), |
float
|
while the spread across |
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
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
|
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
1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 | |
deregister_job
¶
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
get_sheet_state
¶
Get the scheduling state for a specific sheet.
Source code in src/marianne/daemon/baton/core.py
is_job_paused
¶
is_job_complete
¶
Check if all sheets in a job are in terminal state.
Source code in src/marianne/daemon/baton/core.py
has_job
¶
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
get_ready_sheets
¶
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
handle_event
async
¶
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
1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 | |
request_pause
¶
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
run
async
¶
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
get_diagnostics
¶
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.