[GH-ISSUE #2720] [Issue]: Sidecar routes/client store — in-flight inference torn down by download/switch/unload; no abort/disconnect plumbing wedges downloads and cancels #1366

Closed
opened 2026-10-21 05:32:27 +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/2720

Originally assigned to: @SpicyMarinara on GitHub.

Summary

The sidecar routes and client store lack the busy-guards, abort plumbing, and status-driven UI that the rest of the app relies on. Model download/switch/unload tear down the single shared llama-server out from under in-flight inference, and the client has no AbortSignal/disconnect handling, so cancels and reloads wedge the modal or orphan the operation.


1. /download and /download/custom lack the isInferenceBusy() guard (medium)

How it breaks the pipeline: DELETE /model returns 409 when isInferenceBusy(), but /download and /download/custom immediately stop() the shared server and (for a quant switch) unlink the previous GGUF — aborting a streaming tracker/scene request with a connection error or 'model file is missing'.

Steps to replicate: Start a tracker/scene generation, then start a model download/switch from the UI; the in-flight request fails.

Trace: DELETE /model guards with if (isInferenceBusy()) return 409 (sidecar.routes.ts:275-277); /download (235-245) and /download/custom (247-263) do not. stop() SIGTERM/SIGKILLs the child (sidecar-process.service.ts:175-194). Inference streaming runs after ensureReady() releases the lock (sidecar-inference.service.ts:157-219). A quant switch unlinks the previous GGUF (sidecar-model.service.ts:598→316-340).

Suggested Fix: Add if (isInferenceBusy()) return reply.status(409) to /download and /download/custom (or serialize them and refuse while activeRequests>0), matching DELETE /model.


2. /unload kills inference mid-stream with no guard or privileged gate (high)

How it breaks the pipeline: /unload calls unloadModel() → stop() with no isInferenceBusy() check, so it tears down the shared server while a request is streaming; it also lacks the requirePrivilegedAccess gate every other mutating route has.

Steps to replicate: Start a tracker/scene/test generation, hit /sidecar/unload; the active request fails with a stream error.

Trace: /unload (sidecar.routes.ts:284-287) has neither requirePrivilegedAccess nor isInferenceBusy(); unloadModel() is await sidecarProcessService.stop() (sidecar-inference.service.ts:333-335). isInferenceBusy() is true during streaming via withRequestTracking (24-26) but is never consulted here.

Suggested Fix: Add the same if (isInferenceBusy()) return 409 guard and a requirePrivilegedAccess gate to /unload, matching DELETE /model.


3. Download SSE has no client-disconnect handler; client passes no AbortSignal (medium)

How it breaks the pipeline: handleDownloadSse hijacks the socket and cleans up only after task() settles; there is no reply.raw.on('close'). The client's consumeDownloadStream passes no signal. Closing the modal / navigating away abandons the reader while the server keeps downloading, keeps writing SSE to a dead socket, and leaves downloadAbort set so new attempts throw 'Another sidecar download is already in progress'.

Steps to replicate: Start a model/runtime download, close the modal; the download keeps running invisibly and a fresh attempt is blocked.

Trace: handleDownloadSse registers no close hook (sidecar.routes.ts:196-233); downloadFileWithProgress is driven only by options.signal (sidecar-download.ts:90-96); client api.raw is called with no signal (sidecar.store.ts:129-140; api-client.ts:87-107); modal close effect only clears custom models (ModelDownloadModal.tsx:216-228).

Suggested Fix: Pass an AbortController signal from the store into api.raw and abort on modal close/unmount; add reply.raw.on('close', ...) that calls cancelDownload()/cancelInstall() when the client disconnects before {done:true}.


4. Reload during a download hides progress and re-enables buttons (high)

How it breaks the pipeline: After a page reload, the client loses the SSE stream and downloadProgress resets to null, but the server is still downloading (status 'downloading_model'). The modal's blocking UI keys off downloadProgress/'downloading_runtime' only, so it shows the normal download buttons; clicking Download fails with 'Another sidecar download is already in progress'.

Steps to replicate: Start a model download, reload the page; the modal shows active buttons and the in-progress download is invisible.

Trace: initial downloadProgress: null (sidecar.store.ts:239); fetchStatus never reconstructs progress; isBlockingSetup = isDownloading || status === 'downloading_runtime' (ModelDownloadModal.tsx:198) is false for a model download; clicking download throws (sidecar-model.service.ts:745-746).

Suggested Fix: Treat status === 'downloading_model' as blocking and render an indeterminate progress bar + Cancel when status indicates an in-progress download even though downloadProgress is null.


5. Client cancel is undone by the still-open SSE reader (medium)

How it breaks the pipeline: cancelDownload clears downloadProgress but, with no AbortSignal/cancel flag, the still-open reader receives the server's {status:'error', error:'Download cancelled'} SSE event and re-sets an error object, so a deliberate cancel surfaces a misleading error banner instead of a clean idle state.

Steps to replicate: Start a real download, press 'Cancel Setup'; progress clears then a 'Download cancelled' error banner pops back up.

Trace: cancelDownload POSTs cancel and sets downloadProgress:null (sidecar.store.ts:361-370); reader stays open (no signal) and runs the data.status==='error' branch (185-199); server converts the abort to an error SSE event (sidecar.routes.ts:222-228); error banner renders (ModelDownloadModal.tsx:1153-1156).

Suggested Fix: Track an AbortController for the active stream and abort it in cancelDownload (pass its signal into api.raw), and/or set a 'cancelled' flag so the reader ignores late error events; prefer a clean idle state after cancel.


6. cancelDownload cannot stop a server start; no Cancel during starting_server (medium)

How it breaks the pipeline: cancelDownload only aborts download/install controllers, not sidecarProcessService startup, and the modal only shows Cancel while isBlockingSetup is true — not during starting_server. So a long/hung server boot (up to 60s llama / 20min MLX) cannot be cancelled from the UI.

Steps to replicate: Trigger a restart/start, then try to cancel during 'Starting local runtime...'; only Skip/Done render and the start cannot be stopped.

Trace: cancel route calls only model/runtime cancel, never the process service (sidecar.routes.ts:265-271); waitForReady loops with no abort hook (sidecar-process.service.ts:621-656); Cancel gated on isBlockingSetup (ModelDownloadModal.tsx:1160), false during isPreparingServer (198-200).

Suggested Fix: Add a stop/abort endpoint for the starting_server phase and show Cancel when isPreparingServer, or gate Cancel on showSetupProgress so an in-progress boot can be aborted.


7. Runtime-install request failure wedges the client in a transitional status (low)

How it breaks the pipeline: installRuntime optimistically sets status 'downloading_runtime'; on a non-2xx before SSE starts (403 from the privileged gate, network error) the catch only sets downloadProgress to 'error' and never resets status or calls fetchStatus, leaving the modal stuck on a spinning setup card with the model UI hidden (recoverable only via Cancel Setup).

Steps to replicate: On a remote/admin-gated deployment, click Install Runtime and have it return 403; the modal wedges on a spinner.

Trace: optimistic status set (sidecar.store.ts:420-451); consumeDownloadStream throws on !response.ok (142-152); catch never resets status/calls fetchStatus (438-450); isBlockingSetup stays true (ModelDownloadModal.tsx:198).

Suggested Fix: In the catch blocks, call await get().fetchStatus() (or reset status out of the transitional value) so status reconciles with the server; surface the error via downloadProgress without pinning status.


8. deleteModel() unlinkSync unguarded → raw 500 on Windows EBUSY (low)

How it breaks the pipeline: On Windows the GGUF may still be memory-mapped right after stop(), so unlinkSync throws EBUSY/EPERM before the config reset/persist, returning a raw HTTP 500 and a confusing silent no-op delete (inconsistent with clearLegacyRuntimeStamp which try/catches its unlink 30 lines below).

Steps to replicate: On Windows, delete the local model immediately after stopping the server; observe a 500 and the delete appearing to fail.

Trace: unlinkSync(modelPath) with no try/catch (sidecar-model.service.ts:789); config reset/saveConfig/status are after it (793-802); route has no try/catch → global handler maps to 500 (sidecar.routes.ts:273-282). Model is mmapped because buildLlamaArgs omits --no-mmap and stopUnlocked does not await final exit after SIGKILL.

Suggested Fix: Wrap the unlink in a retry/try-catch (retry after a short delay for Windows handle release) and reset+persist config regardless of whether removal succeeded; surface a non-fatal warning instead of a 500.


Affected files

  • packages/server/src/routes/sidecar.routes.ts
  • packages/server/src/services/sidecar/sidecar-inference.service.ts
  • packages/server/src/services/sidecar/sidecar-model.service.ts
  • packages/client/src/stores/sidecar.store.ts
  • packages/client/src/components/modals/ModelDownloadModal.tsx
  • packages/client/src/lib/api-client.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: MEDIUM. 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/2720 Originally assigned to: @SpicyMarinara on GitHub. ## Summary The sidecar routes and client store lack the busy-guards, abort plumbing, and status-driven UI that the rest of the app relies on. Model download/switch/unload tear down the single shared llama-server out from under in-flight inference, and the client has no AbortSignal/disconnect handling, so cancels and reloads wedge the modal or orphan the operation. --- ### 1. /download and /download/custom lack the isInferenceBusy() guard (medium) **How it breaks the pipeline:** `DELETE /model` returns 409 when `isInferenceBusy()`, but `/download` and `/download/custom` immediately `stop()` the shared server and (for a quant switch) unlink the previous GGUF — aborting a streaming tracker/scene request with a connection error or 'model file is missing'. **Steps to replicate:** Start a tracker/scene generation, then start a model download/switch from the UI; the in-flight request fails. **Trace:** DELETE /model guards with `if (isInferenceBusy()) return 409` (sidecar.routes.ts:275-277); /download (235-245) and /download/custom (247-263) do not. `stop()` SIGTERM/SIGKILLs the child (sidecar-process.service.ts:175-194). Inference streaming runs after `ensureReady()` releases the lock (sidecar-inference.service.ts:157-219). A quant switch unlinks the previous GGUF (sidecar-model.service.ts:598→316-340). **Suggested Fix:** Add `if (isInferenceBusy()) return reply.status(409)` to /download and /download/custom (or serialize them and refuse while `activeRequests>0`), matching DELETE /model. --- ### 2. /unload kills inference mid-stream with no guard or privileged gate (high) **How it breaks the pipeline:** `/unload` calls `unloadModel()` → `stop()` with no `isInferenceBusy()` check, so it tears down the shared server while a request is streaming; it also lacks the `requirePrivilegedAccess` gate every other mutating route has. **Steps to replicate:** Start a tracker/scene/test generation, hit `/sidecar/unload`; the active request fails with a stream error. **Trace:** /unload (sidecar.routes.ts:284-287) has neither `requirePrivilegedAccess` nor `isInferenceBusy()`; `unloadModel()` is `await sidecarProcessService.stop()` (sidecar-inference.service.ts:333-335). `isInferenceBusy()` is true during streaming via `withRequestTracking` (24-26) but is never consulted here. **Suggested Fix:** Add the same `if (isInferenceBusy()) return 409` guard and a `requirePrivilegedAccess` gate to /unload, matching DELETE /model. --- ### 3. Download SSE has no client-disconnect handler; client passes no AbortSignal (medium) **How it breaks the pipeline:** `handleDownloadSse` hijacks the socket and cleans up only after `task()` settles; there is no `reply.raw.on('close')`. The client's `consumeDownloadStream` passes no `signal`. Closing the modal / navigating away abandons the reader while the server keeps downloading, keeps writing SSE to a dead socket, and leaves `downloadAbort` set so new attempts throw 'Another sidecar download is already in progress'. **Steps to replicate:** Start a model/runtime download, close the modal; the download keeps running invisibly and a fresh attempt is blocked. **Trace:** `handleDownloadSse` registers no close hook (sidecar.routes.ts:196-233); `downloadFileWithProgress` is driven only by `options.signal` (sidecar-download.ts:90-96); client `api.raw` is called with no signal (sidecar.store.ts:129-140; api-client.ts:87-107); modal close effect only clears custom models (ModelDownloadModal.tsx:216-228). **Suggested Fix:** Pass an AbortController signal from the store into `api.raw` and abort on modal close/unmount; add `reply.raw.on('close', ...)` that calls `cancelDownload()`/`cancelInstall()` when the client disconnects before `{done:true}`. --- ### 4. Reload during a download hides progress and re-enables buttons (high) **How it breaks the pipeline:** After a page reload, the client loses the SSE stream and `downloadProgress` resets to null, but the server is still downloading (status 'downloading_model'). The modal's blocking UI keys off `downloadProgress`/'downloading_runtime' only, so it shows the normal download buttons; clicking Download fails with 'Another sidecar download is already in progress'. **Steps to replicate:** Start a model download, reload the page; the modal shows active buttons and the in-progress download is invisible. **Trace:** initial `downloadProgress: null` (sidecar.store.ts:239); `fetchStatus` never reconstructs progress; `isBlockingSetup = isDownloading || status === 'downloading_runtime'` (ModelDownloadModal.tsx:198) is false for a model download; clicking download throws (sidecar-model.service.ts:745-746). **Suggested Fix:** Treat `status === 'downloading_model'` as blocking and render an indeterminate progress bar + Cancel when status indicates an in-progress download even though `downloadProgress` is null. --- ### 5. Client cancel is undone by the still-open SSE reader (medium) **How it breaks the pipeline:** `cancelDownload` clears `downloadProgress` but, with no AbortSignal/cancel flag, the still-open reader receives the server's `{status:'error', error:'Download cancelled'}` SSE event and re-sets an error object, so a deliberate cancel surfaces a misleading error banner instead of a clean idle state. **Steps to replicate:** Start a real download, press 'Cancel Setup'; progress clears then a 'Download cancelled' error banner pops back up. **Trace:** `cancelDownload` POSTs cancel and sets `downloadProgress:null` (sidecar.store.ts:361-370); reader stays open (no signal) and runs the `data.status==='error'` branch (185-199); server converts the abort to an error SSE event (sidecar.routes.ts:222-228); error banner renders (ModelDownloadModal.tsx:1153-1156). **Suggested Fix:** Track an AbortController for the active stream and abort it in `cancelDownload` (pass its signal into `api.raw`), and/or set a 'cancelled' flag so the reader ignores late error events; prefer a clean idle state after cancel. --- ### 6. cancelDownload cannot stop a server start; no Cancel during starting_server (medium) **How it breaks the pipeline:** `cancelDownload` only aborts download/install controllers, not `sidecarProcessService` startup, and the modal only shows Cancel while `isBlockingSetup` is true — not during `starting_server`. So a long/hung server boot (up to 60s llama / 20min MLX) cannot be cancelled from the UI. **Steps to replicate:** Trigger a restart/start, then try to cancel during 'Starting local runtime...'; only Skip/Done render and the start cannot be stopped. **Trace:** cancel route calls only model/runtime cancel, never the process service (sidecar.routes.ts:265-271); `waitForReady` loops with no abort hook (sidecar-process.service.ts:621-656); Cancel gated on `isBlockingSetup` (ModelDownloadModal.tsx:1160), false during `isPreparingServer` (198-200). **Suggested Fix:** Add a stop/abort endpoint for the starting_server phase and show Cancel when `isPreparingServer`, or gate Cancel on `showSetupProgress` so an in-progress boot can be aborted. --- ### 7. Runtime-install request failure wedges the client in a transitional status (low) **How it breaks the pipeline:** `installRuntime` optimistically sets status 'downloading_runtime'; on a non-2xx before SSE starts (403 from the privileged gate, network error) the catch only sets `downloadProgress` to 'error' and never resets `status` or calls `fetchStatus`, leaving the modal stuck on a spinning setup card with the model UI hidden (recoverable only via Cancel Setup). **Steps to replicate:** On a remote/admin-gated deployment, click Install Runtime and have it return 403; the modal wedges on a spinner. **Trace:** optimistic status set (sidecar.store.ts:420-451); `consumeDownloadStream` throws on `!response.ok` (142-152); catch never resets status/calls fetchStatus (438-450); `isBlockingSetup` stays true (ModelDownloadModal.tsx:198). **Suggested Fix:** In the catch blocks, call `await get().fetchStatus()` (or reset `status` out of the transitional value) so `status` reconciles with the server; surface the error via `downloadProgress` without pinning `status`. --- ### 8. deleteModel() unlinkSync unguarded → raw 500 on Windows EBUSY (low) **How it breaks the pipeline:** On Windows the GGUF may still be memory-mapped right after `stop()`, so `unlinkSync` throws EBUSY/EPERM before the config reset/persist, returning a raw HTTP 500 and a confusing silent no-op delete (inconsistent with `clearLegacyRuntimeStamp` which try/catches its unlink 30 lines below). **Steps to replicate:** On Windows, delete the local model immediately after stopping the server; observe a 500 and the delete appearing to fail. **Trace:** `unlinkSync(modelPath)` with no try/catch (sidecar-model.service.ts:789); config reset/saveConfig/status are after it (793-802); route has no try/catch → global handler maps to 500 (sidecar.routes.ts:273-282). Model is mmapped because `buildLlamaArgs` omits `--no-mmap` and `stopUnlocked` does not await final exit after SIGKILL. **Suggested Fix:** Wrap the unlink in a retry/try-catch (retry after a short delay for Windows handle release) and reset+persist config regardless of whether removal succeeded; surface a non-fatal warning instead of a 500. --- ### Affected files - `packages/server/src/routes/sidecar.routes.ts` - `packages/server/src/services/sidecar/sidecar-inference.service.ts` - `packages/server/src/services/sidecar/sidecar-model.service.ts` - `packages/client/src/stores/sidecar.store.ts` - `packages/client/src/components/modals/ModelDownloadModal.tsx` - `packages/client/src/lib/api-client.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: **MEDIUM**. Line numbers are against the `staging` working tree.
Author
Owner

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

Veracity self-review — correction / clarification
Automated post-filing review of this issue against the current working tree. The reported bug remains valid; the notes below refine its scope, accuracy, or suggested fix for whoever implements it.

Two clarifications after re-verifying against the tree:

  1. Scope — the same teardown-under-inference defect also affects POST /sidecar/restart. Claims #1/#2 cover /download, /download/custom and /unload, but POST /restart (sidecar.routes.ts:114-118) calls sidecarProcessService.restart() -> withLock -> stopUnlocked() (sidecar-process.service.ts:114-124, SIGTERM at :672 then SIGKILL at :682), which kills the shared llama-server mid-stream. It IS requirePrivilegedAccess-gated (sidecar.routes.ts:115) but has NO isInferenceBusy() check, so it tears down an in-flight tracker/scene/test request exactly like the other teardown routes (inference streaming runs after ensureReady() releases the lock, so a concurrent restart kills the child mid-response). The fix for #1/#2 should add the same if (isInferenceBusy()) return reply.status(409) guard to /restart as well.

  2. Description (claim #2) — "lacks the requirePrivilegedAccess gate every other mutating route has" is overstated. PATCH /sidecar/config (sidecar.routes.ts:87-96) mutates and persists config via updateConfig() with no requirePrivilegedAccess (and the inference routes /test-message, /analyze-scene, /tracker, /v1/embeddings also lack it). The precise framing: /unload is a destructive server-teardown route and should carry the same requirePrivilegedAccess gate that the comparably destructive DELETE /model (273-277) and /restart (114-118) already have. (Whether PATCH /config should also be gated is a separate question outside this issue.)

<!-- gh-comment-id:4761102805 --> @kolacheee commented on GitHub (Jun 21, 2026): > **Veracity self-review — correction / clarification** > _Automated post-filing review of this issue against the current working tree. The reported bug remains valid; the notes below refine its scope, accuracy, or suggested fix for whoever implements it._ Two clarifications after re-verifying against the tree: 1) Scope — the same teardown-under-inference defect also affects POST /sidecar/restart. Claims #1/#2 cover /download, /download/custom and /unload, but POST /restart (sidecar.routes.ts:114-118) calls sidecarProcessService.restart() -> withLock -> stopUnlocked() (sidecar-process.service.ts:114-124, SIGTERM at :672 then SIGKILL at :682), which kills the shared llama-server mid-stream. It IS requirePrivilegedAccess-gated (sidecar.routes.ts:115) but has NO isInferenceBusy() check, so it tears down an in-flight tracker/scene/test request exactly like the other teardown routes (inference streaming runs after ensureReady() releases the lock, so a concurrent restart kills the child mid-response). The fix for #1/#2 should add the same `if (isInferenceBusy()) return reply.status(409)` guard to /restart as well. 2) Description (claim #2) — "lacks the requirePrivilegedAccess gate every other mutating route has" is overstated. PATCH /sidecar/config (sidecar.routes.ts:87-96) mutates and persists config via updateConfig() with no requirePrivilegedAccess (and the inference routes /test-message, /analyze-scene, /tracker, /v1/embeddings also lack it). The precise framing: /unload is a destructive server-teardown route and should carry the same requirePrivilegedAccess gate that the comparably destructive DELETE /model (273-277) and /restart (114-118) already have. (Whether PATCH /config should also be gated is a separate question outside this issue.)
Author
Owner

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

Fixed in 5a481bb6. Added inference-busy guards for restart/download/custom-download/unload, privileged unload protection, SSE disconnect cancellation for model/runtime setup, client AbortController cancellation and late-cancel suppression, status reconciliation after failed setup requests, blocking setup UI for reloaded downloads/starts, and non-fatal retry handling for locked model deletion.

<!-- gh-comment-id:4761726773 --> @SpicyMarinara commented on GitHub (Jun 21, 2026): Fixed in 5a481bb6. Added inference-busy guards for restart/download/custom-download/unload, privileged unload protection, SSE disconnect cancellation for model/runtime setup, client AbortController cancellation and late-cancel suppression, status reconciliation after failed setup requests, blocking setup UI for reloaded downloads/starts, and non-fatal retry handling for locked model deletion.
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#1366
No description provided.