[Bug] kilo serve orphaned after VS Code Reload Window (WSL2) — shutdown chain has no timeout, SIGKILL backstop is unref()'d
Description
kilo serve (the Kilo VS Code extension's backend) is orphaned on every VS Code Reload Window observed (3/3 reloads, one machine/config) on WSL2. Each reload leaves one serve running indefinitely (observed: 10+ hours, ~2.4 GB RSS each), re-parented to the WSL init, accumulating zombie children. Orphaned serves persist until manually terminated.
Environment: kilo-code extension 7.8.3, VS Code 1.140.0 (Remote WSL2), Linux x64, bundled kilo CLI (compiled Bun ELF). Codebase indexing: enabled. Workspace: ~325k files / 21 GB. The exthost-side discriminator log line 🔴 Disposing — sending SIGTERM to process group (server-manager.ts:286) was not recoverable from surviving logs after the incident (exthost console output is not captured by the remote exthost log files, and serve logs rotate to the newest 10 files on each serve start).
Steps to reproduce
- Open a workspace in VS Code (Remote WSL), let the Kilo extension spawn its backend (
kilo serve --port 0, spawneddetached: truewithKILO_PARENT_PID=<exthost pid>). - Ensure codebase indexing is enabled and the workspace is large enough that indexing has real work (in our case ~325k files / 21 GB monorepo). Proceed to reload while indexing is in-flight or has recently run.
Developer: Reload Window.ps -eo pid,ppid,etime,rss,args | grep "kilo serve"→ the old serve is still running, now re-parented to init. Repeat reloads accumulate one serve each.
Observed incident
- The extension host spawned its
kilo servebackend at 12:22 and terminated via the normal reload path at 14:34:01 (Extension host terminating: received terminate message from renderer→exiting with code 0). - That serve was still alive 10+ hours later, re-parented to the WSL init process, holding open
kilo.dbhandles and 20+ zombie children (defunct pyright / codebase-memory / playwright processes). - The same pattern repeated on the next reload: a second exthost/serve pair, exthost exited, serve orphaned.
Root-cause analysis (verified structure + incident inference)
Verified by source reading (v7.8.3):
Two structural defects combine; both are present at v7.8.3 (parent-watchdog.ts unchanged since v7.5.5). This code path has no verified working scenario on Reload Window with in-flight indexing work:
1. The serve-side shutdown chain has no timeout and no forced exit (serve.ts:39-51)
The shutdown handler (entered via SIGTERM from either the exthost's process-group kill or the parent watchdog's self-signal) awaits three stages; only the first has a deadline:
// cli/cmd/serve.ts:39-51 (verbatim)
const shutdown = async () => {
stopWatchdog()
try {
await KiloSessions.drainIngestForShutdown() // kilocode_change
await InstanceRuntime.disposeAllInstances()
await server.stop(true)
} finally {
resolve()
}
}
process.once("SIGTERM", shutdown)
process.once("SIGINT", shutdown)
process.once("SIGHUP", shutdown)
Note stopWatchdog() as the first statement: whichever signal starts the shutdown also permanently disarms the parent watchdog. Combined with process.once semantics (a consumed handler means any second SIGTERM takes the default disposition and hard-kills the process), the 10-hour survival proves exactly one SIGTERM was ever delivered and the handler hung. Which signal started the shutdown — the exthost's process-group SIGTERM or the watchdog's self-signal — cannot be determined from the surviving evidence; both paths end in the same hung shutdown with no deadline and no second signal.
KiloSessions.drainIngestForShutdown()— bounded (~3s deadline,ingest-queue.ts:408) — verified not the hangInstanceRuntime.disposeAllInstances→InstanceStore.disposeAllruns uninterruptible (instance-store.ts:209) and disposes the indexing engine, whoseorchestrator.shutdown()doesawait this._active(orchestrator.ts:389) — the in-flight indexing task — after only a cooperative cancel (scanner.cancel()sets a flag checked between batches).- An in-flight batch processing task (
processors/scanner.ts:527,processBatch) performsembedder.createEmbeddings()+ vector-store upsert with no per-request timeout — the [OI] embedder client is constructed without one (embedders/openai.ts:32; SDK default applies), andMAX_BATCH_RETRIES = 3with exponential backoff can stretch a stall much longer. Cooperative cancellation (this._cancelled) is only checked between batches — an already-in-flight embed/upsert cannot be interrupted. (The batch-accumulation mutex atprocessors/scanner.ts:210protects shared producer-side state and is not itself the hang.)
A single stuck embed/upsert request keeps the in-flight indexing task (this._active) pending → the uninterruptible disposeAll never completes → and the SIGTERM handler never finishes: the serve stays alive indefinitely, matching the observed 10-hour survival.
2. The exthost-side SIGKILL backstop is unref()'d (server-manager.ts:291-298)
ServerManager.dispose() sends SIGTERM to the serve's process group and then schedules a SIGKILL fallback after 5s — but that timer is .unref()'d ("so this timer doesn't prevent the extension host from exiting"). On Reload Window the extension host exits quickly after dispose() (observed: exthost logs show exiting with code 0 within seconds of Extension host terminating). If the exthost exits before the 5s timer fires, the .unref()'d fallback is structurally unreachable — the only backstop against a hung serve shutdown never triggers on this path.
3. Dispose closure has no error containment (extension.ts:816-828). Six dispose bodies run sequentially without try/catch; an exception in an earlier one (e.g. KiloProvider.dispose(), ~45 unguarded calls) skips connectionService.dispose() — and thus the server kill entirely. deactivate() does not dispose connectionService as a backup.
Unproven incident-specific inferences (need log evidence that cannot be recovered — see Notes):
- Which shutdown stage actually hung in the observed orphans (drain vs disposeAll vs server.stop)
- Whether the exthost was still alive, zombie, or already reaped when
ServerManager.dispose()ran
Suggested fixes
- Serve-side hard deadline (the important one): arm an unref'd
setTimeout(() => process.exit(1), N)inside the shutdown handler (the HTTP server keeps the loop alive during the hang, so the timer will fire), and register the handler withprocess.onplus an idempotent guard and an escalated second-signal kill (process.exit(1)) instead ofprocess.once— as shipped, a consumedoncehandler means any second SIGTERM takes the default disposition, and no second signal ever arrives to rescue a hung shutdown. - Don't
unref()the SIGKILL fallback inServerManager.dispose()(server-manager.ts:291-298), or send SIGKILL synchronously on a second dispose pass. On Reload Window the extension host exits within ~0.6s of the terminate message (observed), so the currently-unref()'d 5s SIGKILL timer does not fire — the only backstop against a hung serve shutdown is structurally unreachable on this exact path. - Wrap the dispose closure bodies in try/catch (or use a
DisposableStore) soconnectionService.dispose()always runs, and add it todeactivate()as a belt-and-braces path.
Notes
- Cross-referencing #14387 ("Complete automatic server connection lifecycle acceptance") — its acceptance criteria include "No orphaned
kilo serveprocesses after extension teardown (process-table evidence)" and "extension reload while server lives", which is exactly the scenario failing here. - Diagnosability side-note: serve logs are rotated to the newest 10 files (
packages/core/src/util/log.ts,keep = 10), which deleted the logs containing the watchdog/shutdown trace for the affected serves and made this harder to diagnose. ABun.versionline at serve startup would also help future reports pin the embedded runtime. - Happy to test a fix build.
Operating System
Windows (WSL2, Ubuntu), VS Code Remote
I'm working on the serve-side shutdown deadline with AI assistance. On current main, I reproduced the unbounded shutdown using the actual CLI/HTTP server and a registered instance disposer that never resolves: SIGTERM enters disposal, but the server remains alive beyond seven seconds. I plan to match the extension's existing five-second fallback with a backend-owned deadline, preserving normal cleanup and adding a subprocess regression. This does not claim to reproduce the WSL Reload Window incident or address the separate extension disposal-order concern.