Skip to content

[Windows] Idle local STDIO MCP servers can exhaust Tokio blocking pool and stall the app-server #42740

Open

Description

@Bozentan

What version of Codex are you using?

Reproduced from upstream commit 042534ec1ab2f79c2997e779347d5383832ecb2e (Release 0.154.0-alpha.1). The same local-stdio implementation is still present on current main at the time of filing.

Platform

Windows 11 x64.

Summary

On Windows, every quiet local STDIO MCP client can occupy two workers in Tokio's shared blocking pool indefinitely: one pending read for child stdout and one for child stderr. Codex uses Tokio's default blocking-thread limit (512), so enough retained/per-thread MCP clients can prevent unrelated spawn_blocking work from ever starting and stall the entire app-server even though async network I/O can continue.

This is a separate low-level failure mode underneath the already reported MCP process/session multiplication issues. Explicit shutdown helps only after an owner is actually disposed; it does not make hundreds of simultaneously retained local STDIO transports safe on Windows.

Confirmed mechanism

Codex currently does the following:

  1. codex-rs/arg0/src/lib.rs::build_runtime() creates a multi-thread Tokio runtime without setting max_blocking_threads (Tokio default: 512).
  2. codex-rs/rmcp-client/src/local_child.rs starts every local MCP child with piped stdin/stdout/stderr.
  3. The rmcp transport continuously reads stdout.
  4. codex-rs/rmcp-client/src/stdio_server_launcher.rs starts a second continuous BufReader::lines() drain for stderr.
  5. Tokio 1.52.3 represents Windows ChildStdout/ChildStderr as io::blocking::Blocking<ArcFile>, so each pending read consumes a shared blocking worker.

Tokio documents the exact generic failure in tokio-rs/tokio#5777:

on Windows, reading a pipe is a blocking read and will take away a blocking thread forever

and:

spawn_blocking just hangs forever, because all your blocking threads are waiting on a pair of idle pipes (stdout and stderr of a child process, in our case)

Tokio PR tokio-rs/tokio#4824 explains why Windows child stdio was moved to the blocking pool.

Minimal deterministic reproduction

I added a Windows-only codex-rmcp-client integration test with a deliberately small blocking pool:

#[test]
fn idle_mcp_stdio_does_not_exhaust_tokio_blocking_pool() -> anyhow::Result<()> {
    let runtime = tokio::runtime::Builder::new_multi_thread()
        .worker_threads(2)
        .max_blocking_threads(8)
        .enable_all()
        .build()?;

    let sentinel_completed = runtime.block_on(async {
        let launcher = Arc::new(LocalStdioServerLauncher::new(std::env::current_dir()?));
        let mut clients = Vec::new();

        // Alternate Legacy and V20260728 transports. Each initialized server then
        // waits quietly on stdout while Codex independently drains quiet stderr.
        for index in 0..4 {
            let mode = if index % 2 == 0 {
                McpProtocolMode::Legacy
            } else {
                McpProtocolMode::V20260728
            };
            let env = (mode == McpProtocolMode::V20260728).then(|| HashMap::from([(
                OsString::from("CODEX_MCP_PROTOCOL_VERSION"),
                OsString::from("2026-07-28"),
            )]));
            let client = Arc::new(RmcpClient::new_stdio_client_with_protocol_mode(
                stdio_server_bin()?.into(), vec![], env, &[], None,
                launcher.clone(), mode,
            ).await?);
            client.initialize(init_params(), Some(Duration::from_secs(5)), no_elicitation()).await?;
            clients.push(client);
        }

        tokio::time::sleep(Duration::from_millis(250)).await;
        let sentinel = tokio::task::spawn_blocking(|| ());
        let completed = tokio::time::timeout(Duration::from_secs(1), sentinel).await.is_ok();

        // Release the pipe reads before returning so even the pre-fix runtime exits.
        for client in clients { client.shutdown().await; }
        Ok::<_, anyhow::Error>(completed)
    })?;

    assert!(sentinel_completed, "idle MCP stdio exhausted Tokio's blocking pool");
    Ok(())
}

Reproduction result

On exact upstream 042534ec1ab2:

TRY 1 FAIL [1.313s] idle_mcp_stdio_does_not_exhaust_tokio_blocking_pool
TRY 2 FAIL [1.325s] idle_mcp_stdio_does_not_exhaust_tokio_blocking_pool
idle MCP stdout/stderr reads exhausted Tokio's blocking pool

The same test also failed on a direct child of that release before changing the MCP code. There is no diff in the runtime/local-stdio files between those two revisions.

Proof-of-fix result

I prototyped a Windows-only transport replacement:

  • create three unique byte-mode named-pipe pairs per local MCP child;
  • keep parent endpoints as Tokio NamedPipeServer handles opened with FILE_FLAG_OVERLAPPED (IOCP);
  • pass synchronous client endpoints to the child as stdin/stdout/stderr;
  • retain existing Job Object containment and shutdown behavior;
  • leave Unix/macOS unchanged.

With that change, the identical test passes:

PASS [0.299s] idle_mcp_stdio_does_not_exhaust_tokio_blocking_pool

The existing local STDIO tests also pass for both legacy and modern protocol modes, including the Windows Job Object descendant-cleanup test.

Expected behavior

Idle local STDIO MCP servers must not consume the finite shared blocking pool. Long-running app-server operation should preserve capacity for unrelated blocking operations regardless of how many retained MCP sessions exist.

Actual behavior

Approximately two permanently pending blocking reads are created per quiet local STDIO MCP client. With enough retained clients, later spawn_blocking tasks queue indefinitely. At the default limit this is reachable around 256 local clients, or earlier because the pool is shared with other blocking work.

Why raising max_blocking_threads is not sufficient

Increasing the limit only moves the failure threshold, permits more OS threads, and leaves an unbounded resource relationship. Disabling stderr capture frees only one slot per server and can deadlock verbose children on a full stderr pipe.

Related Codex issues/PRs

I searched open and closed Codex issues/PRs for blocking pool, spawn_blocking, max_blocking_threads, ChildStdout, ChildStderr, and 512 threads; I did not find an existing Codex report for this specific mechanism.

Suggested fix

Use IOCP-compatible parent pipe endpoints on Windows (overlapped named pipes are one practical approach), plus retain deterministic process-tree shutdown. Independently, lazy MCP startup/shared bounded connection ownership would reduce process and memory amplification, but it should not be the only protection against exhausting a global runtime resource.

Activity

  1. added
    bug
    windows-os
    mcp
    app-server
    on Sep 4, 2026
  2. argszero commented on Sep 4, 2026

    @argszero

    This is a very well-researched report — thank you for the failing regression test and the proof-of-fix. I independently verified the mechanism against the current code and it holds:

    1. In codex-rs/arg0/src/lib.rs, build_runtime() (lines 290-295) builds a multi-thread Tokio runtime using enable_all() and thread_stack_size(...) but does NOT call max_blocking_threads(...), so Tokio uses its default of 512. Confirmed.

    2. In codex-rs/rmcp-client/src/local_child.rs (lines 23-25), every local MCP child is spawned with piped stdin/stdout/stderr.

    3. In codex-rs/rmcp-client/src/stdio_server_launcher.rs (lines 354-360), a tokio::spawn wraps stderr in BufReader::lines() and loops. On Windows, ChildStderr/ChildStdout are io::blocking::Blocking, so the pending read pins a shared blocking worker for the lifetime of the pipe.

    4. codex-rs/Cargo.lock pins tokio to 1.52.3 (confirmed), so the Windows child-stdio-on-blocking-pool behavior you reference (max_blocking_threads documentation should perhaps indicate that Tokio internally uses those too tokio-rs/tokio#5777, Fix wayland image paste error #4824) applies.

    So the two-pending-reads-per-quiet-client model is accurate: roughly two blocking workers consumed per retained local STDIO MCP server, and at the default 512 limit this becomes reachable — or can starve unrelated spawn_blocking work well before that when the pool is shared.

    On the fix, your IOCP-compatible parent pipe endpoints (overlapped named pipes with FILE_FLAG_OVERLAPPED) are the correct low-level approach: it removes the child stdio from the blocking pool entirely rather than just raising the threshold. I agree with your note that raising max_blocking_threads only moves the failure point and leaves the unbounded resource relationship in place; and that disabling stderr capture is not safe (it can deadlock verbose children on a full pipe).

    One thing worth flagging for the fix review: the change is Windows-only (cfg(windows)), so the regression test needs to remain Windows-gated too, and the existing local-stdio tests (Legacy + V20260728 protocol modes, and the Windows Job Object descendant-cleanup test you mentioned) must still pass. The deterministic shutdown-before-return in the test is a nice touch to avoid the pre-fix runtime hanging.

    This deserves maintainer attention — it is a real shared-runtime-resource exhaustion, and the report is reproducible and has a concrete fix. Happy to help review the PR or validate the cross-platform-safe guard once opened.

  3. kevinwwillis commented on Sep 27, 2026

    @kevinwwillis

    Adding a field data point that matches this exactly (Codex CLI 0.156.0, codex app-server on Windows 11, used as a long-running server for a local chat client).

    The app-server stopped answering thread/start and turn/start (reads such as thread/loaded/list kept working) twice, on two separate server processes. Each time it had 256-257 direct children: 126-128 node_repl.exe plus the same number of CUA node.exe companions, with 136-143 loaded threads.

    On a second, isolated instance we loaded sessions one at a time: with 127 helper pairs thread/start answered in 243 ms; with 128 pairs every thread/start and turn/start timed out (~30 s). 2 helpers x 2 pipes x 128 = 512, the default max_blocking_threads. Minidumps of both the stalled test instance and a stalled production process show 511-512 Tokio blocking workers waiting in NtWaitForSingleObject.

    So on Windows the practical ceiling is about 128 loaded sessions when each session starts two local STDIO MCP servers. The overlapped-pipe fix proposed here would remove it; an explicit unload (#21889) or pooled MCP processes (#20883) would also keep long-running app-servers away from it.

  4. 4Liberty commented on Oct 8, 2026

    @4Liberty

    Additional source-level reproduction and a private prototype against public commit 9b738582b:

    • A Tokio runtime with two blocking workers and four quiet child processes reproduces starvation when stdout and stderr use ordinary process pipes. A spawn_blocking sentinel times out.
    • Replacing all three parent endpoints with Tokio IOCP-backed byte-mode named pipes makes the same workload pass. The child endpoints remain synchronous file handles, preserving existing stdio server behavior.
    • The prototype connects each pair before spawning, uses unpredictable single-instance names, rejects remote pipe clients, and preserves the existing suspended Job Object assignment and fallback.
    • Pipe creation supplies a protected owner/SYSTEM DACL. A native read-back test checks the actual kernel object's access-control entries.
    • Focused native checks pass for stdin/stdout/stderr round trip, stdin EOF, and the ordinary-versus-overlapped blocking-pool comparison. The affected MCP client crate compiles.
    • All five existing native stdio protocol tests pass, covering legacy framing, modern local discovery and MRTR, modern executor behavior, and legacy elicitation fallback.

    The protocol and child-lifecycle checks are kept separate from the pool reproduction. This is a private source prototype, not a shipped desktop fix. Increasing the blocking-pool limit would only raise the saturation threshold; the underlying quiet pipe reads need to stop occupying that pool.

    No external code PR is being opened, in accordance with the repository's current contribution policy.

  5. CrispyW0nton commented on Oct 12, 2026

    @CrispyW0nton

    Additional measured Windows evidence on the newer bundled backend codex-cli 0.162.0-alpha.17.2 (Desktop package 26.1007.2314.0, internal app 26.1007.21434). The local OS probe reports Windows 10 Pro x64, 10.0.19045.

    I investigated this with Codex assistance. In an isolated diagnostic home with 270 configured minimal MCP servers, the direct-stdio case reached 567 backend threads and 516 Windows UserRequest waits. config/read timed out at 8,125 ms and configRequirements/read at 8,062 ms. Those are probe deadlines/lower bounds, not completed request latencies.

    With the diagnostic servers accessed through authenticated literal-loopback Streamable HTTP, the backend had 73 threads and four UserRequest waits; both reads completed in 16 ms. The gateway retained a separate native stdio child per session. This moved pipe-reader pressure out of the Codex backend; it did not pool native session state or eliminate process multiplication.

    Backend private memory was 130.6 MiB in the stdio sample versus 149 MiB in the HTTP sample. These are backend-only snapshots, so I am not claiming reduced total memory use.

    A separate actual-server test used 12 isolated ephemeral contexts � 21 custom MCP servers = 252 live sessions. It recorded zero transport errors, 67 backend threads, three UserRequest waits, config/read median 19.1 ms / p95 29.9 ms / max 30.4 ms, and 12 successful fixed native status reads. Owner exit left zero test sessions. No inference or native asset writes were performed. The 21 Desktop catalogs retained their original 427 tool definitions and filters.

    I also found that a companion host used the same codex-mcp-client identity. Explicit authenticated owner attribution was needed so Desktop exit did not remove the companion host's sessions. The gateway keeps DELETE/owner cleanup, bounded idle cleanup with pending-request protection, authentication and request/session limits.

    The measurements support the local transport-pressure finding in this issue. I have not established that all workspace-routing/remote-compaction errors or long-running rendered UI stalls have this cause.

    Sanitized report, test outline and result data: https://gist.github.com/CrispyW0nton/ec298528829397c5389dd49fba193578

    This is additional field evidence and a local workaround, not an upstream fix or a claim of faster model generation. The bundle does not include a turnkey harness or modified Desktop binaries.

  6. K0enna commented on Oct 17, 2026

    @K0enna

    Windows Desktop confirmation

    On Desktop 26.1013.4894.0 with bundled codex-cli 0.163.0-alpha.10.2, several open chats repeatedly led to thread/read, config/read and tool-discovery timeouts while CPU and disk activity stayed low. Restarting helped temporarily.

    One backend reached 556 OS threads, including 500 Windows UserRequest waits. These counts support resource-pressure investigation but do not identify individual pipe-reader stacks.

    Reproduction

    The adjacent public source reproduces this at the real RmcpClient/LocalStdioServerLauncher boundary:

    1. Use two async workers and an eight-worker blocking pool.
    2. Three MCP clients complete echo calls. Starting a fourth quiet child fills the pool with pending stdout/stderr reads.
    3. An unrelated spawn_blocking task misses its one-second deadline. With overlapped parent pipes, all four clients and the task complete.

    The reduced pool accelerates the failure; four clients is not the normal product limit. The default blocking-pool limit is 512.

    Retention amplifies the pressure

    A separate control against the unchanged installed backend confirmed that an inactive, successfully unsubscribed context retained its quiet MCP process for 1,800.016 seconds before both were retired. That confirms 30-minute retention, rather than a permanent leak. Attribution to individual Desktop helper contexts remains unproven.

    Scoping plugins and running tool-free reviews in isolated CLI processes reduced added MCP pressure, but shared Desktop timeouts later returned. A separate browser CDP timeout was also observed; this investigation does not attribute every stall to the stdio issue.

    Fix

    A local overlapped-pipe repair is implemented and tested. Implementation, verification and deployment limits are in a separate comment. The installed Desktop has not yet been switched to the candidate.

  7. K0enna commented on Oct 18, 2026

    @K0enna

    Local Windows fix implemented

    The local source fix replaces Windows MCP parent stdio with overlapped named pipes. Quiet stdout/stderr reads no longer occupy Tokio's shared blocking workers. Children still receive synchronous standard handles through the existing suspended-spawn and Job Object launcher.

    What changed

    • Parent pipe I/O uses Tokio/IOCP; the existing protocol parsers, frame limits, stderr handling and shutdown paths remain.
    • Pipes are first-instance, local-only and restricted to the current user. Parent handles are non-inheritable.
    • The non-Windows transport is unchanged.

    Verification

    At the real RmcpClient boundary, three clients completed echo calls before a fourth quiet child exhausted an eight-worker blocking pool. An unrelated blocking task then missed its one-second deadline. With the fix, all four clients and that task completed.

    Fifteen focused checks passed, including protocol behavior, pipe security, EOF, cancellation, failed spawn and Job Object containment. Sixteen isolated cleanup repetitions left the process handle count unchanged. A P2 review found a test-isolation issue; it was fixed without changing the production implementation.

    The complete Windows CLI builds. Its 452 exported JSON schema files match the installed backend byte-for-byte. Both binaries passed isolated initialization, config read and harmless command execution. The candidate also opened copies of the existing runtime databases without changing their schemas or migration histories.

    Deployment status and limits

    Active locally. The complete private bundle now runs in Desktop. After correcting the omitted companion executables, it passed an isolated test through the actual code host and command tool. The running app-server and code-host paths/hashes and selectors are verified; real shell execution and native chat reads pass. A bounded fresh-log check found no transport timeouts. Backups and selector rollback are retained.

    This is a local candidate based on public commit cd643519fb56011557d09b41053a3a4c0e013e1f (0.163.0-alpha.10), adjacent to installed 0.163.0-alpha.10.2. Verification used Windows and Rust 1.99 rather than the repository-pinned 1.95. Sustained multi-chat recovery, restricted sandbox behavior and other platforms remain unverified.

    No signed application file has been modified.

  8. PNWGMR commented on Oct 18, 2026

    @PNWGMR

    Two amplifiers on Desktop 26.1013.4894.0 / codex-cli 0.163.0-alpha.10.2

    I reproduced the mechanism in this issue on a private codex app-server (0.163.0-alpha.10.2, scratch CODEX_HOME, one ephemeral thread, K copies of one small stdio MCP server):

    K=200 K=300
    backend OS threads (peak) 458 558
    config/read probes (1/s) 147/147, max 0.04 s 11 answered (all sent before saturation), 136 unanswered after 140 s
    thread/loaded/list probes 147/147, max 0.004 s 147/147, max 0.008 s
    MCP startups 200 ready 260 ready, 34 failed (startup timeout)

    Two code paths make the pool fill sooner and explain why unrelated requests stall together, then flush together. I didn't see either in this thread yet:

    1. An unscoped mcpServerStatus/list cold-starts every configured server. When serverName is absent, even with a threadId, list_mcp_server_status_response calls collect_mcp_server_status_snapshot_with_detail (codex-mcp/src/mcp/mod.rs). That builds a fresh McpConnectionSet with McpStartupPolicy::Eager for all effective servers, then cancels it. Each such call temporarily adds a full extra set of stdio pipe pairs on top of the per-thread sets. On a pool that is nearly full, one status poll is enough to tip it. For example, with 1 thread and 6 concurrent unscoped calls, I counted 63 server processes: 7 copies of a 9-server set.
    2. Config loads are serialized behind a one-permit semaphore that needs spawn_blocking. refresh_application_network_policy() (app-server/src/application_network.rs) holds network_policy_reload, a Semaphore::new(1) (config_manager.rs). It holds it while reading local policy and the cloud-config cache, and the cache read uses spawn_blocking (cloud-config/src/cache.rs). Once the pool is full, the permit holder can't finish. So config/read, configRequirements/read, getAuthStatus, model/list and unscoped mcpServerStatus/list all queue behind it. On the live desktop that produced a 632 s config/read and a 465 s getAuthStatus, while 631 concurrent thread/read calls answered in under 0.2 s.

    Suggested mitigations in addition to the named-pipe fix:

    • Answer an unscoped mcpServerStatus/list that has a threadId from the thread's live connections, not from a cold start.
    • Don't hold the policy-reload permit across blocking I/O.
    • Set max_blocking_threads explicitly until stdio no longer uses the blocking pool.
  9. K0enna commented on Oct 18, 2026

    @K0enna

    Local Windows observation after the pipe repair — 18 October 2026

    The repaired backend answered every check during 125 minutes of normal-use observation (08:24–10:30 UTC), with the same process and no restart. Four scheduled checks, two extra checks and the baseline were completed.

    Measure First Peak Final
    Backend OS threads 81 93 62
    Direct helper processes 206 282 168
    Backend working set 1.90 GiB 3.25 GiB 3.00 GiB
    • 7/7 real command-tool checks passed; 24 native chat reads answered in 0.089–2.565 s.
    • No global backend stall, workspace-sync failure or code-host failure was detected. We checked 16,851 log lines across non-overlapping windows from 08:11–10:30 UTC. Existing app-discovery Auth required warnings continued and were classified separately.
    • One browser-control incident occurred: an Emulation.setFocusEmulationEnabled timeout followed by 30 frame-not-found errors. The affected chat continued command work; recovery of that specific browser operation was not verified.

    The loaded segment included seven responding chats (six active turns and one completing during the sample); a concurrent backup was reported running. Later sampled turns completed and load subsided. Two source-preparation workers also contributed workload; compilation and synthetic load were excluded during the observation.

    This is normal-use evidence, not a controlled A/B benchmark or proof of permanent recovery. Log reads were bounded; retained tails covered their requested windows. Restricted-sandbox behavior remains unverified. Connection-reuse and policy-reload follow-ups are separate drafts and have not been activated. The bounded watch is now paused.

  10. K0enna commented on Oct 18, 2026

    @K0enna

    Fix: An unfiltered mcpServerStatus/list with a threadId reuses matching live connections. Changed registrations still use current configuration.

    Measured results — Windows, 0.163.0-alpha.10 with the pipe and status-reuse patches:

    • Repeated same-thread status requests: cumulative server starts 1 → 2 → 3 → 3 before, 1 → 1 → 1 → 1 after, using the same unchanged stdio fixture.
    • 47 focused tests passed.
    • 104 passive samples over 103 minutes; 3,747 logged responses, including errors. No recurrence of the full backend stop was detected.
    • Three responses took 51.7–58.1 seconds; the maximum over the following 65 minutes was 6.657 seconds.
    • Private memory: 1.75 → 2.71 GiB, peak 2.82 GiB.

    Recommendation: retain the repair and investigate memory growth separately. The observation supports stability under this workload; it does not establish permanent recovery or a matched latency improvement.

  11. Damso74 commented on Oct 22, 2026

    @Damso74

    Additional Windows measurements on exact 0.163.0-alpha.10.2: scoped IOCP patch and later Desktop queue recurrence

    Adding a separate local qualification of the IOCP approach already described above, including an important limitation observed later. This is a locally built workaround, not an upstream release or a claim that all Desktop freezes are fixed.

    Environment: Windows Desktop 26.1013.4894.0; native CLI 0.163.0-alpha.10.2. Source base: tag rust-v0.163.0-alpha.10.2, commit 4ebc485ca321243727539187169425fcf972f2c4.

    Scoped change: keep the existing child launch/job lifecycle, but use Tokio named-pipe servers for the parent's stdin/stdout/stderr endpoints. The child's endpoints remain synchronous handles. Pipe names use random UUIDs, first-instance enforcement, remote-client rejection, and a protected DACL granting the current user and SYSTEM access. Non-Windows spawning and the MCP framing limit are preserved. The diff excludes local launcher changes and workspace-version churn; it is a candidate for review, not a complete Windows/security qualification.

    Native before/after observations — 21 October 2026 UTC

    These were separate runs, not a controlled latency benchmark. Both full-engine fixtures used 260 minimal stdio MCP servers and made no model or business/provider calls.

    Full-engine fixture Original transport Local IOCP transport
    Time 01:38 UTC 03:08 UTC
    Native thread count 558 47 after a 12-second settling interval
    Unrelated config/read Timed out at 5 seconds Three reads: 18.254 / 14.913 / 10.365 ms
    MCP initialization/catalogue Starvation reproduced 260 initializations and 260 catalogues completed

    A corrected-process stack capture unwound 54 threads without errors; the largest identical single-object wait group was 2. The original 512-waiter signature was absent in that capture. Owned fixture processes were closed after the runs.

    A separate reduced-pool probe used four blocking workers: ordinary pipes with 32 children hit the deadline, while IOCP with 260 children / 520 quiet reads allowed an unrelated blocking sentinel to finish in 45 microseconds. Echo, stdin/stdout, stderr, EOF and cleanup checks passed in the IOCP run. These child counts differ; this is a starvation probe, not a matched throughput comparison. The probe source is included below; its arguments are an absolute Python executable path, child count, and optional legacy mode.

    Bounded Desktop observation and later recurrence

    A 30-minute observation (03:14–03:44 UTC, 60 samples) recorded 55–92 native threads and no queue-rejection/routing-timeout markers in that window. Two existing-chat command exchanges also completed. This does not establish long-term stability.

    Later the same day, Desktop admission failures still occurred with the IOCP engine: between 11:32 and 12:25 UTC, logs recorded 990 queue rejections (57 queued expirations and 933 capacity refusals). Of the capacity refusals, 844 concerned mcpServer/tool/call at a 20-pending-per-ephemeral-context boundary. We did not obtain an in-freeze stack proving the original 512-waiter mechanism during this recurrence, so we cannot assign every later stall to the same cause.

    An offline scheduler reproduction, not a live fix, completed 23/100 synthetic requests with 77 rejections under a same-context burst; bounding concurrency to two completed 100/100 without rejection. No renderer/scheduler change or global queue-limit increase was activated. This suggests a separate admission-pressure path to investigate, rather than evidence that the native transport patch solves it. Ambiguous business calls should not be replayed on that basis.

    These are dated local results, not tests of current upstream main. Private paths, session/account identifiers, dumps and application data have been omitted. No production imports or provider actions were used as test fixtures.

    Scoped transport patch and reduced-pool probe, against the source commit above
    diff --git a/codex-rs/rmcp-client/src/bounded_stdio_transport.rs b/codex-rs/rmcp-client/src/bounded_stdio_transport.rs
    index fdde9f6..e6092be 100644
    --- a/codex-rs/rmcp-client/src/bounded_stdio_transport.rs
    +++ b/codex-rs/rmcp-client/src/bounded_stdio_transport.rs
    @@ -10,10 +10,10 @@ use rmcp::service::RxJsonRpcMessage;
     use rmcp::service::TxJsonRpcMessage;
     use rmcp::transport::Transport;
     use tokio::io::AsyncBufReadExt;
    +use tokio::io::AsyncRead;
    +use tokio::io::AsyncWrite;
     use tokio::io::AsyncWriteExt;
     use tokio::io::BufReader;
    -use tokio::process::ChildStdin;
    -use tokio::process::ChildStdout;
     use tokio::sync::Mutex;
     use tracing::debug;
     use tracing::warn;
    @@ -21,15 +21,19 @@ use tracing::warn;
     /// Match the existing executor stdio transport and the production MCP limit.
     pub(crate) const MAX_MCP_STDIO_LINE_BYTES: usize = 8 * 1024 * 1024;
     
    -pub(super) struct BoundedStdioTransport {
    -    stdin: Arc<Mutex<Option<ChildStdin>>>,
    -    stdout: BufReader<ChildStdout>,
    +pub(super) struct BoundedStdioTransport<W, R> {
    +    stdin: Arc<Mutex<Option<W>>>,
    +    stdout: BufReader<R>,
         pending_line: Vec<u8>,
         program_name: String,
     }
     
    -impl BoundedStdioTransport {
    -    pub(super) fn new(stdin: ChildStdin, stdout: ChildStdout, program_name: String) -> Self {
    +impl<W, R> BoundedStdioTransport<W, R>
    +where
    +    W: AsyncWrite + Unpin + Send + 'static,
    +    R: AsyncRead + Unpin + Send + 'static,
    +{
    +    pub(super) fn new(stdin: W, stdout: R, program_name: String) -> Self {
             Self {
                 stdin: Arc::new(Mutex::new(Some(stdin))),
                 stdout: BufReader::new(stdout),
    @@ -97,7 +101,11 @@ impl BoundedStdioTransport {
         }
     }
     
    -impl Transport<RoleClient> for BoundedStdioTransport {
    +impl<W, R> Transport<RoleClient> for BoundedStdioTransport<W, R>
    +where
    +    W: AsyncWrite + Unpin + Send + 'static,
    +    R: AsyncRead + Unpin + Send + 'static,
    +{
         type Error = io::Error;
     
         #[expect(
    diff --git a/codex-rs/rmcp-client/src/local_stdio_transport.rs b/codex-rs/rmcp-client/src/local_stdio_transport.rs
    index 381aad1..a5ace37 100644
    --- a/codex-rs/rmcp-client/src/local_stdio_transport.rs
    +++ b/codex-rs/rmcp-client/src/local_stdio_transport.rs
    @@ -13,9 +13,18 @@ use rmcp::service::RxJsonRpcMessage;
     use rmcp::service::TxJsonRpcMessage;
     use rmcp::transport::Transport;
     use rmcp::transport::async_rw::AsyncRwTransport;
    -use tokio::process::ChildStderr;
    -use tokio::process::ChildStdin;
    -use tokio::process::ChildStdout;
    +#[cfg(not(windows))]
    +type LocalStdin = tokio::process::ChildStdin;
    +#[cfg(not(windows))]
    +type LocalStdout = tokio::process::ChildStdout;
    +#[cfg(not(windows))]
    +pub(super) type LocalStderr = tokio::process::ChildStderr;
    +#[cfg(windows)]
    +type LocalStdin = tokio::net::windows::named_pipe::NamedPipeServer;
    +#[cfg(windows)]
    +type LocalStdout = tokio::net::windows::named_pipe::NamedPipeServer;
    +#[cfg(windows)]
    +pub(super) type LocalStderr = tokio::net::windows::named_pipe::NamedPipeServer;
     
     use crate::bounded_stdio_transport::BoundedStdioTransport;
     use crate::protocol_mode::McpProtocolMode;
    @@ -28,9 +37,9 @@ pub(super) struct LocalStdioTransport {
     
     enum StdioTransport {
         /// Preserve rmcp's existing framing for servers using the initialize handshake.
    -    Legacy(AsyncRwTransport<RoleClient, ChildStdout, ChildStdin>),
    +    Legacy(AsyncRwTransport<RoleClient, LocalStdout, LocalStdin>),
         /// Bound frames and skip messages unknown to the client during 2026-07-28 discovery.
    -    V20260728(BoundedStdioTransport),
    +    V20260728(BoundedStdioTransport<LocalStdin, LocalStdout>),
     }
     
     impl LocalStdioTransport {
    @@ -38,17 +47,26 @@ impl LocalStdioTransport {
             command: Command,
             program_name: String,
             protocol_mode: McpProtocolMode,
    -    ) -> io::Result<(Self, Option<ChildStderr>)> {
    -        let mut child = command.spawn()?;
    -        let stdin = child
    -            .stdin
    -            .take()
    -            .ok_or_else(|| io::Error::other("MCP server stdin was not piped"))?;
    -        let stdout = child
    -            .stdout
    -            .take()
    -            .ok_or_else(|| io::Error::other("MCP server stdout was not piped"))?;
    -        let stderr = child.stderr.take();
    +    ) -> io::Result<(Self, Option<LocalStderr>)> {
    +        #[cfg(windows)]
    +        let (child, stdin, stdout, stderr) = {
    +            let (child, stdin, stdout, stderr) = command.spawn_with_async_stdio()?;
    +            (child, stdin, stdout, Some(stderr))
    +        };
    +        #[cfg(not(windows))]
    +        let (child, stdin, stdout, stderr) = {
    +            let mut child = command.spawn()?;
    +            let stdin = child
    +                .stdin
    +                .take()
    +                .ok_or_else(|| io::Error::other("MCP server stdin was not piped"))?;
    +            let stdout = child
    +                .stdout
    +                .take()
    +                .ok_or_else(|| io::Error::other("MCP server stdout was not piped"))?;
    +            let stderr = child.stderr.take();
    +            (child, stdin, stdout, stderr)
    +        };
             let transport = match protocol_mode {
                 McpProtocolMode::Legacy => StdioTransport::Legacy(AsyncRwTransport::new(stdout, stdin)),
                 McpProtocolMode::V20260728 => {
    diff --git a/codex-rs/rmcp-client/src/stdio_server_launcher.rs b/codex-rs/rmcp-client/src/stdio_server_launcher.rs
    index 92ccfa2..b58d04c 100644
    --- a/codex-rs/rmcp-client/src/stdio_server_launcher.rs
    +++ b/codex-rs/rmcp-client/src/stdio_server_launcher.rs
    @@ -308,7 +308,7 @@ impl LocalStdioServerLauncher {
     
             let spawn_transport = |command: Command| -> io::Result<(
                 StdioServerTransportInner,
    -            Option<tokio::process::ChildStderr>,
    +            Option<crate::local_stdio_transport::LocalStderr>,
                 Option<u32>,
             )> {
                 let (transport, stderr) =
    diff --git a/codex-rs/utils/pty/Cargo.toml b/codex-rs/utils/pty/Cargo.toml
    index f7cabb6..4071697 100644
    --- a/codex-rs/utils/pty/Cargo.toml
    +++ b/codex-rs/utils/pty/Cargo.toml
    @@ -19,6 +19,8 @@ tempfile = { workspace = true }
     pretty_assertions = { workspace = true }
     
     [target.'cfg(windows)'.dependencies]
    +uuid = { workspace = true, features = ["v4"] }
    +windows-sys = { workspace = true, features = ["Win32_Foundation", "Win32_Security", "Win32_Security_Authorization", "Win32_System_Threading"] }
     filedescriptor = "0.8.3"
     lazy_static = { workspace = true }
     log = { workspace = true }
    diff --git a/codex-rs/utils/pty/examples/windows_async_stdio_probe.rs b/codex-rs/utils/pty/examples/windows_async_stdio_probe.rs
    new file mode 100644
    index 0000000..07843f8
    --- /dev/null
    +++ b/codex-rs/utils/pty/examples/windows_async_stdio_probe.rs
    @@ -0,0 +1,92 @@
    +#[cfg(not(windows))]
    +fn main() {}
    +
    +#[cfg(windows)]
    +fn main() -> anyhow::Result<()> {
    +    tokio::runtime::Builder::new_multi_thread()
    +        .worker_threads(2)
    +        .max_blocking_threads(4)
    +        .enable_all()
    +        .build()?
    +        .block_on(run())
    +}
    +
    +#[cfg(windows)]
    +async fn run() -> anyhow::Result<()> {
    +    use codex_utils_pty::Command;
    +    use codex_utils_pty::JobObject;
    +    use tokio::io::AsyncBufReadExt;
    +    use tokio::io::AsyncReadExt;
    +    use tokio::io::AsyncWriteExt;
    +    use tokio::io::BufReader;
    +    use std::time::Duration;
    +
    +    let python = std::env::args().nth(1).expect("absolute Python executable required");
    +    let clients: usize = std::env::args().nth(2).unwrap_or("32".into()).parse()?;
    +    let legacy = std::env::args().nth(3).as_deref() == Some("legacy");
    +    let fixture = "import sys\nprint('READY', flush=True)\nprint('READY', file=sys.stderr, flush=True)\nfor line in sys.stdin:\n print(line.rstrip(), flush=True)\n";
    +    let mut owned = Vec::new();
    +    let mut readers = Vec::new();
    +    for _ in 0..clients {
    +        let python = python.clone();
    +        let spawned = tokio::time::timeout(Duration::from_secs(10), tokio::task::spawn_blocking(move || {
    +            let job = JobObject::create_without_breakaway()?;
    +            let mut command = Command::new(python);
    +            command.args(["-u", "-c", fixture]);
    +            for key in ["SystemRoot", "TEMP", "TMP"] {
    +                if let Some(value) = std::env::var_os(key) { command.env(key, value); }
    +            }
    +            command.prepare_suspended_spawn(&job);
    +            type ReadPipe = Box<dyn tokio::io::AsyncRead + Unpin + Send>;
    +            type WritePipe = Box<dyn tokio::io::AsyncWrite + Unpin + Send>;
    +            let (child, stdin, stdout, stderr): (_, WritePipe, ReadPipe, ReadPipe) = if legacy {
    +                let mut child = command.spawn()?;
    +                let stdin = Box::new(child.stdin.take().expect("piped stdin"));
    +                let stdout = Box::new(child.stdout.take().expect("piped stdout"));
    +                let stderr = Box::new(child.stderr.take().expect("piped stderr"));
    +                (child, stdin, stdout, stderr)
    +            } else {
    +                let (child, stdin, stdout, stderr) = command.spawn_with_async_stdio()?;
    +                (child, Box::new(stdin), Box::new(stdout), Box::new(stderr))
    +            };
    +            anyhow::ensure!(job.assign_and_resume_process(child.id().expect("child id"))?, "Job containment unavailable");
    +            Ok::<_, anyhow::Error>((child, job, stdin, stdout, stderr))
    +        })).await???;
    +        let (child, job, stdin, stdout, stderr) = spawned;
    +        // Keep RAII ownership before testing any protocol step.
    +        owned.push((child, job, stdin));
    +        let mut stdout = BufReader::new(stdout);
    +        let mut stderr = BufReader::new(stderr);
    +        for reader in [&mut stdout, &mut stderr] {
    +            let mut line = String::new();
    +            tokio::time::timeout(Duration::from_secs(5), reader.read_line(&mut line)).await??;
    +            anyhow::ensure!(line.trim_end() == "READY", "stdio framing mismatch");
    +        }
    +        let stdin = &mut owned.last_mut().expect("owned child").2;
    +        stdin.write_all(b"PING\n").await?;
    +        let mut echo = String::new();
    +        tokio::time::timeout(Duration::from_secs(5), stdout.read_line(&mut echo)).await??;
    +        anyhow::ensure!(echo.trim_end() == "PING", "stdin/stdout round trip failed");
    +        readers.push(tokio::spawn(async move {
    +            let mut stdout_bytes = Vec::new();
    +            let mut stderr_bytes = Vec::new();
    +            tokio::try_join!(stdout.read_to_end(&mut stdout_bytes), stderr.read_to_end(&mut stderr_bytes))
    +        }));
    +    }
    +    // All children are now quiet with both output reads outstanding. With normal
    +    // Tokio process pipes this exhausts the four-worker blocking pool.
    +    tokio::time::sleep(Duration::from_millis(100)).await;
    +    let start = std::time::Instant::now();
    +    tokio::time::timeout(Duration::from_millis(500), tokio::task::spawn_blocking(|| 42)).await??;
    +    let pool_latency_us = start.elapsed().as_micros();
    +    for (mut child, job, stdin) in owned {
    +        drop(stdin);
    +        anyhow::ensure!(tokio::time::timeout(Duration::from_secs(5), child.wait()).await??.success(), "child failed");
    +        drop(job);
    +    }
    +    for reader in readers {
    +        tokio::time::timeout(Duration::from_secs(5), reader).await???;
    +    }
    +    println!("{{\"status\":\"PASSED\",\"clients\":{clients},\"blocking_pool_limit\":4,\"quiet_reads\":{},\"pool_latency_us\":{pool_latency_us},\"stdio_echo\":true,\"stderr\":true,\"eof_and_cleanup\":true}}", clients * 2);
    +    Ok(())
    +}
    diff --git a/codex-rs/utils/pty/src/child_command.rs b/codex-rs/utils/pty/src/child_command.rs
    index 452e3ec..7737422 100644
    --- a/codex-rs/utils/pty/src/child_command.rs
    +++ b/codex-rs/utils/pty/src/child_command.rs
    @@ -67,6 +67,8 @@ pub enum ChildStdin {
         Null,
         #[cfg(unix)]
         File(std::os::fd::OwnedFd),
    +    #[cfg(windows)]
    +    File(std::fs::File),
     }
     
     /// A local command whose complete launch contract is known to both backends.
    @@ -244,6 +246,23 @@ impl Command {
             job.prepare_suspended_spawn(&mut self.inner);
         }
     
    +    /// Spawn with IOCP parent pipes while preserving all launch and Job settings.
    +    /// Must be called from a Tokio blocking task (the local MCP launch boundary).
    +    #[cfg(windows)]
    +    pub fn spawn_with_async_stdio(mut self) -> io::Result<(
    +        Child,
    +        tokio::net::windows::named_pipe::NamedPipeServer,
    +        tokio::net::windows::named_pipe::NamedPipeServer,
    +        tokio::net::windows::named_pipe::NamedPipeServer,
    +    )> {
    +        let pipes = crate::windows_async_stdio::AsyncStdio::new()?;
    +        self.stdin = ChildStdin::File(pipes.child_stdin);
    +        self.inner.stdout(TokioStdio::from(pipes.child_stdout));
    +        self.inner.stderr(TokioStdio::from(pipes.child_stderr));
    +        let child = self.spawn()?;
    +        Ok((child, pipes.stdin, pipes.stdout, pipes.stderr))
    +    }
    +
         /// Reject original inputs that std replaced with a NUL-free placeholder.
         #[cfg(unix)]
         pub(crate) fn validate(&self) -> io::Result<()> {
    @@ -289,6 +308,8 @@ impl Command {
                 ChildStdin::Null => TokioStdio::null(),
                 #[cfg(unix)]
                 ChildStdin::File(fd) => TokioStdio::from(fd),
    +            #[cfg(windows)]
    +            ChildStdin::File(file) => TokioStdio::from(file),
             });
             #[cfg(unix)]
             {
    diff --git a/codex-rs/utils/pty/src/lib.rs b/codex-rs/utils/pty/src/lib.rs
    index c2a0629..9c6b7bd 100644
    --- a/codex-rs/utils/pty/src/lib.rs
    +++ b/codex-rs/utils/pty/src/lib.rs
    @@ -21,6 +21,8 @@ mod unix_io;
     mod win;
     #[cfg(windows)]
     mod windows_input;
    +#[cfg(windows)]
    +mod windows_async_stdio;
     
     pub const DEFAULT_OUTPUT_BYTES_CAP: usize = 1024 * 1024;
     
    diff --git a/codex-rs/utils/pty/src/windows_async_stdio.rs b/codex-rs/utils/pty/src/windows_async_stdio.rs
    new file mode 100644
    index 0000000..3122a83
    --- /dev/null
    +++ b/codex-rs/utils/pty/src/windows_async_stdio.rs
    @@ -0,0 +1,163 @@
    +//! Private byte pipes with overlapped parent ends; quiet children consume no
    +//! Tokio blocking workers. Child ends remain synchronous for ordinary stdio.
    +
    +use std::ffi::OsStr;
    +use std::fs::File;
    +use std::fs::OpenOptions;
    +use std::io;
    +use std::os::windows::ffi::OsStrExt;
    +use std::os::windows::io::AsRawHandle;
    +use std::os::windows::io::FromRawHandle;
    +use std::os::windows::io::OwnedHandle;
    +use std::ptr;
    +
    +use tokio::net::windows::named_pipe::NamedPipeServer;
    +use tokio::net::windows::named_pipe::ServerOptions;
    +use windows_sys::Win32::Foundation::LocalFree;
    +use windows_sys::Win32::Security::Authorization::ConvertSidToStringSidW;
    +use windows_sys::Win32::Security::Authorization::ConvertStringSecurityDescriptorToSecurityDescriptorW;
    +use windows_sys::Win32::Security::GetTokenInformation;
    +use windows_sys::Win32::Security::SECURITY_ATTRIBUTES;
    +use windows_sys::Win32::Security::TOKEN_QUERY;
    +use windows_sys::Win32::Security::TOKEN_USER;
    +use windows_sys::Win32::Security::TokenUser;
    +use windows_sys::Win32::System::Threading::GetCurrentProcess;
    +use windows_sys::Win32::System::Threading::OpenProcessToken;
    +
    +struct LocalAllocation(*mut core::ffi::c_void);
    +
    +impl Drop for LocalAllocation {
    +    fn drop(&mut self) {
    +        // SAFETY: these allocations are returned by the LocalAlloc-based SID APIs.
    +        unsafe {
    +            LocalFree(self.0);
    +        }
    +    }
    +}
    +
    +fn private_security_descriptor() -> io::Result<LocalAllocation> {
    +    let mut raw_token = ptr::null_mut();
    +    // SAFETY: output pointers reference initialized local variables.
    +    if unsafe { OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut raw_token) } == 0 {
    +        return Err(io::Error::last_os_error());
    +    }
    +    // SAFETY: ownership of the newly opened token transfers exactly once.
    +    let token = unsafe { OwnedHandle::from_raw_handle(raw_token) };
    +    let mut size = 0;
    +    // SAFETY: a null buffer requests the required allocation size.
    +    unsafe {
    +        GetTokenInformation(
    +            token.as_raw_handle(),
    +            TokenUser,
    +            ptr::null_mut(),
    +            0,
    +            &mut size,
    +        );
    +    }
    +    if size == 0 {
    +        return Err(io::Error::last_os_error());
    +    }
    +    // TOKEN_USER contains pointers; retain pointer alignment in the backing storage.
    +    let mut storage = vec![0usize; (size as usize).div_ceil(size_of::<usize>())];
    +    if unsafe {
    +        GetTokenInformation(
    +            token.as_raw_handle(),
    +            TokenUser,
    +            storage.as_mut_ptr().cast(),
    +            size,
    +            &mut size,
    +        )
    +    } == 0
    +    {
    +        return Err(io::Error::last_os_error());
    +    }
    +    // SAFETY: the successful query initialized a TOKEN_USER in aligned storage.
    +    let user = unsafe { &*storage.as_ptr().cast::<TOKEN_USER>() };
    +    let mut sid_text = ptr::null_mut();
    +    if unsafe { ConvertSidToStringSidW(user.User.Sid, &mut sid_text) } == 0 {
    +        return Err(io::Error::last_os_error());
    +    }
    +    let _sid_allocation = LocalAllocation(sid_text.cast());
    +    let mut len = 0;
    +    // SAFETY: the API returns a null-terminated UTF-16 SID string.
    +    while unsafe { *sid_text.add(len) } != 0 {
    +        len += 1;
    +    }
    +    let sid = String::from_utf16(unsafe { std::slice::from_raw_parts(sid_text, len) })
    +        .map_err(io::Error::other)?;
    +    // Protected DACL: current user and LocalSystem only, with no inherited ACEs.
    +    let sddl: Vec<u16> = OsStr::new(&format!("D:P(A;;GA;;;{sid})(A;;GA;;;SY)"))
    +        .encode_wide()
    +        .chain(Some(0))
    +        .collect();
    +    let mut descriptor = ptr::null_mut();
    +    if unsafe {
    +        ConvertStringSecurityDescriptorToSecurityDescriptorW(
    +            sddl.as_ptr(),
    +            1,
    +            &mut descriptor,
    +            ptr::null_mut(),
    +        )
    +    } == 0
    +    {
    +        return Err(io::Error::last_os_error());
    +    }
    +    Ok(LocalAllocation(descriptor))
    +}
    +
    +fn pair(parent_reads: bool) -> io::Result<(NamedPipeServer, File)> {
    +    let name = format!(r"\\.\pipe\codex-mcp-{}", uuid::Uuid::new_v4());
    +    let descriptor = private_security_descriptor()?;
    +    let mut attributes = SECURITY_ATTRIBUTES {
    +        nLength: size_of::<SECURITY_ATTRIBUTES>() as u32,
    +        lpSecurityDescriptor: descriptor.0,
    +        bInheritHandle: 0,
    +    };
    +    // SAFETY: the descriptor and attributes remain alive until CreateNamedPipeW returns.
    +    let server = unsafe {
    +        ServerOptions::new()
    +            .first_pipe_instance(true)
    +            .max_instances(1)
    +            .reject_remote_clients(true)
    +            .access_inbound(parent_reads)
    +            .access_outbound(!parent_reads)
    +            .create_with_security_attributes_raw(
    +                &name,
    +                (&mut attributes as *mut SECURITY_ATTRIBUTES).cast(),
    +            )?
    +    };
    +    let child = OpenOptions::new()
    +        .read(!parent_reads)
    +        .write(parent_reads)
    +        .open(&name)?;
    +    // Called only from the existing spawn_blocking launch boundary. Connecting
    +    // before spawning also means a suspended child never has to perform setup.
    +    tokio::runtime::Handle::current().block_on(server.connect())?;
    +    Ok((server, child))
    +}
    +
    +/// Parent async ends and private synchronous handles to install as child stdio.
    +pub(crate) struct AsyncStdio {
    +    pub stdin: NamedPipeServer,
    +    pub stdout: NamedPipeServer,
    +    pub stderr: NamedPipeServer,
    +    pub child_stdin: File,
    +    pub child_stdout: File,
    +    pub child_stderr: File,
    +}
    +
    +impl AsyncStdio {
    +    pub(crate) fn new() -> io::Result<Self> {
    +        let (stdin, child_stdin) = pair(false)?;
    +        let (stdout, child_stdout) = pair(true)?;
    +        let (stderr, child_stderr) = pair(true)?;
    +        Ok(Self {
    +            stdin,
    +            stdout,
    +            stderr,
    +            child_stdin,
    +            child_stdout,
    +            child_stderr,
    +        })
    +    }
    +}
  12. collab532 commented on Oct 25, 2026

    @collab532

    Current Windows Desktop recurrence and local IOCP qualification — 24–25 October 2026 UTC

    Adding current-version evidence to this existing Windows blocking-pool report rather than opening a duplicate. The user continues to experience tools appearing active while useful progress stops, across multiple chats. The observations below distinguish the native transport workaround from other unresolved Desktop/CUA failures; they do not establish one cause for every freeze.

    Environment: Windows x64, approximately 32 GB RAM; Desktop MSIX package 26.1021.3705.0; locally built CLI 0.164.0-alpha.11.1, based on public commit 6905ecede7816e91373e9eabda3f6b0368fc747b. The tests below concern a local patched binary and a compatibility-checked CODEX_CLI_PATH launcher, not an official fixed release or a test of current upstream main.

    User-visible stalls and resource use

    • Earlier stock-runtime snapshots on this Desktop/CLI generation showed 559–563 native backend OS threads, with 721–760 processes including the UI and 18.55–19.72 GiB summed private bytes in the Desktop process tree. These are separate scopes: the memory total is not the backend executable's memory alone or resident RAM, and process/thread counts alone do not prove the blocking-pool wait stacks for every occurrence.
    • A captured affected tool call on 24 October ran from 21:16:51.824Z to 21:17:21.870Z (30.046 seconds) and returned js execution timed out; kernel reset, rerun your request. Its underlying browser-operation cause was not established; this exact result was not an automatic-approval deadline error.
    • The user has repeatedly needed recovery/restarts. A responsive run after restart is not being presented as permanent recovery.

    Scoped native transport workaround

    The local Windows-only change uses overlapped named pipes / Tokio IOCP for the parent's stdin/stdout/stderr endpoints; child endpoints remain synchronous. Existing framing, process containment and shutdown behavior are retained. Pipes use unpredictable UUID names, first-instance checks, remote-client rejection, and a protected current-user/SYSTEM DACL. Non-Windows behavior is unchanged. This follows the transport approach already discussed in this issue.

    Completed tests on the current local build

    Check Observed result
    Focused Windows unit checks 3 passed
    Full native integration scenarios 4 passed
    Integration through the actual wrapper/compatibility guard 4 passed: protocol, lifecycle, owner-exit, stress
    Protocol and isolation coverage Backpressure, 1 MiB UTF-8 payload, stderr, configured timeout followed by recovery, two-project cwd/environment isolation, cold resume
    Lifecycle 10 cycles; owner-exit cleanup; owned fixture children confirmed gone
    Retained MCP stress 260 clients retained for 60.02 seconds, all initialized and answered a fixture tool
    Stress control RPC config/read 15–32 ms
    Native OS threads during stress Settled peak 63; startup transient peak 312, not 63 over the entire run
    Normal registered Desktop startup Node win32, CUA getState, and a normal managed workspace terminal echo all passed in an existing chat, without reset/retry in that final run

    The isolated integration fixtures used no model inference, production tools, credentials, or copied chat history. Wire-level MCP cancellation notification/ack was not verified; configured timeout/recovery was verified.

    An initial local rebuild could not open existing state because its embedded SQLx migration checksums differed. Converting only the 77 migration SQL inputs from LF to the matching Windows CRLF byte representation and rebuilding restored compatibility: the new executable's scratch-database migration metadata matched the existing state (61) and other exercised databases (8). Lazy history migrations were checked at source level only. No production DB, checksum metadata or history was edited. This is a local build compatibility observation, not a proposed production DB repair.

    Remaining CUA failures and attribution limits

    Before the final normal restart, two actual CUA getState attempts failed after approximately 0.92 / 0.97 seconds with:

    node_repl kernel exited unexpectedly
    kernel_status=exited(code=22)
    reason=stdout_eof
    stderr: empty
    stream_error=null
    

    One supported js_reset succeeded but the next getState still failed. A later instrumented reset/getState and the final post-restart three-tool check succeeded under the same permission settings. The two exit-22 causes remain unknown.

    There is an important local confound: Desktop's managed Node environment can re-inject CODEX_CLI_PATH pointing at the wrapper, and the wrapper has a compatibility guard. Its status-recording failure can itself produce exit 22 and mask an earlier check failure. We did not capture enough evidence to attribute either failed kernel to that guard, the sandbox launcher, or upstream CUA. A capped process sampler skipped processes; successful sampled guards exiting 0 do not explain the earlier failures. No speculative guard bypass was applied.

    After the normal restart, two short Desktop-tree samples decreased from 351 to 295 processes, 8.34 to 7.38 GiB aggregate private memory, and 56 to 52 native backend threads. These are short post-restart observations, not a matched before/after benchmark, a leak fix, or a long-duration stability result. thread_unload_delay_secs=300 was configured, but its effective runtime value was not independently observed and it is not a hard memory bound for still-subscribed chats.

    Requested upstream resolution

    1. Please confirm whether a supported signed Windows release fixes this stdio blocking-pool mechanism, or provide the upstream fix/release tracking reference.
    2. Please investigate bounded MCP process ownership and cleanup across retained chats, separately from making each transport nonblocking. Large process fleets and aggregate memory remain operational concerns.
    3. Please advise the smallest supported diagnostic capture that distinguishes CUA kernel exit 22, sandbox-helper failures, and local launcher failures, without disclosing session contents.
    4. Please provide a supported update path that survives MSIX updates without rebuilding a private engine or adjusting a private compatibility wrapper each time. Unknown package changes currently fail closed locally.

    These unsigned local builds are not a permanent distributable solution. Smart App Control had already been disabled on the host; this qualification does not demonstrate operation with it enabled. We are requesting a fix that preserves normal sandbox, approval, Windows security and application-update behavior. The final production permission context remained on-request / auto_review / workspace-write with network restricted; a permission-mode change is not claimed as the fix.

    Only sanitized technical observations are included. No raw transcripts, account/session identifiers, private paths, customer data, credentials or dumps are attached. Please split or redirect the residual CUA symptom if it belongs in a separate supported channel.

  13. BlackBadHope commented on Oct 26, 2026

    @BlackBadHope

    Windows Desktop recurrence: 543 backend threads, 253 direct children, global routing stalls

    Additional measured evidence for this existing report, collected on 26 October 2026. I am adding it here rather than opening another duplicate.

    Environment

    • Windows x64, about 32 GiB physical RAM.
    • Desktop package 26.1021.3705.0.
    • The executable path used by the Desktop backend reports codex-cli 0.164.0-alpha.11.1. Local-patch provenance has not been established, so I am not presenting this as a verified pristine upstream build.

    Observed failure

    The user reports a third episode within 24 hours in which all local chats stopped with workspace routing discovery timed out; the UI exhausted reconnect attempts through 5/5.

    Read-only OS measurements during the affected process lifetime:

    Measurement Value
    Main backend OS threads 543
    Main backend handles 4,694
    Direct child processes 253
    Direct Python children 46
    Direct Node children 72
    Direct node_repl children 85
    Direct cmd children 46
    Windows UserRequest thread waits, subsequent sample 507
    CPU, separate nearby sample 13%
    Available physical RAM, same nearby sample about 10.45 GiB

    The remaining direct children were two PowerShell processes, one console host, and one code-mode host. Other independently running CLI processes had roughly 21–27 threads. Samples are separate observations, not a synchronized performance trace.

    The native Desktop tool host still answered tools/list immediately. Requests to read/list chats did not finish within bounded 16–30 second diagnostic limits. The usage-limit API also answered and explicitly allowed ordinary usage, so subscription exhaustion did not explain this episode.

    A separate local memory integration recorded a current-head read failure before sending its provider operation. That establishes a secondary integration failure, not that the integration caused the Desktop routing error.

    Interpretation and limitations

    The approximately 543-thread plateau, 253 retained children, and mostly waiting threads strongly match the blocking-pool mechanism described in this issue. We did not capture native worker stacks, and do not claim that every child or every timeout has been individually attributed.

    A previous forced power-off was followed by loss of chat/project associations and lengthy recovery. That is an owner-reported recovery consequence; it does not prove the pool stall corrupted project state. We preserved valid global-state files and made an online SQLite backup before any further restart. Related persistence reports: #52713 and #56897.

    Related same-version symptom report: #57063.

    Recovery check, 26 October 2026

    After a normal app exit and restart, the main backend had 71 OS threads instead of 543. The installed local current-head reader returned successfully in 0.407 seconds, with its worker reaped. All pre-restart chat/project associations were retained.

    The installed CLI accepted thread_unload_delay_secs = 300 and rejected an invalid value type in an isolated configuration check. We applied the setting and added bounded process cleanup to the local Native bridge. Idle retention only applies to inactive, unsubscribed sessions; many subscribed transports can still accumulate.

    These checks establish immediate recovery. Long-term recurrence and the upstream parent-pipe fix remain open.

    Is there a released Windows parent-pipe/IOCP fix or a supported way to cap retained transports for this Desktop backend generation?

  14. WonderBug88 commented on Oct 27, 2026

    @WonderBug88

    Additional independent Windows source qualification of the IOCP approach already described here, on public tag rust-v0.164.0-alpha.11.1, commit 6905ecede7816e91373e9eabda3f6b0368fc747b:

    • The original local transport modules fail a controlled test with four quiet child processes and eight Tokio blocking workers: an unrelated spawn_blocking sentinel misses its one-second deadline. The reduced pool accelerates the mechanism; four helpers is not the normal Desktop limit.
    • The same regression passes with private overlapped parent pipes and synchronous child standard handles. A measured miniature comparison completed the repaired sentinel in 0.1655 ms while the original remained blocked at 1011.5913 ms.
    • The packaged Windows pipe suite passes 7/7, and the actual transport/process-source suite passes 10/10 (including four existing protocol-mode unit checks). Coverage includes arbitrary-byte round trip, legacy and modern framing, 1 MiB stderr draining, graceful stdin EOF, noninheritable handles, protected current-user/SYSTEM DACLs, failed-spawn handle cleanup, and suspended Job Object descendant cleanup.
    • Full cargo check -p codex-rmcp-client passes on Windows GNU with Rust 1.99.1. The complete Desktop backend executable has not been built or deployed in this qualification.

    The candidate retains the existing parser and process-containment paths and is Windows-gated. It does not raise the blocking-worker limit or suppress stderr. We have source/test evidence ready, but this does not prove this mechanism explains every historical Desktop stall. There is no proof of an Android-app or Playwright-specific cause.

    Deployment limitation: the installed Desktop package is 26.1021.3705.0. Its implemented CODEX_CLI_PATH override also opts out of app-contained-core startup and removes registered-core/package-family environment markers from the child. We have not activated it or demonstrated equivalent containment for an unsigned custom build. No signed files, security controls, credentials, conversations or production databases were modified or copied for these tests.

    Is there a supported signed release or maintainer integration path for this Windows parent-pipe repair that preserves the packaged runtime and normal updates? If a source handoff is wanted, we can provide the scoped patch and portable fake-helper regression fixtures. We will not open an unsolicited code PR or work around Windows controls.

    No raw logs, private paths, user/session identifiers, credentials, conversation contents or memory dumps are included in this comment.

  15. kltyton commented on Oct 30, 2026

    @kltyton

    A reusable Windows x64 repair package is available at https://github.com/kltyton/windows-mcp-runtime-repair, with installation instructions and a formal tool release: https://github.com/kltyton/windows-mcp-runtime-repair/releases/tag/v0.1.0.

    The source patch uses overlapped named pipes / IOCP for parent-side local MCP stdio while retaining synchronous child standard handles and process lifecycle behavior. MCP capabilities and concurrency settings are preserved. Matching backend payloads are published for 0.165.0-alpha.1.2 and 0.163.0-alpha.10.2.

    The desktop keeps its original entry. An internal version selector matches the launching application's backend, and a deployment-triggered task prepares supported updates from the runtime catalog. Helper programs and plugins come from the locally installed matching application package; Store binaries and user configuration are not redistributed.

  16. BlackBadHope commented on Oct 31, 2026

    @BlackBadHope

    Follow-up to my 26.10 measurements: a working fix for the stdio MCP thread-pool exhaustion on Windows, running locally since 27.10.

    What changed
    Windows stdio reads for MCP servers no longer occupy a Tokio blocking-pool thread. The child's stdout/stderr pipes are opened for overlapped I/O, and reads complete through IOCP. A quiet MCP server now holds only a pending overlapped read, not a worker thread, so N idle servers can no longer starve spawn_blocking.

    • utils/pty/src/windows_async_stdio.rs (new): overlapped pipe pair (unique per-process name, DACL limited to the current user's token SID), async reader/writer adapters
    • utils/pty/src/child_command.rs, lib.rs, Cargo.toml: wire the overlapped pipes into child spawn on Windows (uuid, windows-sys features)
    • rmcp-client/src/{local_stdio_transport,bounded_stdio_transport,stdio_server_launcher}.rs: use the async stdio on Windows; non-Windows paths are unchanged
    • utils/pty/examples/windows_async_stdio_probe.rs: standalone probe used for the tests below

    Base: 6905ecede7816e91373e9eabda3f6b0368fc747b (rust-v0.164.0-alpha.11.1). 8 files, +331/−25.

    Test results (Windows, isolated bench)

    Gate Result
    Blocking pool limited to 4 workers, 4 clients, 8 concurrent quiet reads PASS. Pool still responsive, 35 µs scheduling latency
    stdio echo, stderr, EOF + cleanup PASS
    Cancellation: cancel-safe read, job drop cleanup, EOF, exit code 0 PASS
    Control: original transport, same setup Hangs. Killed by watchdog at ~5.17 s (expected timeout)
    app-server protocol schema export 459 files exported, schema check passed

    Live use
    Running in Codex Desktop 26.1021.3705.0 since 27.10, using a self-built CLI from this patch and selected with CODEX_CLI_PATH. The Desktop install itself is unmodified, and unsetting the variable rolls back. An earlier build from 26.10 had a CRLF line-parsing bug on startup and was rolled back. That bug is fixed in this version.

    Limitations

    • No controlled before/after measurements on the live Desktop yet. The evidence above comes from bench gates only.
    • The patch is against alpha.11.1. Current main has changed rmcp-client heavily (local_stdio_transport.rs, stdio_server_launcher.rs, bounded_stdio_transport.rs), so it does not apply to main as-is. I don't see an IOCP/overlapped path on main yet. I'm happy to rebase it into a PR if maintainers want this approach.
    iocp-fix.patch
    diff --git a/codex-rs/rmcp-client/src/bounded_stdio_transport.rs b/codex-rs/rmcp-client/src/bounded_stdio_transport.rs
    index fdde9f6..e6092be 100644
    --- a/codex-rs/rmcp-client/src/bounded_stdio_transport.rs
    +++ b/codex-rs/rmcp-client/src/bounded_stdio_transport.rs
    @@ -10,10 +10,10 @@ use rmcp::service::RxJsonRpcMessage;
     use rmcp::service::TxJsonRpcMessage;
     use rmcp::transport::Transport;
     use tokio::io::AsyncBufReadExt;
    +use tokio::io::AsyncRead;
    +use tokio::io::AsyncWrite;
     use tokio::io::AsyncWriteExt;
     use tokio::io::BufReader;
    -use tokio::process::ChildStdin;
    -use tokio::process::ChildStdout;
     use tokio::sync::Mutex;
     use tracing::debug;
     use tracing::warn;
    @@ -21,15 +21,19 @@ use tracing::warn;
     /// Match the existing executor stdio transport and the production MCP limit.
     pub(crate) const MAX_MCP_STDIO_LINE_BYTES: usize = 8 * 1024 * 1024;
     
    -pub(super) struct BoundedStdioTransport {
    -    stdin: Arc<Mutex<Option<ChildStdin>>>,
    -    stdout: BufReader<ChildStdout>,
    +pub(super) struct BoundedStdioTransport<W, R> {
    +    stdin: Arc<Mutex<Option<W>>>,
    +    stdout: BufReader<R>,
         pending_line: Vec<u8>,
         program_name: String,
     }
     
    -impl BoundedStdioTransport {
    -    pub(super) fn new(stdin: ChildStdin, stdout: ChildStdout, program_name: String) -> Self {
    +impl<W, R> BoundedStdioTransport<W, R>
    +where
    +    W: AsyncWrite + Unpin + Send + 'static,
    +    R: AsyncRead + Unpin + Send + 'static,
    +{
    +    pub(super) fn new(stdin: W, stdout: R, program_name: String) -> Self {
             Self {
                 stdin: Arc::new(Mutex::new(Some(stdin))),
                 stdout: BufReader::new(stdout),
    @@ -97,7 +101,11 @@ impl BoundedStdioTransport {
         }
     }
     
    -impl Transport<RoleClient> for BoundedStdioTransport {
    +impl<W, R> Transport<RoleClient> for BoundedStdioTransport<W, R>
    +where
    +    W: AsyncWrite + Unpin + Send + 'static,
    +    R: AsyncRead + Unpin + Send + 'static,
    +{
         type Error = io::Error;
     
         #[expect(
    diff --git a/codex-rs/rmcp-client/src/local_stdio_transport.rs b/codex-rs/rmcp-client/src/local_stdio_transport.rs
    index 381aad1..a5ace37 100644
    --- a/codex-rs/rmcp-client/src/local_stdio_transport.rs
    +++ b/codex-rs/rmcp-client/src/local_stdio_transport.rs
    @@ -13,9 +13,18 @@ use rmcp::service::RxJsonRpcMessage;
     use rmcp::service::TxJsonRpcMessage;
     use rmcp::transport::Transport;
     use rmcp::transport::async_rw::AsyncRwTransport;
    -use tokio::process::ChildStderr;
    -use tokio::process::ChildStdin;
    -use tokio::process::ChildStdout;
    +#[cfg(not(windows))]
    +type LocalStdin = tokio::process::ChildStdin;
    +#[cfg(not(windows))]
    +type LocalStdout = tokio::process::ChildStdout;
    +#[cfg(not(windows))]
    +pub(super) type LocalStderr = tokio::process::ChildStderr;
    +#[cfg(windows)]
    +type LocalStdin = tokio::net::windows::named_pipe::NamedPipeServer;
    +#[cfg(windows)]
    +type LocalStdout = tokio::net::windows::named_pipe::NamedPipeServer;
    +#[cfg(windows)]
    +pub(super) type LocalStderr = tokio::net::windows::named_pipe::NamedPipeServer;
     
     use crate::bounded_stdio_transport::BoundedStdioTransport;
     use crate::protocol_mode::McpProtocolMode;
    @@ -28,9 +37,9 @@ pub(super) struct LocalStdioTransport {
     
     enum StdioTransport {
         /// Preserve rmcp's existing framing for servers using the initialize handshake.
    -    Legacy(AsyncRwTransport<RoleClient, ChildStdout, ChildStdin>),
    +    Legacy(AsyncRwTransport<RoleClient, LocalStdout, LocalStdin>),
         /// Bound frames and skip messages unknown to the client during 2026-07-28 discovery.
    -    V20260728(BoundedStdioTransport),
    +    V20260728(BoundedStdioTransport<LocalStdin, LocalStdout>),
     }
     
     impl LocalStdioTransport {
    @@ -38,17 +47,26 @@ impl LocalStdioTransport {
             command: Command,
             program_name: String,
             protocol_mode: McpProtocolMode,
    -    ) -> io::Result<(Self, Option<ChildStderr>)> {
    -        let mut child = command.spawn()?;
    -        let stdin = child
    -            .stdin
    -            .take()
    -            .ok_or_else(|| io::Error::other("MCP server stdin was not piped"))?;
    -        let stdout = child
    -            .stdout
    -            .take()
    -            .ok_or_else(|| io::Error::other("MCP server stdout was not piped"))?;
    -        let stderr = child.stderr.take();
    +    ) -> io::Result<(Self, Option<LocalStderr>)> {
    +        #[cfg(windows)]
    +        let (child, stdin, stdout, stderr) = {
    +            let (child, stdin, stdout, stderr) = command.spawn_with_async_stdio()?;
    +            (child, stdin, stdout, Some(stderr))
    +        };
    +        #[cfg(not(windows))]
    +        let (child, stdin, stdout, stderr) = {
    +            let mut child = command.spawn()?;
    +            let stdin = child
    +                .stdin
    +                .take()
    +                .ok_or_else(|| io::Error::other("MCP server stdin was not piped"))?;
    +            let stdout = child
    +                .stdout
    +                .take()
    +                .ok_or_else(|| io::Error::other("MCP server stdout was not piped"))?;
    +            let stderr = child.stderr.take();
    +            (child, stdin, stdout, stderr)
    +        };
             let transport = match protocol_mode {
                 McpProtocolMode::Legacy => StdioTransport::Legacy(AsyncRwTransport::new(stdout, stdin)),
                 McpProtocolMode::V20260728 => {
    diff --git a/codex-rs/rmcp-client/src/stdio_server_launcher.rs b/codex-rs/rmcp-client/src/stdio_server_launcher.rs
    index 92ccfa2..b58d04c 100644
    --- a/codex-rs/rmcp-client/src/stdio_server_launcher.rs
    +++ b/codex-rs/rmcp-client/src/stdio_server_launcher.rs
    @@ -308,7 +308,7 @@ impl LocalStdioServerLauncher {
     
             let spawn_transport = |command: Command| -> io::Result<(
                 StdioServerTransportInner,
    -            Option<tokio::process::ChildStderr>,
    +            Option<crate::local_stdio_transport::LocalStderr>,
                 Option<u32>,
             )> {
                 let (transport, stderr) =
    diff --git a/codex-rs/utils/pty/Cargo.toml b/codex-rs/utils/pty/Cargo.toml
    index f7cabb6..4071697 100644
    --- a/codex-rs/utils/pty/Cargo.toml
    +++ b/codex-rs/utils/pty/Cargo.toml
    @@ -19,6 +19,8 @@ tempfile = { workspace = true }
     pretty_assertions = { workspace = true }
     
     [target.'cfg(windows)'.dependencies]
    +uuid = { workspace = true, features = ["v4"] }
    +windows-sys = { workspace = true, features = ["Win32_Foundation", "Win32_Security", "Win32_Security_Authorization", "Win32_System_Threading"] }
     filedescriptor = "0.8.3"
     lazy_static = { workspace = true }
     log = { workspace = true }
    diff --git a/codex-rs/utils/pty/src/child_command.rs b/codex-rs/utils/pty/src/child_command.rs
    index 452e3ec..7737422 100644
    --- a/codex-rs/utils/pty/src/child_command.rs
    +++ b/codex-rs/utils/pty/src/child_command.rs
    @@ -67,6 +67,8 @@ pub enum ChildStdin {
         Null,
         #[cfg(unix)]
         File(std::os::fd::OwnedFd),
    +    #[cfg(windows)]
    +    File(std::fs::File),
     }
     
     /// A local command whose complete launch contract is known to both backends.
    @@ -244,6 +246,23 @@ impl Command {
             job.prepare_suspended_spawn(&mut self.inner);
         }
     
    +    /// Spawn with IOCP parent pipes while preserving all launch and Job settings.
    +    /// Must be called from a Tokio blocking task (the local MCP launch boundary).
    +    #[cfg(windows)]
    +    pub fn spawn_with_async_stdio(mut self) -> io::Result<(
    +        Child,
    +        tokio::net::windows::named_pipe::NamedPipeServer,
    +        tokio::net::windows::named_pipe::NamedPipeServer,
    +        tokio::net::windows::named_pipe::NamedPipeServer,
    +    )> {
    +        let pipes = crate::windows_async_stdio::AsyncStdio::new()?;
    +        self.stdin = ChildStdin::File(pipes.child_stdin);
    +        self.inner.stdout(TokioStdio::from(pipes.child_stdout));
    +        self.inner.stderr(TokioStdio::from(pipes.child_stderr));
    +        let child = self.spawn()?;
    +        Ok((child, pipes.stdin, pipes.stdout, pipes.stderr))
    +    }
    +
         /// Reject original inputs that std replaced with a NUL-free placeholder.
         #[cfg(unix)]
         pub(crate) fn validate(&self) -> io::Result<()> {
    @@ -289,6 +308,8 @@ impl Command {
                 ChildStdin::Null => TokioStdio::null(),
                 #[cfg(unix)]
                 ChildStdin::File(fd) => TokioStdio::from(fd),
    +            #[cfg(windows)]
    +            ChildStdin::File(file) => TokioStdio::from(file),
             });
             #[cfg(unix)]
             {
    diff --git a/codex-rs/utils/pty/src/lib.rs b/codex-rs/utils/pty/src/lib.rs
    index c2a0629..9c6b7bd 100644
    --- a/codex-rs/utils/pty/src/lib.rs
    +++ b/codex-rs/utils/pty/src/lib.rs
    @@ -21,6 +21,8 @@ mod unix_io;
     mod win;
     #[cfg(windows)]
     mod windows_input;
    +#[cfg(windows)]
    +mod windows_async_stdio;
     
     pub const DEFAULT_OUTPUT_BYTES_CAP: usize = 1024 * 1024;
     
    diff --git a/codex-rs/utils/pty/src/windows_async_stdio.rs b/codex-rs/utils/pty/src/windows_async_stdio.rs
    new file mode 100644
    index 0000000..3122a83
    --- /dev/null
    +++ b/codex-rs/utils/pty/src/windows_async_stdio.rs
    @@ -0,0 +1,163 @@
    +//! Private byte pipes with overlapped parent ends; quiet children consume no
    +//! Tokio blocking workers. Child ends remain synchronous for ordinary stdio.
    +
    +use std::ffi::OsStr;
    +use std::fs::File;
    +use std::fs::OpenOptions;
    +use std::io;
    +use std::os::windows::ffi::OsStrExt;
    +use std::os::windows::io::AsRawHandle;
    +use std::os::windows::io::FromRawHandle;
    +use std::os::windows::io::OwnedHandle;
    +use std::ptr;
    +
    +use tokio::net::windows::named_pipe::NamedPipeServer;
    +use tokio::net::windows::named_pipe::ServerOptions;
    +use windows_sys::Win32::Foundation::LocalFree;
    +use windows_sys::Win32::Security::Authorization::ConvertSidToStringSidW;
    +use windows_sys::Win32::Security::Authorization::ConvertStringSecurityDescriptorToSecurityDescriptorW;
    +use windows_sys::Win32::Security::GetTokenInformation;
    +use windows_sys::Win32::Security::SECURITY_ATTRIBUTES;
    +use windows_sys::Win32::Security::TOKEN_QUERY;
    +use windows_sys::Win32::Security::TOKEN_USER;
    +use windows_sys::Win32::Security::TokenUser;
    +use windows_sys::Win32::System::Threading::GetCurrentProcess;
    +use windows_sys::Win32::System::Threading::OpenProcessToken;
    +
    +struct LocalAllocation(*mut core::ffi::c_void);
    +
    +impl Drop for LocalAllocation {
    +    fn drop(&mut self) {
    +        // SAFETY: these allocations are returned by the LocalAlloc-based SID APIs.
    +        unsafe {
    +            LocalFree(self.0);
    +        }
    +    }
    +}
    +
    +fn private_security_descriptor() -> io::Result<LocalAllocation> {
    +    let mut raw_token = ptr::null_mut();
    +    // SAFETY: output pointers reference initialized local variables.
    +    if unsafe { OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut raw_token) } == 0 {
    +        return Err(io::Error::last_os_error());
    +    }
    +    // SAFETY: ownership of the newly opened token transfers exactly once.
    +    let token = unsafe { OwnedHandle::from_raw_handle(raw_token) };
    +    let mut size = 0;
    +    // SAFETY: a null buffer requests the required allocation size.
    +    unsafe {
    +        GetTokenInformation(
    +            token.as_raw_handle(),
    +            TokenUser,
    +            ptr::null_mut(),
    +            0,
    +            &mut size,
    +        );
    +    }
    +    if size == 0 {
    +        return Err(io::Error::last_os_error());
    +    }
    +    // TOKEN_USER contains pointers; retain pointer alignment in the backing storage.
    +    let mut storage = vec![0usize; (size as usize).div_ceil(size_of::<usize>())];
    +    if unsafe {
    +        GetTokenInformation(
    +            token.as_raw_handle(),
    +            TokenUser,
    +            storage.as_mut_ptr().cast(),
    +            size,
    +            &mut size,
    +        )
    +    } == 0
    +    {
    +        return Err(io::Error::last_os_error());
    +    }
    +    // SAFETY: the successful query initialized a TOKEN_USER in aligned storage.
    +    let user = unsafe { &*storage.as_ptr().cast::<TOKEN_USER>() };
    +    let mut sid_text = ptr::null_mut();
    +    if unsafe { ConvertSidToStringSidW(user.User.Sid, &mut sid_text) } == 0 {
    +        return Err(io::Error::last_os_error());
    +    }
    +    let _sid_allocation = LocalAllocation(sid_text.cast());
    +    let mut len = 0;
    +    // SAFETY: the API returns a null-terminated UTF-16 SID string.
    +    while unsafe { *sid_text.add(len) } != 0 {
    +        len += 1;
    +    }
    +    let sid = String::from_utf16(unsafe { std::slice::from_raw_parts(sid_text, len) })
    +        .map_err(io::Error::other)?;
    +    // Protected DACL: current user and LocalSystem only, with no inherited ACEs.
    +    let sddl: Vec<u16> = OsStr::new(&format!("D:P(A;;GA;;;{sid})(A;;GA;;;SY)"))
    +        .encode_wide()
    +        .chain(Some(0))
    +        .collect();
    +    let mut descriptor = ptr::null_mut();
    +    if unsafe {
    +        ConvertStringSecurityDescriptorToSecurityDescriptorW(
    +            sddl.as_ptr(),
    +            1,
    +            &mut descriptor,
    +            ptr::null_mut(),
    +        )
    +    } == 0
    +    {
    +        return Err(io::Error::last_os_error());
    +    }
    +    Ok(LocalAllocation(descriptor))
    +}
    +
    +fn pair(parent_reads: bool) -> io::Result<(NamedPipeServer, File)> {
    +    let name = format!(r"\\.\pipe\codex-mcp-{}", uuid::Uuid::new_v4());
    +    let descriptor = private_security_descriptor()?;
    +    let mut attributes = SECURITY_ATTRIBUTES {
    +        nLength: size_of::<SECURITY_ATTRIBUTES>() as u32,
    +        lpSecurityDescriptor: descriptor.0,
    +        bInheritHandle: 0,
    +    };
    +    // SAFETY: the descriptor and attributes remain alive until CreateNamedPipeW returns.
    +    let server = unsafe {
    +        ServerOptions::new()
    +            .first_pipe_instance(true)
    +            .max_instances(1)
    +            .reject_remote_clients(true)
    +            .access_inbound(parent_reads)
    +            .access_outbound(!parent_reads)
    +            .create_with_security_attributes_raw(
    +                &name,
    +                (&mut attributes as *mut SECURITY_ATTRIBUTES).cast(),
    +            )?
    +    };
    +    let child = OpenOptions::new()
    +        .read(!parent_reads)
    +        .write(parent_reads)
    +        .open(&name)?;
    +    // Called only from the existing spawn_blocking launch boundary. Connecting
    +    // before spawning also means a suspended child never has to perform setup.
    +    tokio::runtime::Handle::current().block_on(server.connect())?;
    +    Ok((server, child))
    +}
    +
    +/// Parent async ends and private synchronous handles to install as child stdio.
    +pub(crate) struct AsyncStdio {
    +    pub stdin: NamedPipeServer,
    +    pub stdout: NamedPipeServer,
    +    pub stderr: NamedPipeServer,
    +    pub child_stdin: File,
    +    pub child_stdout: File,
    +    pub child_stderr: File,
    +}
    +
    +impl AsyncStdio {
    +    pub(crate) fn new() -> io::Result<Self> {
    +        let (stdin, child_stdin) = pair(false)?;
    +        let (stdout, child_stdout) = pair(true)?;
    +        let (stderr, child_stderr) = pair(true)?;
    +        Ok(Self {
    +            stdin,
    +            stdout,
    +            stderr,
    +            child_stdin,
    +            child_stdout,
    +            child_stderr,
    +        })
    +    }
    +}
    diff --git a/codex-rs/utils/pty/examples/windows_async_stdio_probe.rs b/codex-rs/utils/pty/examples/windows_async_stdio_probe.rs
    new file mode 100644
    index 0000000..07843f8
    --- /dev/null
    +++ b/codex-rs/utils/pty/examples/windows_async_stdio_probe.rs
    @@ -0,0 +1,92 @@
    +#[cfg(not(windows))]
    +fn main() {}
    +
    +#[cfg(windows)]
    +fn main() -> anyhow::Result<()> {
    +    tokio::runtime::Builder::new_multi_thread()
    +        .worker_threads(2)
    +        .max_blocking_threads(4)
    +        .enable_all()
    +        .build()?
    +        .block_on(run())
    +}
    +
    +#[cfg(windows)]
    +async fn run() -> anyhow::Result<()> {
    +    use codex_utils_pty::Command;
    +    use codex_utils_pty::JobObject;
    +    use tokio::io::AsyncBufReadExt;
    +    use tokio::io::AsyncReadExt;
    +    use tokio::io::AsyncWriteExt;
    +    use tokio::io::BufReader;
    +    use std::time::Duration;
    +
    +    let python = std::env::args().nth(1).expect("absolute Python executable required");
    +    let clients: usize = std::env::args().nth(2).unwrap_or("32".into()).parse()?;
    +    let legacy = std::env::args().nth(3).as_deref() == Some("legacy");
    +    let fixture = "import sys\nprint('READY', flush=True)\nprint('READY', file=sys.stderr, flush=True)\nfor line in sys.stdin:\n print(line.rstrip(), flush=True)\n";
    +    let mut owned = Vec::new();
    +    let mut readers = Vec::new();
    +    for _ in 0..clients {
    +        let python = python.clone();
    +        let spawned = tokio::time::timeout(Duration::from_secs(10), tokio::task::spawn_blocking(move || {
    +            let job = JobObject::create_without_breakaway()?;
    +            let mut command = Command::new(python);
    +            command.args(["-u", "-c", fixture]);
    +            for key in ["SystemRoot", "TEMP", "TMP"] {
    +                if let Some(value) = std::env::var_os(key) { command.env(key, value); }
    +            }
    +            command.prepare_suspended_spawn(&job);
    +            type ReadPipe = Box<dyn tokio::io::AsyncRead + Unpin + Send>;
    +            type WritePipe = Box<dyn tokio::io::AsyncWrite + Unpin + Send>;
    +            let (child, stdin, stdout, stderr): (_, WritePipe, ReadPipe, ReadPipe) = if legacy {
    +                let mut child = command.spawn()?;
    +                let stdin = Box::new(child.stdin.take().expect("piped stdin"));
    +                let stdout = Box::new(child.stdout.take().expect("piped stdout"));
    +                let stderr = Box::new(child.stderr.take().expect("piped stderr"));
    +                (child, stdin, stdout, stderr)
    +            } else {
    +                let (child, stdin, stdout, stderr) = command.spawn_with_async_stdio()?;
    +                (child, Box::new(stdin), Box::new(stdout), Box::new(stderr))
    +            };
    +            anyhow::ensure!(job.assign_and_resume_process(child.id().expect("child id"))?, "Job containment unavailable");
    +            Ok::<_, anyhow::Error>((child, job, stdin, stdout, stderr))
    +        })).await???;
    +        let (child, job, stdin, stdout, stderr) = spawned;
    +        // Keep RAII ownership before testing any protocol step.
    +        owned.push((child, job, stdin));
    +        let mut stdout = BufReader::new(stdout);
    +        let mut stderr = BufReader::new(stderr);
    +        for reader in [&mut stdout, &mut stderr] {
    +            let mut line = String::new();
    +            tokio::time::timeout(Duration::from_secs(5), reader.read_line(&mut line)).await??;
    +            anyhow::ensure!(line.trim_end() == "READY", "stdio framing mismatch");
    +        }
    +        let stdin = &mut owned.last_mut().expect("owned child").2;
    +        stdin.write_all(b"PING\n").await?;
    +        let mut echo = String::new();
    +        tokio::time::timeout(Duration::from_secs(5), stdout.read_line(&mut echo)).await??;
    +        anyhow::ensure!(echo.trim_end() == "PING", "stdin/stdout round trip failed");
    +        readers.push(tokio::spawn(async move {
    +            let mut stdout_bytes = Vec::new();
    +            let mut stderr_bytes = Vec::new();
    +            tokio::try_join!(stdout.read_to_end(&mut stdout_bytes), stderr.read_to_end(&mut stderr_bytes))
    +        }));
    +    }
    +    // All children are now quiet with both output reads outstanding. With normal
    +    // Tokio process pipes this exhausts the four-worker blocking pool.
    +    tokio::time::sleep(Duration::from_millis(100)).await;
    +    let start = std::time::Instant::now();
    +    tokio::time::timeout(Duration::from_millis(500), tokio::task::spawn_blocking(|| 42)).await??;
    +    let pool_latency_us = start.elapsed().as_micros();
    +    for (mut child, job, stdin) in owned {
    +        drop(stdin);
    +        anyhow::ensure!(tokio::time::timeout(Duration::from_secs(5), child.wait()).await??.success(), "child failed");
    +        drop(job);
    +    }
    +    for reader in readers {
    +        tokio::time::timeout(Duration::from_secs(5), reader).await???;
    +    }
    +    println!("{{\"status\":\"PASSED\",\"clients\":{clients},\"blocking_pool_limit\":4,\"quiet_reads\":{},\"pool_latency_us\":{pool_latency_us},\"stdio_echo\":true,\"stderr\":true,\"eof_and_cleanup\":true}}", clients * 2);
    +    Ok(())
    +}
    
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

    app-serverbugmcpperformancewindows-os

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions