Expose current turn admission state on CodexThread (#62604)

## Why

A thread can reserve a turn slot and assign a turn ID while it still
waits for host admission. Callers need to distinguish a pending turn
from one cleared to execute.

## What changed

Add `turn_admission_state()` to report `Idle`, `Pending` with an optional
turn ID, or `Admitted` with a turn ID in a single snapshot. Host-managed
turns become admitted after a grant is installed. Native turns are
admitted synchronously, including when no execution guard is needed.
The current slot retains its admitted state through finishing.

Reject superseded submissions before they can overwrite an owned slot,
and verify that a host grant still belongs to the current turn and task
before recording admission.

## Testing

Cover the admission state while a host decision is pending, after an
interrupt, during execution after a grant, and after the slot returns
to idle. Cover native admission without a host guard.

GitOrigin-RevId: 0633dc036aef99433505559c92b0b1b26a023352
This commit is contained in:
keith thornhill
2026-11-19 21:45:13 +00:00
committed by copyberry
parent b16fddf9d0
commit 75f2d93e7c
6 changed files with 157 additions and 15 deletions
+31
View File
@@ -211,6 +211,21 @@ pub use codex_guardian_context::GuardianRootMessage;
pub use codex_guardian_reviewer::GuardianAuthorizationVersion;
pub use codex_guardian_reviewer::GuardianRootSnapshot;
/// An atomic snapshot of admission for the thread's current turn slot.
///
/// A slot may be reserved before Core assigns it a turn ID. This snapshot does
/// not include work draining after an abort removes the slot.
#[derive(Clone, Debug, Eq, PartialEq)]
#[must_use]
pub enum TurnAdmissionState {
/// Core does not own a current turn slot.
Idle,
/// The slot is reserved, but execution has not been admitted.
Pending { turn_id: Option<String> },
/// Execution was admitted; the slot remains admitted through finishing.
Admitted { turn_id: String },
}
pub struct CodexThread {
pub(crate) session: Arc<Session>,
pub(crate) io: SessionIo,
@@ -896,6 +911,22 @@ impl CodexThread {
self.session.active_turn.lock().await.is_some()
}
/// Returns admission and turn identity from the same current-slot snapshot.
pub async fn turn_admission_state(&self) -> TurnAdmissionState {
let active = self.session.active_turn.lock().await;
match active.as_ref() {
None => TurnAdmissionState::Idle,
Some(turn) => match &turn.turn_id {
Some(turn_id) if turn.admitted => TurnAdmissionState::Admitted {
turn_id: turn_id.clone(),
},
turn_id => TurnAdmissionState::Pending {
turn_id: turn_id.clone(),
},
},
}
}
/// Returns the current turn ID, including while its stop hook runs.
pub async fn current_turn_id(&self) -> Option<String> {
self.session
+1
View File
@@ -62,6 +62,7 @@ pub use codex_thread::GuardianAuthorizationVersion;
pub use codex_thread::GuardianRootMessage;
pub use codex_thread::GuardianRootSnapshot;
pub use codex_thread::ThreadConfigSnapshot;
pub use codex_thread::TurnAdmissionState;
pub use guardian::GuardianInferenceContext;
pub use guardian::ScoreAuthorization as GuardianScoreAuthorization;
pub use guardian::guardian_policy_model;
+3
View File
@@ -38,6 +38,8 @@ use codex_protocol::protocol::TokenUsage;
pub(crate) struct ActiveTurn {
/// The slot's owner, retained after its task detaches to emit the terminal event.
pub(crate) turn_id: Option<String>,
/// Set only after execution admission succeeds; retained through finishing.
pub(crate) admitted: bool,
pub(crate) task: Option<RunningTask>,
pub(crate) sampling_interrupt: Option<SamplingInterrupt>,
/// Present when input admission is closed; cancelled when the final batch is recorded.
@@ -70,6 +72,7 @@ impl Default for ActiveTurn {
fn default() -> Self {
Self {
turn_id: None,
admitted: false,
task: None,
sampling_interrupt: None,
finishing: None,
+11 -5
View File
@@ -56,16 +56,22 @@ pub(super) async fn admit(
// A cancelled/replaced task must never install its permit into a newer task,
// even if recovery reused the turn ID.
let mut active = session.active_turn.lock().await;
let task = active
let turn = active
.as_mut()
.filter(|turn| turn.turn_id.as_deref() == Some(context.sub_id.as_str()))
.ok_or_else(|| CodexErr::new(CodexErrorDetails::TurnAborted))?;
let task = turn
.task
.as_mut()
.and_then(|turn| turn.task.as_mut())
.filter(|task| Arc::ptr_eq(&task.turn_context, context))
.filter(|_| !cancellation.is_cancelled())
.ok_or_else(|| CodexErr::new(CodexErrorDetails::TurnAborted))?;
task._agent_execution_guard = Some(guard);
task.pending_initial_input.take().ok_or_else(|| {
let input = task.pending_initial_input.take().ok_or_else(|| {
CodexErr::Fatal("initial input missing from the task awaiting host admission".into())
})
})?;
task._agent_execution_guard = Some(guard);
turn.admitted = true;
Ok(input)
}
impl Session {
+8 -1
View File
@@ -368,8 +368,13 @@ impl Session {
};
}
let turn = active.get_or_insert_with(ActiveTurn::default);
debug_assert!(turn.task.is_none());
if turn.turn_id.is_some() || turn.task.is_some() || turn.finishing.is_some() {
return TurnInputSubmission::NotSubmitted {
reason: NotSubmittedReason::Superseded,
};
}
turn.turn_id = Some(turn_context.sub_id.clone());
turn.admitted = false;
turn.finishing = None;
Arc::clone(&turn.turn_state)
};
@@ -432,6 +437,8 @@ impl Session {
None,
),
};
// Native admission is synchronous, including unrestricted turns that have no guard.
turn.admitted = host_admission.is_none();
let done_clone = Arc::clone(&done);
let session = Arc::clone(self);
let ctx = Arc::clone(&turn_context);
@@ -14,8 +14,10 @@ use codex_core::AgentTurnAdmissionRequest;
use codex_core::CodexThread;
use codex_core::SteerSubmission;
use codex_core::SuspendTurnOutcome;
use codex_core::TurnAdmissionState;
use codex_core::TurnInputRequest;
use codex_core::TurnInputSubmission;
use codex_extension_api::ExtensionRegistryBuilder;
use codex_features::Feature;
use codex_history::RolloutItem;
use codex_protocol::dynamic_tools::DynamicToolFunctionSpec;
@@ -36,6 +38,7 @@ use codex_protocol::protocol::ReviewRequest;
use codex_protocol::protocol::ReviewTarget;
use codex_protocol::user_input::UserInput;
use codex_thread_store::LoadThreadHistoryParams;
use core_test_support::ThreadIdle;
use core_test_support::context_snapshot;
use core_test_support::context_snapshot::ContextSnapshotOptions;
use core_test_support::hooks::trust_discovered_hooks;
@@ -59,6 +62,30 @@ type Decision = oneshot::Sender<CodexResult<AgentExecutionGuard>>;
type Attempt = (AgentTurnAdmissionRequest, Decision);
struct HostAdmission(mpsc::UnboundedSender<Attempt>);
fn with_idle_notifications(builder: TestCodexBuilder) -> TestCodexBuilder {
let mut extensions = ExtensionRegistryBuilder::<codex_core::config::Config>::new();
extensions.thread_lifecycle_contributor(Arc::new(ThreadIdle));
builder.with_extensions(Arc::new(extensions.build()))
}
async fn wait_for_idle(test: &TestCodex) {
loop {
ThreadIdle::wait(&test.codex).await;
if test.codex.turn_admission_state().await == TurnAdmissionState::Idle {
return;
}
}
}
fn hold_tool() -> DynamicToolSpec {
DynamicToolSpec::Function(DynamicToolFunctionSpec {
name: "hold_turn".into(),
description: "Wait for the test to release this turn.".into(),
input_schema: json!({"type": "object", "properties": {}}),
defer_loading: false,
})
}
impl AgentTurnAdmission for HostAdmission {
fn admit_turn(
&self,
@@ -108,12 +135,7 @@ async fn root_with_admission(
if let Some(session_reader) = session_reader {
options.thread_extension_init.insert(session_reader);
}
options.dynamic_tools = vec![DynamicToolSpec::Function(DynamicToolFunctionSpec {
name: "hold_turn".into(),
description: "Wait for the test to release this turn.".into(),
input_schema: json!({"type": "object", "properties": {}}),
defer_loading: false,
})];
options.dynamic_tools = vec![hold_tool()];
test.codex.shutdown_and_wait().await?;
let root = test.thread_manager.start_thread(options).await?;
test.codex = root.thread;
@@ -220,9 +242,20 @@ async fn steered_audio_keeps_bytes_captured_while_admission_is_pending() -> Resu
async fn root_denial_and_interruption_retain_input_and_grants_span_execution() -> Result<()> {
skip_if_no_network!(Ok(()));
let server = responses::start_mock_server().await;
let builder = with_idle_notifications(test_codex());
let (test, mut attempts) =
root_with_admission(&server, test_codex(), /*session_reader*/ None).await?;
root_with_admission(&server, builder, /*session_reader*/ None).await?;
assert_eq!(
test.codex.turn_admission_state().await,
TurnAdmissionState::Idle
);
let (turn_id, decision) = start(&test, &mut attempts, "Denied initial prompt.").await?;
assert_eq!(
test.codex.turn_admission_state().await,
TurnAdmissionState::Pending {
turn_id: Some(turn_id.clone()),
}
);
assert!(
matches!(submit(&test.codex, "Steered while pending.").await?,
TurnInputSubmission::Steered { turn_id: steered, .. } if steered == turn_id)
@@ -245,6 +278,12 @@ async fn root_denial_and_interruption_retain_input_and_grants_span_execution() -
// Retry on the first visible error, while the failed turn may still be finishing.
let (retry_id, pending) = start(&test, &mut attempts, "Interrupted before admission.").await?;
assert_eq!(
test.codex.turn_admission_state().await,
TurnAdmissionState::Pending {
turn_id: Some(retry_id.clone()),
}
);
assert_denied(&wait_for_event(&test.codex, is_terminal).await, &turn_id);
test.codex.submit(Op::Interrupt).await?;
let event = wait_for_event(&test.codex, is_terminal).await;
@@ -253,9 +292,13 @@ async fn root_denial_and_interruption_retain_input_and_grants_span_execution() -
"expected interrupted turn {retry_id}, got {event:?}"
);
assert!(pending.is_closed());
assert_eq!(
test.codex.turn_admission_state().await,
TurnAdmissionState::Idle
);
responses::mount_function_call_agent_response(&server, "hold", "{}", "hold_turn").await;
let (_, grant) = start(&test, &mut attempts, "Continue the work.").await?;
let (admitted_id, grant) = start(&test, &mut attempts, "Continue the work.").await?;
let released = CancellationToken::new();
assert!(
grant
@@ -267,6 +310,12 @@ async fn root_denial_and_interruption_retain_input_and_grants_span_execution() -
|event| matches!(event, EventMsg::DynamicToolCallRequest(call) if call.call_id == "hold"),
)
.await;
assert_eq!(
test.codex.turn_admission_state().await,
TurnAdmissionState::Admitted {
turn_id: admitted_id,
}
);
assert!(!released.is_cancelled());
test.codex
.submit(Op::DynamicToolResponse {
@@ -279,6 +328,7 @@ async fn root_denial_and_interruption_retain_input_and_grants_span_execution() -
.await?;
wait_for_successful_turn(&test.codex).await;
assert!(released.is_cancelled());
wait_for_idle(&test).await;
insta::assert_snapshot!(
"retained_input_after_admission",
context_snapshot::format_request_history_snapshot(
@@ -291,6 +341,48 @@ async fn root_denial_and_interruption_retain_input_and_grants_span_execution() -
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn controller_root_is_admitted_without_a_host_guard() -> Result<()> {
skip_if_no_network!(Ok(()));
let server = responses::start_mock_server().await;
let mut builder = with_idle_notifications(
test_codex().with_config(|config| config.allow_persistent_dynamic_tool_updates = true),
);
let test = builder.build_with_auto_env(&server).await?;
test.codex.replace_dynamic_tools(vec![hold_tool()]).await?;
assert_eq!(
test.codex.turn_admission_state().await,
TurnAdmissionState::Idle
);
responses::mount_function_call_agent_response(&server, "native-hold", "{}", "hold_turn").await;
let TurnInputSubmission::Started { turn_id, .. } =
submit(&test.codex, "Hold this turn.").await?
else {
anyhow::bail!("expected a new controller turn");
};
wait_for_event(&test.codex, |event| {
matches!(event, EventMsg::DynamicToolCallRequest(call) if call.call_id == "native-hold")
})
.await;
assert_eq!(
test.codex.turn_admission_state().await,
TurnAdmissionState::Admitted { turn_id }
);
test.codex
.submit(Op::DynamicToolResponse {
id: "native-hold".into(),
response: DynamicToolResponse {
content_items: vec![],
success: true,
},
})
.await?;
wait_for_successful_turn(&test.codex).await;
wait_for_idle(&test).await;
test.codex.shutdown_and_wait().await?;
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn interrupt_before_admission_skips_submit_hook_and_uninspected_prompt() -> Result<()> {
skip_if_no_network!(Ok(()));
@@ -596,8 +688,9 @@ async fn suspend_and_check_recoverable_prompt(
async fn denied_review_exits_review_mode() -> Result<()> {
skip_if_no_network!(Ok(()));
let server = responses::start_mock_server().await;
let builder = with_idle_notifications(test_codex());
let (test, mut attempts) =
root_with_admission(&server, test_codex(), /*session_reader*/ None).await?;
root_with_admission(&server, builder, /*session_reader*/ None).await?;
test.codex
.submit(Op::Review {
review_request: ReviewRequest {
@@ -626,6 +719,7 @@ async fn denied_review_exits_review_mode() -> Result<()> {
&wait_for_event(&test.codex, is_terminal).await,
&review.turn_id,
);
wait_for_idle(&test).await;
assert!(
responses::received_responses_requests(&server)
.await