Engine

The application owns this lifecycle surface. Components use the separate self.runtime reference. See correspondence for equivalent operations and differences, and ContextRun for returned handles.

class jayrun.Engine(settings: EngineSettings | None = None, graph_registry: GraphRegistry | None = None, *, name: str = 'self', database: Database | None = None)[source]

Run artifact graphs and return stable handles to their contexts.

An engine owns its worker pool, runtime loop, resource cache, and placement capacity. submit() accepts an explicit graph and graph-independent artifact and configuration builders. It returns a ContextRun that remains usable after execution finishes. Use the engine as a context manager for deterministic synchronous shutdown, or call shutdown_async() when the engine shares an application event loop.

Parameters:
  • settings – Optional runtime settings. Defaults to EngineSettings.

  • graph_registry – Optional graph registry. When supplied, submissions and scoped authority declarations must use graphs registered in it.

  • database – Optional managed context/session and timing-profile persistence. None disables durable capture; constructing the engine performs no storage I/O. Enabled synchronous start, submit and apply must run outside an event-loop thread; async callers can use asyncio.to_thread and the existing async wait/shutdown APIs.

  • name – Human-readable engine name. Every engine incarnation appends a compact UUID to this name for its unique engine_id value.

start(loop: AbstractEventLoop | None = None) → None[source]

Start the runtime.

Parameters:

loop – Running application event loop to adopt. When omitted, Jayrun creates and owns a background event loop.

Raises:
  • RuntimeError – If the engine cannot be started from its current state.

  • TimeoutError – If runtime-loop initialization or startup callback acknowledgement exceeds its bounded startup wait. Failure cleanup has separate bounds; this is not an overall start-call deadline.

submit(graph: GraphDefinition | tuple[str, str], artifacts: ArtifactContext | None = None, configs: ConfigContext | None = None, *, settings: ContextSettings | None = None, authority: Supervisor | Controller | None = None) → ContextRun[source]

Submit one execution context and return its live run.

With local routing, ordinary work is assigned to this engine. With controlled routing, it remains in ContextState.ROUTING until an authorized caller selects an exact engine using transfer(). Authority-bearing contexts always run locally through supervision capacity.

Parameters:
  • graph – Confirmed graph to execute, or its registered (key, version) identity. A registry identity is the portable form used by controlling contexts.

  • artifacts – Optional graph-independent builder containing entry-artifact values. Omit it when the graph has no required entry artifacts.

  • configs – Optional graph-independent configuration builder. Omit it when the graph has no required configuration fields.

  • settings – Optional iteration, retry, and retention settings.

  • authority – Optional Supervisor or Controller declaration. A scoped supervisor may observe and control contexts of its exact graph objects; an empty supervisor and a controller cover every graph.

Returns:

A ContextRun for the submitted context.

Raises:
  • TypeError – If a submission argument has an unsupported type.

  • KeyError – If a context contains a declaration outside graph.

  • ValueError – If required values are missing or references or authority graphs are duplicated.

  • RuntimeError – If the engine is not accepting submissions or the graph is not ready for execution. Failed submission leaves both caller contexts unchanged.

apply(snapshot: ContextSnapshot | PressureSnapshot) → None[source]

Apply one context snapshot through the local coordinator.

Jayrun performs no transport. Applications serialize and deliver a snapshot however they choose, then call this method on the receiving engine. A snapshot with a control request is executed only by the current owner; a committed snapshot synchronizes a non-local shadow. When a queued snapshot is assigned to this engine’s engine_id, applying it also admits that context for execution. Stale revisions, duplicate requests, and obsolete ownership generations have no effect.

Fresh work is never submitted through this method. Use submit() with a graph (or graph key), ArtifactContext, and ConfigContext instead.

During graceful shutdown, committed updates for contexts already known to this engine remain accepted so remote owners can return their final snapshots. New contexts and new control requests cannot be introduced after shutdown begins.

Parameters:

snapshot – Immutable snapshot received through application-owned transport.

Raises:
  • TypeError – If snapshot is not a context snapshot.

  • ValueError – If its graph identity or portable payload is invalid.

  • RuntimeError – If the engine is not running or has no graph registry.

wait(runs: ContextRun | tuple[ContextRun, ...], state: ContextState | None = None, *, timeout: int | float | None = None) → ContextRun | tuple[ContextRun, ...][source]

Synchronously wait for one or more context runs.

Waiting without state ends after every run is finalized, when reports and retained artifacts are available. Waiting for a non-terminal state also ends if a run terminates before reaching that state. A tuple shares one timeout budget and is returned unchanged.

Parameters:
  • runs – One run or a tuple of runs.

  • state – Exact non-terminal state to observe, or None to wait for finalization.

  • timeout – Maximum total seconds to wait, or None for no timeout.

Returns:

The same run or tuple supplied by the caller.

Raises:
  • TypeError – If an argument has an unsupported type.

  • ValueError – If state is terminal or timeout is invalid.

  • TimeoutError – If the timeout expires.

  • RuntimeError – If called where synchronous waiting would block a running event loop.

terminal_history(*, after: TerminalCursor | None = None, limit: int = 256) → TerminalHistoryPage[source]

Read immutable, payload-free terminal summaries from this incarnation.

after=None starts at the beginning of the retained window, reporting any earlier loss. Reuse next_cursor to continue. Bounds and shutdown can make data unavailable; no durable or full-report coverage is implied.

observer(*, capacity: int = 256) → ContextObserver[source]

Create a bounded queue of committed context events.

The observer yields lifecycle transitions, stored-value notifications, transfer changes, and remote control requests. Every event carries the atomic ContextSnapshot current at that boundary. Progress alone does not create an event. Both next() and anext() remove the returned event. An observer that reaches capacity is cleared and detached; its next consumption raises ObserverOverflowError.

Parameters:

capacity – Maximum pending events before the observer overflows.

Returns:

A closeable synchronous and asynchronous context observer.

Raises:
  • TypeError – If capacity is not an integer.

  • ValueError – If capacity is not positive.

  • RuntimeError – If the engine is not running or its observer limit has been reached.

async wait_async(runs: ContextRun | tuple[ContextRun, ...], state: ContextState | None = None, *, timeout: int | float | None = None) → ContextRun | tuple[ContextRun, ...][source]

Asynchronously wait for one or more context runs.

This is the non-blocking counterpart of wait(). Tuple members wait concurrently and share one timeout budget.

Parameters:
  • runs – One run or a tuple of runs.

  • state – Exact non-terminal state to observe, or None to wait for finalization.

  • timeout – Maximum total seconds to wait, or None for no timeout.

Returns:

The same run or tuple supplied by the caller.

Raises:
  • TypeError – If an argument has an unsupported type.

  • ValueError – If state is terminal or timeout is invalid.

  • TimeoutError – If the timeout expires.

shutdown(forced: bool = False, timeout: int | float | None = None) → None[source]

Shut down the runtime and release its resources.

Graceful shutdown stops future iterations and settles ordinary contexts before authority contexts, allowing controllers to finish transporting remote snapshots. Authority event queues then close and can drain a normal for or async for loop. Polling authority loops can use self.runtime.alive, which stays true during the ordinary drain and becomes false when authority teardown begins. User code already executing must still return cooperatively.

Parameters:
  • forced – Abort live contexts instead of stopping future iterations and allowing accepted work to drain.

  • timeout – Grace period before an incomplete graceful shutdown escalates to forced cleanup. For an already forced shutdown, it is the coordinator acknowledgement timeout; None uses an internal bounded acknowledgement wait. None on graceful shutdown waits without a graceful deadline.

Raises:
  • TimeoutError – If a concurrent caller does not observe completion within timeout.

  • RuntimeError – If shutdown is requested from an invalid lifecycle state or cleanup fails.

async shutdown_async(forced: bool = False, timeout: int | float | None = None) → None[source]

Asynchronously shut down the runtime and release its resources.

This is the non-blocking counterpart of shutdown() and is suitable when Jayrun uses the application’s event loop. It uses the same ordinary-first graceful ordering and self.runtime.alive cooperative-return boundary.

Parameters:
  • forced – Abort live contexts instead of stopping future iterations and allowing accepted work to drain.

  • timeout – Grace period before an incomplete graceful shutdown escalates to forced cleanup. For an already forced shutdown, it is the coordinator acknowledgement timeout; None uses an internal bounded acknowledgement wait. None on graceful shutdown waits without a graceful deadline.

Raises:
  • TimeoutError – If a concurrent caller does not observe completion within timeout.

  • RuntimeError – If shutdown is requested from an invalid lifecycle state or cleanup fails.

property database: Database | None[source]

Configured persistence component, owned from start through shutdown.

None disables durable recording. wait() still means execution finalization; an explicit database.flush()/flush_async() additionally covers registered history handoffs. Borrowed readers never receive live control authority.

property state: EngineState[source]

Current engine lifecycle state.

property activity: RuntimeActivity[source]

Whether the running engine is idle or actively processing work.

property failure: BaseException | None[source]

Primary runtime failure, if the engine failed.

property secondary_failures: tuple[BaseException, ...][source]

Additional failures observed after the primary runtime failure.

property cleanup_failures: tuple[BaseException, ...][source]

Failures raised while releasing runtime resources.

property graph_registry: GraphRegistry | None[source]

Graph registry constraining submissions, if one was configured.

property name: str[source]

Human-readable name shared by this engine’s incarnations.

property engine_id: str[source]

Unique name and UUID of this engine incarnation.

A newly constructed engine receives a new value even when it reuses the same name. Pass this value to jayrun.context.ContextRun.transfer() when assigning work here.

property pressure: PressureSnapshot[source]

Current engine-wide scheduling and execution pressure snapshot.

State counts include only contexts owned by this engine; remote shadows remain visible through unfinished_contexts but do not consume local pressure. Sampling pressure does not emit an event or update profiling history.

Raises:

RuntimeError – If the engine is not running.

property unfinished_contexts: tuple[ContextRun, ...][source]

Non-terminal context runs in submission order.

Completed runs are released from the engine registry. A ContextRun already held by application code remains usable for reports, stored values, and retained artifacts.

property active_contexts: tuple[ContextRun, ...][source]

Context runs currently active or draining, in submission order.

class jayrun.EngineState(*values)[source]

Lifecycle state of an engine instance.

CREATED = 'created'
STARTING = 'starting'
RUNNING = 'running'
STOPPING = 'stopping'
STOPPED = 'stopped'
FAILED = 'failed'
class jayrun.RuntimeActivity(*values)[source]

Current workload activity of a running engine.

IDLE = 'idle'
ACTIVE = 'active'
class jayrun.Supervisor(*graphs: GraphDefinition)[source]

Grant a submitted context authority over other context runs.

Parameters:

*graphs – Exact graph objects whose contexts may be observed and controlled. When omitted, the authority covers every graph in the engine.

class jayrun.Controller(history: DatabaseReader | None = None)[source]

Grant engine-wide observation and control to a submitted context.

A controller may also submit confirmed graphs or registered identities through self.runtime.submit(...) and asynchronously request engine shutdown. EngineSettings.controller_policy must be DELEGATED to submit children with Supervisor or Controller authority; HOST_ONLY is the default. Controller contexts execute locally through supervision capacity and cannot be transferred. An optional history reader explicitly grants its existing session scope. The runtime lends an attenuated view for this controller lifetime; it cannot close/flush the store or acquire additional live rights.

Reusable submission inputs

class jayrun.Submission(graph: GraphDefinition, artifacts: ArtifactContext | None = None, configs: ConfigContext | None = None, *, settings: ContextSettings | None = None, authority: Supervisor | Controller | None = None)[source]

Resolve and retain inputs for repeated submission of a confirmed graph.

Artifact payloads are shared by reference. Subsequent builder edits affect only new preparations. Keep mutable payloads stable while runs read them.

Parameters:
  • graph – Confirmed graph declaration.

  • artifacts – Native entry-artifact builder.

  • configs – Native configuration overrides.

  • settings – Requested per-context settings.

  • authority – Requested authority, checked by the admitting runtime.

arguments() → dict[source]

Return fresh editable native keyword arguments for one submission.

Successful registration can clear the returned artifact builder. Call this method separately for each attempt, including concurrent calls.

inspect(*, engine_settings: EngineSettings | None = None, redact: tuple[tuple[str | int, ...], ...] = ()) → dict[str, object][source]

Describe graph-relative bindings and optionally project engine settings.

The detached report omits artifact payloads. Redaction paths select report keys and sequence indices. An empty path redacts the whole report.

Construction requires a confirmed graph and accepts the same artifact and config builders as direct submission. Native graph-relative errors are raised immediately. The object retains winning bindings and shares the underlying artifact payloads by reference. The graph, requested settings and authority are preserved in each argument dictionary. The config builder contains explicit overrides, including explicit null and overrides equal to a default. Each admission checks its inputs and the live authority again.

inspect() returns a detached dictionary. Entry rows give graph-local IDs and flag a supplied missing value. Construction rejects absent required bindings. Config rows are indexed by config ID and mark values as explicit, default or omitted. Integers and floats use tagged hexadecimal strings. Tuples use a tagged array. Policy counters larger than 53 bits use the same exact integer tag. Resource rows refer to those same config IDs. Selection IDs group fields bound to the same resource or serializer instance within this graph. The diagnostics retain native edge status and separate graph-iteration and operator-repeat mismatches.

requested_settings preserves omission. graph_settings resolves exit retention and graph-independent defaults. Inherited retry settings remain open. Pass engine_settings= to project the combined context policy in engine_scenario. The admitting Engine determines its actual policy, registration, capacity, placement and authority.

Sensitive configuration names are redacted automatically. For additional redaction, pass a tuple of paths made of dictionary keys and sequence indices. For example, redact=(("configs", 2, "value"),) hides config 2. Append "tuple", 0 to that path to hide its first tuple member. A path of () hides the whole report. Exact config values follow native bounds. Display labels are bounded and inspection raises ValueError if its compact JSON exceeds 32 MiB.