Prevent V2 agent eviction from racing with queued messages (#47240)

## Why

Accepted inter-agent messages can still be waiting in the submission queue when a worker appears idle. Evicting that worker can lose the queued work, while cancelling an eviction caller can leave shutdown unfinished and allow delivery to a closing runtime.

## What changed

- Pin V2 recipients until queued submissions are handled or dropped, and verify that delivery targets the registered runtime.
- Move `Submission` into core so it can carry the residency guard through queue handoffs.
- Give eviction exclusive access to each runtime and keep it counted against capacity until removal. Run teardown in a separate task so it completes even if its caller is cancelled, and remove registry and residency entries together.

## Testing

Add a regression test covering queued follow-up delivery, eviction refusal while mail is pending, cancelled eviction completing teardown, rejection of late delivery, and capacity reuse after removal.

GitOrigin-RevId: d6de3d68cb6b911942e9ddfc05c65b3741b796b2
This commit is contained in:
jif
2026-09-22 09:50:48 +00:00
committed by copyberry
parent b58b05e062
commit acc20df49f
15 changed files with 404 additions and 90 deletions
+19 -2
View File
@@ -395,7 +395,8 @@ pub(crate) struct ResumeThreadWithHistoryOptions {
/// `Arc` reference that can be downgraded to by `LocalAgentControl` while preventing every single
/// function to require an `Arc<&Self>`.
pub(crate) struct ThreadManagerState {
threads: Arc<RwLock<HashMap<ThreadId, Arc<CodexThread>>>>,
// Eviction updates this registry and residency together, locking the registry first.
pub(crate) threads: Arc<RwLock<HashMap<ThreadId, Arc<CodexThread>>>>,
shared_thread_instructions: shared_instructions::SharedThreadInstructionsProviders,
thread_created_tx: broadcast::Sender<ThreadId>,
thread_id_generator: ThreadIdGenerator,
@@ -1690,6 +1691,16 @@ impl ThreadManagerState {
root_turn_id: Option<String>,
) -> CodexResult<String> {
let thread = self.get_thread(thread_id).await?;
let residency_guard = if matches!(op, Op::InterAgentCommunication { .. }) {
thread
.session
.services
.agent_control
.pin_v2_residency(self, &thread)
.await?
} else {
None
};
if let Some(ops_log) = &self.ops_log
&& let Ok(mut log) = ops_log.lock()
&& let Some(captured_op) = capture_test_op(&op)
@@ -1698,7 +1709,13 @@ impl ThreadManagerState {
}
thread
.io
.submit_with_trace(op, /*trace*/ None, parent_turn_id, root_turn_id)
.submit_with_trace(
op,
/*trace*/ None,
parent_turn_id,
root_turn_id,
residency_guard,
)
.await
}