mirror of
https://github.com/Pasta-Devs/Marinara-Engine.git
synced 2026-12-03 19:00:50 +07:00
[GH-ISSUE #2716] [Issue]: Sidecar process lifecycle — unhandled spawn 'error' crashes the whole server (+ orphaned children, stop()/startup race, no reaper) #1363
Labels
No labels
android
bug
bugfix
ci
client
code freeze pause
container
dependencies
docs
documentation
duplicate
enhancement
feature
feature
feature
feature-creep
fixed-in-refactor
fixed-in-staging
good first issue
help wanted
in-pr
in-pr
needs-codeowner-decision
normal-scope
old-codebase
old-codebase
pull-request
qol
question
refactor
regression
revisit later
roadmap
scope-risk
scope-risk
server
server
shared
soup
upstream
windows
No milestone
No project
No assignees
1 participant
Notifications
Due date
No due date set.
Dependencies
No dependencies set.
Reference
Pasta-Devs/Marinara-Engine#1363
Loading…
Add table
Add a link
Reference in a new issue
No description provided.
Delete branch "%!s()"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
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.tshas 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 theChildProcess.bindChildattaches onlystdout/stderr/exitlisteners — never'error'. An unhandled'error'is re-thrown, and there is noprocess.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
existsSynccheck (ENOENT), then trigger a local-model start. The whole server exits.Trace:
bindChildattachesstdout(601)/stderr(604)/exit(607) only (sidecar-process.service.ts:593-610).installLatestchmods inside a swallowing try/catch (sidecar-runtime.service.ts:538-543) andisInstallUsableonly 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'. NouncaughtExceptionhandler exists (only SIGTERM/SIGINT in index.ts). Note the MLX installer spawn at mlx-runtime.service.ts:363 DOES attachchild.on('error', ...)— the inference-pathbindChildsimply forgot.Suggested Fix: In
bindChildattachchild.on('error', ...)converting the spawn failure into a startup rejection thatwaitForReadyobserves; wrap thespawn()calls in try/catch; add a globalprocess.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/currentSignaturenulled, 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:
bindChildattacheschild.on('exit', () => handleChildExit(...))to every child and never removes it (noremoveListener/offin the file).handleChildExit(code, signal)never compares the exiting child tothis.childand unconditionally callscleanupChildState()which nullsthis.child/baseUrl/currentSignatureand endslogStream(sidecar-process.service.ts:691-705). AfterstopUnlockedSIGKILLs slow child A andbindChild(B)resetsintentionalStop=false(599), A's delayed'exit'runshandleChildExit(A)withwasIntentional=false→ corrupts live child B;markReady()does not restore the nulled fields, soisReady()(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); }); makecleanupChildState/handleChildExitno-op whenthis.child !== child; callchild.removeAllListeners()incleanupChildState.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/downloadwhich stops first) performs a kill BEFORE acquiringwithLock, so it runs concurrently with an in-flight startup'swaitForReady. 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 setsintentionalStop=trueandchild.kill('SIGTERM')with no lock (sidecar-process.service.ts:176-183). The startup holds the lock insidestartLlamaForInstalledRuntimeUnlockedawaitingwaitForReady(540);getChildExitErrorreturns aSidecarServerExitError(626-628);shouldRetryStartuptreats it as retryable (374-376), so with defaultgpuLayers=-1on a GPU runtime the loop spawns the CPU-fallback child (530) andbindChildresetsintentionalStop=false(599).Suggested Fix: Add an explicit
stopRequestedflag set bystop()before the kill; check it at the top of each retry iteration and in the catch beforecontinue(bail out, do not fall through to the next plan); do all child mutation insidewithLock; 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 fromindex.ts shutdown()wired to SIGTERM/SIGINT. Any exit that bypassesapp.close()(taskkill /F, OS logoff, Node crash, SIGKILL, bootstrapprocess.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 /Fthe 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/unhandledRejectionhandler exists (only an unrelatedbeforeExitflush in file-backed-store.ts). The spawns pass nodetached/Job-Object option (sidecar-process.service.ts:530-535, 569-578).stopUnlockedonly kills the in-memorythis.childhandle; 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:
waitForReadyuses 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 (notSidecarServerExitError),shouldRetryStartupreturns false, so thegpuLayers:0CPU 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,
getChildExitErrorreturns null (650) solastError(a fetch Error) is thrown (655). The catch callsstopUnlocked()killing the loading child (545), thenshouldRetryStartup(error)is false (548) because the error is not aSidecarServerExitError(374-376) →throw decoratedError(553). DefaultgpuLayers=-1(sidecar.ts:292) is exactly what enables the skipped CPU fallback (sidecar-launch-plan.ts:58-61).Suggested Fix: Make
waitForReadydistinguish '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;
waitForReadywaits up to 20 min insidewithLock, so/configchanges andrestartcannot take effect (andinferenceReadycannot 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/modelswith no AbortSignal shortcut except child exit. The wait runs insidewithLock(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) butrestart()/config patches do not.Suggested Fix: Thread an AbortController/AbortSignal into
waitForReadyso a newer restart/config-change can cancel the wait; perform the MLX weight download outside the lock or report incremental progress viasetStatus; allowrestart()/config-change to preempt an in-flight startup the waystop()does.Affected files
packages/server/src/services/sidecar/sidecar-process.service.tspackages/server/src/index.tspackages/server/src/app.tspackages/server/src/services/sidecar/sidecar-runtime.service.tsAudit 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
stagingworking tree.@SpicyMarinara commented on GitHub (Jun 21, 2026):
Fixed in
c81c063bon 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.@kolacheee commented on GitHub (Jun 21, 2026):
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.