[GH-ISSUE #2716] [Issue]: Sidecar process lifecycle — unhandled spawn 'error' crashes the whole server (+ orphaned children, stop()/startup race, no reaper) #1363

Closed
opened 2026-10-21 05:32:22 +07:00 by bsakaguchi · 2 comments
Owner

Originally created by @kolacheee on GitHub (Jun 21, 2026).
Original GitHub issue: https://github.com/Pasta-Devs/Marinara-Engine/issues/2716

Originally assigned to: @SpicyMarinara on GitHub.

Summary

The sidecar child-process lifecycle in sidecar-process.service.ts has several correctness defects in spawn, exit handling, stop/restart serialization, and shutdown. One is a full-server crash (critical); the others corrupt in-memory state, orphan GPU-holding processes, or wedge the service.


1. No 'error' listener on the spawned child → whole server crash (critical)

How it breaks the pipeline: This is the spawn step of the local pipeline. If the child cannot be spawned, Node emits 'error' (async, e.g. ENOENT/EACCES) on the ChildProcess. bindChild attaches only stdout/stderr/exit listeners — never 'error'. An unhandled 'error' is re-thrown, and there is no process.on('uncaughtException') anywhere, so the entire Node backend dies — all remote chats and the UI backend, not just the local path.

Steps to replicate: Make the runtime binary non-executable (EACCES on Unix) or move/delete it after the existsSync check (ENOENT), then trigger a local-model start. The whole server exits.

Trace: bindChild attaches stdout(601)/stderr(604)/exit(607) only (sidecar-process.service.ts:593-610). installLatest chmods inside a swallowing try/catch (sidecar-runtime.service.ts:538-543) and isInstallUsable only checks existence (sidecar-runtime.service.ts:354-367), so a non-executable binary is spawned (sidecar-process.service.ts:530, MLX:569) and emits async 'error'. No uncaughtException handler exists (only SIGTERM/SIGINT in index.ts). Note the MLX installer spawn at mlx-runtime.service.ts:363 DOES attach child.on('error', ...) — the inference-path bindChild simply forgot.

Suggested Fix: In bindChild attach child.on('error', ...) converting the spawn failure into a startup rejection that waitForReady observes; wrap the spawn() calls in try/catch; add a global process.on('uncaughtException') safety net in index.ts.


2. Stale child's exit listener corrupts the new server's state and orphans it (high)

How it breaks the pipeline: On a restart where the old child is slow to die, the freshly-started healthy server is silently 'forgotten' (isReady() flips false, baseUrl/currentSignature nulled, log stream closed) while the real llama-server keeps running as an orphan holding GPU/port. ensureReady() then throws against a server that is actually up.

Steps to replicate: Restart the sidecar (or change config) while a large model-loaded child is slow to die; the delayed exit of the old child corrupts the new child's state.

Trace: bindChild attaches child.on('exit', () => handleChildExit(...)) to every child and never removes it (no removeListener/off in the file). handleChildExit(code, signal) never compares the exiting child to this.child and unconditionally calls cleanupChildState() which nulls this.child/baseUrl/currentSignature and ends logStream (sidecar-process.service.ts:691-705). After stopUnlocked SIGKILLs slow child A and bindChild(B) resets intentionalStop=false (599), A's delayed 'exit' runs handleChildExit(A) with wasIntentional=false → corrupts live child B; markReady() does not restore the nulled fields, so isReady() (ready && baseUrl!==null) is false.

Suggested Fix: Capture the bound child in the listener and ignore exits from non-current children: child.on('exit', (c,s) => { if (this.child !== child) return; void this.handleChildExit(c,s); }); make cleanupChildState/handleChildExit no-op when this.child !== child; call child.removeAllListeners() in cleanupChildState.


3. stop() races startup outside the lock → spurious CPU fallback / orphaned second child (medium)

How it breaks the pipeline: stop() (from /unload, model delete, or /download which stops first) performs a kill BEFORE acquiring withLock, so it runs concurrently with an in-flight startup's waitForReady. The killed child is observed as an unexpected exit and the retry loop advances to the next plan (CPU fallback), spawning a NEW child and discarding stop's intent — a transient wrong-runtime CPU launch and/or briefly-orphaned second llama-server.

Steps to replicate: Call /sidecar/unload (or trigger a download) while the server is still in its GPU startup window; observe a 'Retrying with CPU fallback' launch and a second child.

Trace: stop() early-kill block sets intentionalStop=true and child.kill('SIGTERM') with no lock (sidecar-process.service.ts:176-183). The startup holds the lock inside startLlamaForInstalledRuntimeUnlocked awaiting waitForReady (540); getChildExitError returns a SidecarServerExitError (626-628); shouldRetryStartup treats it as retryable (374-376), so with default gpuLayers=-1 on a GPU runtime the loop spawns the CPU-fallback child (530) and bindChild resets intentionalStop=false (599).

Suggested Fix: Add an explicit stopRequested flag set by stop() before the kill; check it at the top of each retry iteration and in the catch before continue (bail out, do not fall through to the next plan); do all child mutation inside withLock; do not treat a SIGTERM-induced exit as retryable.


4. Child not detached / no last-resort reaper → orphaned GPU-holding process (medium)

How it breaks the pipeline: Cleanup runs only via app.addHook('onClose') → stop(), reached only from index.ts shutdown() wired to SIGTERM/SIGINT. Any exit that bypasses app.close() (taskkill /F, OS logoff, Node crash, SIGKILL, bootstrap process.exit(1), uncaughtException) leaves the child alive holding the mmap'd GGUF and the localhost port; the next launch loads a second copy (GPU OOM) and model delete hits EBUSY.

Steps to replicate: taskkill /F the Node process (or trigger an uncaught exception after the background bootstrap spawns the child); the llama-server keeps running.

Trace: index.ts:57-62 registers only SIGTERM/SIGINT; no exit/uncaughtException/unhandledRejection handler exists (only an unrelated beforeExit flush in file-backed-store.ts). The spawns pass no detached/Job-Object option (sidecar-process.service.ts:530-535, 569-578). stopUnlocked only kills the in-memory this.child handle; there is no PID file or boot-time stale-sidecar sweep.

Suggested Fix: Add a best-effort synchronous child kill on process.on('exit')/uncaughtException; on Windows spawn the child inside a Job Object with KILL_ON_JOB_CLOSE (and an equivalent strategy on POSIX) so abnormal parent death cannot orphan llama-server/mlx_lm.server.


5. Slow GPU load (>60s) is non-retryable, killing a good server and skipping CPU fallback (high)

How it breaks the pipeline: waitForReady uses a fixed 60s deadline for llama.cpp. A large/cold GGUF still loading (no exit) times out; the still-loading process is killed; and because the timeout error is a plain HTTP/fetch error (not SidecarServerExitError), shouldRetryStartup returns false, so the gpuLayers:0 CPU fallback plan is never attempted. The no-API-key user has no working model.

Steps to replicate: Load a 7B+ GGUF on an HDD / first cold mmap with default gpuLayers=-1; startup fails with 'Timed out waiting for the local sidecar server' and CPU fallback is skipped.

Trace: Fixed 60_000ms deadline for llama.cpp (sidecar-process.service.ts:622, vs 20min for MLX). On deadline expiry with a live child, getChildExitError returns null (650) so lastError (a fetch Error) is thrown (655). The catch calls stopUnlocked() killing the loading child (545), then shouldRetryStartup(error) is false (548) because the error is not a SidecarServerExitError (374-376) → throw decoratedError (553). Default gpuLayers=-1 (sidecar.ts:292) is exactly what enables the skipped CPU fallback (sidecar-launch-plan.ts:58-61).

Suggested Fix: Make waitForReady distinguish 'still loading' from 'dead' (keep waiting while the child is alive / detect llama-server 'loading model' logs / extend the cap), or treat a startup timeout as retryable so the next plan is attempted; do not kill a still-running child purely on the 60s probe deadline.


6. MLX startup holds the lifecycle lock for up to 20 minutes (medium)

How it breaks the pipeline: On first MLX start the child lazily downloads multi-GB weights; waitForReady waits up to 20 min inside withLock, so /config changes and restart cannot take effect (and inferenceReady cannot transition) for the whole window, with no abort path. The UI sits on 'starting_server' with no progress.

Steps to replicate: On Apple Silicon, select an MLX model and start it for the first time; attempt a config change or restart during the multi-minute weight download — it queues for the full window.

Trace: MLX deadline 20 * 60_000 (sidecar-process.service.ts:622), probing /v1/models with no AbortSignal shortcut except child exit. The wait runs inside withLock (109-111, 196-209); every entrypoint (ensureReady, /status sync, /config sync, restart) serializes behind it. stop() has an out-of-band early kill (176-183) but restart()/config patches do not.

Suggested Fix: Thread an AbortController/AbortSignal into waitForReady so a newer restart/config-change can cancel the wait; perform the MLX weight download outside the lock or report incremental progress via setStatus; allow restart()/config-change to preempt an in-flight startup the way stop() does.


Affected files

  • packages/server/src/services/sidecar/sidecar-process.service.ts
  • packages/server/src/index.ts
  • packages/server/src/app.ts
  • packages/server/src/services/sidecar/sidecar-runtime.service.ts

Audit provenance

Found by a multi-agent static audit of the sidecar/local-model subsystem (Round 1 + round-2 gap sweep + completeness critic, each finding adversarially verified). Severity: CRITICAL. Line numbers are against the staging working tree.

Originally created by @kolacheee on GitHub (Jun 21, 2026). Original GitHub issue: https://github.com/Pasta-Devs/Marinara-Engine/issues/2716 Originally assigned to: @SpicyMarinara on GitHub. ## Summary The sidecar child-process lifecycle in `sidecar-process.service.ts` has several correctness defects in spawn, exit handling, stop/restart serialization, and shutdown. One is a full-server crash (critical); the others corrupt in-memory state, orphan GPU-holding processes, or wedge the service. --- ### 1. No 'error' listener on the spawned child → whole server crash (critical) **How it breaks the pipeline:** This is the spawn step of the local pipeline. If the child cannot be spawned, Node emits `'error'` (async, e.g. ENOENT/EACCES) on the `ChildProcess`. `bindChild` attaches only `stdout`/`stderr`/`exit` listeners — never `'error'`. An unhandled `'error'` is re-thrown, and there is no `process.on('uncaughtException')` anywhere, so the entire Node backend dies — all remote chats and the UI backend, not just the local path. **Steps to replicate:** Make the runtime binary non-executable (EACCES on Unix) or move/delete it after the `existsSync` check (ENOENT), then trigger a local-model start. The whole server exits. **Trace:** `bindChild` attaches `stdout`(601)/`stderr`(604)/`exit`(607) only (sidecar-process.service.ts:593-610). `installLatest` chmods inside a swallowing try/catch (sidecar-runtime.service.ts:538-543) and `isInstallUsable` only checks existence (sidecar-runtime.service.ts:354-367), so a non-executable binary is spawned (sidecar-process.service.ts:530, MLX:569) and emits async `'error'`. No `uncaughtException` handler exists (only SIGTERM/SIGINT in index.ts). Note the MLX installer spawn at mlx-runtime.service.ts:363 DOES attach `child.on('error', ...)` — the inference-path `bindChild` simply forgot. **Suggested Fix:** In `bindChild` attach `child.on('error', ...)` converting the spawn failure into a startup rejection that `waitForReady` observes; wrap the `spawn()` calls in try/catch; add a global `process.on('uncaughtException')` safety net in index.ts. --- ### 2. Stale child's exit listener corrupts the new server's state and orphans it (high) **How it breaks the pipeline:** On a restart where the old child is slow to die, the freshly-started healthy server is silently 'forgotten' (`isReady()` flips false, `baseUrl`/`currentSignature` nulled, log stream closed) while the real llama-server keeps running as an orphan holding GPU/port. `ensureReady()` then throws against a server that is actually up. **Steps to replicate:** Restart the sidecar (or change config) while a large model-loaded child is slow to die; the delayed exit of the old child corrupts the new child's state. **Trace:** `bindChild` attaches `child.on('exit', () => handleChildExit(...))` to every child and never removes it (no `removeListener`/`off` in the file). `handleChildExit(code, signal)` never compares the exiting child to `this.child` and unconditionally calls `cleanupChildState()` which nulls `this.child`/`baseUrl`/`currentSignature` and ends `logStream` (sidecar-process.service.ts:691-705). After `stopUnlocked` SIGKILLs slow child A and `bindChild(B)` resets `intentionalStop=false` (599), A's delayed `'exit'` runs `handleChildExit(A)` with `wasIntentional=false` → corrupts live child B; `markReady()` does not restore the nulled fields, so `isReady()` (`ready && baseUrl!==null`) is false. **Suggested Fix:** Capture the bound child in the listener and ignore exits from non-current children: `child.on('exit', (c,s) => { if (this.child !== child) return; void this.handleChildExit(c,s); })`; make `cleanupChildState`/`handleChildExit` no-op when `this.child !== child`; call `child.removeAllListeners()` in `cleanupChildState`. --- ### 3. stop() races startup outside the lock → spurious CPU fallback / orphaned second child (medium) **How it breaks the pipeline:** `stop()` (from `/unload`, model delete, or `/download` which stops first) performs a kill BEFORE acquiring `withLock`, so it runs concurrently with an in-flight startup's `waitForReady`. The killed child is observed as an unexpected exit and the retry loop advances to the next plan (CPU fallback), spawning a NEW child and discarding stop's intent — a transient wrong-runtime CPU launch and/or briefly-orphaned second llama-server. **Steps to replicate:** Call `/sidecar/unload` (or trigger a download) while the server is still in its GPU startup window; observe a 'Retrying with CPU fallback' launch and a second child. **Trace:** `stop()` early-kill block sets `intentionalStop=true` and `child.kill('SIGTERM')` with no lock (sidecar-process.service.ts:176-183). The startup holds the lock inside `startLlamaForInstalledRuntimeUnlocked` awaiting `waitForReady` (540); `getChildExitError` returns a `SidecarServerExitError` (626-628); `shouldRetryStartup` treats it as retryable (374-376), so with default `gpuLayers=-1` on a GPU runtime the loop spawns the CPU-fallback child (530) and `bindChild` resets `intentionalStop=false` (599). **Suggested Fix:** Add an explicit `stopRequested` flag set by `stop()` before the kill; check it at the top of each retry iteration and in the catch before `continue` (bail out, do not fall through to the next plan); do all child mutation inside `withLock`; do not treat a SIGTERM-induced exit as retryable. --- ### 4. Child not detached / no last-resort reaper → orphaned GPU-holding process (medium) **How it breaks the pipeline:** Cleanup runs only via `app.addHook('onClose')` → `stop()`, reached only from `index.ts shutdown()` wired to SIGTERM/SIGINT. Any exit that bypasses `app.close()` (taskkill /F, OS logoff, Node crash, SIGKILL, bootstrap `process.exit(1)`, uncaughtException) leaves the child alive holding the mmap'd GGUF and the localhost port; the next launch loads a second copy (GPU OOM) and model delete hits EBUSY. **Steps to replicate:** `taskkill /F` the Node process (or trigger an uncaught exception after the background bootstrap spawns the child); the llama-server keeps running. **Trace:** index.ts:57-62 registers only SIGTERM/SIGINT; no `exit`/`uncaughtException`/`unhandledRejection` handler exists (only an unrelated `beforeExit` flush in file-backed-store.ts). The spawns pass no `detached`/Job-Object option (sidecar-process.service.ts:530-535, 569-578). `stopUnlocked` only kills the in-memory `this.child` handle; there is no PID file or boot-time stale-sidecar sweep. **Suggested Fix:** Add a best-effort synchronous child kill on `process.on('exit')`/`uncaughtException`; on Windows spawn the child inside a Job Object with KILL_ON_JOB_CLOSE (and an equivalent strategy on POSIX) so abnormal parent death cannot orphan llama-server/mlx_lm.server. --- ### 5. Slow GPU load (>60s) is non-retryable, killing a good server and skipping CPU fallback (high) **How it breaks the pipeline:** `waitForReady` uses a fixed 60s deadline for llama.cpp. A large/cold GGUF still loading (no exit) times out; the still-loading process is killed; and because the timeout error is a plain HTTP/fetch error (not `SidecarServerExitError`), `shouldRetryStartup` returns false, so the `gpuLayers:0` CPU fallback plan is never attempted. The no-API-key user has no working model. **Steps to replicate:** Load a 7B+ GGUF on an HDD / first cold mmap with default `gpuLayers=-1`; startup fails with 'Timed out waiting for the local sidecar server' and CPU fallback is skipped. **Trace:** Fixed 60_000ms deadline for llama.cpp (sidecar-process.service.ts:622, vs 20min for MLX). On deadline expiry with a live child, `getChildExitError` returns null (650) so `lastError` (a fetch Error) is thrown (655). The catch calls `stopUnlocked()` killing the loading child (545), then `shouldRetryStartup(error)` is false (548) because the error is not a `SidecarServerExitError` (374-376) → `throw decoratedError` (553). Default `gpuLayers=-1` (sidecar.ts:292) is exactly what enables the skipped CPU fallback (sidecar-launch-plan.ts:58-61). **Suggested Fix:** Make `waitForReady` distinguish 'still loading' from 'dead' (keep waiting while the child is alive / detect llama-server 'loading model' logs / extend the cap), or treat a startup timeout as retryable so the next plan is attempted; do not kill a still-running child purely on the 60s probe deadline. --- ### 6. MLX startup holds the lifecycle lock for up to 20 minutes (medium) **How it breaks the pipeline:** On first MLX start the child lazily downloads multi-GB weights; `waitForReady` waits up to 20 min inside `withLock`, so `/config` changes and `restart` cannot take effect (and `inferenceReady` cannot transition) for the whole window, with no abort path. The UI sits on 'starting_server' with no progress. **Steps to replicate:** On Apple Silicon, select an MLX model and start it for the first time; attempt a config change or restart during the multi-minute weight download — it queues for the full window. **Trace:** MLX deadline `20 * 60_000` (sidecar-process.service.ts:622), probing `/v1/models` with no AbortSignal shortcut except child exit. The wait runs inside `withLock` (109-111, 196-209); every entrypoint (ensureReady, /status sync, /config sync, restart) serializes behind it. `stop()` has an out-of-band early kill (176-183) but `restart()`/config patches do not. **Suggested Fix:** Thread an AbortController/AbortSignal into `waitForReady` so a newer restart/config-change can cancel the wait; perform the MLX weight download outside the lock or report incremental progress via `setStatus`; allow `restart()`/config-change to preempt an in-flight startup the way `stop()` does. --- ### Affected files - `packages/server/src/services/sidecar/sidecar-process.service.ts` - `packages/server/src/index.ts` - `packages/server/src/app.ts` - `packages/server/src/services/sidecar/sidecar-runtime.service.ts` ### Audit provenance Found by a multi-agent static audit of the sidecar/local-model subsystem (Round 1 + round-2 gap sweep + completeness critic, each finding adversarially verified). Severity: **CRITICAL**. Line numbers are against the `staging` working tree.
Author
Owner

@SpicyMarinara commented on GitHub (Jun 21, 2026):

Fixed in c81c063b on the issue-sweep branch. The sidecar now handles child spawn errors without crashing the server, ignores stale child exits, uses explicit startup cancellation for stop/restart/config changes, treats startup timeouts as retryable for fallback plans, and adds a best-effort process-exit reaper for abnormal shutdowns.

<!-- gh-comment-id:4761675971 --> @SpicyMarinara commented on GitHub (Jun 21, 2026): Fixed in c81c063b on the issue-sweep branch. The sidecar now handles child spawn errors without crashing the server, ignores stale child exits, uses explicit startup cancellation for stop/restart/config changes, treats startup timeouts as retryable for fallback plans, and adds a best-effort process-exit reaper for abnormal shutdowns.
Author
Owner

@kolacheee commented on GitHub (Jun 21, 2026):

Reopening — partially fixed by #2730. A post-merge verification against the merged staging branch confirms the main fix landed, but a cited part of this issue remains unfixed. Residual below, verified by direct read at file:line.

Claim 4's OS-level orphan prevention is unimplemented. The new reaper killCurrentChildForProcessExit (packages/server/src/services/sidecar/sidecar-process.service.ts:224-244) only kills the in-memory this.child via child.kill() and is wired only to Node-level events (index.ts:51-61: process.once("exit"), uncaughtException, unhandledRejection). External hard kills bypass all of these: taskkill /F (the issue's own repro step), Windows logoff, and SIGKILL of the parent fire no Node 'exit' handler, so the reaper never runs. The llama (sidecar-process.service.ts:643-648) and MLX (690-699) spawns pass NO detached option and use no Windows Job Object (KILL_ON_JOB_CLOSE) or POSIX process-group equivalent; there is also no PID file or boot-time stale-sidecar sweep (package-wide grep for detached|JobObject|setpgid|.pid in the lifecycle code returns nothing). Result: on abnormal parent death the GPU/port-holding llama-server is still orphaned, so the next launch OOMs and model delete hits EBUSY — exactly the failure the issue's suggested fix (Windows Job Object + POSIX equivalent) was meant to prevent.

<!-- gh-comment-id:4762835161 --> @kolacheee commented on GitHub (Jun 21, 2026): > **Reopening — partially fixed by #2730.** A post-merge verification against the merged staging branch confirms the main fix landed, but a cited part of this issue remains unfixed. Residual below, verified by direct read at file:line. Claim 4's OS-level orphan prevention is unimplemented. The new reaper killCurrentChildForProcessExit (packages/server/src/services/sidecar/sidecar-process.service.ts:224-244) only kills the in-memory this.child via child.kill() and is wired only to Node-level events (index.ts:51-61: process.once("exit"), uncaughtException, unhandledRejection). External hard kills bypass all of these: `taskkill /F` (the issue's own repro step), Windows logoff, and SIGKILL of the parent fire no Node 'exit' handler, so the reaper never runs. The llama (sidecar-process.service.ts:643-648) and MLX (690-699) spawns pass NO detached option and use no Windows Job Object (KILL_ON_JOB_CLOSE) or POSIX process-group equivalent; there is also no PID file or boot-time stale-sidecar sweep (package-wide grep for detached|JobObject|setpgid|.pid in the lifecycle code returns nothing). Result: on abnormal parent death the GPU/port-holding llama-server is still orphaned, so the next launch OOMs and model delete hits EBUSY — exactly the failure the issue's suggested fix (Windows Job Object + POSIX equivalent) was meant to prevent.
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
Pasta-Devs/Marinara-Engine#1363
No description provided.