Index
baton
¶
The Baton — Marianne's event-driven execution heart.
The baton is the conductor's primary tool. It doesn't decide what to play — the score does. It doesn't decide how to play — the musicians do. The baton controls when and how much: tempo, dynamics, cues, and fermatas.
The baton replaces the current monolithic execution model where
JobService.start_job() runs all sheets sequentially. Instead, the baton
manages sheets across all jobs in a single event-driven loop, dispatching
them to execution when they're ready and the system can handle them.
Package layout::
events.py — All BatonEvent types (dataclasses)
timer.py — Timer wheel (priority queue of future events)
state.py — Baton state models (sheet/instrument/job tracking)
core.py — Event inbox, main loop, sheet registry
musician.py — Single-attempt sheet execution (play once, report)
backend_pool.py — Per-instrument backend instance management
adapter.py — Wires baton into conductor (step 28)
Classes¶
BatonAdapter
¶
BatonAdapter(*, event_bus=None, max_concurrent_sheets=10, state_sync_callback=None, persist_callback=None, learning_store=None, rate_limit_reporter=None, diagnostic_snapshot_fn=None, flow_pause_callback=None, flow_concert_callback=None)
Bridges the conductor (JobManager) and the baton (BatonCore).
The adapter owns: - A BatonCore instance (event loop, sheet registry, state machine) - A mapping of job_id → Sheet[] (for prompt rendering at dispatch time) - Active musician tasks (asyncio.Task per dispatched sheet)
The adapter does NOT own: - The BackendPool (injected by the manager) - The EventBus (injected by the manager) - The CheckpointState (managed by the manager's state backend)
Usage::
adapter = BatonAdapter(event_bus=bus)
adapter.set_backend_pool(pool)
# Register a job
adapter.register_job("j1", sheets, deps)
# Run the baton (blocks until shutdown)
await adapter.run()
Initialize the BatonAdapter.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
event_bus
|
EventBus | None
|
Optional EventBus for publishing events to subscribers. |
None
|
max_concurrent_sheets
|
int
|
Global concurrency ceiling for dispatch. |
10
|
state_sync_callback
|
StateSyncCallback | None
|
Deprecated — kept for backward compat. Phase 2 uses persist_callback instead. |
None
|
persist_callback
|
PersistCallback | None
|
Called with job_id after significant state transitions (terminal, dispatch) to persist CheckpointState to the registry. Replaces the sync layer. |
None
|
learning_store
|
GlobalLearningStore | None
|
Optional GlobalLearningStore handle for injecting learned patterns into prompts (#200). None (and store-less paths) cleanly skip the layer. |
None
|
rate_limit_reporter
|
RateLimitReporter | None
|
Optional async write-through to the daemon's RateLimitCoordinator (#206). Every RateLimitHit the run loop processes is mirrored here so daemon-level consumers (backpressure, submit-time warnings, the scheduler) see the same limits the baton is already enforcing at dispatch. None (tests, standalone use) skips the mirror. |
None
|
diagnostic_snapshot_fn
|
DiagnosticSnapshotFn | None
|
Optional sync runtime-diagnostics provider (#133): observer file/process events + resource state attached to the retry failure-evidence context so the agent sees what its previous attempt actually did. Fail-open; None skips enrichment (plain #201 evidence). |
None
|
Source code in src/marianne/daemon/baton/adapter.py
575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 | |
Attributes¶
Methods:¶
set_backend_pool
¶
Inject the BackendPool for backend acquisition.
Must be called before dispatching any sheets.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pool
|
BackendPool
|
The backend pool from the manager. |
required |
Source code in src/marianne/daemon/baton/adapter.py
set_cron_handler
¶
schedule_cron_tick
¶
Schedule a recurring-score tick on the shared timer wheel.
cancel_cron_tick
¶
set_mcp_pool
¶
set_memory_gate
¶
Inject the memory dispatch gate; jobs already registered are handed to it.
Source code in src/marianne/daemon/baton/adapter.py
configure_retry
¶
configure_retry(*, base_delay=None, exponential_base=None, max_delay=None, jitter=None, startup_failure_floor=None, startup_failure_window=None)
Thread the score's RetryConfig backoff settings to the baton (#196).
Pass-through to BatonCore.configure_retry. Called once per job at
registration (and recovery) so score-level retry: timing reaches the
scheduler instead of the hardcoded defaults.
Source code in src/marianne/daemon/baton/adapter.py
register_job
¶
register_job(job_id, sheets, dependencies, *, max_cost_usd=None, max_sheet_cost_usd=None, max_retries=3, max_completion=5, completion_threshold_percent=0.0, escalation_enabled=False, self_healing_enabled=False, prompt_config=None, learning_config=None, parallel_enabled=None, parallel_max_concurrent=None, parallel_fail_fast=False, cross_sheet=None, pacing_seconds=0.0, live_sheets=None, techniques=None, memory=None, memory_movement_names=None, stale_detection=None, spec_config=None, spec_tags=None, stagger_delay_ms=0, skip_when=None, code_execution=None, agent_card=None, cleanup_generation=None, schedule_id=None, scheduled_due_at=None, loops=None, triggers=None, flow_state=None, flow_variables=None, declared_products=None, ledger_scope=None)
Register a job with the baton for event-driven execution.
Converts Sheet entities to SheetExecutionState and registers them with the baton's sheet registry.
Phase 2: when live_sheets is provided, uses those SheetState
objects directly instead of creating new ones. This ensures the
baton writes to the same objects that live in _live_states,
eliminating the need for a sync layer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
job_id
|
str
|
Unique job identifier (conductor job_id). |
required |
sheets
|
list[Sheet]
|
Sheet entities from build_sheets(). |
required |
dependencies
|
dict[int, list[int]]
|
Dependency graph {sheet_num: [dep_nums]}. |
required |
max_cost_usd
|
float | None
|
Optional per-job cost limit. |
None
|
max_retries
|
int
|
Max normal retry attempts per sheet. |
3
|
max_completion
|
int
|
Max completion mode attempts per sheet. |
5
|
escalation_enabled
|
bool
|
Enter fermata on exhaustion. |
False
|
self_healing_enabled
|
bool
|
Try self-healing on exhaustion. |
False
|
prompt_config
|
PromptConfig | None
|
Optional PromptConfig for full prompt rendering. When provided, creates a PromptRenderer for this job that handles the complete 9-layer prompt assembly pipeline. |
None
|
parallel_enabled
|
bool | None
|
Whether parallel execution is enabled. Explicit False enforces the score-facing serial contract; None retains legacy direct-caller scheduling behavior. |
None
|
parallel_max_concurrent
|
int | None
|
Score-owned dispatch ceiling when parallel execution is enabled. None preserves legacy/global behavior. |
None
|
parallel_fail_fast
|
bool
|
Stop starting new sheets in this job after a failure when parallel execution is enabled. |
False
|
cross_sheet
|
CrossSheetConfig | None
|
Optional CrossSheetConfig for cross-sheet context (F-210). When provided, the adapter collects previous sheet outputs and workspace files at dispatch time. |
None
|
cleanup_generation
|
str | None
|
Optional manager-issued execution generation. Direct adapter registrations allocate their own local value. |
None
|
Source code in src/marianne/daemon/baton/adapter.py
886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 | |
get_router
¶
Return the per-job TechniqueRouter, or None if not activated.
The router is created by :meth:register_job when the job declares
one or more techniques. Jobs without techniques (the default for
legacy scores) have no router and classification is skipped.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
job_id
|
str
|
The job to look up. |
required |
Returns:
| Type | Description |
|---|---|
TechniqueRouter | None
|
The job's TechniqueRouter if one was activated, else None. |
Source code in src/marianne/daemon/baton/adapter.py
get_a2a_inbox
¶
Return the per-job A2A inbox, or None when no card is registered.
get_process_group_cleanup_result
¶
Return the live cleanup evidence for a deregistered job.
The returned result is intentionally live while the SIGTERM grace
callback is pending. Callers can therefore observe the later
SIGKILL and residual-process check instead of retaining the initial
pending snapshot forever.
Source code in src/marianne/daemon/baton/adapter.py
begin_cleanup_generation
¶
Begin or bind one local execution generation for cleanup evidence.
Source code in src/marianne/daemon/baton/adapter.py
deregister_job
¶
Remove a job from the adapter and baton.
Cleans up all per-job state including active tasks.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
job_id
|
str
|
The job to remove. |
required |
Source code in src/marianne/daemon/baton/adapter.py
1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 | |
recover_job
¶
recover_job(job_id, sheets, dependencies, checkpoint, *, max_cost_usd=None, max_sheet_cost_usd=None, max_retries=3, max_completion=5, completion_threshold_percent=0.0, escalation_enabled=False, self_healing_enabled=False, prompt_config=None, learning_config=None, parallel_enabled=None, parallel_max_concurrent=None, parallel_fail_fast=False, cross_sheet=None, pacing_seconds=0.0, live_sheets=None, techniques=None, memory=None, memory_movement_names=None, stale_detection=None, spec_config=None, spec_tags=None, stagger_delay_ms=0, skip_when=None, code_execution=None, agent_card=None, loops=None, triggers=None, flow_variables=None, declared_products=None, ledger_scope=None)
Recover a job from a checkpoint after conductor restart.
Rebuilds baton state from the persisted CheckpointState. Terminal sheets (completed, failed, skipped) keep their status. In-progress sheets are reset to PENDING because their musicians died when the conductor restarted. Attempt counts are preserved to avoid infinite retries.
Design invariant: Checkpoint is the source of truth. The baton rebuilds from checkpoint, not the reverse.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
job_id
|
str
|
Unique job identifier. |
required |
sheets
|
list[Sheet]
|
Sheet entities from build_sheets() — same config that produced the original job. |
required |
dependencies
|
dict[int, list[int]]
|
Dependency graph {sheet_num: [dep_nums]}. |
required |
checkpoint
|
CheckpointState
|
Persisted CheckpointState loaded from workspace. |
required |
max_cost_usd
|
float | None
|
Optional per-job cost limit. |
None
|
max_retries
|
int
|
Max normal retry attempts per sheet. |
3
|
max_completion
|
int
|
Max completion mode attempts per sheet. |
5
|
escalation_enabled
|
bool
|
Enter fermata on exhaustion. |
False
|
self_healing_enabled
|
bool
|
Try self-healing on exhaustion. |
False
|
prompt_config
|
PromptConfig | None
|
Optional PromptConfig for prompt rendering. |
None
|
parallel_enabled
|
bool | None
|
Whether parallel execution is enabled. Explicit False restores the score-facing serial contract; None retains legacy direct-caller scheduling behavior. |
None
|
parallel_max_concurrent
|
int | None
|
Restored score-owned dispatch ceiling. |
None
|
parallel_fail_fast
|
bool
|
Restored score-owned fail-fast policy. |
False
|
cross_sheet
|
CrossSheetConfig | None
|
Optional CrossSheetConfig for cross-sheet context (F-210). |
None
|
Source code in src/marianne/daemon/baton/adapter.py
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 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 | |
get_sheet
¶
Get a Sheet entity for a registered job.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
job_id
|
str
|
The job identifier. |
required |
sheet_num
|
int
|
The sheet number. |
required |
Returns:
| Type | Description |
|---|---|
Sheet | None
|
The Sheet entity, or None if not found. |
Source code in src/marianne/daemon/baton/adapter.py
wait_for_completion
async
¶
Wait until a job reaches terminal state.
Blocks until all sheets in the job are completed, failed, skipped, or cancelled. Used by the manager's _run_job_task to await baton execution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
job_id
|
str
|
The job to wait for. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if all sheets completed successfully, False if any failed. |
Raises:
| Type | Description |
|---|---|
KeyError
|
If the job is not registered. |
Source code in src/marianne/daemon/baton/adapter.py
has_job
¶
Whether the baton is currently tracking this job.
Delegates to the baton's presence predicate. Used by the manager to cancel auto-recovered baton jobs that have no wrapper task (#162).
Source code in src/marianne/daemon/baton/adapter.py
has_completed_sheets
¶
Check if any sheet in the job reached COMPLETED status.
F-145: Used by the manager to set completed_new_work after baton execution. The zero-work guard for concert chaining needs to know whether any sheet completed new work — not just whether all sheets succeeded.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
job_id
|
str
|
The job to check. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if at least one sheet completed, False otherwise. |
Source code in src/marianne/daemon/baton/adapter.py
clear_instrument_rate_limit
¶
Clear instrument rate limit state in the baton core.
Delegates to BatonCore.clear_instrument_rate_limit(). Also
moves WAITING sheets 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/adapter.py
publish_sheet_skipped
async
¶
Publish a sheet skip event to the EventBus.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
event
|
SheetSkipped
|
The sheet skip event. |
required |
Source code in src/marianne/daemon/baton/adapter.py
publish_job_event
async
¶
Publish a job-level event to the EventBus.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
job_id
|
str
|
The job identifier. |
required |
event_name
|
str
|
Event name (e.g., "job.started", "job.completed"). |
required |
data
|
dict[str, Any] | None
|
Optional event data. |
None
|
Source code in src/marianne/daemon/baton/adapter.py
active_musicians
¶
Every musician still in flight: job, sheet, instrument, model, elapsed.
The rows a graceful drain is waiting on (GH #476). Task authority is what counts — a sheet relabelled WAITING on the baton side is still in flight while its task runs.
Source code in src/marianne/daemon/baton/adapter.py
set_max_concurrent_sheets
¶
Live-resize the global sheet-dispatch ceiling (#408, #231 pattern).
The run loop rebuilds DispatchConfig from this attribute every
cycle, so an in-place update takes effect on the next dispatch pass —
no object replacement, no baton restart. Lowering never cancels
in-flight sheets: running executions drain, new dispatch waits until
the global running count drops below the new limit. Raising enqueues a
coalesced DispatchRetry so waiting sheets dispatch immediately
instead of idling until an unrelated event.
Source code in src/marianne/daemon/baton/adapter.py
sync_model_concurrency
¶
Replace the live per-model cap map from fresh profiles (#408).
Delegates to BatonCore.sync_model_concurrency (atomic swap with
removal) and wakes the dispatch loop so a raised cap releases
waiting sheets without waiting for an unrelated event.
Source code in src/marianne/daemon/baton/adapter.py
model_concurrency_snapshot
¶
resolve_fermata
¶
Resolve a FERMATA sheet on the composer's behalf (#361).
Backs mzt resolve via the job.resolve_escalation IPC method.
Writes the SAME decision marker a composer would create by hand,
then enqueues an immediate FermataCheck so the existing poll
handler consumes it — one consumption path, restart-safe (the
marker survives a crash between write and consumption), and the
consumed/ audit trail is preserved.
Returns:
| Type | Description |
|---|---|
bool
|
|
str
|
the decision is invalid or the sheet is not in FERMATA. |
Source code in src/marianne/daemon/baton/adapter.py
run
async
¶
Run the baton's event loop with dispatch integration.
Processes events from the inbox, updates state, dispatches ready sheets, and publishes events to the EventBus.
Runs until the baton receives a ShutdownRequested event.
Source code in src/marianne/daemon/baton/adapter.py
5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 | |
shutdown
async
¶
Gracefully shut down the adapter.
Cancels all active musician tasks and closes the backend pool.
Source code in src/marianne/daemon/baton/adapter.py
BackendPool
¶
Manages Backend instances for per-sheet execution.
The baton acquires a backend before dispatching a sheet and releases it after the sheet completes (or fails). The pool enforces per-instrument concurrency by tracking in-flight instances.
Usage::
pool = BackendPool(registry)
# Dispatch a sheet
backend = await pool.acquire("claude-code", working_directory=ws)
try:
result = await backend.execute(prompt)
finally:
await pool.release("claude-code", backend)
# Job done
await pool.close_all()
Source code in src/marianne/daemon/baton/backend_pool.py
Methods:¶
acquire
async
¶
Acquire a Backend instance for an instrument.
For CLI instruments: returns a free instance if available, otherwise creates a new one. For HTTP instruments: returns the shared singleton (creating it on first call).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
instrument_name
|
str
|
Name of the instrument (from registry). |
required |
model
|
str | None
|
Optional model override for this execution. |
None
|
working_directory
|
Path | None
|
Working directory for the backend. |
None
|
interactive
|
bool | None
|
Tri-state execution-mode request. None (default) = use the profile's default — interactive when the profile carries verified interactive support, headless otherwise. True = force interactive (error if unsupported). False = force headless. Interactive instances live in their own free list — they never cross-pollinate with headless ones. |
None
|
Returns:
| Type | Description |
|---|---|
Backend
|
A Backend instance ready for execution. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the instrument is not registered, or interactive was explicitly requested for an instrument without verified interactive support. |
RuntimeError
|
If the pool has been closed. |
Source code in src/marianne/daemon/baton/backend_pool.py
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 | |
release
async
¶
Release a Backend instance back to the pool.
For CLI instruments: the backend goes back to the free list for reuse. For HTTP instruments: no-op (the singleton stays active).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
instrument_name
|
str
|
The instrument name used in |
required |
backend
|
Backend
|
The Backend instance to release. |
required |
Source code in src/marianne/daemon/baton/backend_pool.py
invalidate
¶
Drop cached backends so the next acquire rebuilds from the current registry profiles (#171 hot-reload).
Idle backends (free lists, HTTP singletons) are dropped now; in-flight backends finish on their loaded profile and are dropped on release via the generation check. Synchronous + lock-free: it only bumps a counter and clears dicts, so it is safe to call from the SIGHUP handler.
Source code in src/marianne/daemon/baton/backend_pool.py
in_flight_count
¶
How many backends are currently acquired for this instrument.
Used by the baton's dispatch logic to enforce per-instrument concurrency limits.
Source code in src/marianne/daemon/baton/backend_pool.py
total_in_flight
¶
create_one_off
¶
Create a one-off Backend outside the dispatch-pool lifecycle.
Public seam for daemon-side services (interactive model nudges)
that need an LLM backend without acquiring a dispatch slot.
Delegates to create_backend_for_instrument — the single
creation path — so service backends and musician backends can
never drift. The caller owns closing the returned backend.
Source code in src/marianne/daemon/baton/backend_pool.py
close_all
async
¶
Close all Backend instances and mark the pool as closed.
Called at job completion, cancellation, or conductor shutdown.
After this call, acquire() raises RuntimeError.
Source code in src/marianne/daemon/baton/backend_pool.py
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.
Source code in src/marianne/daemon/baton/core.py
CancelJob
dataclass
¶
Cancel all sheets for a job and deregister it from the baton.
In-flight sheet tasks are cancelled. The job is marked as cancelled in CheckpointState.
CircuitBreakerRecovery
dataclass
¶
Timer fired — check if a circuit-broken instrument can accept a probe.
When a circuit breaker trips OPEN, the baton schedules this event via the timer wheel. On fire, the instrument transitions from OPEN to HALF_OPEN, allowing one probe request through. The next dispatch cycle picks up any PENDING sheets blocked by the dead-ended fallback chain.
If the probe succeeds, the breaker closes. If it fails, the breaker reopens and a new recovery timer is scheduled with increased backoff.
GH#169: Without this, sheets whose entire fallback chain is circuit-broken stay PENDING forever — the score appears RUNNING but is dead.
ConfigReloaded
dataclass
¶
Config has changed for a job (SIGHUP, mzt modify, resume -c).
The baton rebuilds pending sheets from the new config. Completed sheets are preserved. Cost limits may be reset if they changed.
CronTick
dataclass
¶
Timer fired — a cron-scheduled job should be submitted.
The baton submits the configured score as a new job and schedules the next tick. If a previous run is still active, this tick is skipped.
DispatchRetry
dataclass
¶
Internal signal to retry dispatch after a backpressure delay.
When the baton encounters backpressure during dispatch, it schedules this event via the timer wheel rather than blocking.
EscalationNeeded
dataclass
¶
EscalationNeeded(job_id, sheet_num, reason, options=list(), timestamp=time(), *, event_generation=None)
A sheet execution requires composer judgment — enter fermata.
The baton pauses the job's dispatch and notifies the composer (human or AI) via configured channels. A timeout timer is scheduled.
EscalationResolved
dataclass
¶
The composer has made a decision on a fermata.
The baton applies the decision and resumes dispatching for the job.
Arrives via IPC (job.resolve_escalation method).
EscalationTimeout
dataclass
¶
Timer fired — no escalation response received within the deadline.
The baton defaults to the safe action: fail the sheet (not the job) and resume dispatching for other sheets.
FermataCheck
dataclass
¶
Timer fired — poll for a composer's resolution marker on a FERMATA sheet (#361).
A sheet in FERMATA is paused awaiting a composer decision. The adapter
polls {workspace}/markers/fermata/{job_id}/sheet-{N}.{decision} and, on
a valid marker, emits the existing EscalationResolved event. The poll
reschedules itself only while the sheet remains FERMATA.
JobTimeout
dataclass
¶
Timer fired — a job has exceeded its wall-clock time limit.
The baton cancels all remaining sheets for this job.
PacingComplete
dataclass
¶
Timer fired — the inter-sheet pacing delay for a job has elapsed.
The baton clears the pacing flag, allowing the next sheet to dispatch.
Implements pause_between_sheets_seconds from score config.
PauseJob
dataclass
¶
Pause dispatching for a job. In-flight sheets continue to completion.
No new sheets are dispatched until ResumeJob is received. Retry timers are preserved — when resumed, scheduled retries fire normally.
ProcessExited
dataclass
¶
Observer detected that a backend process died unexpectedly.
The baton checks if this was a sheet's backend process and, if so, marks the sheet as crashed — faster than waiting for timeout.
RateLimitExpired
dataclass
¶
Timer fired — check if the rate-limited instrument is available again.
If the instrument is still unavailable, the baton schedules another timer. If available, sheets waiting on this instrument become ready.
RateLimitHit
dataclass
¶
An instrument hit a rate limit. NOT a failure — a tempo change.
The baton marks the instrument as rate-limited and schedules a timer for recovery. Sheets targeting this instrument move to waiting state. Other instruments are completely unaffected.
ResourceAnomaly
dataclass
¶
Observer/monitor detected a resource pressure event.
Critical severity triggers backpressure — the baton stops dispatching new sheets and lets running sheets drain.
ResumeJob
dataclass
¶
Resume dispatching for a paused job, optionally with new config.
When new_config is provided, pending sheets are rebuilt from the
new config. Completed sheets are preserved. Failed sheets being
retried use the new config for the retry.
RetryDue
dataclass
¶
Timer fired — a previously failed sheet is ready for retry.
The baton moves the sheet from retry-scheduled to ready state. The next dispatch cycle will pick it up.
SheetAttemptResult
dataclass
¶
SheetAttemptResult(job_id, sheet_num, instrument_name, attempt, execution_success=True, exit_code=None, duration_seconds=0.0, validations_passed=0, validations_total=0, validation_pass_rate=0.0, validation_details=None, error_classification=None, error_message=None, error_code=None, exit_reason=None, rate_limited=False, rate_limit_wait_seconds=None, cost_usd=0.0, input_tokens=0, output_tokens=0, cache_read_tokens=0, cache_write_tokens=0, cost_uncertain=False, preflight_warnings=list(), prompt_receipt=None, model_used=None, stdout_tail='', stderr_tail='', structured_output=None, structured_output_omitted=False, output_kind=None, tool_calls=list(), a2a_requests=list(), timestamp=time(), model_echo_status=None, model_observed=None, model_requested=None, *, event_generation=None, dispatch_epoch=None)
A musician reports the result of a single sheet attempt.
This is the central event in the baton's event loop. The musician plays once and reports in full detail. The conductor (baton) decides what happens next — retry, completion mode, healing, escalation, or accept.
Rate limits are NOT failures. When rate_limited is True, the baton
re-queues the sheet for when the instrument recovers. No retry budget
is consumed.
Attributes¶
validation_pass_rate
class-attribute
instance-attribute
¶
Percentage of validations that passed (0.0-100.0).
CRITICAL CONTRACT (F-018): Set to 100.0 when execution succeeds with no validation rules OR when all validations pass. The baton treats the default (0.0) as "all validations failed" and will retry.
A musician that reports execution_success=True with
validations_total=0 but leaves this at 0.0 will trigger
unnecessary retries until max_retries is exhausted.
rate_limit_wait_seconds
class-attribute
instance-attribute
¶
Parsed wait duration from the API's rate limit error message.
When set, the baton uses this instead of the default 60s for scheduling the recovery timer. This is the actual duration the API told us to wait.
SheetSkipped
dataclass
¶
SheetSkipped(job_id, sheet_num, reason, timestamp=time(), *, event_generation=None, dispatch_epoch=None)
A sheet was skipped due to skip_when condition or start_sheet override.
The baton propagates skip state to dependents — downstream sheets that depend on a skipped sheet receive a skip sentinel, not empty string.
ShutdownRequested
dataclass
¶
The conductor is shutting down (SIGTERM, mzt stop).
When graceful is True, the baton waits for in-flight sheets
to complete (up to the configured drain timeout) before stopping.
When False, sheets are cancelled immediately.
StaleCheck
dataclass
¶
Timer fired — check if a running sheet has gone stale.
If no output progress has been received within the configured idle timeout, the baton kills the stale sheet and reschedules or fails it.
PromptRenderer
¶
PromptRenderer(prompt_config, total_sheets, total_stages, parallel_enabled, *, job_id=None, schedule_id=None, scheduled_due_at=None)
Renders full prompts for baton musicians.
Bridges the PromptBuilder pipeline with the baton's Sheet-based execution model. Handles template rendering, injection resolution, preamble assembly, and validation requirements — everything the old runner's context mixin did, but without the runner dependency.
Create one per job (or share across jobs with the same config).
Call render() per sheet dispatch.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prompt_config
|
PromptConfig
|
The job's PromptConfig (template, variables, etc.). |
required |
total_sheets
|
int
|
Total sheets in the job (for preamble). |
required |
total_stages
|
int
|
Total stages before fan-out expansion (for template aliases). |
required |
parallel_enabled
|
bool
|
Whether parallel execution is enabled (for preamble). |
required |
Source code in src/marianne/daemon/baton/prompt.py
Methods:¶
render
¶
render(sheet, attempt_context, *, patterns=None, failure_history=None, spec_fragments=None, technique_manifest=None, technique_skill_docs=None, raw_prompt=False, memory_manifest=None)
Render a full prompt for a sheet execution.
Performs the complete 9-layer prompt assembly: template rendering -> injection resolution -> optional layers -> validation requirements -> completion suffix.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sheet
|
Sheet
|
The Sheet entity to render for. |
required |
attempt_context
|
AttemptContext
|
Context from the baton (attempt number, mode). |
required |
patterns
|
list[str] | None
|
Optional learned pattern descriptions to inject. |
None
|
failure_history
|
list[HistoricalFailure] | None
|
Optional historical failures from previous sheets. |
None
|
spec_fragments
|
list[SpecFragment] | None
|
Optional spec corpus fragments to inject. |
None
|
technique_manifest
|
str | None
|
Optional technique manifest text to inject as a skill-category item. Generated by the technique resolver from the job's technique declarations filtered by phase. |
None
|
technique_skill_docs
|
Mapping[str, str] | Sequence[str] | None
|
Optional list of technique document contents discovered by the technique resolver. Each entry is the full text of a skill-kind technique document, injected as a skill-category item alongside the manifest. |
None
|
memory_manifest
|
str | None
|
The memory block for this sheet. Its own channel, never
part of the technique manifest, so a template that already lists
techniques cannot suppress it. Injected once, as |
None
|
raw_prompt
|
bool
|
When True (driven by the instrument profile's
|
False
|
Returns:
| Type | Description |
|---|---|
RenderedPrompt
|
RenderedPrompt with fully rendered prompt and preamble. |
Source code in src/marianne/daemon/baton/prompt.py
149 150 151 152 153 154 155 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 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 | |
RenderedPrompt
dataclass
¶
Output of the prompt rendering pipeline.
Contains both the rendered prompt (for backend execution) and the preamble (set on the backend before execution). Separating them allows the musician to configure the backend correctly.
Attributes¶
prompt_extensions
class-attribute
instance-attribute
¶
Request-local additional directives appended by the backend.
context_manifest
class-attribute
instance-attribute
¶
Hash-only manifest of context and technique bytes in prompt.
prompt_receipt
class-attribute
instance-attribute
¶
Per-source sizes, hashes and drop reasons for this prompt (GH #546).
AttemptContext
dataclass
¶
AttemptContext(attempt_number, mode, dispatch_epoch=None, flow_vars=dict(), completion_prompt_suffix=None, healing_context=None, previous_results=None, learned_patterns=None, total_sheets=1, total_movements=1, previous_outputs=dict(), previous_files=dict(), response_format=RESPONSE_FORMAT_UNSET, model=None, max_tokens=None, temperature=None, http_timeout_seconds=None, expected_route=None, route_model_override=None, route_provider_override=None, first_output_timeout_seconds=FIRST_OUTPUT_TIMEOUT_UNSET, effort=None, tools=None)
Context provided by the conductor to the musician for a single attempt.
Each dispatch carries this context so the musician knows: - Which attempt this is (1 = first try, 2+ = retry) - What mode to operate in (normal/completion/healing) - Any extra context for non-normal modes - Learned patterns from the learning store (instrument-scoped) - Previous attempt results (for failure history injection)
Attributes¶
attempt_number
instance-attribute
¶
1-based attempt number. First try = 1, first retry = 2, etc.
flow_vars
class-attribute
instance-attribute
¶
The execution mode for this attempt.
completion_prompt_suffix
class-attribute
instance-attribute
¶
For completion mode: appended to the prompt to fix partial failures.
healing_context
class-attribute
instance-attribute
¶
For healing mode: diagnostic context from self-healing analysis.
previous_results
class-attribute
instance-attribute
¶
Previous attempt results for failure history injection into prompts.
learned_patterns
class-attribute
instance-attribute
¶
Patterns from the learning store, scoped to this instrument.
total_sheets
class-attribute
instance-attribute
¶
Total concrete sheet count in the job (for preamble and template vars).
total_movements
class-attribute
instance-attribute
¶
Total movement count in the job (for template vars).
previous_outputs
class-attribute
instance-attribute
¶
Stdout outputs from completed sheets. Keys are sheet numbers (1-indexed). Populated by the adapter from completed sheet attempt results.
previous_files
class-attribute
instance-attribute
¶
File contents captured via capture_files patterns. Keys are file paths. Populated by the adapter from workspace files matching CrossSheetConfig patterns.
response_format
class-attribute
instance-attribute
¶
Per-sheet structured-output resolution for this attempt (W-F1/W-F2).
Tri-state: RESPONSE_FORMAT_UNSET (the sheet did not configure one —
the backend applies its profile default at execute), None (explicit
opt-out of a profile default), or a validated mapping forwarded to the
OpenAI-compatible wire contract. Resolved ONCE at dispatch (adapter,
validated by the shared wire-contract validator) and consumed
request-locally by the musician via SheetRequestState — it never
rides the shared pooled backend as mutable attribute state.
first_output_timeout_seconds
class-attribute
instance-attribute
¶
CLI first-output bound: unset inherits the profile, None disables it, and a positive number overrides it request-locally for this attempt.
effort
class-attribute
instance-attribute
¶
Reasoning-effort level from this attempt's chain entry (instrument_config.effort, GH #535); None keeps the profile default. Checked against the profile at dispatch, consumed request-locally.
tools
class-attribute
instance-attribute
¶
Harness tool names from this attempt's chain entry (instrument_config.tools, GH #534); None keeps the harness default and () means no tools. Checked against the profile at dispatch, consumed request-locally.
AttemptMode
¶
Bases: str, Enum
The mode a sheet attempt runs in.
NORMAL— standard execution (first try or retry)COMPLETION— partial validation passed, trying to completeHEALING— self-healing after retry exhaustion
BatonJobState
dataclass
¶
The baton's per-job tracking during a performance.
Contains all sheet states for a job, plus job-level flags (paused, pacing, cost tracking).
Attributes¶
paused
class-attribute
instance-attribute
¶
Whether dispatching is paused for this job.
pacing_active
class-attribute
instance-attribute
¶
Whether inter-sheet pacing delay is currently active.
sheets
class-attribute
instance-attribute
¶
Map of sheet_num → SheetExecutionState.
terminal_count
property
¶
Number of sheets in a terminal status (completed, failed, skipped).
Methods:¶
register_sheet
¶
get_sheet
¶
CircuitBreakerState
¶
Bases: str, Enum
Three-state circuit breaker for per-instrument health tracking.
CLOSED— healthy, accepting requestsOPEN— unhealthy, rejecting requests, waiting for recovery timerHALF_OPEN— probing, allowing one request to test recovery
InstrumentState
dataclass
¶
InstrumentState(name, max_concurrent, running_count=0, last_dispatch_at=0.0, rate_limited=False, rate_limit_expires_at=None, circuit_breaker=CLOSED, consecutive_failures=0, circuit_breaker_threshold=5, circuit_breaker_recovery_at=None)
Per-instrument state tracking for rate limits, circuit breakers, and concurrency.
The baton tracks each instrument's health independently. Rate limits on claude-code don't affect gemini-cli. Circuit breaker thresholds are per-instrument. Concurrency limits come from the InstrumentProfile.
Attributes¶
max_concurrent
instance-attribute
¶
Maximum concurrent sheets on this instrument (from InstrumentProfile).
running_count
class-attribute
instance-attribute
¶
Number of currently running sheets on this instrument.
last_dispatch_at
class-attribute
instance-attribute
¶
Monotonic time of the most recent dispatch on this instrument (#340).
The dispatch stagger gate skips a same-instrument sheet when
now - last_dispatch_at < stagger_delay_ms, spreading a burst of
simultaneously-ready same-instrument sheets to avoid a same-provider API
burst. Default 0.0 means "never dispatched" (gate passes immediately).
rate_limited
class-attribute
instance-attribute
¶
Whether this instrument is currently rate-limited.
rate_limit_expires_at
class-attribute
instance-attribute
¶
Monotonic time when the rate limit is expected to clear.
circuit_breaker
class-attribute
instance-attribute
¶
circuit_breaker = CircuitBreakerState.CLOSED
Current circuit breaker state.
consecutive_failures
class-attribute
instance-attribute
¶
Consecutive failures across all jobs for this instrument.
circuit_breaker_threshold
class-attribute
instance-attribute
¶
Number of consecutive failures to trip the circuit breaker.
circuit_breaker_recovery_at
class-attribute
instance-attribute
¶
Monotonic time for circuit breaker recovery check.
is_available
property
¶
Whether this instrument can accept new sheets.
Available when not rate-limited and circuit breaker is not open. Half-open allows one probe request through.
Methods:¶
record_success
¶
Record a successful execution on this instrument.
Resets consecutive failures. If circuit breaker is half-open, closes it (the probe succeeded).
Source code in src/marianne/daemon/baton/state.py
record_failure
¶
Record a failed execution on this instrument.
Increments consecutive failures. If threshold reached, opens the circuit breaker. If already half-open, reopens it.
Source code in src/marianne/daemon/baton/state.py
to_dict
¶
Serialize to a dict for SQLite persistence.
Source code in src/marianne/daemon/baton/state.py
from_dict
classmethod
¶
Restore from a serialized dict.
Source code in src/marianne/daemon/baton/state.py
TimerHandle
dataclass
¶
Opaque handle returned by schedule(). Used for cancellation.
Attributes:
| Name | Type | Description |
|---|---|---|
fire_at |
float
|
Monotonic time when the event should fire. |
event |
BatonEvent
|
The BatonEvent to deliver to the inbox. |
TimerWheel
¶
Priority queue of future events with a background drain task.
Usage::
inbox = asyncio.Queue()
wheel = TimerWheel(inbox)
# Schedule a retry in 30 seconds
handle = wheel.schedule(
30.0,
RetryDue(job_id="j1", sheet_num=5, event_generation=1),
)
# Cancel if no longer needed
wheel.cancel(handle)
# Run the drain task (usually as asyncio.create_task(wheel.run()))
await wheel.run() # blocks forever, fires events into inbox
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
inbox
|
Queue[Any]
|
The asyncio.Queue that receives fired events. This is the baton's event inbox — the same queue that receives musician results, external commands, etc. |
required |
Source code in src/marianne/daemon/baton/timer.py
Attributes¶
Methods:¶
schedule
¶
Schedule an event to fire after delay_seconds.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
delay_seconds
|
float
|
Seconds from now. Clamped to >= 0. |
required |
event
|
BatonEvent
|
The BatonEvent to deliver when the timer fires. |
required |
Returns:
| Type | Description |
|---|---|
TimerHandle
|
A TimerHandle that can be passed to |
Source code in src/marianne/daemon/baton/timer.py
cancel
¶
Cancel a scheduled timer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
handle
|
TimerHandle
|
The handle returned by |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if the timer was pending and is now cancelled. |
bool
|
False if it was already cancelled or already fired. |
Source code in src/marianne/daemon/baton/timer.py
snapshot
¶
Export pending (non-cancelled) timers for persistence.
Returns a list of (fire_at, event) tuples — the data needed to reconstruct the timer wheel after a restart.
Source code in src/marianne/daemon/baton/timer.py
run
async
¶
Background drain task — fire timers into the inbox.
This coroutine runs indefinitely. Cancel the task to stop it. It sleeps until the next timer is due (or a wake signal arrives), fires all due timers, and repeats.
Source code in src/marianne/daemon/baton/timer.py
shutdown
async
¶
Fire all pending timers immediately and stop.
Used during graceful shutdown — ensures no events are lost. Events are placed into the inbox in fire_at order.
Source code in src/marianne/daemon/baton/timer.py
Functions:¶
sheet_task
async
¶
sheet_task(*, job_id, sheet, backend, attempt_context, inbox, total_sheets=1, total_movements=1, rendered_prompt=None, preamble=None, memory_manifest=None, cost_per_1k_input=None, cost_per_1k_output=None, cost_per_1k_cache_read=None, cost_per_1k_cache_write=None, instrument_override=None, technique_router=None, code_executor=None, context_delivery=None, event_generation=None)
Execute a single sheet attempt and report the result.
This is the musician's entire job. Play once, report in full detail. The conductor (baton) decides what happens next.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
job_id
|
str
|
The job this sheet belongs to. |
required |
sheet
|
Sheet
|
The sheet to execute (prompt, validations, timeout, etc.). |
required |
backend
|
Backend
|
The backend to execute through. |
required |
attempt_context
|
AttemptContext
|
Context from the conductor (attempt number, mode, etc.). |
required |
inbox
|
Queue[SheetAttemptResult]
|
The baton's event inbox to report results to. |
required |
total_sheets
|
int
|
Total concrete sheets in the job (for template variables). |
1
|
total_movements
|
int
|
Total movements in the job (for template variables). |
1
|
rendered_prompt
|
str | None
|
Optional pre-rendered prompt from PromptRenderer. When provided, the musician uses this directly instead of calling _build_prompt(). This enables the full 9-layer prompt assembly pipeline including spec fragments, learned patterns, and failure history. |
None
|
preamble
|
str | None
|
Optional pre-built preamble. Passed to the backend request-locally at execution (SheetRequestState — W-F3), never via the mutable set_preamble() slot. Only used when rendered_prompt is also provided (the PromptRenderer separates them). |
None
|
cost_per_1k_input
|
float | None
|
Cost per 1000 input tokens (USD) from the instrument profile's ModelCapacity. None uses hardcoded fallback. |
None
|
cost_per_1k_output
|
float | None
|
Cost per 1000 output tokens (USD) from the instrument profile's ModelCapacity. None uses hardcoded fallback. |
None
|
instrument_override
|
str | None
|
When set, used as the instrument_name in the SheetAttemptResult instead of sheet.instrument_name. Required after instrument fallback — the Sheet entity keeps the original instrument but the baton's SheetExecutionState tracks the fallback instrument. Without this, attempt results credit the wrong instrument for success/failure tracking. |
None
|
Never raises — all exceptions are caught and reported via the inbox.
Source code in src/marianne/daemon/baton/musician.py
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 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 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 | |