A turn is one task on its own tokio task, and its heart is
run_turn: a loop that sends a sampling request, starts
tools while the response still streams, records their outputs in call
order, and asks one boolean question before it goes round again. Input
that arrives mid-turn joins the running loop instead of starting a new
one, and an interrupt cancels a token tree, waits 100 ms, and then
aborts.
Chapter 4 ended with a user
message entering the submission queue as
SubmissionOp::TurnInput. This chapter follows it from
admission to the terminal event: the tasks a session runs, the two
contexts that freeze a turn’s settings, the run_turn loop,
steering and interruption, and the bookkeeping at the end. The model
request belongs to Chapter 6, the
prompt’s contents to Chapter 7,
and compaction to Chapter 8; here
they appear only as calls that run_turn makes.
The picture
A turn starts from Idle, records its
input, and samples; after tool outputs drain, the follow-up decision
loops back to Sampling, sometimes through mid-turn compaction, or moves
to Finishing, which emits TurnComplete or reopens sampling for a late
steer; an interrupt cancels the task, waits up to 100 ms, and ends in
TurnAborted.
The main path runs left to right. start_task claims the
session’s one turn slot, and Preparing is where run_turn
compacts if needed and records the input. Each pass through Sampling
streams the model’s response, runs its tools, and drains their outputs
before the follow-up decision. A true decision loops back to Sampling,
sometimes through Compacting. A false one moves to Finishing, where
on_task_finished emits TurnComplete, unless a
late steer left input pending, in which case run_turns
samples again. An interrupt sends the task through Cancelling, with its
100 ms grace, to TurnAborted.
Admission: steer or start
submission_loop hands each TurnInput to
turn_input::admit in
codex-rs/core/src/session/turn_input.rs. admit
validates the request and routes on TurnInputMode; for
StartOrSteer it calls start_or_steer. That
function sends agent messages to native delivery and accepts only user
input or a standalone function-call output from everyone else. It
prepares the requested thread settings, then tries to steer first:
Call Session::steer_input. If a turn is running and
accepts the input, apply the settings for later turns and reply
Steered.
If steer_input returns NoActiveTurn, ask
the extensions for admit_turn_start. If the host is
draining, reply NotSubmitted { ServerDraining }.
Build a TurnContext with apply_started,
using the submission ID as the turn ID.
Call
session.spawn_task(turn_context, task_input, RegularTask::new())
and return its result, normally Started.
Trying to steer first removes a race. The loop handles one submission
at a time, so of two simultaneous messages the second sees the first
turn and joins it. The test
turn_input_submission_reports_started_and_steered_for_concurrent_submissions
in codex-rs/core/tests/suite/turn_input_submission.rs sends
two messages through a barrier and expects exactly one
Started and one Steered with the same turn
ID.
Tasks
Four kinds of task
A task is the unit of work that owns a turn. SessionTask
in codex-rs/core/src/tasks/mod.rs has four methods:
kind, span_name, run, and an
abort hook whose default does nothing. Its doc comment asks
implementers to “terminate quickly” once the cancellation token fires.
Because run returns impl Future, a twin trait,
AnySessionTask, boxes the future for dynamic dispatch. That
is the strategy pattern with type erasure: four workflows share one
lifecycle.
The four implementations compare as follows.
Task
TaskKind
Span name
Started by
RegularTask
Regular
session_task.turn
user input, agent mail
ReviewTask
Review
session_task.review
Op::Review
CompactTask
Compact
session_task.compact
Op::Compact
UserShellCommandTask
Regular
session_task.user_shell
Op::RunUserShellCommand
TaskKind has only three values, and the shell task
reports Regular. The kind matters for steering:
steer_input accepts input only for a Regular
task and rejects the other two with ActiveTurnNotSteerable.
A !command sent while a turn runs does not become a task at
all; run_user_shell_command spawns it beside the turn in
UserShellCommandMode::ActiveTurnAuxiliary.
spawn_task
replaces what is running
A session runs at most one task. Session::spawn_task
enforces that rule by force:
So Op::Compact during a turn ends that turn with
TurnAborted { reason: Replaced }. The review path calls
abort_all_tasks(TurnAbortReason::Replaced) itself before
start_task. TurnAbortReason has four values:
Interrupted, Replaced,
ReviewEnded, and BudgetLimited.
start_task claims the slot under the
active_turn lock. It returns
NotSubmitted { ServerDraining } if turn starts are closed,
and NotSubmitted { Superseded } if the slot already holds a
turn ID, a task, or a finishing token. It moves queued agent mail into
the new turn’s pending input, creates a root
CancellationToken, and launches the task with
tokio::spawn. The handle goes into a
RunningTask as an AbortOnDropHandle, so
dropping the record kills the task.
Abort: cancel, wait 100 ms,
then kill
handle_task_abort stops a running task in three moves.
It cancels the task’s token. It waits for the join handle under
tokio::time::timeout with
GRACEFULL_INTERRUPTION_TIMEOUT_MS, which is 100. If the
task has not finished, it calls handle.abort(), and a
warning records that the task “did not finish gracefully”.
The grace period lets a cooperative task save partial work. Every
layer of a turn holds a child of the root token: the task, each
run_turn call, each sampling request, and each tool call.
One cancel reaches them all.
After the wait, an Interrupted abort does extra work
before it sends TurnAborted. It records agent mail that was
already accepted, records the interrupted-turn marker in history,
flushes the rollout, and runs interrupt hooks. Pending approvals are
cleared only after the task has seen cancellation. A comment explains
why: otherwise “an in-flight approval wait can surface as a
model-visible rejection before TurnAborted.”
Two contexts: the turn and
the step
A TurnContext is built once per turn and shared as an
Arc. It holds the turn ID in sub_id, the
config: Arc<Config>, the provider,
final_output_json_schema, the
turn_timing_state, the terminal_error slot,
and an extension_data store. Several of its accessors are
marked legacy; approval_policy() “returns the frozen
initial-turn approval policy”, and step-scoped code should read its
StepContext instead.
A StepContext is captured before each sampling request.
Its doc comment reads “Request-scoped state that may change between
model sampling requests.” It freezes the settings (a
ResolvedStepSettings with model metadata, reasoning
summary, and service tier), the tool_router for this
request, the MCP binding, the environments, and a preempt
token. The tools the model sees and the tools a call can reach come from
one snapshot, and a settings change made mid-turn takes effect at the
next step.
The run_turn loop
RegularTask::run sends TurnStarted first,
so the first turn does not wait on startup prewarm, and then calls
RegularTask::run_turns, which calls run_turn
in codex-rs/core/src/session/turn.rs. The doc comment on
run_turn states the contract: if the model requests a
function call, “we execute it and send the output back to the model in
the next sampling request”; if it sends only an assistant message, the
turn is complete.
Before the first request
Create one ModelClientSession for the turn; it “caches
WebSocket + sticky routing state,” so retries reuse it.
Run run_pre_sampling_compact if auto-compaction is on.
It runs before the input is recorded, and on failure the input is still
recorded.
Find the MCP servers and plugins the input mentions, then capture
the first StepContext.
Record context updates, run user-prompt hooks, and record the input
with PersistContext::TurnStart. A blocking hook ends the
turn here.
Record skill and plugin injections.
One iteration
Each pass of the loop does the same work:
Drain pending input, unless this is the first pass and the turn
already has fresh input. Record any drained input with
PersistContext::SteeredUserInput.
Reuse the first step context, or capture a new one.
Snapshot history with SamplingInput::capture, which
clones it under the session lock.
Call run_sampling_request, which builds the prompt,
opens the stream, and retries on transient errors (Chapter 6).
Compute the follow-up decision, check compaction, and either
continue or leave the loop.
Tools start while the
response streams
Inside the request, try_run_sampling_request reads
ResponseEvents. On each OutputItemDone it
calls handle_output_item_done in
codex-rs/core/src/stream_events_utils.rs. If the tool
router recognizes a tool call, that function records the call item at
once, builds a future for
ToolCallRuntime::handle_tool_call, and sets
needs_follow_up = true. The future goes into a
FuturesOrdered named in_flight and starts
running while the model is still streaming.
A non-tool item, such as an assistant message, becomes a
TurnItem: the function sends ItemStarted if
the item was not already streaming, then ItemCompleted, and
records it. When the stream ends, drain_in_flight awaits
the tool futures and records each output. FuturesOrdered
yields in push order, so outputs enter history in call order even when a
later call finishes first; a fast output waits behind a slow earlier
one. Only after the drain does the request send TokenCount,
because a tool such as request_user_input can pause the
turn and the client should not see progress while it waits.
The follow-up decision
The first boolean,
,
is set inside try_run_sampling_request:
where
is true when output item
is a tool call,
is the number of output items,
is the optional end_turn flag on
ResponseEvent::Completed, and
is true when queued mail or a user steer cut the stream short. Back in
run_turn, the code combines
with two more facts:
where
is needs_follow_up,
is worker_self_stop (a multi-agent worker’s own tool asked
to stop), and
is has_pending_input. The source line is
let needs_follow_up = model_needs_follow_up || has_pending_input;,
one line after model_needs_follow_up absorbs
.
The disjunction with
is what lets a steer keep a turn alive: even when the model gave a final
answer, queued input sends the loop round again.
Compaction checkpoints
The loop checks compaction at three points, named by
CompactionPhase: PreTurn before the first
request, MidTurn between requests, and
PostTurn after the answer. The mid-turn rule is a second
formula:
where
is should_roll_over,
is a pending request for a new context window,
is whether auto-compaction is enabled,
is worker_self_stop from Formula 5.2,
is token_limit_reached, and
is true when a background compaction result is ready. Apart from a
requested window reset after a worker stops itself, mid-turn compaction
needs
,
so it runs only when the turn will sample again. Foreground post-turn
compaction runs only when
model_post_turn_compact_threshold_percent is above 0, and
its default is 0. When async compaction is enabled, a background
compaction can also start at each checkpoint. Chapter 8 explains the token limit and
both kinds of compaction.
How the loop ends
The loop has four kinds of exit:
Finished.
is false. Stop hooks run; a blocking hook with a prompt records that
prompt and continues the loop. Otherwise the loop breaks and returns the
last assistant message.
Error. Most sampling errors send
EventMsg::Error and break, with the comment “let the user
continue the conversation”. An invalid image ends the turn with “Invalid
image in your last message. Please remove it and try again.”
Cancelled.CodexErr::TurnAborted
propagates up and the turn ends as aborted.
Hook stop. A user-prompt or session-start hook that
blocks ends the turn early.
run_turns then decides whether to run
run_turn again. It returns when the turn has a terminal
error, the budget is exhausted, a sampling interrupt was requested, or
no input is pending.
Steering, pending
input, and interruption
Steering a running turn
steer_input takes the active_turn lock and
checks in turn: no task gives NoActiveTurn, a
Review or Compact task gives
ActiveTurnNotSteerable, empty input gives
EmptyInput, and a different output schema gives
ActiveTurnOutputSchemaMismatch. Otherwise it appends an
InputQueueEntry to the turn’s pending input, notifies
waiters, and returns the active turn’s ID. The running loop picks the
entry up at step 1 of its next iteration. With the
InstantInterrupt feature on, each step also carries a
preempt token whose doc comment says it “Preempts this
request and yields its code-mode observations when user input arrives,”
so the new message reaches the model sooner.
The late steer
A steer can lose the race with the loop’s last pass: the input lands
after run_turns returned but before the turn finished.
on_task_finished handles that case. It keeps the turn open
when this holds:
where
is true when the task returned regular output,
is a recorded terminal error,
is an exhausted budget,
is a requested sampling interrupt,
is whether the turn still accepts mailbox delivery, and
is non-empty pending input. When the formula holds,
on_task_finished returns the turn’s MCP requirements
instead of finishing, and the task future calls
RegularTask::run_turns again with the same
TurnContext. The client sees one turn ID and one terminal
event.
Interruption
Op::Interrupt calls interrupt_task, which
takes the turn out of its slot and aborts it with
TurnAbortReason::Interrupted through
handle_task_abort. Afterwards
maybe_start_turn_for_pending_work lets queued mail start
the next turn. A softer SamplingInterrupt, used only by
multi-agent v3 turns and some v2 child turns, stops at an item boundary
(see Chapter 20).
Ending a turn
The terminal event
on_task_finished sends exactly one terminal event. It
sends TurnAborted when the task error is
TurnAborted, and TurnComplete otherwise,
including after errors that were already reported.
TurnCompleteEvent carries turn_id,
root_turn_id, last_agent_message,
error, started_at, completed_at,
duration_ms, and time_to_first_token_ms. If
the turn applied patches, finish_turn_diff sends
TurnDiff with the turn’s net unified diff just before the
terminal event; it does so only for TurnComplete. The
rollout is flushed before finalization and again after the terminal
event.
Token usage
TokenUsage counts six quantities: input, cached input,
cache-write input, output, reasoning output, and total tokens. On each
Completed event the loop calls
record_token_usage_info, which adds to the thread’s running
total. At the end of the turn, on_task_finished computes
the turn’s own usage from a snapshot taken when the task started:
where
ranges over the six counters,
is the thread total at the end of the turn,
is the total recorded in token_usage_at_turn_start, and
is the turn’s usage. The clamp at 0 guards against a total that moved
backwards. The values feed span fields such as
codex.turn.token_usage.input_tokens and a per-model
histogram from TurnTokenUsage.
Timing milestones
TurnTimingState records the turn’s start, first token,
first message, and each item’s start time. duration_ms runs
from the start to the first completion notice, and
time_to_first_token_ms from the start to the first token. A
profile splits the turn into phases such as sampling, compaction, and
tool blocking. A forced abort marks the critical-path profile incomplete
with ForcedTeardown, so a slow-to-cancel task shows up in
the data.
The budget gate is a stub
run_turn consults a TurnWork object after
each response and is written to stop or retry on its answer. In this
tree codex-rs/core/src/rollout_budget/work_gate.rs stubs
those checkpoints: WorkCheckpoint::should_retry and
is_finished always return false,
should_finish_after_compaction returns
Ok(false), and TurnWork::take_answer returns
None. The rollout-wide gate, RolloutWorkGate,
is real: once a budget owner calls stop_new_work, new work
fails with SessionBudgetExceeded.
TurnWork::accept_response forwards to that gate through
check_start; apart from that call, the per-turn checkpoints
never end a turn early. The code’s shape suggests another build supplies
a real work_gate.rs; that is an inference.
Worked example: one
turn with a tool call
The test
exec_command_tool_executes_command_and_streams_output in
codex-rs/core/tests/suite/tool_harness.rs scripts a mock
model with two responses. The first streams a function call and
completes:
The second sends the assistant message “all done” and completes; the
usage object is trimmed here and is all zeros. The test sends “please
run the shell command” with AskForApproval::Never, waits
for TurnComplete, and asserts that the second request
carries the output Wall time: ...,
Process exited with code 0, and tool harness.
The client sees the sequence below; the order is derived from code, not
asserted by the test, and session-level events are omitted.
TurnStarted.
ItemStarted and ItemCompleted with
TurnItem::UserMessage, then the older
UserMessage.
Request 1. The function call is recorded, its future starts, and
becomes true.
The command’s own events: ItemStarted with
CommandExecution and the older
ExecCommandBegin, any output deltas, then
ItemCompleted and ExecCommandEnd (Chapter
10).
drain_in_flight records the output, then
TokenCount.
Formula 5.2 gives
,
so the loop runs again.
Request 2. The message yields ItemStarted,
ItemCompleted with AgentMessage, and the older
AgentMessage; then TokenCount.
Now
.
With no Stop hooks configured, the loop breaks.
TurnComplete with last_agent_message set
to “all done”.
One part of this order is asserted elsewhere. In
codex-rs/core/tests/suite/exec_policy.rs,
git_status_requires_approval_under_unless_trusted records
the command’s events with an approval in the middle and expects
["start", "prompt", "launch", "finish", "exit"]:
ItemStarted, ExecApprovalRequest,
ExecCommandBegin, ItemCompleted, and
ExecCommandEnd.
Status at commit 081295be9d.run_turn, task replacement, steering, and the 100 ms abort
grace: IMPLEMENTED. Per-turn budget checkpoints (TurnWork,
WorkCheckpoint): stubs that never stop a turn on their own.
Feature::InstantInterrupt (UNDER DEVELOPMENT, on by
default) arms the step preempt token.
Feature::CodeModeInterrupt (STABLE, on) also stops
code-mode cells on interrupt. Feature::TokenBudget (UNDER
DEVELOPMENT, off) turns off the summarizing compaction paths in
run_turn, such as foreground post-turn compaction.
Feature::CriticalPathTiming (UNDER DEVELOPMENT, off)
enables the critical-path profile. Read in code, not run.
What breaks
Symptom
Cause
Check
TurnAborted { reason: replaced } without a user
interrupt
/compact or a review replaced the turn
spawn_task calls
abort_all_tasks(Replaced)
Steer returns ActiveTurnNotSteerable
The running task is a review or compaction
steer_input checks TaskKind
Input returns NotSubmitted { Superseded }
The turn slot still holds a turn or finishing token
Turn ends with “Invalid image in your last message.”
The model API rejected an image
run_turn error arm
No TokenCount while a turn waits
A tool such as request_user_input is pending
try_run_sampling_request emits after the drain
Warning “Failed to save the conversation transcript”
The rollout flush before finalization failed
thread store logs
Code map
What it is
Where it lives
Identifier
Admission
codex:codex-rs/core/src/session/turn_input.rs
async fn start_or_steer
Task trait and replacement
codex:codex-rs/core/src/tasks/mod.rs
pub async fn spawn_task
Abort with grace period
codex:codex-rs/core/src/tasks/mod.rs
async fn handle_task_abort
Turn finalization
codex:codex-rs/core/src/tasks/mod.rs
pub(crate) async fn on_task_finished
Regular task
codex:codex-rs/core/src/tasks/regular.rs
fn run_turns
Turn loop
codex:codex-rs/core/src/session/turn.rs
pub(crate) async fn run_turn
Per-item handling
codex:codex-rs/core/src/stream_events_utils.rs
pub(crate) async fn handle_output_item_done
Step snapshot
codex:codex-rs/core/src/session/step_context.rs
pub(crate) struct StepContext
Recall check
What does start_or_steer try first, and
why? steer_input; the loop handles one submission at a time, so
two simultaneous messages produce one Started and one
Steered.
What happens to a running turn when Op::Compact
arrives? spawn_task aborts it with
TurnAbortReason::Replaced and starts a
CompactTask.
Why are tool outputs recorded in call order?
The tool futures sit in a FuturesOrdered, which yields in
push order regardless of finish order.
When does run_turn sample again?
When
holds: the model asked for more (or called a tool) and the worker did
not self-stop, or input is pending.
What does the 100 ms constant control?
How long handle_task_abort waits after cancelling a task’s
token before it calls handle.abort().