Thread Execution Lifecycle
A thread execution is one accepted input that owns a thread exclusively. It is different from a message turn, model request, tool call, workflow run, and the long-lived thread runtime.
Ownership has one authority: the session store's execution controller. Standalone runs, hosted inputs, subagents, goal continuations, and parent questions all acquire and read the same controller, so they agree on which execution is live. Acquiring commits THREAD_EXECUTION_STARTED; releasing ends every request the execution left unanswered (AgentRequestTerminatedEvent, Abandoned) and commits THREAD_EXECUTION_FINISHED. Both are published live as well as committed.
From Input To Finish
The coordinating runtime follows one ordered lifecycle:
submit input
-> reserve the thread and assign ThreadExecutionId
-> commit THREAD_EXECUTION_STARTED
-> dispatch the input through HPD Agent
-> commit THREAD_EXECUTION_FINISHED
-> release the threadOne thread runs one execution at a time. A user message sent while a turn runs joins that turn instead of starting another execution. Other work on a busy thread waits for it by default; a run with WhenBusy = AgentBusyBehavior.Reject is refused instead. Active controls target the active execution immediately and never create another thread execution. Different threads can execute concurrently.
Start A Run
runtime.RunAsync(input) returns an AgentRun. The input names the agent that runs it in AgentId; an input that names none runs the runtime's default agent. Await it for the result. Its Started task completes as soon as the run owns its thread, before the work finishes:
var run = runtime.RunAsync(input, new AgentRunOptions { WhenBusy = AgentBusyBehavior.Reject });
switch (await run.Started)
{
case AgentRunStart.Started started:
Console.WriteLine($"Running as {started.ThreadExecutionId}");
break;
case AgentRunStart.Busy busy:
Console.WriteLine($"Thread busy with {busy.ActiveThreadExecutionId}");
break;
}
var result = await run;Started | Meaning | Awaited result |
|---|---|---|
AgentRunStart.Started | The run owns the thread as this execution. | The run's result. |
AgentRunStart.Busy | The thread was busy and the run asked to be rejected. | AgentInputResult.Rejected with the active execution id. |
AgentRunStart.NoExecution | The input started no execution: a control, such as a response or a cancel, or a user message that joined the running turn. | The control's result, or AgentInputResult.Steered with the running execution id. |
Started faults or cancels when the run ends before it starts. run.Completion is the result as a Task<AgentInputResult> for APIs that take a task. Hosted input submission runs other work with Reject, which is why a second compaction on a busy thread returns 409 ThreadExecutionActive; a user message never does.
Send A Message While A Turn Runs
A UserMessagesInputEvent names no execution. When the thread's running turn is a message turn that still accepts input, the message joins it: the run completes with AgentInputResult.Steered and the running execution id, and the turn reads the message before its next model request. Otherwise the message starts the next turn, after any work that is finishing.
var run = runtime.RunAsync(new UserMessagesInputEvent
{
SessionId = sessionId,
ThreadId = "main",
Messages = [new ChatMessage(ChatRole.User, "Also check the tests")]
});
if (await run.Started is AgentRunStart.NoExecution &&
await run is AgentInputResult.Steered steered)
Console.WriteLine($"Joined {steered.ThreadExecutionId}");A joined message is committed as an ordinary thread-history message with AgentMessageSource.Steering. It does not emit another execution start or finish. When the turn is cancelled or fails before reading joined messages, the agent answers all of them in one follow-up turn.
The finish event has exactly one terminal outcome:
| Outcome | Error | Meaning |
|---|---|---|
Succeeded | none | The accepted input completed normally. |
Cancelled | none | Cancellation ended the accepted input. |
Failed | required ThreadExecutionError | Execution ended with a structured failure. |
FinishedAt records when the accepted input became terminal. The start and finish correlate through the same ThreadExecutionId.
The coordinator attempts to commit the finish event before releasing ownership. In 0.9.7, release removes the in-process lease in a finally block even if finish persistence fails. A failed finish therefore leaves a committed start without a terminal fact; historical projection reports that execution as Interrupted, while the thread is available for new work.
Live Ownership And Durable History
activeExecution is the runtime coordinator's authoritative present-tense ownership state. THREAD_EXECUTION_STARTED and THREAD_EXECUTION_FINISHED are durable historical facts used by projections and rehydration.
Replaying an old start event does not reserve the live thread. If recovery finds a committed start without a matching finish, historical execution projection reports Interrupted. Interrupted describes recovery from an incomplete historical pair; it is not a normal ThreadExecutionOutcome emitted by a functioning coordinator.
This separation matters for clients:
- use execution events to render history;
- use
activeExecutionto decide whether the thread is busy; - use the live active execution id as interruption authority;
- never infer present ownership from journal replay alone.
Inspect A Thread's Execution
runtime.Executions reads execution state in process, for every agent of the runtime. It never starts or controls work; that goes through RunAsync.
var thread = new ThreadKey(sessionId, "main");
var active = await runtime.Executions.GetActiveAsync(thread);
if (active.IsActive)
Console.WriteLine($"{active.ThreadExecutionId} started at {active.StartedAt}");
var state = await runtime.Executions.GetStateAsync(thread);
if (state is not null)
Console.WriteLine($"Journal head {state.Head.SequenceNumber}; busy: {state.Active.IsActive}");
var activity = await runtime.Executions.GetActivityAsync(thread);
Console.WriteLine($"{activity.Status}: {activity.Report}");
foreach (var execution in await runtime.Executions.ListAsync(thread) ?? [])
Console.WriteLine($"{execution.ThreadExecutionId} by {execution.AgentId}: {execution.Status}");
// Where an agent has run: its executions across sessions, newest first.
foreach (var execution in await runtime.Executions.QueryAsync(new ThreadExecutionQuery("planner", MaxCount: 50)))
Console.WriteLine($"{execution.SessionId}/{execution.ThreadId}: {execution.Status}");| Method | Returns |
|---|---|
GetActiveAsync(thread) | The live execution as an ActiveThreadExecutionLookup: IsActive, ThreadExecutionId, the AgentId of the agent running it, and StartedAt. |
GetStateAsync(thread) | The journal head and the live execution together, or null when the thread does not exist. An execution that started but has no live owner, such as one interrupted by a restart, is finished as failed first, so the state never reports work that is no longer running. |
GetActivityAsync(thread) | The latest execution's Status, the Report it submitted, and how many user questions, parent questions, and other requests it is waiting on. |
ListAsync(thread) | Every execution of the thread as a ThreadExecution, oldest first, whichever agent ran it, or null when the thread does not exist. The live execution is active even before its start event is readable. |
QueryAsync(query) | One agent's executions across the store, newest first, as ThreadExecution values. ThreadExecutionQuery names the agent and optionally one SessionId and a MaxCount. The store finds the runs from its execution-start rows without reading journals; each run is then read the way ListAsync reads it. |
GetAsync(thread, threadExecutionId) | One ThreadExecution, or null when the thread or execution does not exist. |
WaitForFinishAsync(thread, threadExecutionId) | The execution once it has ended. It follows the thread's committed events instead of polling, and returns at once for an execution that already ended. Cancelling the token stops the wait, not the execution. |
A ThreadExecution carries the agent, Status, StartedAt, FinishedAt, the Error of a failed execution, the operations it registered, and Models: the distinct ThreadExecutionModel(ProviderKey, ModelId) pairs its model calls used, in the order it first used them. Either part is null when the client did not report it. Status is one of the ThreadExecutionStatus values: active, succeeded, failed, cancelled, or interrupted for an execution that started but has no live owner and no finish. IsTerminal is true for every status but active.
GetActivityAsync statuses are idle, running, waiting for parent, waiting for user, waiting for input, finishing, completed, stopped without result, failed, cancelled, and runtime unavailable. A subagent's executions are the executions of its child thread, so the same calls inspect a subagent.
Read the journal head and the live execution from one GetStateAsync call when a client renders history and then decides whether the thread is busy. The hosted thread state route returns the same pair.
Control An Active Execution Safely
Exact-execution cancellation is a CancelInputEvent with the session, thread, and active execution id:
var result = await runtime.RunAsync(new CancelInputEvent
{
SessionId = sessionId,
ThreadId = "main",
ThreadExecutionId = activeExecutionId,
Reason = "stop pressed"
});The result is AgentInputResult.Control carrying the disposition. Cancellation is accepted as soon as the execution's token is cancelled; to wait until the execution has ended, call runtime.Executions.WaitForFinishAsync(thread, activeExecutionId). A CancelInputEvent targets exactly one thing: an execution (SessionId, ThreadId, ThreadExecutionId) or a runtime-owned operation (OperationId). Naming both, or neither, is rejected with ArgumentException. The awaited run that was cancelled observes OperationCanceledException.
Cancellation compares the requested id with the current live execution before dispatching:
AgentInputDisposition | Meaning |
|---|---|
Accepted | The matching active execution owns the control. |
NoActiveExecution | The thread has no active execution. |
ActiveExecutionMismatch | A different execution currently owns the thread. |
Do not automatically retry a mismatch. The reported active execution may be newer work started by another client.
Background Correlation
Work created during an execution may carry OriginatingThreadExecutionId after the execution has released the thread. This identifies provenance only. It does not extend ownership or make the originating execution active again.
Hosted Projection
Hosting exposes two separate views:
/executionsreturns historical thread executions;- thread
/statereturns the liveactiveExecutionand pending requests.
On restart or reconnection, rebuild transcript and historical status from committed events, then reconcile present-tense controls with authoritative runtime state. See Hosted Lifecycle And Recovery and Canonical Thread Journal.