mirror of
https://github.com/openai/codex.git
synced 2026-12-02 00:31:03 +00:00
Preserve status for evicted V2 agents
V2 residency eviction removes idle agents from ThreadManager while leaving their logical identities in AgentRegistry. Status queries therefore report NotFound for completed and errored agents after eviction, even though callers can still address those agents. When eviction removes the expected CodexThread, retain its bounded terminal status in the matching AgentMetadata. Under the ThreadManager write lock, publish the status only if the registry still contains the same metadata generation. This makes the status available before the matching removal becomes visible without publishing through a stale metadata handle. Tie each cached status to its CodexThread source. Reloaded threads clear the cache, and status reads reject a cache from another CodexThread. Limit cached text to 128 bytes because status can enter model-visible tool output. Keep existing behavior for interrupted agents and for Missing or Replaced removals, where eviction did not remove the captured thread.
This commit is contained in:
@@ -219,9 +219,15 @@ impl AgentControl {
|
||||
result: CodexResult<String>,
|
||||
) -> CodexResult<String> {
|
||||
if matches!(result, Err(CodexErr::InternalAgentDied)) {
|
||||
let _ = state.remove_thread(&agent_id).await;
|
||||
let removed_thread = state.remove_thread(&agent_id).await;
|
||||
self.forget_v2_residency(agent_id);
|
||||
self.state.release_spawned_thread(agent_id);
|
||||
if self
|
||||
.state
|
||||
.cold_status(agent_id, removed_thread.as_ref())
|
||||
.is_none()
|
||||
{
|
||||
self.state.release_spawned_thread(agent_id);
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
@@ -229,13 +235,28 @@ impl AgentControl {
|
||||
/// Fetch the last known status for `agent_id`, returning `NotFound` when unavailable.
|
||||
pub(crate) async fn get_status(&self, agent_id: ThreadId) -> AgentStatus {
|
||||
let Ok(state) = self.upgrade() else {
|
||||
// No agent available if upgrade fails.
|
||||
return AgentStatus::NotFound;
|
||||
return self
|
||||
.state
|
||||
.cold_status(agent_id, /*live_thread*/ None)
|
||||
.unwrap_or(AgentStatus::NotFound);
|
||||
};
|
||||
let Ok(thread) = state.get_thread(agent_id).await else {
|
||||
return AgentStatus::NotFound;
|
||||
let thread = match state.get_thread(agent_id).await {
|
||||
Ok(thread) => thread,
|
||||
Err(_) => {
|
||||
let cold_status = self.state.cold_status(agent_id, /*live_thread*/ None);
|
||||
match state.get_thread(agent_id).await {
|
||||
Ok(thread) => thread,
|
||||
Err(_) => return cold_status.unwrap_or(AgentStatus::NotFound),
|
||||
}
|
||||
}
|
||||
};
|
||||
thread.agent_status().await
|
||||
if let Some(status) = self.state.cold_status(agent_id, Some(&thread)) {
|
||||
return status;
|
||||
}
|
||||
let status = thread.agent_status().await;
|
||||
self.state
|
||||
.cold_status(agent_id, Some(&thread))
|
||||
.unwrap_or(status)
|
||||
}
|
||||
|
||||
pub(crate) fn register_session_root(
|
||||
@@ -307,8 +328,29 @@ impl AgentControl {
|
||||
agent_id: ThreadId,
|
||||
) -> CodexResult<watch::Receiver<AgentStatus>> {
|
||||
let state = self.upgrade()?;
|
||||
let thread = state.get_thread(agent_id).await?;
|
||||
Ok(thread.subscribe_status())
|
||||
let thread = match state.get_thread(agent_id).await {
|
||||
Ok(thread) => thread,
|
||||
Err(err) => {
|
||||
let cold_status = self.state.cold_status(agent_id, /*live_thread*/ None);
|
||||
match state.get_thread(agent_id).await {
|
||||
Ok(thread) => thread,
|
||||
Err(_) => {
|
||||
return cold_status
|
||||
.map(|status| watch::channel(status).1)
|
||||
.ok_or(err);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
if let Some(status) = self.state.cold_status(agent_id, Some(&thread)) {
|
||||
return Ok(watch::channel(status).1);
|
||||
}
|
||||
let status = thread.subscribe_status();
|
||||
Ok(self
|
||||
.state
|
||||
.cold_status(agent_id, Some(&thread))
|
||||
.map(|status| watch::channel(status).1)
|
||||
.unwrap_or(status))
|
||||
}
|
||||
|
||||
pub(crate) async fn format_environment_context_subagents(
|
||||
@@ -531,6 +573,7 @@ impl AgentControl {
|
||||
agent_nickname,
|
||||
agent_role,
|
||||
last_task_message: None,
|
||||
..Default::default()
|
||||
};
|
||||
Ok((session_source, agent_metadata))
|
||||
}
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
use super::AgentControl;
|
||||
use crate::agent::AgentStatus;
|
||||
use crate::agent::registry::AgentRegistry;
|
||||
use crate::codex_thread::CodexThread;
|
||||
use crate::config::Config;
|
||||
use crate::thread_manager::RemoveThreadIfSameResult;
|
||||
use crate::thread_manager::ThreadManagerState;
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::error::CodexErr;
|
||||
@@ -55,7 +57,7 @@ impl AgentControl {
|
||||
.effective_agent_max_threads(MultiAgentVersion::V2)
|
||||
.unwrap_or(usize::MAX);
|
||||
Arc::clone(&self.v2_residency)
|
||||
.reserve_slot(state, capacity, protected_thread_id)
|
||||
.reserve_slot(state, self.state.as_ref(), capacity, protected_thread_id)
|
||||
.await
|
||||
}
|
||||
|
||||
@@ -80,6 +82,7 @@ impl V2Residency {
|
||||
async fn reserve_slot(
|
||||
self: Arc<Self>,
|
||||
manager: &Arc<ThreadManagerState>,
|
||||
registry: &AgentRegistry,
|
||||
capacity: usize,
|
||||
protected_thread_id: Option<ThreadId>,
|
||||
) -> CodexResult<V2ResidencySlot> {
|
||||
@@ -91,7 +94,7 @@ impl V2Residency {
|
||||
});
|
||||
}
|
||||
if !self
|
||||
.try_unload_one_resident(manager, protected_thread_id)
|
||||
.try_unload_one_resident(manager, registry, protected_thread_id)
|
||||
.await
|
||||
{
|
||||
return Err(CodexErr::AgentLimitReached {
|
||||
@@ -116,6 +119,7 @@ impl V2Residency {
|
||||
async fn try_unload_one_resident(
|
||||
&self,
|
||||
manager: &Arc<ThreadManagerState>,
|
||||
registry: &AgentRegistry,
|
||||
protected_thread_id: Option<ThreadId>,
|
||||
) -> bool {
|
||||
let candidates_to_scan = self.resident_count();
|
||||
@@ -123,6 +127,7 @@ impl V2Residency {
|
||||
let Some(candidate_thread_id) = self.pop_lru_candidate(protected_thread_id) else {
|
||||
return false;
|
||||
};
|
||||
let metadata = registry.agent_metadata_for_thread(candidate_thread_id);
|
||||
let Some(candidate_thread) = manager
|
||||
.get_thread(candidate_thread_id)
|
||||
.await
|
||||
@@ -131,10 +136,22 @@ impl V2Residency {
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
if !is_unloadable(candidate_thread.as_ref()).await {
|
||||
let status = candidate_thread.agent_status().await;
|
||||
if !is_unloadable(candidate_thread.as_ref(), &status).await {
|
||||
self.touch(candidate_thread_id);
|
||||
continue;
|
||||
}
|
||||
let cold_status = match status {
|
||||
AgentStatus::Completed(_) | AgentStatus::Errored(_) => Some(status),
|
||||
AgentStatus::Interrupted => None,
|
||||
AgentStatus::PendingInit
|
||||
| AgentStatus::Running
|
||||
| AgentStatus::Shutdown
|
||||
| AgentStatus::NotFound => {
|
||||
self.touch(candidate_thread_id);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
candidate_thread.ensure_rollout_materialized().await;
|
||||
if let Err(err) = candidate_thread.shutdown_and_wait().await {
|
||||
warn!(
|
||||
@@ -143,8 +160,24 @@ impl V2Residency {
|
||||
self.touch(candidate_thread_id);
|
||||
continue;
|
||||
}
|
||||
let _ = manager.remove_thread(&candidate_thread_id).await;
|
||||
return true;
|
||||
let removal = manager
|
||||
.remove_thread_if_same(&candidate_thread_id, &candidate_thread, || {
|
||||
if let (Some(metadata), Some(status)) = (&metadata, cold_status) {
|
||||
registry.publish_cold_status_if_current(
|
||||
candidate_thread_id,
|
||||
metadata,
|
||||
&candidate_thread,
|
||||
status,
|
||||
);
|
||||
}
|
||||
})
|
||||
.await;
|
||||
match removal {
|
||||
RemoveThreadIfSameResult::Removed | RemoveThreadIfSameResult::Missing => {
|
||||
return true;
|
||||
}
|
||||
RemoveThreadIfSameResult::Replaced => {}
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
@@ -222,9 +255,9 @@ pub(super) fn is_v2_resident_session_source(session_source: &SessionSource) -> b
|
||||
matches!(session_source, SessionSource::SubAgent(_))
|
||||
}
|
||||
|
||||
async fn is_unloadable(thread: &CodexThread) -> bool {
|
||||
async fn is_unloadable(thread: &CodexThread, status: &AgentStatus) -> bool {
|
||||
matches!(
|
||||
thread.agent_status().await,
|
||||
status,
|
||||
AgentStatus::Completed(_) | AgentStatus::Errored(_) | AgentStatus::Interrupted
|
||||
) && thread.codex.session.active_turn.lock().await.is_none()
|
||||
&& !thread
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
use crate::ThreadManager;
|
||||
use crate::agent::AgentControl;
|
||||
use crate::agent::AgentStatus;
|
||||
use crate::agent::registry::AgentMetadata;
|
||||
use crate::codex_thread::CodexThread;
|
||||
use crate::config::Config;
|
||||
use crate::config::test_config;
|
||||
@@ -8,6 +10,7 @@ use codex_features::Feature;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::error::CodexErr;
|
||||
use codex_protocol::protocol::ErrorEvent;
|
||||
use codex_protocol::protocol::EventMsg;
|
||||
use codex_protocol::protocol::SessionSource;
|
||||
use codex_protocol::protocol::SubAgentSource;
|
||||
@@ -46,7 +49,19 @@ async fn residency_slot_reservation_unloads_oldest_idle_v2_agent() {
|
||||
let first =
|
||||
spawn_v2_subagent(&control, &state, config.clone(), root.thread_id, "worker-1").await;
|
||||
first_slot.commit(first.thread_id);
|
||||
mark_thread_completed(first.thread.as_ref()).await;
|
||||
let reservation = control
|
||||
.state
|
||||
.reserve_spawn_slot(/*max_threads*/ None)
|
||||
.expect("reserve registry slot");
|
||||
reservation.commit(AgentMetadata {
|
||||
agent_id: Some(first.thread_id),
|
||||
..Default::default()
|
||||
});
|
||||
mark_thread_status(
|
||||
first.thread.as_ref(),
|
||||
AgentStatus::Errored("é".repeat(3000)),
|
||||
)
|
||||
.await;
|
||||
|
||||
let second_slot = control
|
||||
.reserve_v2_residency_slot(&state, &config, /*protected_thread_id*/ None)
|
||||
@@ -57,8 +72,21 @@ async fn residency_slot_reservation_unloads_oldest_idle_v2_agent() {
|
||||
Err(err) => panic!("expected evicted thread to be missing, got {err:?}"),
|
||||
Ok(_) => panic!("expected evicted thread to be missing"),
|
||||
}
|
||||
let expected_status = AgentStatus::Errored(format!("{}...[truncated]", "é".repeat(57)));
|
||||
assert_eq!(control.get_status(first.thread_id).await, expected_status);
|
||||
let status = control
|
||||
.subscribe_status(first.thread_id)
|
||||
.await
|
||||
.expect("evicted agent status should remain subscribable");
|
||||
assert_eq!(*status.borrow(), expected_status);
|
||||
let second = spawn_v2_subagent(&control, &state, config, root.thread_id, "worker-2").await;
|
||||
second_slot.commit(second.thread_id);
|
||||
assert_eq!(
|
||||
control
|
||||
.state
|
||||
.cold_status(first.thread_id, Some(&second.thread)),
|
||||
None
|
||||
);
|
||||
|
||||
assert!(manager.get_thread(root.thread_id).await.is_ok());
|
||||
assert!(manager.get_thread(second.thread_id).await.is_ok());
|
||||
@@ -92,7 +120,7 @@ async fn interrupted_v2_agent_is_lost_after_residency_eviction() {
|
||||
let first =
|
||||
spawn_v2_subagent(&control, &state, config.clone(), root.thread_id, "worker-1").await;
|
||||
first_slot.commit(first.thread_id);
|
||||
mark_thread_interrupted(first.thread.as_ref()).await;
|
||||
mark_thread_status(first.thread.as_ref(), AgentStatus::Interrupted).await;
|
||||
|
||||
let second_slot = control
|
||||
.reserve_v2_residency_slot(&state, &config, /*protected_thread_id*/ None)
|
||||
@@ -106,7 +134,11 @@ async fn interrupted_v2_agent_is_lost_after_residency_eviction() {
|
||||
let second =
|
||||
spawn_v2_subagent(&control, &state, config.clone(), root.thread_id, "worker-2").await;
|
||||
second_slot.commit(second.thread_id);
|
||||
mark_thread_completed(second.thread.as_ref()).await;
|
||||
mark_thread_status(
|
||||
second.thread.as_ref(),
|
||||
AgentStatus::Completed(Some("done".to_string())),
|
||||
)
|
||||
.await;
|
||||
|
||||
let err = control
|
||||
.ensure_v2_agent_loaded(config, first.thread_id)
|
||||
@@ -150,40 +182,32 @@ async fn spawn_v2_subagent(
|
||||
.expect("spawn v2 subagent")
|
||||
}
|
||||
|
||||
async fn mark_thread_completed(thread: &CodexThread) {
|
||||
async fn mark_thread_status(thread: &CodexThread, status: AgentStatus) {
|
||||
let turn = thread.codex.session.new_default_turn().await;
|
||||
thread
|
||||
.codex
|
||||
.session
|
||||
.send_event(
|
||||
turn.as_ref(),
|
||||
EventMsg::TurnComplete(TurnCompleteEvent {
|
||||
turn_id: turn.sub_id.clone(),
|
||||
last_agent_message: Some("done".to_string()),
|
||||
completed_at: None,
|
||||
duration_ms: None,
|
||||
time_to_first_token_ms: None,
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
clear_active_turn(thread).await;
|
||||
}
|
||||
|
||||
async fn mark_thread_interrupted(thread: &CodexThread) {
|
||||
let turn = thread.codex.session.new_default_turn().await;
|
||||
thread
|
||||
.codex
|
||||
.session
|
||||
.send_event(
|
||||
turn.as_ref(),
|
||||
EventMsg::TurnAborted(TurnAbortedEvent {
|
||||
turn_id: Some(turn.sub_id.clone()),
|
||||
reason: TurnAbortReason::Interrupted,
|
||||
completed_at: None,
|
||||
duration_ms: None,
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
let event = match status {
|
||||
AgentStatus::Completed(last_agent_message) => EventMsg::TurnComplete(TurnCompleteEvent {
|
||||
turn_id: turn.sub_id.clone(),
|
||||
last_agent_message,
|
||||
completed_at: None,
|
||||
duration_ms: None,
|
||||
time_to_first_token_ms: None,
|
||||
}),
|
||||
AgentStatus::Errored(message) => EventMsg::Error(ErrorEvent {
|
||||
message,
|
||||
codex_error_info: None,
|
||||
}),
|
||||
AgentStatus::Interrupted => EventMsg::TurnAborted(TurnAbortedEvent {
|
||||
turn_id: Some(turn.sub_id.clone()),
|
||||
reason: TurnAbortReason::Interrupted,
|
||||
completed_at: None,
|
||||
duration_ms: None,
|
||||
}),
|
||||
status @ (AgentStatus::PendingInit
|
||||
| AgentStatus::Running
|
||||
| AgentStatus::Shutdown
|
||||
| AgentStatus::NotFound) => panic!("unsupported fixture status: {status:?}"),
|
||||
};
|
||||
thread.codex.session.send_event(turn.as_ref(), event).await;
|
||||
clear_active_turn(thread).await;
|
||||
}
|
||||
|
||||
|
||||
@@ -120,14 +120,15 @@ impl AgentControl {
|
||||
thread_id: ThreadId,
|
||||
) -> CodexResult<()> {
|
||||
let state = self.upgrade()?;
|
||||
let metadata = self
|
||||
.state
|
||||
.agent_metadata_for_thread(thread_id)
|
||||
.ok_or(CodexErr::ThreadNotFound(thread_id))?;
|
||||
if state.get_thread(thread_id).await.is_ok() {
|
||||
metadata.clear_cold_status();
|
||||
self.touch_loaded_v2_residency(&state, thread_id).await;
|
||||
return Ok(());
|
||||
}
|
||||
if self.state.agent_metadata_for_thread(thread_id).is_none() {
|
||||
return Err(CodexErr::ThreadNotFound(thread_id));
|
||||
}
|
||||
|
||||
let stored_thread = state
|
||||
.read_stored_thread(ReadThreadParams {
|
||||
thread_id,
|
||||
@@ -179,12 +180,14 @@ impl AgentControl {
|
||||
.await
|
||||
{
|
||||
Ok(reloaded_thread) => {
|
||||
metadata.clear_cold_status();
|
||||
residency_slot.commit(reloaded_thread.thread_id);
|
||||
state.notify_thread_created(reloaded_thread.thread_id);
|
||||
Ok(())
|
||||
}
|
||||
Err(err) => {
|
||||
if state.get_thread(thread_id).await.is_ok() {
|
||||
metadata.clear_cold_status();
|
||||
drop(residency_slot);
|
||||
self.touch_loaded_v2_residency(&state, thread_id).await;
|
||||
return Ok(());
|
||||
|
||||
@@ -623,29 +623,85 @@ async fn ensure_v2_agent_loaded_reloads_registered_unloaded_agent() {
|
||||
.await
|
||||
.expect("child thread should shut down");
|
||||
|
||||
assert!(
|
||||
harness
|
||||
.manager
|
||||
.remove_thread(&spawned_agent.thread_id)
|
||||
.await
|
||||
.is_some()
|
||||
let metadata = harness
|
||||
.control
|
||||
.get_agent_metadata(spawned_agent.thread_id)
|
||||
.expect("registered child metadata");
|
||||
let cold_status = AgentStatus::Completed(Some("child persisted".to_string()));
|
||||
harness.control.state.publish_cold_status_if_current(
|
||||
spawned_agent.thread_id,
|
||||
&metadata,
|
||||
&child_thread,
|
||||
cold_status.clone(),
|
||||
);
|
||||
assert_eq!(
|
||||
harness.control.get_status(spawned_agent.thread_id).await,
|
||||
cold_status
|
||||
);
|
||||
let state = harness.control.upgrade().expect("thread manager is live");
|
||||
let result = harness
|
||||
.control
|
||||
.handle_thread_request_result(
|
||||
spawned_agent.thread_id,
|
||||
&state,
|
||||
Err(CodexErr::InternalAgentDied),
|
||||
)
|
||||
.await;
|
||||
assert_matches!(result, Err(CodexErr::InternalAgentDied));
|
||||
match harness.manager.get_thread(spawned_agent.thread_id).await {
|
||||
Err(CodexErr::ThreadNotFound(id)) => assert_eq!(id, spawned_agent.thread_id),
|
||||
Err(err) => panic!("expected ThreadNotFound, got {err:?}"),
|
||||
Ok(_) => panic!("expected thread to be removed"),
|
||||
}
|
||||
assert!(
|
||||
harness
|
||||
.control
|
||||
.get_agent_metadata(spawned_agent.thread_id)
|
||||
.is_some()
|
||||
);
|
||||
|
||||
harness
|
||||
.control
|
||||
.ensure_v2_agent_loaded(harness.config.clone(), spawned_agent.thread_id)
|
||||
.await
|
||||
.expect("known v2 agent should reload");
|
||||
let _ = harness
|
||||
let reloaded_thread = harness
|
||||
.manager
|
||||
.get_thread(spawned_agent.thread_id)
|
||||
.await
|
||||
.expect("reloaded child thread should exist");
|
||||
assert_eq!(
|
||||
harness
|
||||
.control
|
||||
.state
|
||||
.cold_status(spawned_agent.thread_id, Some(&reloaded_thread)),
|
||||
None
|
||||
);
|
||||
let mut status = harness
|
||||
.control
|
||||
.subscribe_status(spawned_agent.thread_id)
|
||||
.await
|
||||
.expect("reloaded agent status should be subscribable");
|
||||
let turn = reloaded_thread.codex.session.new_default_turn().await;
|
||||
reloaded_thread
|
||||
.codex
|
||||
.session
|
||||
.send_event(
|
||||
turn.as_ref(),
|
||||
EventMsg::TurnComplete(TurnCompleteEvent {
|
||||
turn_id: turn.sub_id.clone(),
|
||||
last_agent_message: Some("reloaded done".to_string()),
|
||||
completed_at: None,
|
||||
duration_ms: None,
|
||||
time_to_first_token_ms: None,
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
status.changed().await.expect("live status update");
|
||||
assert_eq!(
|
||||
*status.borrow(),
|
||||
AgentStatus::Completed(Some("reloaded done".to_string()))
|
||||
);
|
||||
|
||||
let communication = InterAgentCommunication::new(
|
||||
AgentPath::root(),
|
||||
|
||||
@@ -1,18 +1,25 @@
|
||||
use crate::codex_thread::CodexThread;
|
||||
use codex_protocol::AgentPath;
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::error::CodexErr;
|
||||
use codex_protocol::error::Result;
|
||||
use codex_protocol::protocol::AgentStatus;
|
||||
use codex_protocol::protocol::SessionSource;
|
||||
use codex_protocol::protocol::SubAgentSource;
|
||||
use codex_utils_string::take_bytes_at_char_boundary;
|
||||
use rand::prelude::IndexedRandom;
|
||||
use std::collections::HashMap;
|
||||
use std::collections::HashSet;
|
||||
use std::collections::hash_map::Entry;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::Weak;
|
||||
use std::sync::atomic::AtomicUsize;
|
||||
use std::sync::atomic::Ordering;
|
||||
|
||||
const COLD_STATUS_MAX_BYTES: usize = 128;
|
||||
const COLD_STATUS_TRUNCATION_MARKER: &str = "...[truncated]";
|
||||
|
||||
/// This structure is used to add some limits on the multi-agent capabilities for Codex. In
|
||||
/// the current implementation, it limits:
|
||||
/// * Total number of sub-agents (i.e. threads) per user session
|
||||
@@ -39,6 +46,62 @@ pub(crate) struct AgentMetadata {
|
||||
pub(crate) agent_nickname: Option<String>,
|
||||
pub(crate) agent_role: Option<String>,
|
||||
pub(crate) last_task_message: Option<String>,
|
||||
pub(crate) cold_status: Arc<Mutex<Option<ColdStatus>>>,
|
||||
pub(crate) generation: Arc<()>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct ColdStatus {
|
||||
status: AgentStatus,
|
||||
source: Weak<CodexThread>,
|
||||
}
|
||||
|
||||
impl AgentMetadata {
|
||||
fn cold_status(&self, live_thread: Option<&Arc<CodexThread>>) -> Option<AgentStatus> {
|
||||
let mut cold_status = self
|
||||
.cold_status
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let status = cold_status.as_ref()?;
|
||||
if let Some(live_thread) = live_thread
|
||||
&& !status
|
||||
.source
|
||||
.upgrade()
|
||||
.is_some_and(|source| Arc::ptr_eq(&source, live_thread))
|
||||
{
|
||||
*cold_status = None;
|
||||
return None;
|
||||
}
|
||||
Some(status.status.clone())
|
||||
}
|
||||
|
||||
fn install_cold_status(&self, source: &Arc<CodexThread>, status: AgentStatus) {
|
||||
let status = match status {
|
||||
AgentStatus::Completed(message) => {
|
||||
AgentStatus::Completed(message.map(bound_cold_status_text))
|
||||
}
|
||||
AgentStatus::Errored(message) => AgentStatus::Errored(bound_cold_status_text(message)),
|
||||
AgentStatus::PendingInit
|
||||
| AgentStatus::Running
|
||||
| AgentStatus::Interrupted
|
||||
| AgentStatus::Shutdown
|
||||
| AgentStatus::NotFound => return,
|
||||
};
|
||||
*self
|
||||
.cold_status
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner) = Some(ColdStatus {
|
||||
status,
|
||||
source: Arc::downgrade(source),
|
||||
});
|
||||
}
|
||||
|
||||
pub(crate) fn clear_cold_status(&self) {
|
||||
*self
|
||||
.cold_status
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner) = None;
|
||||
}
|
||||
}
|
||||
|
||||
fn format_agent_nickname(name: &str, nickname_reset_count: usize) -> String {
|
||||
@@ -194,6 +257,38 @@ impl AgentRegistry {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn cold_status(
|
||||
&self,
|
||||
thread_id: ThreadId,
|
||||
live_thread: Option<&Arc<CodexThread>>,
|
||||
) -> Option<AgentStatus> {
|
||||
self.agent_metadata_for_thread(thread_id)
|
||||
.and_then(|metadata| metadata.cold_status(live_thread))
|
||||
}
|
||||
|
||||
pub(crate) fn publish_cold_status_if_current(
|
||||
&self,
|
||||
thread_id: ThreadId,
|
||||
expected: &AgentMetadata,
|
||||
source: &Arc<CodexThread>,
|
||||
status: AgentStatus,
|
||||
) {
|
||||
let active_agents = self
|
||||
.active_agents
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let Some(metadata) = active_agents
|
||||
.agent_tree
|
||||
.values()
|
||||
.find(|metadata| metadata.agent_id == Some(thread_id))
|
||||
else {
|
||||
return;
|
||||
};
|
||||
if Arc::ptr_eq(&metadata.generation, &expected.generation) {
|
||||
metadata.install_cold_status(source, status);
|
||||
}
|
||||
}
|
||||
|
||||
fn register_spawned_thread(&self, agent_metadata: AgentMetadata) {
|
||||
let Some(thread_id) = agent_metadata.agent_id else {
|
||||
return;
|
||||
@@ -305,6 +400,16 @@ impl AgentRegistry {
|
||||
}
|
||||
}
|
||||
|
||||
fn bound_cold_status_text(message: String) -> String {
|
||||
if message.len() <= COLD_STATUS_MAX_BYTES {
|
||||
return message;
|
||||
}
|
||||
let content_max_bytes = COLD_STATUS_MAX_BYTES - COLD_STATUS_TRUNCATION_MARKER.len();
|
||||
let mut bounded = take_bytes_at_char_boundary(&message, content_max_bytes).to_string();
|
||||
bounded.push_str(COLD_STATUS_TRUNCATION_MARKER);
|
||||
bounded
|
||||
}
|
||||
|
||||
pub(crate) struct SpawnReservation {
|
||||
state: Arc<AgentRegistry>,
|
||||
active: bool,
|
||||
|
||||
@@ -14,6 +14,20 @@ fn agent_metadata(thread_id: ThreadId) -> AgentMetadata {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cold_status_text_stays_compact_when_json_escaped() {
|
||||
let control_characters = (0..=31).map(char::from).collect::<String>();
|
||||
let status = AgentStatus::Errored(bound_cold_status_text(control_characters.repeat(32)));
|
||||
|
||||
let AgentStatus::Errored(message) = &status else {
|
||||
panic!("expected errored status");
|
||||
};
|
||||
assert_eq!(message.len(), COLD_STATUS_MAX_BYTES);
|
||||
assert!(message.ends_with(COLD_STATUS_TRUNCATION_MARKER));
|
||||
assert!(message.contains('\0'));
|
||||
assert!(serde_json::to_vec(&status).expect("serialize status").len() < 1024);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn format_agent_nickname_adds_ordinals_after_reset() {
|
||||
assert_eq!(
|
||||
|
||||
@@ -1144,6 +1144,24 @@ impl ThreadManagerState {
|
||||
self.threads.write().await.remove(thread_id)
|
||||
}
|
||||
|
||||
pub(crate) async fn remove_thread_if_same(
|
||||
&self,
|
||||
thread_id: &ThreadId,
|
||||
expected: &Arc<CodexThread>,
|
||||
on_removed: impl FnOnce(),
|
||||
) -> RemoveThreadIfSameResult {
|
||||
let mut threads = self.threads.write().await;
|
||||
match threads.get(thread_id) {
|
||||
Some(thread) if Arc::ptr_eq(thread, expected) => {
|
||||
threads.remove(thread_id);
|
||||
on_removed();
|
||||
RemoveThreadIfSameResult::Removed
|
||||
}
|
||||
Some(_) => RemoveThreadIfSameResult::Replaced,
|
||||
None => RemoveThreadIfSameResult::Missing,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn effective_multi_agent_version_for_spawn(
|
||||
&self,
|
||||
initial_history: &InitialHistory,
|
||||
@@ -1674,6 +1692,12 @@ impl ThreadManagerState {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) enum RemoveThreadIfSameResult {
|
||||
Removed,
|
||||
Missing,
|
||||
Replaced,
|
||||
}
|
||||
|
||||
fn stored_thread_to_initial_history(
|
||||
stored_thread: StoredThread,
|
||||
rollout_path: Option<PathBuf>,
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
use anyhow::Result;
|
||||
use codex_features::Feature;
|
||||
use codex_protocol::error::CodexErr;
|
||||
use codex_protocol::protocol::AgentStatus;
|
||||
use core_test_support::responses::ev_assistant_message;
|
||||
use core_test_support::responses::ev_completed;
|
||||
use core_test_support::responses::ev_function_call_with_namespace;
|
||||
@@ -14,6 +16,7 @@ use std::time::Duration;
|
||||
|
||||
const FIRST_PROMPT: &str = "spawn the first worker";
|
||||
const FIRST_TASK: &str = "first worker task";
|
||||
const SECOND_PROMPT: &str = "spawn the second worker";
|
||||
const SECOND_TASK: &str = "second worker task";
|
||||
const MULTI_AGENT_V2_NAMESPACE: &str = "collaboration";
|
||||
|
||||
@@ -131,3 +134,158 @@ async fn v2_nested_spawn_checks_shared_active_execution_capacity() -> Result<()>
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn v2_evicted_completed_agent_keeps_final_status() -> Result<()> {
|
||||
let server = start_mock_server().await;
|
||||
let first_args = serde_json::to_string(&json!({
|
||||
"message": FIRST_TASK,
|
||||
"task_name": "first",
|
||||
}))?;
|
||||
mount_sse_once_match(
|
||||
&server,
|
||||
|request: &wiremock::Request| body_contains(request, FIRST_PROMPT),
|
||||
sse(vec![
|
||||
ev_response_created("first-response"),
|
||||
ev_function_call_with_namespace(
|
||||
"first-call",
|
||||
MULTI_AGENT_V2_NAMESPACE,
|
||||
"spawn_agent",
|
||||
&first_args,
|
||||
),
|
||||
ev_completed("first-response"),
|
||||
]),
|
||||
)
|
||||
.await;
|
||||
mount_sse_once_match(
|
||||
&server,
|
||||
|request: &wiremock::Request| {
|
||||
body_contains(request, FIRST_TASK) && !has_function_call_output(request, "first-call")
|
||||
},
|
||||
sse(vec![
|
||||
ev_response_created("first-worker-response"),
|
||||
ev_assistant_message("first-worker-message", "first worker done"),
|
||||
ev_completed("first-worker-response"),
|
||||
]),
|
||||
)
|
||||
.await;
|
||||
mount_sse_once_match(
|
||||
&server,
|
||||
|request: &wiremock::Request| has_function_call_output(request, "first-call"),
|
||||
sse(vec![
|
||||
ev_response_created("first-followup-response"),
|
||||
ev_assistant_message("first-followup-message", "spawned"),
|
||||
ev_completed("first-followup-response"),
|
||||
]),
|
||||
)
|
||||
.await;
|
||||
|
||||
let second_args = serde_json::to_string(&json!({
|
||||
"message": SECOND_TASK,
|
||||
"task_name": "second",
|
||||
}))?;
|
||||
mount_sse_once_match(
|
||||
&server,
|
||||
|request: &wiremock::Request| body_contains(request, SECOND_PROMPT),
|
||||
sse(vec![
|
||||
ev_response_created("second-response"),
|
||||
ev_function_call_with_namespace(
|
||||
"second-call",
|
||||
MULTI_AGENT_V2_NAMESPACE,
|
||||
"spawn_agent",
|
||||
&second_args,
|
||||
),
|
||||
ev_completed("second-response"),
|
||||
]),
|
||||
)
|
||||
.await;
|
||||
mount_sse_once_match(
|
||||
&server,
|
||||
|request: &wiremock::Request| {
|
||||
body_contains(request, SECOND_TASK) && !has_function_call_output(request, "second-call")
|
||||
},
|
||||
sse(vec![
|
||||
ev_response_created("second-worker-response"),
|
||||
ev_assistant_message("second-worker-message", "second worker done"),
|
||||
ev_completed("second-worker-response"),
|
||||
]),
|
||||
)
|
||||
.await;
|
||||
mount_sse_once_match(
|
||||
&server,
|
||||
|request: &wiremock::Request| has_function_call_output(request, "second-call"),
|
||||
sse(vec![
|
||||
ev_response_created("second-followup-response"),
|
||||
ev_function_call_with_namespace(
|
||||
"interrupt-call",
|
||||
MULTI_AGENT_V2_NAMESPACE,
|
||||
"interrupt_agent",
|
||||
&serde_json::to_string(&json!({"target": "first"}))?,
|
||||
),
|
||||
ev_completed("second-followup-response"),
|
||||
]),
|
||||
)
|
||||
.await;
|
||||
let interrupt_followup = mount_sse_once_match(
|
||||
&server,
|
||||
|request: &wiremock::Request| has_function_call_output(request, "interrupt-call"),
|
||||
sse(vec![
|
||||
ev_response_created("interrupt-followup-response"),
|
||||
ev_assistant_message("interrupt-followup-message", "done"),
|
||||
ev_completed("interrupt-followup-response"),
|
||||
]),
|
||||
)
|
||||
.await;
|
||||
|
||||
let mut builder = test_codex().with_model("koffing").with_config(|config| {
|
||||
config
|
||||
.features
|
||||
.enable(Feature::Collab)
|
||||
.expect("test config should allow feature update");
|
||||
config
|
||||
.features
|
||||
.enable(Feature::MultiAgentV2)
|
||||
.expect("test config should allow feature update");
|
||||
config.multi_agent_v2.max_concurrent_threads_per_session = 2;
|
||||
});
|
||||
let test = builder.build_with_auto_env(&server).await?;
|
||||
test.submit_turn(FIRST_PROMPT).await?;
|
||||
|
||||
let first_id = test
|
||||
.thread_manager
|
||||
.list_thread_ids()
|
||||
.await
|
||||
.into_iter()
|
||||
.find(|id| *id != test.session_configured.thread_id)
|
||||
.expect("first worker should be resident");
|
||||
let first_thread = test.thread_manager.get_thread(first_id).await?;
|
||||
tokio::time::timeout(Duration::from_secs(2), async {
|
||||
loop {
|
||||
if first_thread.agent_status().await
|
||||
== AgentStatus::Completed(Some("first worker done".to_string()))
|
||||
&& first_thread.inject_if_running(Vec::new()).await.is_err()
|
||||
{
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
})
|
||||
.await?;
|
||||
|
||||
test.submit_turn(SECOND_PROMPT).await?;
|
||||
|
||||
match test.thread_manager.get_thread(first_id).await {
|
||||
Err(CodexErr::ThreadNotFound(thread_id)) => assert_eq!(thread_id, first_id),
|
||||
Err(err) => panic!("expected evicted thread to be missing, got {err:?}"),
|
||||
Ok(_) => panic!("expected evicted thread to be missing"),
|
||||
}
|
||||
let interrupt_output = interrupt_followup
|
||||
.function_call_output_text("interrupt-call")
|
||||
.expect("interrupt_agent output should reach the model");
|
||||
assert_eq!(
|
||||
serde_json::from_str::<serde_json::Value>(&interrupt_output)?,
|
||||
json!({"previous_status": {"completed": "first worker done"}})
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user