Skip to content

MultiAgentV2 concurrent follow-up during eviction can leave a removed runtime in residency #36095

Open

Description

@dragonfly-engineer

Environment

  • Upstream commit: 61a44880a85d2fd0d8770908dea5733495e571c8
  • Feature mode: MultiAgentV2 enabled
  • Reproduction: deterministic codex-core test fixture with V2 resident capacity set to one

Summary

At the V2 residency limit, eviction can select a completed runtime, A, and remove A from the resident LRU while A is still loaded in the thread manager.

During the asynchronous eviction window, a concurrent followup_task can find A through the loaded-runtime path and touch A back into residency. The original eviction can then continue, shut down A, and successfully remove that exact runtime from the thread manager.

The thread-manager removal path does not reconcile the concurrent residency touch. Residency can therefore continue to contain A even though the thread manager no longer does. The next valid slot reservation then returns a false:

AgentLimitReached { max_threads: 1 }

That failed reservation removes the stale entry as a side effect, so an immediate retry succeeds.

This is distinct from #33777: in this reproduction, eviction does not hang. Shutdown and exact thread-manager removal complete successfully, but the concurrent residency touch survives that removal.

It is also distinct from #32353 and #34518: the target is not kept non-unloadable by pending queue-only mail. It passes the unloadability check and is removed, after which stale residency accounting causes the false capacity rejection.

Deterministic reproduction

I added a test-only one-shot synchronization point that pauses the real eviction path after the production unloadability check and before rollout materialization and shutdown.

The controlled interleaving is:

1. Completed runtime A occupies the only V2 residency slot.

2. Eviction selects A and removes it from the resident LRU.

3. Eviction passes the real unloadability check and pauses.

4. A remains present in the thread manager.

5. The real followup_task handler resolves A through the loaded-runtime path.

6. That path touches A back into V2 residency.

7. The test observes mailbox activity and TurnStarted.

8. Eviction resumes, shuts down A, and removes the exact A runtime from the
   thread manager.

9. Residency still contains A.

10. The next reservation returns AgentLimitReached.

11. An immediate retry reserves successfully.

The synchronization only controls scheduling at an existing production transition. It does not construct an otherwise unreachable state, and it does not rely on arbitrary sleeps.

Independent fixture runs create different thread UUIDs, so the result is not tied to a particular ID.

Expected behavior

After a runtime is successfully removed from the thread manager, its old lifecycle must no longer consume V2 residency capacity.

A subsequent valid reservation must not fail because of a stale residency entry for a runtime that no longer exists in the manager.

Actual behavior

Two deterministic assertions fail on the upstream implementation:

  • Manager removal succeeds, but residency remains residents = [A] with no pending slot.
  • At capacity one, the first reservation returns AgentLimitReached { max_threads: 1 }, while an immediate retry reserves successfully.

This is a false capacity failure: no loaded or legitimately resident runtime occupies the rejected slot.

Root cause

Eviction candidate selection does not retain shared ownership of the runtime's residency lifecycle.

The relevant sequence is effectively:

remove A from residency
→ asynchronously inspect, materialize, and shut down A
→ eventually remove A from the thread manager

Removing A from residency does not remove it from the thread manager. During the asynchronous gap, the manager still exposes A as loaded.

A concurrent delivery can therefore touch A back into residency while the original eviction still holds A and continues toward shutdown and removal.

The manager-removal boundary does not perform final residency reconciliation, so the reinserted entry survives after removal.

The subsequent reservation discovers and removes the stale entry, but the fixed candidate scan ends without retrying admission in the same operation. That reconciliation is therefore incorrectly surfaced as AgentLimitReached.

Proposed implementation

I have a focused implementation that addresses this specific accounting and lifecycle gap:

  • Tokenized RAII eviction claims. Selecting a candidate creates a unique in-flight claim rather than leaving its lifecycle unrepresented. The claim continues to consume capacity exactly once and is restored only while its token remains current.

  • Centralized residency reconciliation. Successful thread-manager removal synchronously and idempotently removes every matching resident occurrence and eviction claim.

  • Exact-runtime removal. Removal verifies the selected Arc<CodexThread> rather than relying only on thread ID, preventing an old eviction operation from removing a newer same-ID replacement.

  • Explicit eviction outcomes. Successful eviction and residency reconciliation both retry admission within the same reservation operation. Only a genuine lack of an unloadable candidate becomes AgentLimitReached.

  • Deterministic regression coverage. Tests cover the concurrent follow-up race, stale residency, false capacity rejection, cancellation restoration, competing removal, exact-runtime mismatch, idempotent cleanup, and claim/resident capacity accounting.

The implementation is intentionally limited to:

  • stale V2 residency after concurrent touch and removal;
  • the resulting false first-attempt capacity rejection;
  • cancellation-safe and same-ID/ABA-safe accounting in the changed path.

Locking model

The resulting lock order is:

loaded delivery:
thread-manager read lock
→ residency mutex

successful removal:
thread-manager write lock
→ residency mutex

claim and slot operations:
residency mutex only

There is no residency-to-thread-manager lock edge, and the residency mutex is not held across asynchronous shutdown or materialization work.

This also linearizes the demonstrated race:

  • If delivery obtains the manager read lock first, removal waits and subsequently reconciles the residency touch.
  • If removal obtains the manager write lock first, the later loaded-runtime lookup cannot find A and therefore cannot touch it.

Validation

Final-source validation recorded:

  • Focused race tests: 2/2 passed
  • Complete residency-module filter: 7/7 passed
  • Existing V2 follow-up completion test: 1/1 passed
  • Stress validation: 20 iterations and 40/40 race-test executions passed
  • Focused run plus stress: 42 successful executions of the two race tests
  • No recorded hang
  • Formatting and scoped Clippy checks completed successfully

The full codex-core test suite was not run, so I am not claiming full-suite validation.

Related issues

I did not find an existing public report describing this complete sequence:

eviction selects A
→ concurrent follow-up touches A
→ exact manager removal succeeds
→ stale A remains in residency
→ first reservation falsely fails
→ immediate retry succeeds

Scope and remaining risks

This implementation does not establish that:

  • A follow-up accepted after the unloadability check prevents shutdown.
  • Accepted work cannot be interrupted during shutdown.
  • Channel submission, mailbox enqueue, or TurnStarted guarantees durable processing, completion, persistence, or recovery.
  • Every timeout and unbounded cleanup path associated with MultiAgentV2 spawn_agent can hang indefinitely while evicting a terminal resident thread #33777 is addressed.
  • Unrelated ID-only shutdown or removal paths are safe.
  • Cancellation after runtime shutdown but before manager removal is fully recovered.

This issue is specifically about residency reconciliation and false capacity accounting, not proof of permanent accepted-work loss.

PR invitation request

I have a focused implementation and deterministic regression coverage ready for this stale-residency and false-capacity failure.

The reproduction, root cause, ownership boundary, locking model, cancellation behavior, and remaining scope are documented above. If this approach aligns with the intended MultiAgentV2 lifecycle design, would a maintainer be willing to invite a focused PR for review?

I will wait for explicit maintainer alignment and invitation before opening the PR.

Activity

  1. added
    bug
    CLI
    subagent
    on Jul 30, 2026
  2. deepkilo commented on Sep 22, 2026

    @deepkilo

    Additional evidence on Codex App Server 0.155.1 / MultiAgentV2: the stale-residency / false-first-rejection part of this report also appears relevant to the explicit archive/client-removal path, without requiring the concurrent follow-up interleaving described above.

    Observed environment and limits of the observation

    • Linux; the running daemon reports appServerVersion: 0.155.1 through codex app-server daemon version.
    • Configured agents.max_concurrent_threads_per_session = 3.
    • In the affected workflow, settled children were explicitly archived and unloading was confirmed as notLoaded, yet a subsequent native spawn reported collab spawn failed: agent thread limit reached. A later exact-target lookup across archived/unarchived child metadata found no created target for the rejected assignment.
    • This is not an assertion that UI “Done” alone proves free capacity. We did not capture the live process's private residency queue. The deterministic evidence below isolates the reservation failure; it does not constitute an end-to-end archive RPC reproduction or proof that every observed live rejection has this cause.

    Additional producer path in the release source

    Source examined: rust-v0.155.1, commit be2951ea34f0d295ed0becf97079f92fa5f6950e.

    1. prepare_thread_for_archive / prepare_thread_for_removal calls remove_thread_for_client, then waits for shutdown and finalizes teardown.
    2. remove_thread_for_client removes the runtime from the manager map. Neither that method nor the inspected teardown helper reconciles the parent's V2 residency queue.
    3. try_unload_one_resident removes missing-runtime entries while scanning, but can return false after freeing capacity if it did not unload a live runtime.
    4. reserve_slot turns that false into AgentLimitReached without checking the now-reconciled capacity. The next identical reservation can succeed.

    The archive/removal trigger is a source-based diagnosis; the state transition in steps 3–4 is directly reproduced below. This complements the original concurrent-touch trigger rather than claiming to reproduce that race.

    Deterministic isolated reproduction

    The script below fetches the release's production residency structs/methods verbatim, compiles them with rustc, and mocks the surrounding thread manager/runtime. Every still-loaded mock runtime is active/non-unloadable. It does not call an LLM, archive a real thread, or run the full codex-core test suite.

    Initial fixture: capacity 3, residency entries [1, 2, 3], pending slots 0, loaded runtimes [3]. The missing entries represent the post-removal state under investigation; this fixture deliberately does not test how that state was reached.

    Results with rustc 1.94.0:

    observed_false_rejection_then_success ... ok
    genuinely_full_remains_rejected ... ok
    first_reservation_should_use_capacity_freed_by_reconciliation ... FAILED
    assertion: two slots are free
    

    The first two tests characterize current behavior and the true-full control. The explicitly run, normally ignored third test asserts the desired first-attempt behavior and fails on this release. Its failure is intentional, not a passing regression claim.

    Runnable reproducer (Python 3, gh with public repository read access, rustc supporting edition 2024)

    Save as repro.py in a scratch directory and run python3 repro.py. It writes only repro.rs and the test binary beside itself; it reads the public GitHub source. The wrapper checks that the expected-behavior test exits with Rust's test-failure code.

    import base64
    import json
    from pathlib import Path
    import subprocess
    
    # Copy the production residency structs/methods verbatim; mock only their surroundings.
    response = subprocess.check_output([
        'gh', 'api', 'repos/openai/codex/contents/codex-rs/core/src/agent/control/residency.rs',
        '-X', 'GET', '-f', 'ref=rust-v0.155.1',
    ], text=True)
    source = base64.b64decode(json.loads(response)['content']).decode()
    production = source[source.index('#[derive(Default)]'):source.index('impl AgentControl {')]
    production += source[source.index('impl V2Residency {'):source.index('fn is_resident_candidate(')]
    mock = r'''
    #![allow(dead_code)]
    mod isolated {
    use std::{collections::{HashMap, VecDeque}, sync::{Arc, Mutex}, future::Future,
              task::{Context, Poll, Waker}};
    type ThreadId = u64;
    type CodexResult<T> = Result<T, CodexErr>;
    #[derive(Debug)] struct CodexErr(CodexErrorDetails);
    #[derive(Debug)] enum CodexErrorDetails { AgentLimitReached { max_threads: usize } }
    impl CodexErr { fn new(e: CodexErrorDetails) -> Self { Self(e) } }
    macro_rules! warn { ($($t:tt)*) => {}; }
    #[derive(Default)] struct ThreadManagerState { threads: Mutex<HashMap<u64, Arc<CodexThread>>> }
    impl ThreadManagerState {
        async fn get_thread(&self, id: u64) -> Result<Arc<CodexThread>, ()> {
            self.threads.lock().unwrap().get(&id).cloned().ok_or(())
        }
        async fn remove_thread(&self, id: &u64) -> Option<Arc<CodexThread>> {
            self.threads.lock().unwrap().remove(id)
        }
    }
    #[derive(Default)] struct CodexThread { session: Session }
    #[derive(Default)] struct Session { services: Services }
    #[derive(Default)] struct Services { agent_control: AgentControl }
    #[derive(Default)] struct AgentControl { state: Saved }
    #[derive(Default)] struct Saved;
    impl Saved { fn save_evicted_environments(&self, _: u64, _: ()) {} }
    impl CodexThread {
        async fn ensure_rollout_materialized(&self) {}
        async fn shutdown_and_wait(&self) -> Result<(), ()> { Ok(()) }
        async fn environment_selections(&self) {}
    }
    fn is_resident_candidate(_: &CodexThread) -> bool { true }
    // Every still-loaded mock thread is active and therefore not unloadable.
    async fn is_unloadable(_: &CodexThread) -> bool { false }
    fn run<F: Future>(future: F) -> F::Output {
        let mut future = std::pin::pin!(future);
        match future.as_mut().poll(&mut Context::from_waker(Waker::noop())) {
            Poll::Ready(value) => value,
            Poll::Pending => panic!("unexpected asynchronous wait in this isolated fixture"),
        }
    }
    '''
    tests = r'''
    fn setup(loaded: &[u64]) -> (Arc<V2Residency>, Arc<ThreadManagerState>) {
        let residency = Arc::new(V2Residency::default());
        for id in [1, 2, 3] { residency.touch(id); }
        let manager = Arc::new(ThreadManagerState::default());
        for id in loaded { manager.threads.lock().unwrap().insert(*id, Arc::new(CodexThread::default())); }
        (residency, manager)
    }
    #[test]
    fn observed_false_rejection_then_success() {
        let (r, m) = setup(&[3]); // Entries 1/2 have no loaded runtime; 3 is active.
        assert!(run(r.clone().reserve_slot(&m, 3, None)).is_err());
        assert_eq!(r.resident_count(), 1); // Rejection itself cleaned the stale entries.
        let slot = run(r.clone().reserve_slot(&m, 3, None)).expect("second call succeeds");
        drop(slot);
    }
    #[test]
    fn genuinely_full_remains_rejected() {
        let (r, m) = setup(&[1, 2, 3]);
        for _ in 0..2 { assert!(run(r.clone().reserve_slot(&m, 3, None)).is_err()); }
        assert_eq!(r.resident_count(), 3);
    }
    #[test]
    #[ignore = "expected behavior: fails on rust-v0.155.1"]
    fn first_reservation_should_use_capacity_freed_by_reconciliation() {
        let (r, m) = setup(&[3]);
        assert!(run(r.reserve_slot(&m, 3, None)).is_ok(), "two slots are free");
    }
    }
    '''
    root = Path(__file__).resolve().parent
    (root / 'repro.rs').write_text(mock + production + tests)
    subprocess.run(['rustc', '--edition=2024', '--test', str(root / 'repro.rs'), '-o', str(root / 'repro')], check=True)
    subprocess.run([str(root / 'repro')], check=True)
    expected_failure = subprocess.run([str(root / 'repro'), '--ignored'])
    assert expected_failure.returncode == 101, 'Expected-behavior regression unexpectedly passed'

    Suggested upstream acceptance criterion

    A reservation that removes stale entries and thereby creates space should retry admission within that same operation. A genuinely full set of active/protected runtimes should still fail. Successful client removal should also reconcile the owning residency state. This is aligned with the reconciliation/admission distinction in the original report; it is not a proposal to raise the limit or introduce an unbounded retry loop.

    We have only added a downstream, tightly bounded recovery for this exact version/error: confirm settled unload evidence, verify the intended child was not created, then retry the identical native spawn once. This is a workaround, not an upstream fix or proof of reliable long-running recovery. We have not validated the latest complete App Server against this scenario.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    CLIbugsubagent

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions