mirror of
https://github.com/Pasta-Devs/Marinara-Engine.git
synced 2026-12-03 19:00:50 +07:00
[GH-ISSUE #2717] [Issue]: Sidecar model/runtime provisioning trusts presence over content (unverified downloads, corrupt-file reuse, phantom MLX download, GPU runtime deleted on transient failure) #1361
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#1361
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/2717
Originally assigned to: @SpicyMarinara on GitHub.
Summary
Local model and runtime provisioning derives 'downloaded'/'ready'/'usable' from file presence or a socket binding rather than verified content, and it makes destructive, unconditional decisions (delete the whole HF cache, delete the GPU runtime, pin to one GPU) on weak signals. The result is phantom-downloaded models, corrupt files that can never be re-fetched in-app, and silent GPU→CPU demotions.
1. Downloads never verified (truncated model accepted) (high)
How it breaks the pipeline:
downloadFileWithProgressis the sole writer of model bytes fed tollama-server -m. A cleanly-ended but short HTTP body (chunked stream ending early, or no/zero Content-Length) is renamed in as the canonical model with nodownloaded === totalor checksum check; llama-server later fails to load it.Steps to replicate: Serve a curated GGUF over a connection that closes cleanly after fewer bytes than expected (chunked / no Content-Length). The short file is accepted as complete and blocks re-download.
Trace:
total = parseInt(content-length) || 0(sidecar-download.ts:107); loop pushes untildone(118-122) with no size comparison;renameSync(temp→dest)unconditionally after the pipeline resolves (148-149); status 'complete' emitted withtotal || downloaded(150-156).sha256?is declared (sidecar.ts:267) but never populated or read.Suggested Fix: After the pipeline resolves, assert
statSync(tempPath).size === total(whentotal>0) and/or compare a hash tomodelInfo.sha256beforerenameSync; throw on mismatch so the catch deletes the temp file.2. existsSync short-circuit reuses a corrupt file forever (high)
How it breaks the pipeline: Re-requesting the same quant/custom model reports 'complete' instantly without downloading because the (possibly corrupt/zero-byte) file 'exists', so the user can never recover via the Download button.
Steps to replicate: Truncate/zero the on-disk GGUF (or have bug #1 leave a short file), click Download again — instant 'complete', still broken.
Trace:
download()curated branch:if (existsSync(destination)) { status='downloaded'; emit complete with modelInfo.sizeBytes; return; }(sidecar-model.service.ts:566-583); identical indownloadCustomModel(693-714). Presence-only;getConfiguredModelSize(282-300) usesstatSync().sizeonly for display, never to gate.Suggested Fix: When the destination exists, validate
statSync(destination).sizeagainst expected size (with tolerance) and/or sha256; unlink and re-download on mismatch instead of treating existence as completion.3. MLX 'download' is a no-op (phantom local model) (high)
How it breaks the pipeline: On MLX,
download()/downloadCustomModel()only write config + status 'downloaded' and emit a synthetic 'complete' without fetching any bytes;modelDownloaded/modelSizereport a phantom local model, and the real ~6GB HF pull is deferred to the firstmlx_lm.serverlaunch — a multi-minute hang or hard failure offline behind a green 'ready' state.Steps to replicate: On Apple Silicon, download an MLX model (instant 'ready'), then send the first message — it hangs for minutes while weights download.
Trace: MLX branch sets
modelRepo,saveConfig, status 'downloaded', emits{status:'complete', downloaded: sizeBytes}and returns with nodownloadModelFile()(sidecar-model.service.ts:528-553, 648-674).hasConfiguredModelreturns true on!!modelRepo(278-280); real fetch deferred tomlx_lm.server --model <repo>(sidecar-process.service.ts:358-360). The 20-minwaitForReadybudget exists precisely to cover this.Suggested Fix: Pre-fetch the MLX repo into
MLX_HF_HOMEduringdownload()(e.g. uv-runsnapshot_downloadwith progress wired toonProgress) before status 'downloaded', or report a distinct 'downloading on first run' state so the UI/timeouts account for the inline fetch.4. MLX readiness probe marks ready before the model loads (medium)
How it breaks the pipeline:
mlx_lm.serveranswers/v1/modelsfrom its static registry as soon as the socket binds — before weights are fetched/loaded — somarkReady()flips status 'ready' (green UI) early; the first request then races a multi-minute load and can blow the 45s test-message / 5min budgets.Steps to replicate: Cold MLX model: status shows 'ready' immediately, but the first chat/test-message hangs or fails.
Trace:
waitForReadyprobes/v1/modelsfor MLX (sidecar-process.service.ts:632);startMlxUnlockedcallsmarkReady()immediately after (583-584). Upstreammlx_lm.serverloads lazily inside request handling, not at startup; llama.cpp's/healthreturns 503 until loaded, so the two backends are not equivalent.Suggested Fix: For MLX, gate readiness on an actual lightweight 1-token completion (or on the target model reporting loaded), not merely a 200 from
/v1/models.5. Switching MLX models wipes the whole shared HF cache (medium)
How it breaks the pipeline:
clearModelCache()rmSyncs the entireMLX_HF_HOME(the shared hub for ALL MLX models) on a model switch, so switching back re-downloads several GB; the llama.cpp path only deletes the single previous GGUF.Steps to replicate: Download two MLX models, switch between them; the previously cached model is gone and re-downloads.
Trace:
clearModelCache()doesrmSync(MLX_HF_HOME, {recursive,force})(mlx-runtime.service.ts:152-154);MLX_HF_HOME/hubis shared by all repos (sidecar-process.service.ts:573-574).cleanupPreviousModelcalls it wheneverpreviousBackend==='mlx'and repo differs (sidecar-model.service.ts:316-340).Suggested Fix: Delete only the previous repo's snapshot dir (
hub/models--<owner>--<repo>); reserve fullclearModelCache()for explicit delete/reset.6. Transient GPU boot failure permanently deletes the GPU runtime (medium)
How it breaks the pipeline: One failed GPU boot (VRAM momentarily busy, driver hiccup) triggers a cross-variant fallback that downloads a lower-tier runtime and then
cleanupBundledArtifactsdeletes every other runtime dir including the just-failed GPU one. The user is stuck on the slower runtime across launches.Steps to replicate: Cause a transient CUDA boot failure once (with a successful alternate download available); the CUDA runtime dir is wiped and replaced.
Trace: Any startup error on a GPU runtime calls
ensureRuntimeInstalled('llama_cpp', {excludeVariants})(sidecar-process.service.ts:482-486) with no error-type inspection →installLatest→writeCurrentInstall(sidecar-runtime.service.ts:561) →cleanupBundledArtifacts(562) whichrmSync-deletes non-kept dirs incl. the GPU one (404-427).Suggested Fix: Do not download+replace+delete on a transient failure; prefer already-installed alternates, keep the failed GPU runtime on disk, and reserve permanent replacement for confirmed-incompatible cases (missing CUDA DLLs).
7. Windows Vulkan false-negative without vulkaninfo.exe (medium)
How it breaks the pipeline:
detectVulkanSupporton Windows returns true only ifvulkaninfo --summarysucceeds; vulkaninfo ships with the Vulkan SDK and is absent on most consumer machines even with working drivers, sopreferVulkan=falseand the Vulkan build is never auto-selected — dropping AMD/Intel users to CPU after a HIP/SYCL boot failure.Steps to replicate: On a Windows AMD/Intel GPU box without the Vulkan SDK, let the vendor build fail to boot; the runtime resolves to CPU despite a usable Vulkan GPU.
Trace: Win32 returns
commandSucceeds('vulkaninfo', ['--summary'])else false (sidecar-runtime.service.ts:723-729);buildPreferredRuntimeVariantspusheswin-x64-vulkanonly whenpreferVulkan(sidecar-runtime-selection.ts:110); fallback recomputes the same capabilities.Suggested Fix: On Windows detect Vulkan via loader/ICD presence (
vulkan-1.dllin System32, orHKLM\SOFTWARE\Khronos\Vulkan\Drivers); treat vulkaninfo only as a positive signal.8. -sm none forced on every CUDA launch (medium)
How it breaks the pipeline:
-sm noneis pushed for ALL CUDA launches (not gated to the Gemma model its comment names), disabling multi-GPU split; a large BYO model that should split across GPUs is forced onto GPU 0, OOMs, and the per-plan fallback runs CPU-only.Steps to replicate: On a multi-GPU NVIDIA box, download a large BYO GGUF that needs both GPUs; it OOMs on GPU 0 and falls back to CPU.
Trace:
if (/cuda/i.test(runtimeVariant) && gpuLayers > 0) args.push('-sm', 'none')(sidecar-launch-plan.ts:38-39), unconditional, despite the line 36-37 'Gemma 4' comment; withgpuLayers=999all layers land on one device. OOM →SidecarServerExitError→ retryable → next plangpuLayers=0(CPU).Suggested Fix: Gate
-sm noneto the specific model family that needs it (detect from the model filename/path) or make it a config option; default multi-GPU CUDA launches should allow llama.cpp's normal layer split.Affected files
packages/server/src/services/sidecar/sidecar-download.tspackages/server/src/services/sidecar/sidecar-model.service.tspackages/server/src/services/sidecar/sidecar-process.service.tspackages/server/src/services/sidecar/sidecar-runtime.service.tspackages/server/src/services/sidecar/mlx-runtime.service.tspackages/server/src/services/sidecar/sidecar-launch-plan.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: HIGH. Line numbers are against the
stagingworking tree.@kolacheee commented on GitHub (Jun 21, 2026):
Two notes for fixers. These do NOT change any of the eight bug claims, all of which verified against the current tree (citations match within 0-1 lines).
Claim 6 (GPU runtime deleted on transient failure) — sharpen the suggested fix. The bundled-runtime system keeps exactly ONE install: a single current.json (getCurrentInstall reads one record, sidecar-runtime.service.ts:294-300), and cleanupBundledArtifacts() rmSyncs every directory except the just-written one (lines 418/424). When the GPU runtime fails to boot, ensureInstalled() excludes it via excludeVariants (line 340), so getCurrentInstall's GPU record can never be reused and the code always falls through to installLatest() -> writeCurrentInstall (561) -> cleanupBundledArtifacts(directoryName) (562), which deletes the GPU dir. Consequently the suggested-fix phrase "prefer already-installed alternates" is NOT achievable as written — there is never a second runtime on disk to prefer. The actionable fix is the rest of what the issue already proposes: stop the destructive cleanup of non-current runtime dirs on a transient boot failure, and keep the failed GPU runtime on disk so it survives across launches. Reserve permanent deletion/replacement for confirmed-incompatible cases — for Windows CUDA, findMissingWindowsCudaDlls(install.directoryPath).length > 0 already exists (helper at line 166, used as the usability gate at 362-363) and is the correct "permanent replacement" signal.
Claim 1 (download size assertion) — minor edge-case caveat (optional). Node's fetch (undici) auto-decompresses content-encoded responses, so on a gzip/deflate/br body the on-disk decoded size can legitimately exceed Content-Length, which would make a bare "statSync(tempPath).size === total" check fail on a complete download. In practice this never fires for raw GGUF over HuggingFace's LFS CDN (binary GGUF is not content-encoded), and the issue's "when total>0" guard already limits it, so this is a defensive nicety rather than a blocker. If implementing the size assertion, prefer the sha256 comparison when a hash is available — but note modelInfo.sha256 is currently unpopulated for every SIDECAR_MODELS entry, so the hash path requires populating those hashes first.
@SpicyMarinara commented on GitHub (Jun 21, 2026):
Fixed in
bca13ef6on the issue-sweep branch. Changes cover the still-valid findings: GGUF downloads now verify expected byte counts before promotion, existing corrupt/zero-byte model files are rejected and re-downloaded, MLX model downloads prefetch the HuggingFace snapshot and status checks require a real cached snapshot, MLX readiness waits for a tiny completion probe, switching MLX models clears only the previous repo cache, transient fallback installs no longer overwrite/delete the saved GPU runtime, Windows Vulkan detection checks the loader DLL when vulkaninfo is absent, and CUDA split-mode disabling is limited to Gemma-named models.