Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

refuse local media jobs when the vLLM container is holding the GPU (#4766)

[._.]/ Adam Eivy4381623b9eb2
diff --git a/docs/features/qwen38-rtx3090.md b/docs/features/qwen38-rtx3090.md
index 448bd44d27..177b86bb74 100644
--- a/docs/features/qwen38-rtx3090.md
+++ b/docs/features/qwen38-rtx3090.md
@@ -15,10 +15,22 @@ PortOS talks to `http://127.0.0.1:18020/v1` and nothing more.
**It holds the entire GPU.** The stack occupies roughly 23 GB of the 3090's
24 GB. Local image and video generation on the same card cannot run alongside
-it. There is no arbitration in PortOS: stop the container before a media job, or
-run media generation on a different machine. This is also why PortOS never
-auto-starts it — a container that came up on boot would silently take the card
-away from whatever else the box does.
+it. There is no arbitration in PortOS — but there is **detection**: every
+GPU-heavy local job (image, video, image-to-3D, LoRA training) probes this
+endpoint first and refuses up front, naming the container and the
+`docker compose --profile single stop` that frees the card, instead of dying
+with an out-of-memory error minutes into its model load (#4766). Stop the
+container before a media job, or run media generation on a different machine.
+
+PortOS will not stop it for you, in either direction: nothing would restart it, an
+agent session attached to it dies with it, and a cold start is ~5–7 minutes. That
+symmetry is also why PortOS never auto-starts it — a container that came up on
+boot would silently take the card away from whatever else the box does.
+
+The probe costs nothing on a machine this does not apply to: it is skipped
+entirely when no `vllmBacked` provider is enabled, and on any host without an
+NVIDIA GPU. A probe that fails or times out means the container is *not* serving,
+so the job proceeds — "couldn't check" never becomes "blocked".
**Apple Silicon is not supported.** DFlash 2 has not been proven on Apple
Silicon in this project, and this is a CUDA / Marlin / FlashInfer container —
diff --git a/server/lib/README.md b/server/lib/README.md
index e2c0f4c16d..af3ccd1ede 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -186,7 +186,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `imageRgba.js` | Sharp-backed RGBA boundary: `decodeRgbaFrame` decodes an image to `{ data, width, height }`, and `encodePng` turns a raw frame into PNG bytes for the caller's destination/hash policy. |
| `imageWatermark.js` | `removeCornerWatermark` (erases the visible Gemini/Nano-Banana bottom-right ✦ via dependency-free harmonic/Laplace inpaint) + pure helpers `resolveWatermarkRegion` / `inpaintRegion`. Distinct from SynthID regen — this targets the *visible* corner logo. |
| `localImageFilename.js` | `localImageFilename(urlOrPath)` resolves a stored image reference to the bare gallery-image filename under `data/images/` (or null for empty/external-URL/non-image-path) — the unit the peer-sync asset pipeline hashes + transfers. Single source of truth for the authors/artists/albums/Creative-Director filename resolvers (`headshotImageFilename`/`portraitImageFilename`/`coverImageFilename`/`startingImageFilename` are thin wrappers). Also exports `assetBasename(pathOrName)`, the shared strip-querystring→basename primitive (reused by moodBoard's `imageUrlToAppAsset`). |
-| `localMemory.js` | Shared best-effort local-model unload + available-memory report (`prepareLocalMemory`) for GPU-heavy local work; only loopback Ollama / LM Studio backends are evicted. |
+| `localMemory.js` | Shared preflight for GPU-heavy local work: `prepareLocalMemory` unloads resident local models (only loopback Ollama / LM Studio backends are evicted) and reports available memory, plus a `blockers` array from `detectGpuBlockers` — a serving vLLM Qwen container holds ~23 GB of a 24 GB card, is invisible to the unload path, and would otherwise fail the job with an OOM inside model load naming neither vLLM nor a remedy. Detect and refuse, never auto-stop (#4766): `gpuBlockersMessage` renders the refusal that names `docker compose --profile single stop` and its project directory. Skips the probe entirely with no enabled `vllmBacked` provider or on a non-CUDA host, and a failed/timed-out probe never blocks. |
| `threejsModel.js` | Validated declarative procedural-model schema plus deterministic standalone Three.js factory export for the Three.js Models workspace. Also the cross-section gate: `evaluateThreejsFlatness(spec)` counts distinct vertex planes per axis — relative to the mesh's own size, with a rotation-invariant zero-volume check behind it — and treats an `extrude` with no bevel thickness as the two-plane slab it is to report when the majority of identity-priority features are built only from flat parts — a model that reads right head-on and like cardboard when orbited. `buildThreejsFlatnessFeedback(flatness)` turns that into default refinement feedback; `listSpecNames(names)` is the shared capped name-list formatter both gates use in finding messages. Also the material-plausibility gate: `evaluateThreejsMaterialPlausibility(spec)` keys a bounded per-family prior table (metal, wood, plastic, glass, fabric, ceramic, rubber, stone, leather, paper) off tokens in each material's id and reports channels whose values the named substance does not support — metalness 0.9 oak, transmission 1.0 steel — skipping any id that names no family or two, and any channel the material's `type` never forwards to Three.js. Advisory only: it never clamps, because a stylized model may legitimately break every prior. `buildThreejsMaterialFeedback(plausibility)` turns that into default refinement feedback. The same pass emits a `reflective-material-without-environment` note when a spec authors reflective channels (metalness above 0.6, or any transmission/clearcoat/iridescence) while `environment.preset` is `none` — those channels read off an environment, so in that scene their values cannot be judged at all. Attachments are declared in two forms — the original anchor-less `attachmentPartIds` and the anchored `attachments: [{ partId, anchorPartId | anchorSocket, maxOffset }]` — and `resolveThreejsAttachments(articulation)` merges them into one canonical list (an anchored entry wins over a bare id) so every gate reads the same set; `isThreejsAttachmentAnchored(attachment)` is the shared anchored/unanchored predicate and `DEFAULT_ATTACHMENT_MAX_OFFSET` the default tolerance. The spec-level refinement rejects an anchor that does not resolve, one that is the attachment itself, an anchor chain that cycles, and the model root (the sole top-level part) — which carries no relationship to any body part. The spec carries an optional `environment` block (see `threejsModelEnvironment.js`), and `buildThreejsFactorySource()` stamps its render profile onto `root.userData.sculptRuntime.render` and exports it as `renderProfile`, so a consumer wiring their own `WebGLRenderer` reproduces the model instead of a differently tone-mapped approximation. |
| `threejsModelAnimation.js` | `summarizeThreejsAnimation(spec)` — clip inventory *and* playback gate over an already-validated Three.js spec: `{ animated, clipCount, cueCount, sequenceCount, movingPartCount, longestClipSeconds, findings, warningCount, clips }`. The schema proves a declared `animation` block is well *formed* (sequences on real parts, inside their clip, never two on one channel at once, never a cue without motion); this reports what the model *declared* — one entry per clip with its role, duration, sequence and distinct-cue counts — plus the ways a well-formed clip still plays badly: a clip authored against a pose the assembly does not build (`clip-start-pose-mismatch`), a handover between sequences that do not meet (`clip-sequence-jump`), a `loop: true` clip that does not return to where it began, a one-shot `idle`, an unfired cue, a long dead tail, and an articulation graph with no clip at all. Advisory warnings only — a static assembly is a complete answer. `buildThreejsAnimationFeedback(animation)` turns those findings into default refinement feedback. A spec with no `animation` key summarizes as not animated — never as evaluated-and-empty. |
| `threejsModelCoverage.js` | `evaluateThreejsPartCoverage(spec, { family })` — structural assembly gate over an already-validated Three.js spec: flags promised features fused onto the same part set, geometry claimed by no detail, and details nothing was built for (folded minor relief stays a `note`). With a subject family it also warns on a required component the spec never mentions at all — the one check that can fault a spec for what it failed to *promise*. `buildThreejsCoverageFeedback(coverage)` turns the error findings (plus any family gap) into default refinement feedback. |
diff --git a/server/lib/localMemory.js b/server/lib/localMemory.js
index d7a368a6f0..fbf3130f2e 100644
--- a/server/lib/localMemory.js
+++ b/server/lib/localMemory.js
@@ -5,6 +5,11 @@ import { platform, freemem, totalmem } from 'os';
import { promisify } from 'util';
import { getLoadedModels as ollamaLoadedModels, unloadModel as ollamaUnload, getBaseUrl as ollamaBaseUrl } from '../services/ollamaManager.js';
import { getLoadedModels as lmStudioLoadedModels, unloadModel as lmStudioUnload, getBaseUrl as lmStudioBaseUrl } from '../services/lmStudioManager.js';
+import { getAllProviders } from '../services/providers.js';
+import { probeOpenAiModels } from './openAiModelsProbe.js';
+import { getCudaCapability } from './cudaCapability.js';
+import { localRuntimeForProvider, LOCAL_RUNTIMES } from './localProviderRuntime.js';
+import { resolveVllmProjectDir } from './vllmQwenProject.js';
const execFileAsync = promisify(execFile);
const GB = 2 ** 30;
@@ -36,6 +41,110 @@ export async function unloadResidentModels() {
return unloaded;
}
+/**
+ * Short on purpose. This runs on the hot path of every GPU-heavy local job, and
+ * the only question it asks is whether something on loopback answers *now* — a
+ * container that needs longer than this to reply is not the thing about to lose
+ * the VRAM race.
+ */
+export const GPU_BLOCKER_PROBE_TIMEOUT_MS = 1_500;
+
+/**
+ * The refusal prose for a serving vLLM container. Written the way
+ * `vllmStartBlockedReason` writes its refusals: it names the one command that
+ * fixes it, and says why PortOS will not run that command for the operator.
+ */
+const vllmBlockerReason = ({ endpoint, projectDir }) =>
+ `${LOCAL_RUNTIMES.vllm.label} is serving at ${endpoint} and holds nearly all of this GPU's VRAM, so this job would run out of memory partway through its model load. Stop the container with \`docker compose --profile single stop\` in ${projectDir}, then start this job again. PortOS will not stop it for you: nothing would restart it, an agent session attached to it dies with it, and a cold start takes roughly 5–7 minutes.`;
+
+/**
+ * GPU tenants that make a local media job unwinnable *before* it spends minutes
+ * loading a model into VRAM it cannot have.
+ *
+ * Today that is exactly one thing: the vLLM Qwen3.8-27B compose container, which
+ * holds ~23 GB of a 24 GB RTX 3090. `unloadResidentModels()` above cannot help —
+ * it evicts loopback Ollama / LM Studio, and a container is invisible to both.
+ * The job therefore proceeded, allocated, and died inside the model load with an
+ * OOM naming neither vLLM nor a remedy.
+ *
+ * **Detect and refuse — never auto-stop** (#4766). An Ollama unload is
+ * transparent (the next request reloads); stopping this container is not.
+ * Nothing restarts it, an attached CoS session dies with it, and a cold start is
+ * ~5–7 minutes. PortOS deliberately never *starts* this container either — both
+ * directions stay operator decisions, and the refusal prose is what makes that
+ * actionable.
+ *
+ * **Sentinel discipline.** A probe that fails, times out, or throws means "the
+ * container is not serving" → **no blocker, proceed**. *Couldn't check* must
+ * never collapse into *is blocking*, or an unrelated network hiccup would refuse
+ * every media job on the box. Only an endpoint that actually answers blocks —
+ * including a 401/403, which is a container up behind `VLLM_API_KEY`.
+ *
+ * Two cheap gates keep the common path free of latency, in cost order:
+ * 1. No **enabled** `vllmBacked` provider → nothing to probe, no network call.
+ * 2. `getCudaCapability()` says `'absent'` → this host has no NVIDIA GPU to
+ * contend over. `'unknown'` (nvidia-smi wedged or too old) is NOT a
+ * negative and still probes — same sentinel rule as above, in the other
+ * direction.
+ *
+ * @param {{env?: NodeJS.ProcessEnv, providers?: Array<object>|null, timeoutMs?: number}} [opts]
+ * `providers` is injectable for tests; production reads the provider store.
+ * @returns {Promise<Array<{runtime: string, providerId: string|null, providerName: string|null,
+ * endpoint: string, reason: string}>>} empty when nothing is holding the GPU
+ */
+export async function detectGpuBlockers({ env = process.env, providers = null, timeoutMs = GPU_BLOCKER_PROBE_TIMEOUT_MS } = {}) {
+ const all = Array.isArray(providers) ? providers : await getAllProviders().catch(() => []);
+ const candidates = (Array.isArray(all) ? all : []).filter((p) => p?.enabled === true && p?.vllmBacked === true);
+ if (!candidates.length) return [];
+
+ // No custom timeout: this shares the memo the image-to-3D lane gating already
+ // fills, and a shorter deadline here would write an 'unknown' into it that the
+ // other reader would have to treat as "couldn't detect".
+ const cuda = await getCudaCapability().catch(() => null);
+ if (cuda?.status === 'absent') return [];
+
+ // Two providers can point at one container with different credentials, and a
+ // remote endpoint is a different machine's GPU — `localRuntimeForProvider`
+ // drops the latter and returns null for it.
+ const byEndpoint = new Map();
+ for (const provider of candidates) {
+ const runtime = localRuntimeForProvider(provider);
+ if (runtime?.kind !== 'vllm' || !runtime.endpoint) continue;
+ const existing = byEndpoint.get(runtime.endpoint);
+ // Prefer the credentialed record: an unauthenticated probe still detects the
+ // container (401 ⇒ reachable), but a readable listing is the cleaner signal.
+ if (!existing || (!existing.apiKey && typeof provider.apiKey === 'string' && provider.apiKey !== '')) {
+ byEndpoint.set(runtime.endpoint, { provider, apiKey: typeof provider.apiKey === 'string' ? provider.apiKey : '' });
+ }
+ }
+ if (!byEndpoint.size) return [];
+
+ const projectDir = resolveVllmProjectDir(env);
+ const probes = await Promise.all([...byEndpoint].map(async ([endpoint, { provider, apiKey }]) => {
+ const probe = await probeOpenAiModels(endpoint, { timeoutMs, apiKey }).catch(() => null);
+ if (!probe?.reachable) return null;
+ return {
+ runtime: 'vllm',
+ providerId: provider?.id ?? null,
+ providerName: provider?.name ?? null,
+ endpoint,
+ reason: vllmBlockerReason({ endpoint, projectDir }),
+ };
+ }));
+ return probes.filter(Boolean);
+}
+
+/**
+ * One refusal message for a `blockers` array, so all four GPU-heavy callers word
+ * the refusal identically instead of each joining the reasons their own way.
+ *
+ * @param {Array<{reason?: string}>|null|undefined} blockers
+ * @returns {string} `''` when nothing is blocking — callers gate on
+ * `blockers.length`, never on this string
+ */
+export const gpuBlockersMessage = (blockers) =>
+ (Array.isArray(blockers) ? blockers : []).map((b) => b?.reason).filter(Boolean).join(' ');
+
const parsePageSize = (out) => Number(out.match(/page size of (\d+) bytes/i)?.[1] || 4096);
async function darwinAvailableGb() {
@@ -54,9 +163,21 @@ export async function getAvailableMemoryGb() {
return freemem() / GB;
}
+/**
+ * The preflight every GPU-heavy local job runs: refuse-or-reclaim, then report
+ * the headroom the caller sizes its run against.
+ *
+ * `blockers` is additive (#4766) — a non-empty array means the job cannot
+ * succeed no matter how much system RAM is free, and the caller must fail fast
+ * with `gpuBlockersMessage(...)` rather than start a model load.
+ *
+ * Nothing is unloaded while blocked: evicting the user's resident LLM is a real
+ * cost, and paying it for a run that is about to be refused helps nobody.
+ */
export async function prepareLocalMemory() {
- const unloaded = await unloadResidentModels().catch(() => []);
+ const blockers = await detectGpuBlockers().catch(() => []);
+ const unloaded = blockers.length ? [] : await unloadResidentModels().catch(() => []);
const availableGb = await getAvailableMemoryGb().catch(() => 0);
const totalGb = totalmem() / GB;
- return { unloaded, availableGb, totalGb, budgetGb: Math.min(totalGb, availableGb) };
+ return { unloaded, availableGb, totalGb, budgetGb: Math.min(totalGb, availableGb), blockers };
}
diff --git a/server/lib/localMemory.test.js b/server/lib/localMemory.test.js
new file mode 100644
index 0000000000..79b0d0a920
--- /dev/null
+++ b/server/lib/localMemory.test.js
@@ -0,0 +1,187 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+// Hoisted mock state so the factory closures below can reach it.
+const h = vi.hoisted(() => ({
+ providers: [],
+ providersThrows: false,
+ cuda: { status: 'available' },
+ probe: vi.fn(),
+ ollamaUnload: vi.fn(),
+ lmUnload: vi.fn(),
+}));
+
+vi.mock('../services/ollamaManager.js', () => ({
+ getLoadedModels: vi.fn(async () => [{ name: 'llama3' }]),
+ unloadModel: (...a) => h.ollamaUnload(...a),
+ getBaseUrl: () => 'http://localhost:11434',
+}));
+vi.mock('../services/lmStudioManager.js', () => ({
+ getLoadedModels: vi.fn(async () => []),
+ unloadModel: (...a) => h.lmUnload(...a),
+ getBaseUrl: () => 'http://localhost:1234',
+}));
+vi.mock('../services/providers.js', () => ({
+ getAllProviders: vi.fn(async () => {
+ // The real one rejects when the AI toolkit was never initialized — the
+ // failure mode this module must survive without blocking a job.
+ if (h.providersThrows) throw new Error('toolkit not initialized');
+ return h.providers;
+ }),
+}));
+vi.mock('./cudaCapability.js', () => ({ getCudaCapability: vi.fn(async () => h.cuda) }));
+vi.mock('./openAiModelsProbe.js', () => ({ probeOpenAiModels: (...a) => h.probe(...a) }));
+
+const { detectGpuBlockers, gpuBlockersMessage, prepareLocalMemory } = await import('./localMemory.js');
+const { getCudaCapability } = await import('./cudaCapability.js');
+
+const VLLM_ENDPOINT = 'http://127.0.0.1:18020/v1';
+const vllmProvider = (over = {}) => ({
+ id: 'opencode-vllm-tui', name: 'OpenCode vLLM TUI', enabled: true, vllmBacked: true,
+ endpoint: VLLM_ENDPOINT, ...over,
+});
+const serving = { reachable: true, models: ['qwen3.8-27b'], error: null };
+const notServing = { reachable: false, models: null, error: 'ECONNREFUSED' };
+
+beforeEach(() => {
+ h.providers = [];
+ h.providersThrows = false;
+ h.cuda = { status: 'available' };
+ h.probe = vi.fn(async () => serving);
+ h.ollamaUnload = vi.fn(async () => ({ unloaded: true }));
+ h.lmUnload = vi.fn(async () => ({ success: true }));
+ getCudaCapability.mockClear();
+ // A deliberately fake home so no assertion can be answered by the developer's
+ // real `~/qwen-serving`.
+ process.env.VLLM_QWEN_PROJECT_DIR = '/srv/example/qwen-serving';
+});
+
+describe('detectGpuBlockers', () => {
+ it('issues no probe when no vllmBacked provider is enabled', async () => {
+ h.providers = [{ id: 'ollama', enabled: true, ollamaBacked: true, endpoint: 'http://127.0.0.1:11434/v1' }];
+ await expect(detectGpuBlockers()).resolves.toEqual([]);
+ expect(h.probe).not.toHaveBeenCalled();
+ // The cheapest gate first: a host with nothing to contend over never even
+ // pays for the (memoized, but still spawning) nvidia-smi probe.
+ expect(getCudaCapability).not.toHaveBeenCalled();
+ });
+
+ it('issues no probe when the only vllmBacked provider is disabled', async () => {
+ h.providers = [vllmProvider({ enabled: false })];
+ await expect(detectGpuBlockers()).resolves.toEqual([]);
+ expect(h.probe).not.toHaveBeenCalled();
+ });
+
+ it('issues no probe on a non-CUDA host', async () => {
+ h.providers = [vllmProvider()];
+ h.cuda = { status: 'absent' };
+ await expect(detectGpuBlockers()).resolves.toEqual([]);
+ expect(h.probe).not.toHaveBeenCalled();
+ });
+
+ it('still probes when the CUDA probe itself could not answer', async () => {
+ // `unknown` means nvidia-smi failed, NOT that there is no GPU — collapsing
+ // the two would silently disarm the guard on a host with a wedged driver.
+ h.providers = [vllmProvider()];
+ h.cuda = { status: 'unknown' };
+ await expect(detectGpuBlockers()).resolves.toHaveLength(1);
+ });
+
+ it('reports a blocker when the container answers', async () => {
+ h.providers = [vllmProvider()];
+ const blockers = await detectGpuBlockers();
+ expect(blockers).toEqual([expect.objectContaining({
+ runtime: 'vllm', providerId: 'opencode-vllm-tui', endpoint: VLLM_ENDPOINT,
+ })]);
+ expect(h.probe).toHaveBeenCalledWith(VLLM_ENDPOINT, expect.objectContaining({ apiKey: '' }));
+ });
+
+ it('names the container, the project directory and the stop command', async () => {
+ h.providers = [vllmProvider()];
+ const [blocker] = await detectGpuBlockers();
+ expect(blocker.reason).toContain('vLLM (Qwen3.8-27B)');
+ expect(blocker.reason).toContain('/srv/example/qwen-serving');
+ expect(blocker.reason).toContain('docker compose --profile single stop');
+ // The decision in #4766: PortOS refuses, it never stops the container.
+ expect(blocker.reason).toMatch(/will not stop it for you/i);
+ });
+
+ it('reads the project directory off the passed env, not the ambient one', async () => {
+ h.providers = [vllmProvider()];
+ const [blocker] = await detectGpuBlockers({ env: { VLLM_QWEN_PROJECT_DIR: '/opt/example/vllm' } });
+ expect(blocker.reason).toContain('/opt/example/vllm');
+ });
+
+ it('does not block when the probe says nothing is serving', async () => {
+ h.providers = [vllmProvider()];
+ h.probe = vi.fn(async () => notServing);
+ await expect(detectGpuBlockers()).resolves.toEqual([]);
+ });
+
+ it('does not block when the probe times out', async () => {
+ h.providers = [vllmProvider()];
+ h.probe = vi.fn(async () => ({ reachable: false, models: null, error: 'timed out' }));
+ await expect(detectGpuBlockers()).resolves.toEqual([]);
+ });
+
+ it('does not block when the probe throws outright', async () => {
+ h.providers = [vllmProvider()];
+ h.probe = vi.fn(async () => { throw new Error('boom'); });
+ await expect(detectGpuBlockers()).resolves.toEqual([]);
+ });
+
+ it('does block on a 401 — a container behind VLLM_API_KEY is definitively up', async () => {
+ h.providers = [vllmProvider()];
+ h.probe = vi.fn(async () => ({ reachable: true, models: null, error: 'authentication required' }));
+ await expect(detectGpuBlockers()).resolves.toHaveLength(1);
+ });
+
+ it('does not block on a vLLM served from another machine', async () => {
+ // Another box's GPU is not this box's GPU — `localRuntimeForProvider` drops it.
+ h.providers = [vllmProvider({ endpoint: 'http://192.0.2.10:18020/v1' })];
+ await expect(detectGpuBlockers()).resolves.toEqual([]);
+ expect(h.probe).not.toHaveBeenCalled();
+ });
+
+ it('probes one endpoint once and prefers the credentialed record', async () => {
+ h.providers = [
+ vllmProvider({ id: 'a', apiKey: '' }),
+ vllmProvider({ id: 'b', apiKey: 'vllm-key' }),
+ ];
+ const blockers = await detectGpuBlockers();
+ expect(blockers).toHaveLength(1);
+ expect(h.probe).toHaveBeenCalledTimes(1);
+ expect(h.probe).toHaveBeenCalledWith(VLLM_ENDPOINT, expect.objectContaining({ apiKey: 'vllm-key' }));
+ });
+
+ it('does not block when the provider store cannot be read', async () => {
+ h.providersThrows = true;
+ await expect(detectGpuBlockers()).resolves.toEqual([]);
+ expect(h.probe).not.toHaveBeenCalled();
+ });
+});
+
+describe('gpuBlockersMessage', () => {
+ it('joins every reason and tolerates an empty or absent list', () => {
+ expect(gpuBlockersMessage([{ reason: 'one.' }, { reason: 'two.' }])).toBe('one. two.');
+ expect(gpuBlockersMessage([])).toBe('');
+ expect(gpuBlockersMessage(undefined)).toBe('');
+ });
+});
+
+describe('prepareLocalMemory', () => {
+ it('reports no blockers and still unloads on a clean host', async () => {
+ const report = await prepareLocalMemory();
+ expect(report.blockers).toEqual([]);
+ expect(report.unloaded).toEqual(['ollama:llama3']);
+ });
+
+ it('evicts nothing while blocked — the job is about to be refused', async () => {
+ h.providers = [vllmProvider()];
+ const report = await prepareLocalMemory();
+ expect(report.blockers).toHaveLength(1);
+ expect(report.unloaded).toEqual([]);
+ expect(h.ollamaUnload).not.toHaveBeenCalled();
+ // The headroom fields stay populated so no caller trips over `undefined`.
+ expect(Number.isFinite(report.budgetGb)).toBe(true);
+ });
+});
diff --git a/server/services/imageGen/local.js b/server/services/imageGen/local.js
index e0ddacfbfb..e9be74bf64 100644
--- a/server/services/imageGen/local.js
+++ b/server/services/imageGen/local.js
@@ -31,7 +31,7 @@ import { extractGatedRepo, isGatedRepoError } from '../../lib/hfErrors.js';
import { killWithEscalation } from '../../lib/killWithEscalation.js';
import { createLineReader } from '../../lib/streamLines.js';
import { claimHeavyLocalJob } from '../../lib/heavyJobClaim.js';
-import { prepareLocalMemory } from '../../lib/localMemory.js';
+import { prepareLocalMemory, gpuBlockersMessage } from '../../lib/localMemory.js';
import { safeChildProcessOptions } from '../../lib/processEnv.js';
import { IMAGE_GEN_MODE, LOCAL_IMAGEGEN_DEFAULT_MODEL } from './modes.js';
import { computePixelDelta } from './regen.js';
@@ -599,6 +599,12 @@ export async function generateImage({ pythonPath, prompt = '', negativePrompt =
let claimHandedOff = false;
try {
const memoryReport = await prepareLocalMemory();
+ // Something the unload above cannot evict already owns the GPU (today: the
+ // vLLM Qwen container). Refuse here rather than let mflux die inside its
+ // model load with an OOM that names neither the tenant nor the fix (#4766).
+ if (memoryReport.blockers.length) {
+ throw new ServerError(gpuBlockersMessage(memoryReport.blockers), { status: 409, code: 'GPU_BLOCKED', context: { blockers: memoryReport.blockers } });
+ }
if (memoryReport.unloaded.length) console.log(`🧹 Image generation [${jobId.slice(0, 8)}] freed ${memoryReport.unloaded.length} resident model(s)`);
console.log(`🎨 Generating image [${jobId.slice(0, 8)}] local: ${modelId} ${width}x${height} steps=${actualSteps}`);
@@ -610,7 +616,14 @@ export async function generateImage({ pythonPath, prompt = '', negativePrompt =
await heavyClaim.handoffTo?.(proc.pid);
claimHandedOff = true;
} catch (err) {
- if (!claimHandedOff) await releaseHeavyClaim();
+ // Nothing is wired to this job yet, so it can never report its own terminal
+ // event — unwind it exactly the way the busy branch above does, or a refusal
+ // strands a `running` entry and its stepwise dir every time.
+ if (!claimHandedOff) {
+ await releaseHeavyClaim();
+ jobs.delete(jobId);
+ await rm(stepwiseDir, { recursive: true, force: true }).catch(() => {});
+ }
throw err;
}
// Spawn ENOENT (missing/non-executable pythonPath) fires BOTH 'error' and
diff --git a/server/services/imageTo3d/models.js b/server/services/imageTo3d/models.js
index 9d805b5058..3387107d5c 100644
--- a/server/services/imageTo3d/models.js
+++ b/server/services/imageTo3d/models.js
@@ -21,7 +21,7 @@ import { rm, access } from 'node:fs/promises';
import { ServerError } from '../../lib/errorHandler.js';
import { PATHS, resolveGalleryImage, ensureDir } from '../../lib/fileUtils.js';
import { claimHeavyLocalJob } from '../../lib/heavyJobClaim.js';
-import { prepareLocalMemory } from '../../lib/localMemory.js';
+import { prepareLocalMemory, gpuBlockersMessage } from '../../lib/localMemory.js';
import { slugifyForFilename } from '../../lib/civitai.js';
import {
detectHostCapabilities, resolveTarget, renderOptionSupportFor, DEFAULT_IMAGE_TO_3D_TARGET,
@@ -180,6 +180,12 @@ async function executeRender({ id, operationId, adapter, sourcePath, caps, optio
throw new ServerError(heavyClaim.message, { status: 409, code: 'HEAVY_LOCAL_JOB_BUSY', context: { holder: heavyClaim.holder } });
}
const memoryReport = await prepareLocalMemory();
+ // A GPU tenant the unload path cannot evict (today: the vLLM Qwen container)
+ // makes this render unwinnable — refuse before the model load rather than
+ // after minutes of it, with the prose that names the stop command.
+ if (memoryReport.blockers.length) {
+ throw new ServerError(gpuBlockersMessage(memoryReport.blockers), { status: 409, code: 'GPU_BLOCKED', context: { blockers: memoryReport.blockers } });
+ }
if (memoryReport.unloaded.length) console.log(`🧹 Image-to-3D render freed ${memoryReport.unloaded.length} resident model(s)`);
// Resolve this target's own credential/env needs via its adapter (e.g.
// TRELLIS.2 resolves the stored Hugging Face token) — omitted for a target
diff --git a/server/services/imageTo3d/models.test.js b/server/services/imageTo3d/models.test.js
index 62eb5c1891..99f43e4ce7 100644
--- a/server/services/imageTo3d/models.test.js
+++ b/server/services/imageTo3d/models.test.js
@@ -51,8 +51,9 @@ const { claimRelease } = vi.hoisted(() => ({ claimRelease: vi.fn(async () => {})
vi.mock('../../lib/heavyJobClaim.js', () => ({
claimHeavyLocalJob: vi.fn(async () => ({ ok: true, holder: {}, release: claimRelease })),
}));
-vi.mock('../../lib/localMemory.js', () => ({
- prepareLocalMemory: vi.fn(async () => ({ unloaded: [], availableGb: 64, totalGb: 64, budgetGb: 64 })),
+vi.mock('../../lib/localMemory.js', async (importOriginal) => ({
+ ...(await importOriginal()),
+ prepareLocalMemory: vi.fn(async () => ({ unloaded: [], availableGb: 64, totalGb: 64, budgetGb: 64, blockers: [] })),
}));
vi.mock('./db.js', () => ({
diff --git a/server/services/loraTraining/index.js b/server/services/loraTraining/index.js
index ba630524c6..5aef3eed46 100644
--- a/server/services/loraTraining/index.js
+++ b/server/services/loraTraining/index.js
@@ -42,7 +42,7 @@ import {
} from './runtimes.js';
import { makeTrainingLineHandler } from './progress.js';
import { makeStallDetector } from './stallDetector.js';
-import { prepareMemoryForTraining, TRAINING_MIN_HEADROOM_GB } from './memoryPrep.js';
+import { prepareMemoryForTraining, gpuBlockersMessage, TRAINING_MIN_HEADROOM_GB } from './memoryPrep.js';
import { claimHeavyLocalJob, adoptHeavyLocalJob } from '../../lib/heavyJobClaim.js';
import { classifyTrainingFailure } from './failure.js';
import { buildTrainedSidecar, trainedLoraFilename } from './sidecar.js';
@@ -530,6 +530,11 @@ export async function runTraining({ jobId, runId, pythonPath = null, resumeCheck
// (rather than crash mid-run) when headroom is below the floor. The budget
// also sizes the mflux quantize/low_ram tier below.
const memReport = await prepareMemoryForTraining();
+ // A GPU tenant the unload path cannot evict (today: the vLLM Qwen container)
+ // makes the run unwinnable regardless of system-RAM headroom, so it is checked
+ // BEFORE the budget gate below — that gate reports free system RAM, which says
+ // nothing about VRAM on exactly the discrete-GPU host this matters on.
+ if (memReport.blockers.length) return failBeforeSpawn(gpuBlockersMessage(memReport.blockers));
if (memReport.unloaded.length) {
console.log(`🧹 training [${shortId(jobId)}] freed ${memReport.unloaded.length} resident model(s): ${memReport.unloaded.join(', ')}`);
}
diff --git a/server/services/loraTraining/memoryPrep.js b/server/services/loraTraining/memoryPrep.js
index 1d50930418..304db3eb7e 100644
--- a/server/services/loraTraining/memoryPrep.js
+++ b/server/services/loraTraining/memoryPrep.js
@@ -2,7 +2,7 @@
import { prepareLocalMemory } from '../../lib/localMemory.js';
-export { unloadResidentModels, getAvailableMemoryGb, isLocalBackendUrl } from '../../lib/localMemory.js';
+export { unloadResidentModels, getAvailableMemoryGb, isLocalBackendUrl, gpuBlockersMessage } from '../../lib/localMemory.js';
// Below this floor even a small 4-bit training run risks swap-thrash. Larger
// run sizing remains training-specific and still consumes `budgetGb` below.
diff --git a/server/services/loraTraining/memoryPrep.test.js b/server/services/loraTraining/memoryPrep.test.js
index d9953b3a2b..107cbe9152 100644
--- a/server/services/loraTraining/memoryPrep.test.js
+++ b/server/services/loraTraining/memoryPrep.test.js
@@ -25,7 +25,11 @@ vi.mock('../../services/lmStudioManager.js', () => ({
unloadModel: (...a) => h.lmUnload(...a),
getBaseUrl: () => h.lmUrl,
}));
-vi.mock('os', () => ({
+// Spread the real module: the preflight's own dependency graph reaches other
+// `os` exports (`homedir`, via the vLLM project-dir resolver), and a
+// listed-exports-only mock fails the whole file the moment it reaches one more.
+vi.mock('os', async (importOriginal) => ({
+ ...(await importOriginal()),
platform: () => h.platform,
totalmem: () => h.totalBytes,
freemem: () => h.freeBytes,
diff --git a/server/services/videoGen/local.js b/server/services/videoGen/local.js
index 17a739f7cf..a134bd215d 100644
--- a/server/services/videoGen/local.js
+++ b/server/services/videoGen/local.js
@@ -22,7 +22,7 @@ import { spawnDetached } from '../../lib/detachedSpawn.js';
import { killWithEscalation } from '../../lib/killWithEscalation.js';
import { createLineReader } from '../../lib/streamLines.js';
import { claimHeavyLocalJob } from '../../lib/heavyJobClaim.js';
-import { prepareLocalMemory } from '../../lib/localMemory.js';
+import { prepareLocalMemory, gpuBlockersMessage } from '../../lib/localMemory.js';
import { ServerError } from '../../lib/errorHandler.js';
import { videoLoraLayoutIssue } from '../../lib/safetensors.js';
import { videoGenEvents } from './events.js';
@@ -2120,6 +2120,11 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m
try {
const memoryReport = await prepareLocalMemory();
+ // Something else already owns the GPU (today: the vLLM Qwen container). Refuse
+ // here rather than let the render die inside its model load with an OOM that
+ // names neither the tenant nor the fix — the throw converges on
+ // abandonBeforeWiring like every other pre-wiring failure.
+ if (memoryReport.blockers.length) throw new Error(gpuBlockersMessage(memoryReport.blockers));
if (memoryReport.unloaded.length) console.log(`🧹 Video generation [${jobId.slice(0, 8)}] freed ${memoryReport.unloaded.length} resident model(s)`);
// History-calibrated wall-clock estimate (#3801). `null` when this install
diff --git a/server/services/videoGen/local.test.js b/server/services/videoGen/local.test.js
index a68fcd625b..633c2d538e 100644
--- a/server/services/videoGen/local.test.js
+++ b/server/services/videoGen/local.test.js
@@ -16,14 +16,15 @@ const { heavyClaimRelease, heavyClaimHandoff, mockPrepareLocalMemory } = vi.hois
// omitted so a test can make it fail, which is how the relaunch path's
// spawned-but-never-wired child becomes observable.
heavyClaimHandoff: vi.fn(async () => {}),
- mockPrepareLocalMemory: vi.fn(async () => ({ unloaded: [], availableGb: 64, totalGb: 64, budgetGb: 64 })),
+ mockPrepareLocalMemory: vi.fn(async () => ({ unloaded: [], availableGb: 64, totalGb: 64, budgetGb: 64, blockers: [] })),
}));
vi.mock('../../lib/heavyJobClaim.js', () => ({
claimHeavyLocalJob: vi.fn(async () => ({
ok: true, holder: {}, release: heavyClaimRelease, handoffTo: heavyClaimHandoff,
})),
}));
-vi.mock('../../lib/localMemory.js', () => ({
+vi.mock('../../lib/localMemory.js', async (importOriginal) => ({
+ ...(await importOriginal()),
prepareLocalMemory: mockPrepareLocalMemory,
}));
@@ -2577,6 +2578,34 @@ describe('generateVideo — heavy claim setup cleanup (#4364)', () => {
expect(heavyClaimRelease).toHaveBeenCalledTimes(1);
});
+
+ // #4766 — the vLLM Qwen container holds ~23 GB of a 24 GB card and is invisible
+ // to the resident-model unload, so the render used to die inside its model load
+ // with an OOM naming neither vLLM nor a fix. Refuse up front, with the prose.
+ it('refuses before spawn when something else is holding the GPU', async () => {
+ const { spawnDetached } = await import('../../lib/detachedSpawn.js');
+ vi.mocked(spawnDetached).mockClear();
+ mockPrepareLocalMemory.mockResolvedValueOnce({
+ unloaded: [], availableGb: 64, totalGb: 64, budgetGb: 64,
+ blockers: [{
+ runtime: 'vllm', providerId: 'opencode-vllm-tui', providerName: 'OpenCode vLLM TUI',
+ endpoint: 'http://127.0.0.1:18020/v1',
+ reason: 'vLLM (Qwen3.8-27B) is serving and holds the GPU. Stop it with `docker compose --profile single stop` in /srv/example/qwen-serving.',
+ }],
+ });
+
+ await expect(generateVideo({
+ jobId: 'gpu-blocked',
+ pythonPath: '/usr/bin/python3',
+ modelId: 'ltx2_unified',
+ prompt: 'a clip',
+ width: 512, height: 512, numFrames: 25, fps: 24,
+ mode: 'text',
+ })).rejects.toThrow('docker compose --profile single stop');
+
+ expect(spawnDetached).not.toHaveBeenCalled();
+ expect(heavyClaimRelease).toHaveBeenCalledTimes(1);
+ });
});
describe('generateVideo — close-handler resilience (issue #1334)', () => {