jcode icon indicating copy to clipboard operation
jcode copied to clipboard

Windows: orphaned `server keepalive` respawns the daemon forever when the hotkey listener dies without closing the lifetime stdin pipe (3,733 processes / 14.26 GB)

Open viccom opened this issue 3 months ago • 3 comments

Environment

  • OS: Windows 10 Enterprise LTSC, build 19044
  • jcode version: jcode v0.81.4 (896f866eb)
  • Terminal: Windows Terminal 1.24.11911.0
  • Shell: PowerShell 5.1.19041.3930 / pwsh 7
  • RAM: 48 GB, no pagefile configured (AutomaticManagedPagefile: False)

Summary

On Windows, jcode.exe --provider auto serve processes accumulate continuously — roughly one new process every ~2 minutes, ~700–714 per day. On this machine the count reached 3,733 processes consuming 14.26 GB of system commit memory before I cleaned them up manually.

Root cause (located in source)

crates/jcode-setup-hints/src/windows_setup.rs:330 — prewarm_windows_server() spawns the keepalive helper using stdin as a lifetime pipe:

// The listener is launched at interactive login and remains resident, so
// it is the natural place to pay the daemon's cold-start cost before the
// user opens a terminal. The child keeps one lightweight server connection
// open using stdin as a lifetime pipe. Killing or uninstalling this listener
// closes the pipe, so the helper exits and normal server idle shutdown resumes.
std::process::Command::new(exe)
    .args(["--provider", "auto", "server", "keepalive"])
    .stdin(std::process::Stdio::piped())
    .stdout(std::process::Stdio::null())
    .stderr(std::process::Stdio::null())
    .creation_flags(CREATE_NO_WINDOW)
    .spawn()

The receiving side, src/cli/dispatch.rs:1387 — run_server_keepalive(), exits only on stdin EOF:

let mut owner_closed = tokio::task::spawn_blocking(|| {
    let mut stdin = std::io::stdin();
    let mut buffer = [0u8; 256];
    loop {
        match std::io::Read::read(&mut stdin, &mut buffer) {
            Ok(0) | Err(_) => return,
            Ok(_) => {}
        }
    }
});
let mut client: Option<server::Client> = None;
let mut first_attempt = true;

loop {
    let delay = if first_attempt {
        first_attempt = false;
        std::time::Duration::ZERO
    } else if client.is_some() {
        std::time::Duration::from_secs(30)
    } else {
        std::time::Duration::from_secs(1)
    };
    tokio::select! {
        _ = &mut owner_closed => return Ok(()),
        _ = tokio::time::sleep(delay) => {
            // ... health probe; on failure:
            if spawn_server(provider_choice, model, provider_profile).await.is_ok() { /* ... */ }
        }
    }
}

The design relies on the Child bound at windows_setup.rs:360 (let _server_keepalive = prewarm_windows_server();) being dropped so the stdin pipe closes. When the hotkey listener is terminated without a clean drop — crash, forced kill, upgrade while running, or multiple login sessions each leaving a listener behind — the pipe never closes, owner_closed never resolves, and the loop keeps respawning the server every 1–30 seconds forever.

Worth noting: the listener is a login-startup resident process (create_startup_shortcut) launched with CREATE_NO_WINDOW, so several listener instances can accumulate across logins and upgrades, each pulling its own keepalive.

spawn_server() does dedupe (src/cli/dispatch.rs:1280, if server_is_running_at(&socket_path).await { return Ok(()) }), but that only prevents a second concurrent server — it does not stop the retry loop from firing on every iteration where the socket probe races or the server is briefly unavailable.

Reproduction

  1. On Windows, run jcode setup-hotkey (installs the login shortcut).
  2. Log in / reboot a few times, or upgrade jcode while a listener is running.
  3. Wait several hours, then count:
@(Get-CimInstance Win32_Process -Filter "Name='jcode.exe'").Count
Get-CimInstance Win32_Process -Filter "Name='jcode.exe'" | Group-Object CommandLine
  1. Observe the count growing ~1 per 2 minutes, dominated by jcode.exe --provider auto serve.

Observed data

Per-day growth on this machine (grouped by process creation date):

2026-08-28: 450    2026-08-31: 714
2026-08-29: 714    2026-09-01: 714
2026-08-30: 713    2026-09-02: 428

Totals before cleanup: 3,733 processes / 14.26 GB private commit. Grouped by command line:

1589 : jcode.exe --provider auto serve
   1 : jcode.exe --provider auto server keepalive
   1 : jcode.exe setup-hotkey --listen-windows-hotkey

Process count before/after manual cleanup: 4,112 → 371; handle count 597,633 → 288,550.

86400 / 714 ≈ 121 s, the same order of magnitude as the 30 s keepalive retry interval — consistent with a respawn loop rather than a one-time leak.

Impact

System commit memory reached 43.2 / 47.7 GB (only 4.5 GB free) with no pagefile configured, leaving the machine with almost no commit headroom. After cleanup: 27.7 GB committed.

Some instances also resisted termination: taskkill /F /IM jcode.exe /T returned "Access denied" (原因: 拒绝访问) from a non-elevated shell, because the listeners are started by a login startup entry in a different session/integrity level. An elevated process-tree kill was required.

Expected behavior

An orphaned keepalive helper should exit once its owning listener is gone, instead of respawning the server indefinitely.

Suggested directions

  • Make the keepalive detect owner death independently of stdin — e.g. pass the listener PID as an argument and poll OpenProcess / WaitForSingleObject, rather than relying solely on stdin EOF.
  • Add a hard cap or exponential backoff to spawn_server() retries instead of retrying every 1–30 s forever.
  • On Windows, place the listener and its children in a job object so descendants die with the parent.
  • Have server keepalive refuse to start (or exit immediately) when an equivalent keepalive is already running.

Notes

Per CONTRIBUTING.md, this is a Windows-specific issue, so I understand a PR capturing the local-environment behavior may be more useful than an issue alone. Happy to provide one, or to run any instrumentation you want on this machine — I can reproduce the accumulation.

viccom avatar Sep 02 '26 08:09 viccom

Root cause analysis looks right (keepalive only exits on stdin EOF; orphaned listener keeps the pipe open). The fix involves Windows process-lifetime handling (job objects or parent-PID watch) that I cannot test from this Linux host, so leaving it for a maintainer with a Windows box.


— Jcode agent (automated triage), on behalf of @1jehuang

1jehuang avatar Sep 02 '26 22:09 1jehuang

I'm on Windows and can reproduce and test this, so I'd like to take it.

Plan: on Windows, tie the keepalive's lifetime to its parent instead of relying only on stdin EOF. Put the spawned processes in a Job Object with JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE, so they're cleaned up when the owner goes away, and also have the keepalive watch the parent PID and exit when it's gone. That stops an orphaned keepalive from respawning the daemon. I'll test it by killing the hotkey listener and checking that the process count stays flat.

iakshkhurana avatar Oct 01 '26 18:10 iakshkhurana

Seeing the same pile-up on v0.99.1 (7206efd0c), Windows 11 26100, but in my case the hotkey listener is still alive, so the keepalive isn't orphaned. It still spawned a new --provider auto serve every ~2 minutes: 18 of them between 23:51 and 00:24, and not one ever started listening.

I think there's a second reason the loop never stops: the serve that keepalive spawns just hangs. Its log ends right here:

jcode starting (… exe=…\builds\shared-server\jcode.exe)
perf: tier=full terminal=unknown …
AUTH event=runtime_activation_clear_initial_provider provider=runtime selection=auto
AUTH event=auth_status_check_fast provider=all …

and then nothing, no Server listening. If I run exactly the same command myself with stdout redirected to a file, it prints Using OpenRouter (use /model to switch models) and starts listening right away. And when a client window spawns serve, the next thing in the log after auth_status_check_fast is the "Found existing … credentials … will not read them without confirmation" warning. So my guess is it gets stuck on its first stdout write, or on that confirmation path, with whatever handles it inherits from keepalive (keepalive itself has stdout set to null).

Once I started a server by hand outside of any terminal, keepalive stopped spawning new ones, which fits: its health check finally passes.

(Separate issue about why this matters for windows: #2177)

Aether0Pneuma avatar Nov 15 '26 00:11 Aether0Pneuma