Skip to content

Windows sandbox: setup payload passed on the command line exceeds the CreateProcess limit (os error 206) #38985

Open

Description

@ArsAsier

Environment

  • Windows 11
  • Codex Desktop app 26.810.7004.0 (helper: app\resources\codex-windows-sandbox-setup.exe); sandbox bin: codex-command-runner-0.148.0-alpha.9.exe, codex.exe
  • sandbox_mode = "workspace-write", [windows] sandbox = "elevated", LongPathsEnabled = 1

Symptom

Every command executed through the Windows sandbox fails before it even runs:

[codex.exe] setup refresh: spawning ...\\codex-windows-sandbox-setup.exe (cwd=..., payload_len=35044)
[codex.exe] setup refresh: setup refresh failed to launch helper: helper=...\\codex-windows-sandbox-setup.exe, ...
error=The filename or extension is too long. (os error 206)

This is ERROR_FILENAME_EXCED_RANGE returned by CreateProcess: the assembled command line
(helper path + cwd + embedded payload) exceeds Windows' 32,767-character limit.

Repro

  1. Place ~700 loose files directly in the user profile (e.g. C:\Users<user>*.sh).
  2. Run any command through the Windows sandbox (default, non-escalated path).
  3. The sandbox "setup refresh" step spawns codex-windows-sandbox-setup.exe with a payload
    whose size grows roughly linearly with the top-level item count of the user profile.
    Observed in %USERPROFILE%.codex.sandbox\sandbox.YYYY-MM-DD.log:
    • ~150 top-level items -> payload_len=15108, helper completes normally
    • ~500 top-level items -> still fine
    • ~700 top-level items -> payload_len=35044, CreateProcess fails with 206;
      EVERY sandboxed command fails from then on.
  4. Escalated (non-sandboxed) commands bypass the helper and keep working,
    which makes the failure mode hard to diagnose.

Boundary (useful data point)

The threshold lies between 500 and 700 top-level profile items. After moving ~200 items
into a subfolder (697 -> 498 top-level entries) the sandbox recovered immediately on the
next command, no restart required.

Suggested fixes

  • Pass the setup payload to the helper via a temp file or a pipe instead of the command line.
  • Or keep the embedded profile-item list bounded (only roots that actually exist, or a
    digest instead of the full flat list).

Logs

%USERPROFILE%.codex.sandbox\sandbox.YYYY-MM-DD.log

Activity

  1. added
    bug
    app
    windows-os
    sandbox
    on Aug 17, 2026
  2. jdcodes1 commented on Aug 17, 2026

    @jdcodes1

    Verified against main @ 1f41cc5 — your diagnosis is exactly right, and the code shows both why the payload is unbounded and why it ended up on the command line in the first place.

    The two halves of the mechanism:

    1. Unbounded payload: the deny-read configuration is expanded into a flat enumerated list of every matching filesystem path — collect_existing_glob_matches recursively walks the scan roots and pushes each concrete match:

      fn collect_existing_glob_matches(
      path: &Path,
      matcher: &ReadDenyMatcher,
      paths: &mut Vec<AbsolutePathBuf>,
      seen_paths: &mut HashSet<PathBuf>,
      seen_scan_dirs: &mut HashSet<PathBuf>,
      max_depth: Option<usize>,
      depth: usize,
      ) -> Result<(), String> {
      if !path.exists() {
      return Ok(());
      }
      if matcher.is_read_denied(path) {
      push_absolute_path(paths, seen_paths, path.to_path_buf())?;
      }
      let Ok(metadata) = path.metadata() else {
      return Ok(());
      };
      if !metadata.is_dir() {
      return Ok(());
      }
      // Canonical directory keys keep recursive scans from following a symlink or
      // junction cycle forever while preserving the original matched path for the
      // ACL layer.
      let scan_key = dunce::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
      if !seen_scan_dirs.insert(scan_key) {
      return Ok(());
      }
      if max_depth.is_some_and(|max_depth| depth >= max_depth) {
      return Ok(());
      }
      let Ok(entries) = std::fs::read_dir(path) else {
      return Ok(());
      };
      for entry in entries.flatten() {
      collect_existing_glob_matches(
      &entry.path(),
      matcher,
      paths,
      seen_paths,
      seen_scan_dirs,
      max_depth,
      depth + 1,
      )?;
      }
      Ok(())
      }

      With deny globs anchored at the user profile, the list scales with your top-level item count — your ~50-bytes-per-item slope (15,108 chars at ~150 items → 35,044 at ~700) is just path length × base64 overhead.

    2. Payload on argv: the refresh path serializes the whole SetupPayload to JSON, base64-encodes it, and passes it as a single argument to the helper:

      let json = serde_json::to_vec(&payload)?;
      let b64 = BASE64_STANDARD.encode(json);
      run_setup_singleflight(b64.clone(), || {
      run_setup_refresh_payload(&b64, request.codex_home)
      })
      }
      fn run_setup_refresh_payload(b64: &str, codex_home: &Path) -> Result<()> {
      let exe = find_setup_exe();
      let sbx_dir = sandbox_dir(codex_home);
      let log_path = current_log_file_path(&sbx_dir);
      let cleared_report = match clear_setup_error_report(codex_home) {
      Ok(()) => true,
      Err(err) => {
      log_note(
      &format!("setup refresh: failed to clear setup_error.json before launch: {err}"),
      Some(&sbx_dir),
      );
      false
      }
      };
      // Refresh should never request elevation; ensure verb isn't set and we don't trigger UAC.
      let mut cmd = Command::new(&exe);
      cmd.arg(b64)
      .stdin(Stdio::null())
      .stdout(Stdio::null())

      Base64 inflates by 4/3, so the effective JSON budget under the 32,767-char CreateProcess limit is only ~24 KB — a ceiling any large profile can hit, as you demonstrated.

    Why argv was chosen (and why the fix is still easy): the initial setup path launches the helper via ShellExecuteExW for UAC elevation (setup.rs#L916+), and ShellExecute can only pass parameters through the command line — no stdin piping. That constraint got inherited by the refresh path, but the refresh explicitly never elevates (the comment at #L373 says so) and spawns via plain Command — so it can switch to a piped stdin write with a very small diff, no temp-file lifetime questions. For the elevated initial path, a temp file whose path is the argv (with the payload’s ACL restricted to the invoking user) fits within limits regardless of profile size.

    One more fix worth taking regardless of transport: expanding globs on the orchestrator side and shipping the concrete path list also bakes in a TOCTOU gap — the profile contents can change between enumeration and the helper applying ACLs. Passing the patterns + scan roots and letting the helper expand them in-process both bounds the payload (it becomes O(config), not O(filesystem)) and closes that drift. Your observed recovery-by-reorganizing (697 → 498 items) works precisely because the payload is O(filesystem) today.

    Cheap guard for the interim: the spawn site already logs payload_len; a pre-flight check (b64.len() > ~30_000 → fail with "sandbox setup payload exceeds the Windows command-line limit; N deny-list entries — see ") would at least convert the opaque os error 206 into an actionable message, given your point that escalated commands silently bypass the helper and mask the failure.

    Regression test shape: construct a payload with ~1,000 synthetic deny paths and assert the chosen transport delivers it (stdin/temp-file round-trip), plus a unit assert that refresh-payload size is independent of the number of concrete glob matches once patterns-not-paths lands.

  3. LittleBitPlanet commented on Aug 28, 2026

    @LittleBitPlanet

    Additional datapoint from a different trigger path, same error class, on CLI 0.150.1 and 0.151.0-alpha.6 (npm install, Windows 11 26200, [windows] sandbox = "elevated"):

    Session INIT (not per-command execution) fails deterministically on write-capable profiles with failed to load AGENTS.md instructions for environment 'local': The filename or extension is too long. (os error 206), before the TUI ever appears. Read-only profiles on the same home are fine.

    Two observations that may help narrow the payload contributor:

    1. The user profile root here has only 169 top-level items, far below the ~500-700 boundary in the report above, so the flat profile-item list cannot be the whole payload. This CODEX_HOME is long-established (since March) and its cap_sid has accumulated 90 per-cwd/per-root sandbox SIDs (8,938 bytes); the sandbox log shows setup refresh: spawning codex-windows-sandbox-setup.exe (payload_len=9208) cycles completing, so the spawn that dies with 206 appears to be a later, unlogged helper invocation with a larger assembled command line.
    2. A byte-identical robocopy clone of the same CODEX_HOME under a different path starts fine, but only because the clone silently runs a reduced sandbox flow (its .sandbox-bin never receives a command-runner), which masks the failure and makes fresh-home repro attempts misleading.

    Resetting the accumulated state (cap_sid pruned to 6 live entries, .sandbox renamed aside, both together) did NOT clear it here, so the payload contributor is something else that survives a state reset. Filed the startup-walk hang that was masking this as #41257; happy to provide full logs from this machine if useful.

  4. BreBryBro commented on Sep 11, 2026

    @BreBryBro

    Additional measurements from a Windows 11 workstation running codex-cli 0.153.2 (source pin 657a993) with the elevated sandbox, in case they help size the fix. Nothing below identifies the machine; lengths and counts only.

    Where the length goes. run_setup_refresh_payload (codex-rs/windows-sandbox-rs/src/setup.rs:359-392 at the pin; unchanged on current main at :378) builds the ElevationPayload, serialises it to JSON, base64-encodes it, and passes the whole string as ONE argv element to the setup helper, which reads it back with args.remove(1) (bin/setup_main/win.rs:440-447, :496 on main). CreateProcessW caps the command line at 32,767 UTF-16 units including the terminator, so a lower bound on the command line is len(helper exe path) + 1 + payload_len + 1 (quoting can add a few more characters, so the totals below are lower bounds, not exact lengths).

    Measured on this host:

    quantity value
    helper exe path length 181 chars
    failing spawn, payload_len= in the sandbox log 32,604 (total >= 32,787 > 32,767)
    passing spawn immediately after 32,548 (total >= 32,731)
    steady state at the primary cwd (136 consecutive spawns) 32,380 (total >= 32,563; at most ~204 chars of headroom)
    other values seen the same day 32,436 / 32,460 / 32,516

    So a nested cwd two or three directories below the workspace root is enough to cross the line, which matches the reporter's symptom exactly.

    What fills the payload. profile_read_roots (setup.rs:531-548) is read_dir(%USERPROFILE%) minus 12 fixed exclusions (:56-69), pulled in through gather_full_read_roots_for_permissions (:556-585) whenever has_symbolic_root_read_access (:593) holds. On this host the profile root has ~348 top-level entries (109 directories, 229 files, 10 other), and those names alone account for roughly 26K of the 32,380 bytes. Most of them are small per-process state files written by unrelated tooling; moving them into one subdirectory recovers about 20K of headroom, which is consistent with the recovery described in the original report.

    Suggestion. A bounded, permission-restricted temp file (its path as the single argv element) or a stdin/pipe transport avoids the command-line limit entirely; the file ACL and cleanup would need the same care the current payload gets. Separately, profile_read_roots lists every entry it is NOT excluding; emitting the profile directory once and enumerating only the exclusions would shrink the payload, but only if it is proven to grant exactly the same read set as today (no widening), so I am noting it as a direction rather than recommending it as a drop-in.

    Cross-reference: #32315 (same mechanism, earlier report) and #41809 (deny-read glob expansion, same ceiling). Happy to run a patched build against this host's profile if that would help.

  5. zhengui0211-dot commented on Sep 13, 2026

    @zhengui0211-dot

    Adding a Windows desktop reproduction of the same helper-launch error.

    Environment

    • Windows x64.
    • Codex desktop package version visible in a recent screenshot: 26.908.4834.0.
    • Exact Windows build and bundled CLI version have not been independently verified in this report.

    Observed failure
    A minimal default-sandbox, read-only command such as Get-Location fails before the requested shell command starts. Sanitized error:

    orchestrator_helper_launch_failed:
    setup refresh failed to launch helper:
    helper=codex-windows-sandbox-setup.exe
    error=The filename or extension is too long. (os error 206)
    

    Computer Use runtime initialization and browser-control initialization also returned the same helper-launch error before those runtimes initialized.

    Fully reopening the desktop app and trying a separate new task were previously attempted; the default-sandbox failure persisted. This report establishes the matching error and pre-command failure, not the underlying payload contributor on this machine.

    Separate diagnostic limitation
    The normal approval flow has also been unreliable: some static read-only file checks succeeded, but later read-only checks and codex doctor --help failed during automatic approval review with:

    Automatic approval review failed:
    stream disconnected before completion
    

    These attempts returned an approval-stage error rather than command output. It is not established whether this approval-stream failure and the sandbox error share a cause; it currently limits further diagnostics.

    Expected / requested
    Read-only commands should initialize through the configured sandbox and normal approval flow. Please advise whether a released desktop fix addresses this helper-launch failure, or provide supported non-destructive diagnostics that do not require weakening sandbox/approval protections, deleting user state, or changing existing network settings.

    No raw logs, screenshots, account identifiers, credentials, local paths, or project data are attached.

  6. stanpoet commented on Sep 21, 2026

    @stanpoet

    Confirming on codex-cli 0.155.1, Windows 11 Pro 10.0.26220, [windows] sandbox = "elevated". Every helper launch failed from the moment the sandbox was provisioned (no successful launch in two days of logs), in every cwd, not only the profile root.

    Token-free repro: codex sandbox cmd /c "echo ok", then read payload_len= in CODEX_HOME/.sandbox/sandbox.<date>.log.

    What the payload scales with: the top-level entries of the user profile folder, files included.

    profile-root entries payload_len result
    724 35,072 os error 206
    725 (one extra file, 93-char name) 35,220 os error 206
    486 26,056 helper launches, command runs as the sandbox user

    A JSON list of the 724 paths, base64-encoded, comes to 34,288 characters, which accounts for almost all of the payload. Disabling 32 plugins changed the payload by zero.

    Workaround until the payload moves off the command line: move loose files out of the profile root. Setting sandbox = "unelevated" also avoids the helper launch.

  7. kenta-0420 commented on Sep 24, 2026

    @kenta-0420

    Still reproduces on codex-cli 0.156.1 (Windows 11 Home 10.0.26200, codex exec review, default sandbox). Here's another data point, plus where the profile entries came from in my case.

    Growth over time (min/max payload_len per day, from .codex/.sandbox/sandbox.*.log):

    date payload_len
    09-10 21,584 – 22,540
    09-17 25,164 – 26,972
    09-23 29,212 – 31,152
    09-24 30,752 – 32,928 → helper launch fails with os error 206

    The payload grew by about 700 a day. From the first failure onward, every exec_command in the review failed. codex exec review still exited 0 and reported "could not read the diff", so a script that only checks the exit code sees nothing wrong.

    Cause on this machine: %USERPROFILE% had 450 top-level entries (about 22.5k chars of paths). profile_read_roots puts every one of them into read_roots, so the base64 payload hit the limit. Two things had filled the profile:

    Things that did not help:

    • a shorter cwd (subst X:): payload_len was still 32,772
    • pruning dead entries in .codex/cap_sid: no measurable change

    What fixed it: deleting those files (450 → 75 top-level entries). payload_len dropped to about 4,800 and the 206 errors went away.

    So anything that drops files into the home directory can eventually break the Windows sandbox, with no error from Codex pointing at the cause. Collapsing profile_read_roots to the profile root plus exclusions, or passing the payload by file or pipe instead of argv, would remove the cliff. A length check before CreateProcess would at least give an actionable error.

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

    appbugsandboxwindows-os

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions