base
base
¶
Shared execution contracts for profile-driven instruments.
Classes¶
SheetRequestState
dataclass
¶
SheetRequestState(response_format=RESPONSE_FORMAT_UNSET, model=None, max_tokens=None, temperature=None, http_timeout_seconds=None, http_timeout_resolved=False, preamble=None, prompt_extensions=(), expected_route=None, route_model_override=None, route_provider_override=None, job_id=None, sheet_num=None, first_output_timeout_seconds=FIRST_OUTPUT_TIMEOUT_UNSET, effort=None, tools=None)
Per-sheet outbound-request state, resolved once at dispatch.
The pooled HTTP backend is a daemon-global singleton shared by
concurrent sheets across jobs; per-sheet values riding as mutable
backend attributes can transfer between in-flight sheets (W-F1/W-F2)
or smear sequentially across release (W-F3). Dispatch resolves this
immutable state and execute() consumes it request-locally —
nothing in the request build is read from (or written to) shared
backend state.
response_format is tri-state: RESPONSE_FORMAT_UNSET (the sheet
did not configure one — the backend applies its profile default),
None (explicit opt-out of a profile default), or a validated
mapping (forwarded). Only the OpenAI-compatible HTTP contract consumes
it; other backends ignore it (the adapter logs the capability warning
at dispatch).
Attributes¶
first_output_timeout_seconds
class-attribute
instance-attribute
¶
CLI first-output bound: unset uses the profile, None disables it, and a positive number overrides it, capped by the sheet timeout.
effort
class-attribute
instance-attribute
¶
Reasoning-effort level (instrument_config.effort, GH #535), already checked against the profile at dispatch. None keeps the profile's default effort flags. CLI and interactive backends replace their effort flag value with it; it never rides a pooled backend as mutable state.
tools
class-attribute
instance-attribute
¶
Harness tool names (instrument_config.tools, GH #534), already checked against the profile at dispatch. None keeps the harness's default toolset; () means no tools. CLI and interactive backends deliver it through the profile's tools: flag; it never rides a pooled backend as mutable state.
ExecutionResult
dataclass
¶
ExecutionResult(success, stdout, stderr, duration_seconds, exit_code=None, exit_signal=None, exit_reason='completed', started_at=utc_now(), rate_limited=False, rate_limit_wait_seconds=None, error_type=None, error_message=None, model=None, tokens_used=None, input_tokens=None, output_tokens=None, cache_read_tokens=None, cache_write_tokens=None, usage_unmeasured=False, structured_output=None, model_echo_status=None, model_observed=None, model_requested=None)
Result of executing a prompt through a backend.
Captures all relevant output and metadata for validation and debugging.
Note: Fields are ordered with required fields first, then optional fields with defaults, as required by Python dataclasses.
Attributes¶
exit_code
class-attribute
instance-attribute
¶
Process exit code or HTTP status code. None if killed by signal.
exit_signal
class-attribute
instance-attribute
¶
Signal number if process was killed by a signal (e.g., 9=SIGKILL, 15=SIGTERM).
On Unix, when a process is killed by a signal, returncode = -signal_number. This field extracts that signal for clearer diagnostics.
exit_reason
class-attribute
instance-attribute
¶
Why the execution ended: - completed: Normal exit (exit_code set) - timeout: Process was killed due to timeout - killed: Process was killed by external signal - error: Internal error prevented execution
started_at
class-attribute
instance-attribute
¶
started_at = field(default_factory=utc_now)
When execution started.
rate_limited
class-attribute
instance-attribute
¶
Whether rate limiting was detected.
rate_limit_wait_seconds
class-attribute
instance-attribute
¶
Parsed wait duration from rate limit error, in seconds.
When set, this is the actual duration extracted from the API's error message (e.g. 'retry after 300 seconds'). When None, callers should use their default wait time.
error_message
class-attribute
instance-attribute
¶
Human-readable error message.
tokens_used
class-attribute
instance-attribute
¶
Total tokens consumed (API backend only).
.. deprecated::
Use input_tokens + output_tokens instead. This field will be
removed in a future version.
Equivalent: tokens_used == (input_tokens or 0) + (output_tokens or 0).
input_tokens
class-attribute
instance-attribute
¶
Input tokens consumed (prompt tokens). None if not available from backend.
output_tokens
class-attribute
instance-attribute
¶
Output tokens consumed (completion tokens). None if not available from backend.
cache_read_tokens
class-attribute
instance-attribute
¶
Input tokens the provider served from its prompt cache this attempt.
Counted separately from input_tokens because they are billed at the
cache rate and because they are what a token-efficiency measure moves.
None when the backend or profile does not report them.
cache_write_tokens
class-attribute
instance-attribute
¶
Input tokens written into the provider's prompt cache this attempt.
usage_unmeasured
class-attribute
instance-attribute
¶
True when this backend could not measure token usage (GH #533).
The attempt's token fields are then absent, not zero; the musician flags
the attempt cost_uncertain so status never shows it as free.
structured_output
class-attribute
instance-attribute
¶
The validated JSON object of a response_format sheet (GH #489).
Set only when the backend ran in schema/JSON mode and the object passed
its conformance check. None for every other execution.
model_echo_status
class-attribute
instance-attribute
¶
HTTP model-field provenance; None means no transport evidence is available.
model_observed
class-attribute
instance-attribute
¶
Nonempty server response model, verbatim; never a request fallback.
model_requested
class-attribute
instance-attribute
¶
Exact model sent in the corresponding HTTP request.
Methods:¶
__post_init__
¶
Validate invariant: success=True requires exit_code 0 or None.
Source code in src/marianne/execution/base.py
Backend
¶
Bases: ABC
Abstract execution contract for profile-driven instruments.
Backends handle the actual execution of prompts through Claude, whether via CLI subprocess or direct API calls.
Attributes¶
working_directory
property
writable
¶
Working directory for backend execution.
Subprocess-based instruments use this as the cwd for child processes. API-based backends store it but don't use it directly.
Returns None if no working directory is set, meaning the process CWD is used.
Thread/Concurrency Safety: This property is NOT safe to mutate while executions are in-flight. The worktree isolation layer sets it before any sheet execution starts, and restores it in the finally block after all sheets complete. During parallel execution, all concurrent sheets share the same working directory (the worktree path), so the value is read-only while sheets are running. Never change this property from a concurrent task mid-execution.
override_lock
property
¶
Lock for serializing apply_overrides → execute → clear_overrides cycles.
Parallel sheet execution must acquire this lock around the entire override lifecycle to prevent concurrent sheets from stomping on each other's saved originals.
Methods:¶
execute
abstractmethod
async
¶
Execute a prompt and return the result.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prompt
|
str
|
The prompt to send to Claude |
required |
timeout_seconds
|
float | None
|
Per-call timeout override. If provided, overrides the backend's default timeout for this single execution. |
None
|
request
|
SheetRequestState | None
|
Per-sheet outbound-request state resolved once at
dispatch (W-F1/W-F2/W-F3). Pooled backends are shared by
concurrent sheets across jobs, so per-sheet values must
travel here, never as mutable backend attributes read at
payload build. |
None
|
Returns:
| Type | Description |
|---|---|
ExecutionResult
|
ExecutionResult with output and metadata |
Source code in src/marianne/execution/base.py
health_check
abstractmethod
async
¶
Check if the backend is available and working.
Used to verify connectivity before starting a job, and to check if rate limits have lifted.
Returns:
| Type | Description |
|---|---|
bool
|
True if backend is ready, False otherwise |
Source code in src/marianne/execution/base.py
availability_check
async
¶
Lightweight check: is the backend reachable without consuming API quota?
Unlike health_check(), this must NOT send prompts or consume tokens. Used after quota exhaustion waits where sending a prompt would fail.
Default returns True (assume available). Backends override for real checks.
Source code in src/marianne/execution/base.py
close
async
¶
Close the backend and release resources.
Override in subclasses that hold persistent connections or resources. Default implementation is a no-op for backends without cleanup needs.
This method should be idempotent - calling it multiple times should be safe.
Source code in src/marianne/execution/base.py
__aenter__
async
¶
__aexit__
async
¶
Async context manager exit — ensures close() is called.
apply_overrides
¶
Apply per-sheet parameter overrides for the next execution.
Called per-sheet by the musician when sheet_overrides is configured.
Subclasses store the overrides and apply them in execute().
clear_overrides() is called after execution to restore defaults.
Callers MUST hold override_lock for the entire
apply → execute → clear window when parallel execution is possible.
Default implementation is a no-op for backends without override support.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
overrides
|
dict[str, object]
|
Dict of parameter name → value. Only non-None values
from |
required |
Source code in src/marianne/execution/base.py
clear_overrides
¶
Clear per-sheet parameter overrides, restoring defaults.
Called after each sheet execution to ensure the next sheet uses global config. Default implementation is a no-op.
set_preamble
¶
Set the dynamic preamble for the next execution.
Direct-use contract: the dispatch path carries the per-attempt
preamble request-locally on SheetRequestState (W-F3 — a pooled
backend shared across sheets must never hold another sheet's prompt
bytes in a mutable slot). This setter remains for exclusively-owned
backends and direct callers; clear_overrides() must reset it.
Override in subclasses that support prompt injection. Default implementation is a no-op for backends without this capability.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
_preamble
|
str | None
|
Preamble text to prepend, or None to clear. |
required |
Source code in src/marianne/execution/base.py
set_prompt_extensions
¶
Set prompt extensions for the next execution.
Extensions are additional directive blocks injected after the
preamble. Direct-use contract — the dispatch path carries them on
SheetRequestState (see set_preamble). clear_overrides()
must reset them.
Override in subclasses that support prompt injection. Default implementation is a no-op for backends without this capability.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
_extensions
|
list[str]
|
List of extension text blocks. |
required |
Source code in src/marianne/execution/base.py
HttpxClientMixin
¶
Shared lazy httpx.AsyncClient lifecycle for HTTP-based backends.
Provides _get_client() for lazy initialization with connection pooling
and _close_httpx_client() for cleanup. HTTP instrument adapters share
this same pattern.
Functions:¶
is_first_output_timeout_unset
¶
True when value is the unset sentinel (inherit the profile bound).