codex icon indicating copy to clipboard operation
codex copied to clipboard

Python SDK: concurrent async turn streams can starve interrupt and close operations

Open dovvnloading opened this issue 3 weeks ago • 1 comments

What issue are you seeing?

Concurrent active Python SDK async turn streams can occupy every worker in the event loop's default ThreadPoolExecutor. Once this happens, AsyncTurnHandle.interrupt() and AsyncCodex.close() cannot run: both depend on AsyncCodexClient._call_sync(), which queues their synchronous operations on that same executor.

This is not a hung app-server or an abandoned/cancelled stream. A responsive server can receive zero turn/interrupt requests because the SDK never schedules the RPC.

Affected source: main at 4dcd8df891ad38ed7d4ea59c44b817c293ffc0e2 (also reproduced against 1885417cd45a8da5bfdeb7864a5380a7481d48f2). Platform tested: Linux x86_64, Python 3.12.14 in the original validation; a controlled local JSON-RPC subprocess (no model or credentials). Original validation: 13 simultaneous waiting streams occupied the default 13-worker pool. Before saturation, interrupt succeeded; with saturation, both interrupt and close timed out and the synthetic server received 0 interrupts; after releasing the stream workers, interrupt succeeded. A one-worker control reproduced the same scheduling failure.

What steps can reproduce the bug?

This smaller SDK-level reproducer uses the real AsyncTurnHandle/AsyncCodexClient methods but stubs the synchronous transport and the subscription to isolate executor admission. It requires only the checkout's Python SDK dependencies. Save as repro.py:

import asyncio
from concurrent.futures import ThreadPoolExecutor
from threading import Event

from openai_codex.api import AsyncTurnHandle
from openai_codex.async_client import AsyncCodexClient


class WaitingSubscription:
    def __init__(self):
        self.entered = Event()
        self.release = Event()

    def next(self):
        self.entered.set()
        self.release.wait()
        raise RuntimeError("fixture released")

    def close(self):
        self.release.set()


class SyncTransportStub:
    def __init__(self):
        self.calls = []

    def turn_interrupt(self, thread_id, turn_id):
        self.calls.append(("interrupt", thread_id, turn_id))
        return "ack"

    def close(self):
        self.calls.append(("close",))


class InitializedCodexStub:
    def __init__(self, client):
        self._client = client

    async def _ensure_initialized(self):
        pass


async def main():
    asyncio.get_running_loop().set_default_executor(
        ThreadPoolExecutor(max_workers=1)
    )
    client = AsyncCodexClient()
    transport = SyncTransportStub()
    client._sync = transport
    sub = WaitingSubscription()
    handle = AsyncTurnHandle(
        InitializedCodexStub(client), "thread-1", "turn-1", _subscription=sub
    )
    stream = handle.stream()
    reader = asyncio.create_task(anext(stream))

    try:
        for _ in range(100):
            if sub.entered.is_set():
                break
            await asyncio.sleep(0.01)
        assert sub.entered.is_set(), "stream did not enter the blocking read"

        for name, operation in [
            ("interrupt", handle.interrupt),
            ("close", client.close),
        ]:
            try:
                await asyncio.wait_for(operation(), timeout=0.2)
                raise AssertionError(name + " unexpectedly ran")
            except asyncio.TimeoutError:
                print(name + ": timed out")

        print("transport calls before releasing stream:", transport.calls)
        assert transport.calls == []

        sub.release.set()
        try:
            await reader
        except RuntimeError:
            pass
        print("interrupt after release:",
              await asyncio.wait_for(handle.interrupt(), timeout=2))
    finally:
        sub.release.set()
        await stream.aclose()
        await client.close()


asyncio.run(main())

Run from the checkout:

PYTHONPATH=sdk/python/src python3 repro.py

The one-worker executor makes the scheduling defect deterministic without needing to start a model turn. The original reproduction also exercised a real local stdio JSON-RPC child with the default executor.

What is the expected behavior?

Even if all waiting streams are idle, interrupt and close should remain schedulable. A caller's ability to stop work must not depend on another turn sending a notification or being cancelled.

Additional information

Suggested fix: asynchronously wake stream readers without assigning a blocking worker per active stream, or provide a separate reserved control path. Regression tests should fill the notification-consumer capacity, then assert that interrupt reaches the server and close settles without first sending stream events.

Related but distinct: #49671 concerns cancellation of a global notification waiter; #51542 concerns cancelling stream_text and retaining a blocked worker. Neither requires multiple active streams to saturate the shared executor. I searched existing issues/PRs for executor starvation, simultaneous async streams, and interruption and found no matching report.

Limits: This demonstrates a client-side executor starvation failure, not a native app-server deadlock, model-side failure, or a claim that the default executor is always saturated.

dovvnloading avatar Nov 10 '26 01:11 dovvnloading

Thanks to @dovvnloading for the detailed report and reproducer, and to everyone involved.

I did some additional offline validation of the reported executor-starvation mechanism. It ran locally with test doubles and a small fake JSON-RPC subprocess over stdio: no external network access, no model inference, no API key, and not the real Codex executable.

Revision tested: c6a41e32f673bf8bc57684b7ac699c11b3b14a83

What I observed (additional validation, not a claim about every setup):

  • When N blocking stream readers occupy all N workers of the event loop's default executor, turn_interrupt() and close() do not reach the transport while those workers stay occupied.
  • The tests first check that exactly N workers are inside their blocking wait right now, and no stream event is fed before the control call.
  • The main scenarios require the control call to reach the transport and finish within a 1.5 s test timeout. This is a test threshold, not a latency claim. Some scenarios use other limits (e.g. repeated close 1.8 s, real subprocess close up to 5 s), and the success checks differ slightly between scenario groups.
  • Coverage: pool sizes 1, 2, 6; varying stream counts; more readers than workers; interrupt and close separately; a second client; repeated/parallel close; cancellation; and the local subprocess (interrupt arrives, response returns, close ends the process and releases all readers).

Results on the unmodified commit: 34 test cases, of which 19 failed, 13 passed, and 2 were strict xfails documenting known limits. Two runs gave the same result. The attached test source and logs identify the individual outcomes.

Local mitigation experiment: a dedicated executor only for interrupt/close (same pattern as _TURN_START_EXECUTOR, with copy_context()). With it, the 32 non-xfail cases passed in three runs. Reverting it reproduced the same 19 failures. Two mutation checks also triggered test failures: removing copy_context() produced 4 failures, and routing close() back through the default executor produced 11 failures (one of them a strict xfail that unexpectedly passed).

The queued-call cancellation control passed both before and after the mitigation. It checks that a cancelled queued call never reaches the transport; it does not demonstrate the starvation fix.

SDK suite before adding the new validation cases: 281 passed / 2 failed / 38 skipped. With the local mitigation and the 34 added cases: 313 passed / 2 failed / 38 skipped / 2 xfailed. The same two test cases failed in both runs. Their root causes were not investigated, so I cannot establish whether the failures are unrelated.

This is a scoped mitigation for starvation caused by the default executor, not a general guarantee that interrupt or close will complete:

  • Interrupt and close share the dedicated executor's finite capacity. With enough hung interrupts, close() cannot start. The capacity is also shared by all clients in the process. These two limits are covered by the two strict xfail cases; they show the symptom, not a full root-cause proof.
  • Waiting stream readers still occupy workers of the default executor.
  • I only tested with local substitutes, not with a real Codex process.

I understand that external code contributions and pull requests are not accepted. The attached diff only documents my local experiment, together with the offline reproducer and regression tests. If the team pursues a different implementation, I can rerun the same validation suite against it.

Attached: validation_bundle_60491.txt (environment, commands, diff, raw logs and test source).

Prepared with AI assistance. Validation is documented in the attached test code, commands, and execution logs.

validation bundle 60491.txt

lucafranco1994pot-cloud avatar Nov 17 '26 17:11 lucafranco1994pot-cloud