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

fix: cap the media queue at 250 waiting jobs (#8326)

[._.]/ Adam Eivye498d0610e7c
diff --git a/docs/STORAGE.md b/docs/STORAGE.md
index 8821b05fd3..fc4a141ee8 100644
--- a/docs/STORAGE.md
+++ b/docs/STORAGE.md
@@ -128,7 +128,7 @@ PostgreSQL is a **required** install/runtime dependency (see [Backup & Restore](
**Examples.**
- Upload staging — `data/uploads/*`. Ephemeral; do not put in DB except as job references.
-- Media job queue — runtime queue state can stay file-backed short term, but **job history and artifact lineage are `db-primary`** and should move to the DB. Admission is durable: `enqueueJob` resolves only once a snapshot containing the job is written, a failed write refuses the job (`503 MEDIA_QUEUE_PERSIST_FAILED`) before any dispatch, and graceful shutdown runs the bounded `flushMediaJobQueue()` before exit. The one exception is a boot that found the snapshot unreadable: persistence stays latched off to preserve that file, and the queue keeps accepting work in memory only. Local video failure holds live in the existing `data/media-jobs.json` envelope as `videoHolds`, beside unchanged `jobs`. They are machine-local dispatch state, never federated and never sent in capability/status payloads to peers; the local queue API exposes them on retained jobs and through `GET /api/media-jobs/holds`, so status and resume remain available when no retained jobs remain. Three matching terminal causes hold one catalog model/runtime until explicit resume. If hold metadata is damaged, boot restores unrelated work but holds all local video, including new submissions, behind an explicit session-only recovery action; the original snapshot stays preserved until repaired and restarted. Migration 344 adds an empty hold list to legacy envelopes without changing jobs; fresh installs use the empty seed. The envelope retains its existing filesystem backup coverage, with no new store, search index, sync cursor, or tombstone.
+- Media job queue — runtime queue state can stay file-backed short term, but **job history and artifact lineage are `db-primary`** and should move to the DB. Admission is durable: `enqueueJob` resolves only once a snapshot containing the job is written, a failed write refuses the job (`503 MEDIA_QUEUE_PERSIST_FAILED`) before any dispatch, and graceful shutdown runs the bounded `flushMediaJobQueue()` before exit. The one exception is a boot that found the snapshot unreadable: persistence stays latched off to preserve that file, and the queue keeps accepting work in memory only. Waiting work is bounded: at 250 queued jobs across all lanes (`MAX_PENDING_MEDIA_JOBS`, separate from each lane's running concurrency) a new submission is refused with a retryable `429 MEDIA_QUEUE_FULL` before any state changes; a restored snapshot above the bound is kept whole and only blocks new admissions until it drains. Local video failure holds live in the existing `data/media-jobs.json` envelope as `videoHolds`, beside unchanged `jobs`. They are machine-local dispatch state, never federated and never sent in capability/status payloads to peers; the local queue API exposes them on retained jobs and through `GET /api/media-jobs/holds`, so status and resume remain available when no retained jobs remain. Three matching terminal causes hold one catalog model/runtime until explicit resume. If hold metadata is damaged, boot restores unrelated work but holds all local video, including new submissions, behind an explicit session-only recovery action; the original snapshot stays preserved until repaired and restarted. Migration 344 adds an empty hold list to legacy envelopes without changing jobs; fresh installs use the empty seed. The envelope retains its existing filesystem backup coverage, with no new store, search index, sync cursor, or tombstone.
- Browser CDP profile / downloads — `data/browser-profile/`, `data/browser-downloads/` — cache, non-overridable backup excludes.
- Brain parity audit results — `data/brain_parity_reports.json` (`server/services/brainParity.js`, #4519). The last record-level brain-parity report per peer, keyed by peer `instanceId` (the same key `data/instances_sync_cursors.json` uses). `ephemeral-file` because it is a point-in-time *observation* about two installs, fully regenerable by re-running the audit, and stale the moment either side syncs — the durable state it describes lives in the brain stores. **Intentionally machine-local — never federated**: it is this install's view of a peer, and each peer computes its own. No sync cursor, no tombstone, no migration (an absent file reads as "nothing audited yet"). Per-type record lists are capped at 25 ids with a `truncated` flag so a badly diverged install can't grow the file without bound.
- Persistent-mind rollups and decision journal — `data/cos/persistent-mind-rollups.json` (`server/services/persistentMindContext.js`) and `data/cos/persistent-mind-journal.json` (`server/services/persistentMindJournal.js`). The rollups are sealed prose summaries of ranges that have left raw retention; the journal is the typed, individually addressable record of what the mind decided, committed to, is still asking, and is watching, each entry citing the message sequences it was drawn from. `file-primary` rather than `ephemeral-file`: both outlive the raw events they were derived from, so neither is regenerable, and a corrupt store fails CLOSED rather than resetting to `[]`. **Intentionally machine-local — never federated**: both quote one human private conversation, so the [machine-local privacy ADR](./decisions/2026-08-08-privacy-records-machine-local.md) keeps them off the federation layer entirely — no `PORTOS_SCHEMA_VERSIONS` entry, no sync cursor, no tombstone. No migration and no `data.reference/` seed: an absent file is the correct empty state. Retirement is a STATUS TRANSITION, never a deletion — a superseded entry stays readable with a pointer to what replaced it. Bounded (100 rollups; 500 journal entries, shedding settled history before anything still active), and backed up with the rest of `data/cos/`. The `history` cleanup scope clears the journal along with the messages it cites; a context-only clear does not.
diff --git a/server/routes/imageGen.multipart.test.js b/server/routes/imageGen.multipart.test.js
index 3f838d56c5..c66ee88b66 100644
--- a/server/routes/imageGen.multipart.test.js
+++ b/server/routes/imageGen.multipart.test.js
@@ -73,6 +73,7 @@ tryReadFile: vi.fn().mockResolvedValue(null),
}));
vi.mock('../services/mediaJobQueue/index.js', () => ({
+ assertMediaQueueRoom: vi.fn(),
enqueueJob: vi.fn(() => ({ jobId: 'multipart-job', position: 1, status: 'queued' })),
attachSseClient: vi.fn(() => false),
cancelJob: vi.fn(),
diff --git a/server/routes/imageGen.test.js b/server/routes/imageGen.test.js
index 540d9df2a9..a09d0e18ce 100644
--- a/server/routes/imageGen.test.js
+++ b/server/routes/imageGen.test.js
@@ -129,6 +129,7 @@ vi.mock('../lib/systemCapabilities.js', async () => {
});
vi.mock('../services/mediaJobQueue/index.js', () => ({
+ assertMediaQueueRoom: vi.fn(),
enqueueJob: vi.fn(({ kind }) => ({ jobId: `mock-${kind}-job`, position: 1, status: 'queued' })),
attachSseClient: vi.fn(() => false),
cancelJob: vi.fn(async () => ({ ok: true, status: 'canceling' })),
@@ -564,6 +565,24 @@ describe('Image Gen Routes', () => {
expect(JSON.stringify(recordUserAction.mock.calls[0][0])).not.toContain('a fox in a forest');
});
+ // #8326: a full media queue must answer with a retryable refusal before
+ // any job id exists — and before the render's inputs are staged.
+ it('answers a full media queue with a retryable 429 and no job id', async () => {
+ const { mediaQueueFullError } = await import('../services/mediaJobQueue/admission.js');
+ getSettings.mockResolvedValueOnce({ imageGen: { mode: 'local', local: { pythonPath: '/usr/bin/python3' } } });
+ mediaJobQueue.assertMediaQueueRoom.mockImplementationOnce(() => { throw mediaQueueFullError({ pending: 250 }); });
+
+ const response = await request(app)
+ .post('/api/image-gen/generate')
+ .send({ prompt: 'a fox in a forest' });
+
+ expect(response.status).toBe(429);
+ expect(response.body).toMatchObject({ code: 'MEDIA_QUEUE_FULL', context: { retryable: true, maxPendingJobs: 250 } });
+ expect(response.body.jobId).toBeUndefined();
+ expect(mediaJobQueue.enqueueJob).not.toHaveBeenCalled();
+ expect(recordUserAction).not.toHaveBeenCalled();
+ });
+
it('local mode maps cfgScale to guidance before enqueueing', async () => {
getSettings.mockResolvedValueOnce({ imageGen: { mode: 'local', local: { pythonPath: '/usr/bin/python3' } } });
mediaJobQueue.enqueueJob.mockReturnValueOnce({ jobId: 'queued-job-cfg', position: 1, status: 'queued' });
diff --git a/server/routes/universeBuilder/index.test.js b/server/routes/universeBuilder/index.test.js
index 7e0b7057d5..a1e5d98f2a 100644
--- a/server/routes/universeBuilder/index.test.js
+++ b/server/routes/universeBuilder/index.test.js
@@ -198,8 +198,10 @@ vi.mock('../../services/settings.js', () => ({
saveSettings: vi.fn(),
}));
-vi.mock('../../services/mediaJobQueue/index.js', () => ({
- enqueueJob: vi.fn(({ params }) => ({ jobId: `job-${++uuidCounter}`, position: 1, status: 'queued', params })),
+vi.mock('../../services/mediaJobQueue/index.js', async () => ({
+ assertMediaQueueRoom: vi.fn(),
+ partialBatchAdmissionError: (await import('../../services/mediaJobQueue/admission.js')).partialBatchAdmissionError,
+ enqueueJob: vi.fn(async ({ params }) => ({ jobId: `job-${++uuidCounter}`, position: 1, status: 'queued', params })),
}));
// Tiny in-memory store so repeat-render tests can verify the new
diff --git a/server/services/creativeDirector/videoAudio.js b/server/services/creativeDirector/videoAudio.js
index 401ace1539..0198b243ae 100644
--- a/server/services/creativeDirector/videoAudio.js
+++ b/server/services/creativeDirector/videoAudio.js
@@ -1,6 +1,7 @@
/** Standalone soundtrack selection over the existing music library and audio queue. */
import { canonicalSnapshotChecksum } from '../../lib/snapshotChecksum.js';
import { ServerError } from '../../lib/errorHandler.js';
+import { isMediaAdmissionRefusal } from '../mediaJobQueue/admission.js';
import { sleep } from '../../lib/fileUtils.js';
const blocked = message => new ServerError(message, { status: 409, code: 'VIDEO_AUDIO_BLOCKED' });
@@ -60,7 +61,7 @@ export async function prepareVideoSoundtrack(project, isCurrent) {
const audioRevision = canonicalSnapshotChecksum(audio);
if (project.musicBed?.audioRevision === audioRevision && await resolveMusicTrackPath(project.musicBed.filename)) return project.musicBed;
const { reserveVideoAttempt, assertVideoAttemptDispatch, settleVideoAttempt } = await import('./videoExecution.js');
- const { getJob, enqueueJob, MEDIA_QUEUE_PERSIST_FAILED } = await import('../mediaJobQueue/index.js');
+ const { getJob, enqueueJob } = await import('../mediaJobQueue/index.js');
const { getProject, mutateVideoProject } = await import('./local.js');
const key = `audio:${audioRevision}`;
let attempt = [...(project.videoExecution.attempts || [])].reverse().find(row => row.key === key && ['submitting', 'queued', 'running', 'completed', 'uncertain'].includes(row.status));
@@ -74,9 +75,10 @@ export async function prepareVideoSoundtrack(project, isCurrent) {
params: { engine: audio.providerId, modelId: audio.model, prompt: audio.prompt, durationSec: audio.durationSec,
videoProduction: { projectId: project.id, attemptId: attempt.id, executionId: attempt.executionId } } })
.catch(async (error) => {
- // A refused admission (#8325) submitted nothing; fail the receipt so the
- // next Resume retries instead of treating it as an uncertain submission.
- if (error.code === MEDIA_QUEUE_PERSIST_FAILED) await settleVideoAttempt(project.id, attempt.id, { status: 'failed' });
+ // A refused admission (#8325 failed snapshot, #8326 full queue) submitted
+ // nothing; fail the receipt so the next Resume retries instead of
+ // treating it as an uncertain submission.
+ if (isMediaAdmissionRefusal(error)) await settleVideoAttempt(project.id, attempt.id, { status: 'failed' });
throw error;
});
await settleVideoAttempt(project.id, attempt.id, { status: 'queued', jobId });
diff --git a/server/services/creativeDirector/videoExecution.js b/server/services/creativeDirector/videoExecution.js
index c626f42c56..1e758090a5 100644
--- a/server/services/creativeDirector/videoExecution.js
+++ b/server/services/creativeDirector/videoExecution.js
@@ -2,6 +2,7 @@
import { randomUUID } from 'crypto';
import { canonicalSnapshotChecksum } from '../../lib/snapshotChecksum.js';
import { ServerError } from '../../lib/errorHandler.js';
+import { isMediaAdmissionRefusal } from '../mediaJobQueue/admission.js';
import { creativeDirectorVideoLimitsSchema } from '../../lib/creativeDirectorValidation.js';
import { assertVideoOwner } from '../../lib/creativeDirectorVideoReview.js';
@@ -301,11 +302,12 @@ export async function enqueueVideoProductionJob(project, { kind = 'video', param
await settleVideoAttempt(project.id, attempt.id, { status: 'queued', jobId: result.jobId });
return { ...result, attemptId: attempt.id };
} catch (error) {
- // A refused queue admission (#8325) withdrew the job before dispatch, so
- // nothing was submitted — as certain a failure as a blocked dispatch. (The
- // literal mirrors mediaJobQueue's MEDIA_QUEUE_PERSIST_FAILED; importing the
- // queue here would close a static cycle with its dynamic import of us.)
- const uncertain = error.code !== 'VIDEO_DISPATCH_BLOCKED' && error.code !== 'MEDIA_QUEUE_PERSIST_FAILED';
+ // A refused queue admission — a failed snapshot (#8325) or a full queue
+ // (#8326) — created no job, so nothing was submitted: as certain a failure
+ // as a blocked dispatch, and Resume may retry it without charging twice.
+ // (The predicate lives in the queue's light admission module; importing the
+ // queue itself would close a static cycle with its dynamic import of us.)
+ const uncertain = error.code !== 'VIDEO_DISPATCH_BLOCKED' && !isMediaAdmissionRefusal(error);
await settleVideoAttempt(project.id, attempt.id, { status: uncertain ? 'uncertain' : 'failed' });
await pauseVideoExecution(project.id, uncertain ? 'Submission could not be confirmed. Reconcile the queue or explicitly authorize retry; it may charge again.' : error.message);
throw new ServerError(error.message, { status: 409, code: uncertain ? 'VIDEO_SUBMISSION_UNCERTAIN' : error.code });
diff --git a/server/services/creativeDirector/videoExecution.test.js b/server/services/creativeDirector/videoExecution.test.js
index eba8cf182f..85146f9185 100644
--- a/server/services/creativeDirector/videoExecution.test.js
+++ b/server/services/creativeDirector/videoExecution.test.js
@@ -17,7 +17,6 @@ vi.mock('./sceneEvaluator.js', () => ({ resolveVisionEvalTarget: vi.fn(async ()
vi.mock('../videoGen/reactor.js', () => ({ REACTOR_MODEL_ID: 'fast-h3' }));
vi.mock('../videoGen/modelSelection.js', () => ({ resolveVideoModelSelection: vi.fn() }));
vi.mock('../mediaJobQueue/index.js', () => ({ listJobs: vi.fn(() => state.jobs), getJob: vi.fn(id => state.jobs.find(job => job.id === id)),
- MEDIA_QUEUE_PERSIST_FAILED: 'MEDIA_QUEUE_PERSIST_FAILED',
enqueueJob: vi.fn(async job => { const jobId = `example-audio-${state.jobs.length}`; state.jobs.push({ ...job, id: jobId, status: 'completed', result: { filename: 'example-bed.wav', durationSec: 10 } }); return { jobId }; }),
}));
vi.mock('../pipeline/musicGen.js', () => ({ ENGINES: { 'example-audio': { id: 'example-audio', models: [{ id: 'example-model' }], defaultModelId: 'example-model', minDurationSec: 1, maxDurationSec: 30 } }, isEngineHealthy: vi.fn(async () => true) }));
@@ -160,6 +159,19 @@ it('keeps uncertain submissions inert until the user explicitly acknowledges a p
expect(startCreativeDirectorProject).toHaveBeenCalledTimes(2);
});
+// #8326: a full queue created no job, so nothing could have been charged —
+// treating it as uncertain would park the project behind a duplicate-charge
+// acknowledgement for a submission that never happened.
+it('treats a full media queue as a certain non-submission that a plain Resume retries', async () => {
+ await startVideoExecution('example-video', await startInput());
+ enqueueUnattendedMediaJob.mockRejectedValueOnce(Object.assign(new Error('The media queue is full'), { code: 'MEDIA_QUEUE_FULL', status: 429 }));
+ await expect(enqueue()).rejects.toMatchObject({ code: 'MEDIA_QUEUE_FULL' });
+ expect(state.project.videoExecution.attempts[0].status).toBe('failed');
+ expect(state.project).toMatchObject({ status: 'paused', videoExecution: { blocker: 'The media queue is full' } });
+ await startVideoExecution('example-video', await startInput());
+ expect(startCreativeDirectorProject).toHaveBeenCalledTimes(2);
+});
+
it('reconciles completed clips without a rerender and requires Resume after restart', async () => {
await startVideoExecution('example-video', await startInput());
const queued = await enqueue();
diff --git a/server/services/deckRender.js b/server/services/deckRender.js
index f30c2b6e16..37ddbbdd35 100644
--- a/server/services/deckRender.js
+++ b/server/services/deckRender.js
@@ -40,7 +40,7 @@ export async function renderDeckCards(deckId, { cardIds, onlyMissing = false, mo
// request — this module is reached by the route + hook graphs, which never
// need them instantiated (server/AGENTS.md "Import scoping").
const [
- { enqueueJob }, { getSettings }, { resolveRenderTargetConfig }, { resolveLocalImageModel }, { resolveImageCleaners },
+ { enqueueJob, assertMediaQueueRoom, partialBatchAdmissionError }, { getSettings }, { resolveRenderTargetConfig }, { resolveLocalImageModel }, { resolveImageCleaners },
] = await Promise.all([
import('./mediaJobQueue/index.js'), import('./settings.js'), import('./imageGen/cloudProviderConfig.js'),
import('./imageGen/prepareParams.js'), import('./imageGen/index.js'),
@@ -74,6 +74,9 @@ export async function renderDeckCards(deckId, { cardIds, onlyMissing = false, mo
? resolveLocalImageModel(settings, { modelId: model || localPinModel || undefined })
: null;
const { cleanC2PA, denoise } = resolveImageCleaners(undefined, settings, mode);
+ // Refuse a batch the media queue cannot hold (#8326) whole, before any card
+ // is queued, rather than landing part of it.
+ assertMediaQueueRoom(targets.length);
const jobs = [];
const stamps = [];
@@ -98,11 +101,12 @@ export async function renderDeckCards(deckId, { cardIds, onlyMissing = false, mo
...(localModel?.selectedModel?.id ? { modelId: localModel.selectedModel.id } : {}),
...base,
};
- // A refused admission (#8325) still stamps the cards already queued, so
- // the deck shows the renders that WILL land before the error surfaces.
+ // A refused admission (#8325, or #8326 when another producer filled the
+ // queue mid-batch) still stamps the cards already queued, so the deck shows
+ // the renders that WILL land, and the error says how many did.
const { jobId } = await enqueueJob({ kind: 'image', params, owner: 'decks' }).catch(async (err) => {
if (stamps.length) await markCardsRenderQueued(deck.id, stamps);
- throw err;
+ throw partialBatchAdmissionError(err, { admitted: jobs.length, total: targets.length, noun: 'card renders' });
});
jobs.push({ cardId: card.id, key: card.key, jobId });
stamps.push({ cardId: card.id, render: {
diff --git a/server/services/deckRender.test.js b/server/services/deckRender.test.js
index ac568ea5bf..a25a2a43bb 100644
--- a/server/services/deckRender.test.js
+++ b/server/services/deckRender.test.js
@@ -5,7 +5,12 @@ const getSettings = vi.fn();
const getDeck = vi.fn();
const markCardsRenderQueued = vi.fn(async () => ({}));
const resolveLocalImageModel = vi.fn(() => ({ pythonPath: '/py', selectedModel: { id: 'flux2-klein-4b' } }));
-vi.mock('./mediaJobQueue/index.js', () => ({ enqueueJob }));
+const assertMediaQueueRoom = vi.fn();
+vi.mock('./mediaJobQueue/index.js', async () => ({
+ enqueueJob,
+ assertMediaQueueRoom,
+ partialBatchAdmissionError: (await import('./mediaJobQueue/admission.js')).partialBatchAdmissionError,
+}));
vi.mock('./settings.js', () => ({ getSettings }));
vi.mock('./decks.js', () => ({ getDeck, markCardsRenderQueued }));
vi.mock('./imageGen/index.js', () => ({ resolveImageCleaners: () => ({ cleanC2PA: false, denoise: false }) }));
@@ -68,6 +73,23 @@ describe('renderDeckCards', () => {
expect(markCardsRenderQueued).toHaveBeenCalledWith('d1', [{ cardId: 'a', render: expect.objectContaining({ jobId: 'job-1', status: 'queued', mode: 'local', model: 'flux2-klein-4b' }) }]);
});
+ // #8326: another producer can fill the queue between the batch preflight and
+ // the last enqueue. The cards that DID queue must still be stamped, and the
+ // error must say how many landed rather than read as a total failure.
+ it('stamps the queued cards and reports the partial batch when the queue fills mid-batch', async () => {
+ resolveRenderTargetConfig.mockReturnValue({ mode: 'local', cloud: null });
+ enqueueJob.mockImplementationOnce(async () => ({ jobId: 'job-1', position: 1, status: 'queued' }))
+ .mockImplementationOnce(async () => {
+ throw Object.assign(new Error('The media queue is full'), { status: 429, code: 'MEDIA_QUEUE_FULL' });
+ });
+ await expect(renderDeckCards('d1', {})).rejects.toMatchObject({
+ status: 429, code: 'MEDIA_QUEUE_FULL', message: 'Queued 1 of 2 card renders — The media queue is full',
+ context: { admitted: 1, total: 2 },
+ });
+ expect(assertMediaQueueRoom).toHaveBeenCalledWith(2);
+ expect(markCardsRenderQueued).toHaveBeenCalledWith('d1', [{ cardId: 'a', render: expect.objectContaining({ jobId: 'job-1' }) }]);
+ });
+
it('spreads the cloud job params under the card params and threads the resolved model', async () => {
resolveRenderTargetConfig.mockReturnValue({ mode: 'codex', cloud: { enabled: true, modelId: 'gpt-image-2', jobParams: { mode: 'codex', model: 'gpt-image-2', effort: 'high' } } });
await renderDeckCards('d1', { cardIds: ['b'] });
diff --git a/server/services/federatedMediaProvider.js b/server/services/federatedMediaProvider.js
index 39bec3aa85..e03c3159cb 100644
--- a/server/services/federatedMediaProvider.js
+++ b/server/services/federatedMediaProvider.js
@@ -41,6 +41,7 @@ import {
laneConcurrencyFor,
listJobs,
} from './mediaJobQueue/index.js';
+import { MEDIA_QUEUE_FULL } from './mediaJobQueue/admission.js';
import { listMusicEngineCapabilities } from './musicEngineCapabilities.js';
import { BYOV_VIDEO_RUNTIMES, isByovRuntimeReady } from './videoGen/runtimes.js';
import { minimaxH3ControlError } from './videoGen/minimaxH3Controls.js';
@@ -862,6 +863,14 @@ export async function submitFederatedMediaJob({ callerId, config, input, idempot
kind: input.kind,
owner: jobOwner(callerId),
params: buildQueueParams(input, capability, federatedMedia, inputAssetParams),
+ }).catch((error) => {
+ // The shared queue's own pending ceiling (#8326) is the same capacity
+ // refusal as the provider bound above; answer in the wire's vocabulary so
+ // the consumer retries later instead of seeing a local queue code.
+ if (error?.code === MEDIA_QUEUE_FULL) {
+ unavailable('Provider queue is at capacity', 'MEDIA_PROVIDER_BUSY', 429, { retryable: true });
+ }
+ throw error;
});
return {
replayed: false,
diff --git a/server/services/federatedMediaProvider.test.js b/server/services/federatedMediaProvider.test.js
index 36a3671e10..cfa4689ced 100644
--- a/server/services/federatedMediaProvider.test.js
+++ b/server/services/federatedMediaProvider.test.js
@@ -66,7 +66,7 @@ vi.mock('./mediaJobQueue/index.js', () => ({
laneConcurrencyFor: vi.fn((job) => state.laneWidthByKind[job?.kind] ?? 1),
isRemoteMediaJob: (job) => job?.kind === 'audio' && job.params?.remoteMedia !== undefined,
getJob: vi.fn((id) => state.jobs.find((job) => job.id === id) || null),
- enqueueJob: vi.fn(({ kind, owner, params }) => {
+ enqueueJob: vi.fn(async ({ kind, owner, params }) => {
const suffix = String(state.nextId++).padStart(12, '0');
const id = `00000000-0000-4000-8000-${suffix}`;
const job = {
@@ -455,6 +455,15 @@ describe('federated media provider capacity and idempotency', () => {
expect(enqueueJob).not.toHaveBeenCalled();
});
+ it('reports a full local media queue to the peer as retryable provider capacity', async () => {
+ enqueueJob.mockImplementationOnce(async () => {
+ throw Object.assign(new Error('The media queue is full'), { status: 429, code: 'MEDIA_QUEUE_FULL' });
+ });
+ await expect(submitFederatedMediaJob({
+ callerId: 'peer-example', config: config(), input: input(), idempotencyKey: 'queue-full',
+ })).rejects.toMatchObject({ status: 429, code: 'MEDIA_PROVIDER_BUSY', context: { retryable: true } });
+ });
+
it('does not count outgoing proxy jobs against this machine provider capacity', async () => {
state.jobs = [
{
diff --git a/server/services/imageGen/prepareParams.js b/server/services/imageGen/prepareParams.js
index 0fd21bac25..7b15cfbc09 100644
--- a/server/services/imageGen/prepareParams.js
+++ b/server/services/imageGen/prepareParams.js
@@ -38,6 +38,7 @@ import {
cloudPromptRequired, maxInputImages, resolveCloudProviderConfig, resolveRenderTargetConfig,
} from './cloudProviderConfig.js';
import { RENDER_TARGET, recordRenderPin } from '../../lib/renderTargets.js';
+import { QUEUEABLE_IMAGE_MODES } from '../../lib/generationModes.js';
import { getProject as getMusicVideoProject } from '../musicVideo/projects.js';
import { getUniverseRenderPin } from '../universeBuilder/crud.js';
import { getImageModels, isFlux2, isEditOnly } from '../../lib/mediaModels.js';
@@ -245,6 +246,18 @@ export async function prepareGenerateParams({ data, files, referenceImageFields
throw cloudConfig.disabledError;
}
+ // A full media queue (#8326) is refused before anything is staged too — the
+ // route's enqueue would refuse the same render, after these copies landed.
+ // Lazy: only a queue-bound render needs the queue loaded.
+ if (data.mediaProviderPeerId || QUEUEABLE_IMAGE_MODES.includes(mode)) {
+ await import('../mediaJobQueue/index.js')
+ .then(({ assertMediaQueueRoom }) => assertMediaQueueRoom(1))
+ .catch((err) => {
+ cleanupReqFilesTemp();
+ throw err;
+ });
+ }
+
// Resolve cleaners ONCE at the route layer so all three dispatch paths
// (synchronous external, codex queue, local queue) see the same values.
// Stamp onto `data` so they flow through the spread-into-params calls
diff --git a/server/services/loraDatasetGenerate.js b/server/services/loraDatasetGenerate.js
index 9810385e6c..a6f22f6515 100644
--- a/server/services/loraDatasetGenerate.js
+++ b/server/services/loraDatasetGenerate.js
@@ -38,7 +38,7 @@ import {
extractCharacterPromptCommon,
REFERENCE_SHEET_CONSTANTS,
} from './universeCharacterSheet.js';
-import { enqueueJob, mediaJobEvents } from './mediaJobQueue/index.js';
+import { assertMediaQueueRoom, enqueueJob, mediaJobEvents, partialBatchAdmissionError } from './mediaJobQueue/index.js';
import { IMAGE_GEN_MODE } from './imageGen/modes.js';
import { resolveRenderTargetConfig } from './imageGen/cloudProviderConfig.js';
import { selectLocalImageModelFromSettings } from './imageGen/prepareParams.js';
@@ -312,13 +312,20 @@ export async function generateDatasetImages(datasetId, options = {}) {
});
const { base, activeMode, modelId } = await resolveRenderParams(options);
+ // Refuse a batch the media queue cannot hold (#8326) whole, before any
+ // image entry is appended.
+ assertMediaQueueRoom(variations.length);
const launched = [];
for (const variation of variations) {
const imageId = uuidv4();
const file = `${imageId}.png`;
const { prompt, negativePrompt } = buildDatasetImagePrompt(universe, subject, variation, entryKind);
- const queued = await enqueueJob({ kind: 'image', params: { ...base, prompt, negativePrompt } });
+ // Refused part-way (the queue filled after the preflight): the images
+ // already launched keep their entries and renders; report how many.
+ const queued = await enqueueJob({ kind: 'image', params: { ...base, prompt, negativePrompt } }).catch((err) => {
+ throw partialBatchAdmissionError(err, { admitted: launched.length, total: variations.length, noun: 'dataset images' });
+ });
const jobId = queued.jobId;
const entry = {
diff --git a/server/services/loraDatasetGenerate.test.js b/server/services/loraDatasetGenerate.test.js
index 164036df77..a3bd6b05f0 100644
--- a/server/services/loraDatasetGenerate.test.js
+++ b/server/services/loraDatasetGenerate.test.js
@@ -37,7 +37,9 @@ vi.mock('sharp', () => ({
})),
}));
vi.mock('./settings.js', () => ({ getSettings: (...args) => renderMocks.getSettings(...args) }));
-vi.mock('./mediaJobQueue/index.js', () => ({
+vi.mock('./mediaJobQueue/index.js', async () => ({
+ assertMediaQueueRoom: vi.fn(),
+ partialBatchAdmissionError: (await import('./mediaJobQueue/admission.js')).partialBatchAdmissionError,
enqueueJob: (...args) => renderMocks.enqueueJob(...args),
mediaJobEvents: { on: vi.fn(), off: vi.fn() },
}));
@@ -263,7 +265,7 @@ describe('generateDatasetImages local model selection', () => {
renderMocks.getSettings.mockResolvedValue({
imageGen: { mode: 'local', local: { pythonPath: '/python', modelId: 'pinned-model' } },
});
- renderMocks.enqueueJob.mockReturnValue({ jobId: 'job-1' });
+ renderMocks.enqueueJob.mockResolvedValue({ jobId: 'job-1' });
renderMocks.getImageModels.mockReturnValue(renderModels);
});
diff --git a/server/services/loraTraining/captionLeakStaging.test.js b/server/services/loraTraining/captionLeakStaging.test.js
index 534b65585a..e803d26fef 100644
--- a/server/services/loraTraining/captionLeakStaging.test.js
+++ b/server/services/loraTraining/captionLeakStaging.test.js
@@ -33,6 +33,7 @@ vi.mock('./dataset.js', () => ({ validateDatasetReady: (...a) => validateDataset
vi.mock('../settings.js', () => ({ getSettings: vi.fn(async () => ({})) }));
vi.mock('../loraDatasets.js', () => ({ updateDataset: (...a) => updateDatasetMock(...a) }));
vi.mock('../mediaJobQueue/index.js', () => ({
+ assertMediaQueueRoom: vi.fn(),
enqueueJob: vi.fn(),
getJob: vi.fn(),
mediaJobEvents: { emit: vi.fn(), on: vi.fn() },
diff --git a/server/services/loraTraining/datasetReset.test.js b/server/services/loraTraining/datasetReset.test.js
index 5097101228..2c8ef98ad8 100644
--- a/server/services/loraTraining/datasetReset.test.js
+++ b/server/services/loraTraining/datasetReset.test.js
@@ -26,6 +26,7 @@ vi.mock('../../lib/pythonSetup.js', () => ({
resolveFlux2Python: vi.fn(() => '/venv/python'),
}));
vi.mock('../mediaJobQueue/index.js', () => ({
+ assertMediaQueueRoom: vi.fn(),
enqueueJob: vi.fn(),
getJob: vi.fn(),
mediaJobEvents: { emit: vi.fn(), on: vi.fn() },
diff --git a/server/services/loraTraining/index.js b/server/services/loraTraining/index.js
index 4135b6d055..4d55c0f8b4 100644
--- a/server/services/loraTraining/index.js
+++ b/server/services/loraTraining/index.js
@@ -27,7 +27,7 @@ import { getImageModels } from '../../lib/mediaModels.js';
import { resolveFlux2Python, isFlux2VenvHealthy, resolveMfluxPython } from '../../lib/pythonSetup.js';
import { getSettings } from '../settings.js';
import { writeLoraSidecar } from '../loras.js';
-import { enqueueJob, getJob, mediaJobEvents } from '../mediaJobQueue/index.js';
+import { assertMediaQueueRoom, enqueueJob, getJob, mediaJobEvents } from '../mediaJobQueue/index.js';
import { updateDataset } from '../loraDatasets.js';
import { trainingEvents } from './events.js';
import { sleepDisplayForTraining, wakeDisplay } from './displayPower.js';
@@ -188,6 +188,10 @@ export async function startTrainingRun({
}
}
+ // A full media queue (#8326) refuses the launch before the run row exists,
+ // so the common case leaves no failed run behind; the enqueue below still
+ // re-checks (and fails the row) if another producer filled the queue since.
+ assertMediaQueueRoom(1);
const mergedParams = mergeParams(settings, params);
const runId = uuidv4();
const run = {
diff --git a/server/services/loraTraining/mpsGuard.test.js b/server/services/loraTraining/mpsGuard.test.js
index 8f56a537b9..e1be58c661 100644
--- a/server/services/loraTraining/mpsGuard.test.js
+++ b/server/services/loraTraining/mpsGuard.test.js
@@ -31,6 +31,7 @@ vi.mock('./dataset.js', () => ({ validateDatasetReady: (...a) => validateDataset
vi.mock('../settings.js', () => ({ getSettings: vi.fn(async () => ({})) }));
vi.mock('../loraDatasets.js', () => ({ updateDataset: vi.fn(async () => {}) }));
vi.mock('../mediaJobQueue/index.js', () => ({
+ assertMediaQueueRoom: vi.fn(),
enqueueJob: (...a) => enqueueJobMock(...a),
getJob: vi.fn(),
mediaJobEvents: { emit: vi.fn(), on: vi.fn() },
diff --git a/server/services/loraTraining/resume.test.js b/server/services/loraTraining/resume.test.js
index f6ab354ab1..493aabe866 100644
--- a/server/services/loraTraining/resume.test.js
+++ b/server/services/loraTraining/resume.test.js
@@ -33,6 +33,7 @@ vi.mock('../../lib/pythonSetup.js', () => ({
resolveMfluxPython: (p) => p || null,
}));
vi.mock('../mediaJobQueue/index.js', () => ({
+ assertMediaQueueRoom: vi.fn(),
enqueueJob: (...a) => enqueueJobMock(...a),
getJob: vi.fn(),
mediaJobEvents: { emit: vi.fn(), on: vi.fn() },
diff --git a/server/services/mediaJobQueue/admission.js b/server/services/mediaJobQueue/admission.js
new file mode 100644
index 0000000000..e9af0d8314
--- /dev/null
+++ b/server/services/mediaJobQueue/admission.js
@@ -0,0 +1,72 @@
+/**
+ * Media-queue admission contract — the refusal codes, the pending-job ceiling,
+ * and the errors that carry them.
+ *
+ * Kept apart from the queue so a producer can recognize a refused admission
+ * without importing the queue (creativeDirector/videoExecution.js cannot: the
+ * queue dynamically imports it, and a static edge back would close a cycle).
+ */
+import { ServerError } from '../../lib/errorHandler.js';
+
+// Hard ceiling on WAITING jobs across every lane (#8326). Separate from each
+// lane's running concurrency: it bounds the in-memory queue and the snapshot
+// every admission rewrites, so a runaway producer cannot grow either without
+// limit. Never enforced by eviction — a restored backlog above it is kept and
+// only new admissions wait for it to drain.
+export const MAX_PENDING_MEDIA_JOBS = 250;
+
+// The job was withdrawn before any dispatch because its snapshot write failed
+// (#8325).
+export const MEDIA_QUEUE_PERSIST_FAILED = 'MEDIA_QUEUE_PERSIST_FAILED';
+// The job was never created: the queue already holds MAX_PENDING_MEDIA_JOBS.
+export const MEDIA_QUEUE_FULL = 'MEDIA_QUEUE_FULL';
+// A batch preflight asked for more room than the ceiling itself — no amount of
+// draining admits it, so it is not a retryable refusal.
+export const MEDIA_BATCH_TOO_LARGE = 'MEDIA_BATCH_TOO_LARGE';
+
+const REFUSAL_CODES = new Set([MEDIA_QUEUE_PERSIST_FAILED, MEDIA_QUEUE_FULL]);
+
+/**
+ * True when `error` is a refused admission: no job exists and no provider work
+ * started, so the submission is definitively not made and may be retried.
+ */
+export const isMediaAdmissionRefusal = (error) => REFUSAL_CODES.has(error?.code);
+
+/**
+ * The queue-full refusal. 429 like the federated provider's MEDIA_PROVIDER_BUSY:
+ * capacity, not a fault, and safe to retry once jobs finish.
+ */
+export function mediaQueueFullError({ pending, requested = 1 }) {
+ // A batch bigger than the whole ceiling can never fit, so waiting would not
+ // help — say so instead of inviting a retry that always fails.
+ if (requested > MAX_PENDING_MEDIA_JOBS) {
+ return new ServerError(
+ `This batch needs ${requested} jobs but the media queue holds at most ${MAX_PENDING_MEDIA_JOBS} waiting — render a smaller selection.`,
+ { status: 400, code: MEDIA_BATCH_TOO_LARGE, context: { retryable: false, requested, maxPendingJobs: MAX_PENDING_MEDIA_JOBS } },
+ );
+ }
+ const room = Math.max(0, MAX_PENDING_MEDIA_JOBS - pending);
+ const message = requested > 1 && room > 0
+ ? `The media queue has room for ${room} more job(s) but this batch needs ${requested} — try again once some finish.`
+ : `The media queue is full (${pending} jobs waiting, limit ${MAX_PENDING_MEDIA_JOBS}) — try again once some finish.`;
+ return new ServerError(message, {
+ status: 429,
+ code: MEDIA_QUEUE_FULL,
+ context: { retryable: true, pending, requested, maxPendingJobs: MAX_PENDING_MEDIA_JOBS },
+ });
+}
+
+/**
+ * Re-throwable error for a batch whose admission was refused part-way: the
+ * jobs already admitted keep running, so the caller is told how many landed
+ * rather than seeing a bare failure (or, worse, a success). Any other error,
+ * or a refusal before anything landed, passes through unchanged.
+ */
+export function partialBatchAdmissionError(error, { admitted, total, noun = 'jobs' }) {
+ if (!admitted || !isMediaAdmissionRefusal(error)) return error;
+ return new ServerError(`Queued ${admitted} of ${total} ${noun} — ${error.message}`, {
+ status: error.status || 503,
+ code: error.code,
+ context: { ...(error.context || {}), admitted, total },
+ });
+}
diff --git a/server/services/mediaJobQueue/index.js b/server/services/mediaJobQueue/index.js
index 8ac73249df..e0cf03d2c2 100644
--- a/server/services/mediaJobQueue/index.js
+++ b/server/services/mediaJobQueue/index.js
@@ -50,6 +50,17 @@ import { VIDEO_GEN_MODE, CLOUD_VIDEO_GEN_MODES, mediaJobExecutionLane } from '..
import { REMOTE_MEDIA_MODULES, isRemoteMediaJob } from './remoteMediaJob.js';
import { createVideoHolds } from './videoHolds.js';
import { routedJobParams } from '../federatedMedia/routedJobParams.js';
+import {
+ MAX_PENDING_MEDIA_JOBS, MEDIA_QUEUE_PERSIST_FAILED, mediaQueueFullError,
+} from './admission.js';
+
+// The admission contract lives in ./admission.js so producers that cannot
+// import the queue can still recognize a refusal; re-exported where callers
+// have always found the queue's API.
+export {
+ MAX_PENDING_MEDIA_JOBS, MEDIA_QUEUE_PERSIST_FAILED, MEDIA_QUEUE_FULL, isMediaAdmissionRefusal,
+ partialBatchAdmissionError,
+} from './admission.js';
// Cloud-CLI jobs (Codex/Grok/Agy images, Grok videos) share one parallel lane —
// each render
@@ -347,8 +358,10 @@ export function laneConcurrencyFor(job) {
* are answered here for the same reason `isRemoteMediaJob` has one definition.
*
* `limit` is the lane's configured concurrency, NOT a queue bound: work over
- * the limit waits rather than being rejected. The federated-provider admission
- * bound is a separate setting (see federatedMediaProvider.js).
+ * the limit waits rather than being rejected. Waiting work is bounded once,
+ * across all lanes, by MAX_PENDING_MEDIA_JOBS (see assertMediaQueueRoom). The
+ * federated-provider admission bound is a separate setting (see
+ * federatedMediaProvider.js).
*
* @returns {{lanes: Record<'gpu'|'cloud'|'remote', {running: number, queued: number, limit: number}>,
* byKind: Record<string, {running: number, queued: number}>,
@@ -1234,9 +1247,22 @@ async function runJob(job) {
dispatcher.detach();
}
-// Error code of a refused admission. The job was withdrawn before any dispatch,
-// so a caller may treat the submission as definitively not made.
-export const MEDIA_QUEUE_PERSIST_FAILED = 'MEDIA_QUEUE_PERSIST_FAILED';
+/**
+ * Refuse up front when `count` more jobs would not fit under the pending-job
+ * ceiling (#8326). enqueueJob calls it with 1; a batch producer calls it with
+ * its size before creating records, so an oversized batch is refused whole
+ * instead of landing half-queued. Advisory for batches — other producers can
+ * still fill the queue before the batch finishes enqueueing, which each
+ * enqueueJob call re-checks.
+ *
+ * `queue` holds exactly the waiting jobs (including ones mid-admission):
+ * running jobs sit in the lane slots, so the ceiling never counts them.
+ */
+export function assertMediaQueueRoom(count = 1) {
+ if (queue.length + count <= MAX_PENDING_MEDIA_JOBS) return;
+ console.warn(`⚠️ media queue full — refused ${count} job(s) with ${queue.length} waiting (limit ${MAX_PENDING_MEDIA_JOBS})`);
+ throw mediaQueueFullError({ pending: queue.length, requested: count });
+}
// Admission is durable (#8325): the job is acknowledged — and made eligible for
// dispatch — only after a snapshot containing it has been written. Until then it
@@ -1247,10 +1273,16 @@ export const MEDIA_QUEUE_PERSIST_FAILED = 'MEDIA_QUEUE_PERSIST_FAILED';
// Exception: under the #4115 latch (an unreadable snapshot preserved for repair)
// nothing is written by design and the queue deliberately keeps working in
// memory, so admission succeeds without durability; boot already reported it.
+//
+// Bounded (#8326): at MAX_PENDING_MEDIA_JOBS waiting jobs the submission is
+// refused (429 MEDIA_QUEUE_FULL) before ANY state changes — no id, no queue
+// entry, no SSE entry, no snapshot write. The check and the push below run in
+// one synchronous stretch, so concurrent submissions cannot overshoot it.
export async function enqueueJob({ kind, params, owner = null }) {
if (!JOB_KINDS.includes(kind)) {
throw new Error(`enqueueJob: invalid kind '${kind}'`);
}
+ assertMediaQueueRoom(1);
const id = randomUUID();
// Every routed job is normalized HERE rather than at each caller (#4683): the
// downgrade contract only holds if it is unbypassable, and a future enqueue
diff --git a/server/services/mediaJobQueue/index.test.js b/server/services/mediaJobQueue/index.test.js
index 91eb92e2f6..642b1b9092 100644
--- a/server/services/mediaJobQueue/index.test.js
+++ b/server/services/mediaJobQueue/index.test.js
@@ -2227,3 +2227,92 @@ describe('durable admission and shutdown flush', () => {
await expect(mediaJobQueue.flushMediaJobQueue()).resolves.toEqual({ ok: true });
});
});
+
+// #8326: waiting work is bounded across every lane, separately from each
+// lane's running concurrency, and the bound never evicts a persisted job.
+describe('pending-job ceiling', () => {
+ const jobsFile = () => join(tempDataDir, 'media-jobs.json');
+ const queueFull = { status: 429, code: 'MEDIA_QUEUE_FULL' };
+ const waiting = () => mediaJobQueue.listJobs({ status: 'queued' }).length;
+
+ beforeEach(() => {
+ stubs.generateVideo.mockImplementation(() => new Promise(() => {}));
+ });
+
+ it('admits exactly the ceiling under concurrent submission and refuses the next without touching state', async () => {
+ const { MAX_PENDING_MEDIA_JOBS } = mediaJobQueue;
+ // A running job holds the only GPU slot, so everything below waits.
+ const blocker = await mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'running' } });
+ await waitFor(() => mediaJobQueue.getJob(blocker.jobId)?.status === 'running');
+
+ // One synchronous check-and-push per submission: firing them all at once
+ // must not let in-flight snapshot writes admit past the ceiling.
+ const results = await Promise.allSettled(Array.from({ length: MAX_PENDING_MEDIA_JOBS + 1 },
+ (_, i) => mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: `wait-${i}` } })));
+ expect(results.filter((r) => r.status === 'fulfilled')).toHaveLength(MAX_PENDING_MEDIA_JOBS);
+ expect(results.filter((r) => r.status === 'rejected').map((r) => r.reason)).toEqual([expect.objectContaining(queueFull)]);
+ expect(waiting()).toBe(MAX_PENDING_MEDIA_JOBS);
+ await flush();
+
+ const snapshot = readFileSync(jobsFile(), 'utf8');
+ const liveCount = mediaJobQueue.listJobs().length;
+ const enqueued = vi.fn();
+ mediaJobQueue.mediaJobEvents.on('enqueued', enqueued);
+ atomicWriteSpy.mockClear();
+ await expect(mediaJobQueue.enqueueJob({ kind: 'image', params: { prompt: 'one more' } }))
+ .rejects.toMatchObject({ ...queueFull, context: { retryable: true, maxPendingJobs: MAX_PENDING_MEDIA_JOBS } });
+ await flush();
+ expect(mediaJobQueue.listJobs()).toHaveLength(liveCount);
+ expect(enqueued).not.toHaveBeenCalled();
+ expect(atomicWriteSpy).not.toHaveBeenCalled();
+ expect(readFileSync(jobsFile(), 'utf8')).toBe(snapshot);
+ mediaJobQueue.mediaJobEvents.off('enqueued', enqueued);
+
+ // Draining one waiting job frees exactly one slot.
+ await mediaJobQueue.cancelJob(mediaJobQueue.listJobs({ status: 'queued' })[0].id);
+ await expect(mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'after drain' } }))
+ .resolves.toMatchObject({ status: 'queued' });
+ });
+
+ // A batch preflight: one that fits is admitted to try, one that could fit
+ // after a drain is retryable, one bigger than the ceiling never can be.
+ it('distinguishes a batch that must wait from one that can never fit', async () => {
+ const { MAX_PENDING_MEDIA_JOBS } = mediaJobQueue;
+ expect(() => mediaJobQueue.assertMediaQueueRoom(MAX_PENDING_MEDIA_JOBS)).not.toThrow();
+ expect(() => mediaJobQueue.assertMediaQueueRoom(MAX_PENDING_MEDIA_JOBS + 1))
+ .toThrow(expect.objectContaining({ status: 400, code: 'MEDIA_BATCH_TOO_LARGE' }));
+ await mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'running' } });
+ await mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'waiting' } });
+ await waitFor(() => waiting() === 1);
+ expect(() => mediaJobQueue.assertMediaQueueRoom(MAX_PENDING_MEDIA_JOBS))
+ .toThrow(expect.objectContaining({ ...queueFull, message: expect.stringContaining('room for 249 more') }));
+ });
+
+ it('restores a snapshot above the ceiling intact and blocks only new admissions until it drains', async () => {
+ const { MAX_PENDING_MEDIA_JOBS } = mediaJobQueue;
+ const count = MAX_PENDING_MEDIA_JOBS + 10;
+ const ids = Array.from({ length: count }, (_, i) => `00000000-0000-4000-8000-${String(i).padStart(12, '0')}`);
+ writeFileSync(jobsFile(), JSON.stringify({
+ jobs: ids.map((id) => ({ id, kind: 'video', status: 'queued', queuedAt: '2026-09-01T00:00:00.000Z', params: { prompt: 'restored' } })),
+ }));
+
+ await importFresh();
+ await mediaJobQueue.initMediaJobQueue();
+ await waitFor(() => stubs.generateVideo.mock.calls.length === 1);
+ await flush();
+
+ // Nothing evicted — in memory or on disk.
+ expect(mediaJobQueue.listJobs().map((j) => j.id).sort()).toEqual([...ids].sort());
+ expect(JSON.parse(readFileSync(jobsFile(), 'utf8')).jobs.map((j) => j.id).sort()).toEqual([...ids].sort());
+ expect(waiting()).toBe(count - 1);
+
+ await expect(mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'new' } })).rejects.toMatchObject(queueFull);
+
+ // Drain to one below the ceiling; admission reopens for exactly that room.
+ const queuedIds = mediaJobQueue.listJobs({ status: 'queued' }).map((j) => j.id);
+ for (const id of queuedIds.slice(0, count - MAX_PENDING_MEDIA_JOBS)) await mediaJobQueue.cancelJob(id);
+ expect(waiting()).toBe(MAX_PENDING_MEDIA_JOBS - 1);
+ await expect(mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'fits' } })).resolves.toMatchObject({ status: 'queued' });
+ await expect(mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'full again' } })).rejects.toMatchObject(queueFull);
+ });
+});
diff --git a/server/services/universeBuilderCollectionHook.js b/server/services/universeBuilderCollectionHook.js
index 24eea1a88d..f97cd44032 100644
--- a/server/services/universeBuilderCollectionHook.js
+++ b/server/services/universeBuilderCollectionHook.js
@@ -38,6 +38,19 @@ export function registerUniverseBuilderRun({ runId, universeId, jobCount }) {
activeRuns.set(runId, { universeId, pending: jobCount });
}
+// A batch refused part-way by the media queue (#8326) never enqueues
+// `unadmitted` of the jobs it registered. Drop them from the count so the run's
+// coalesced emit still fires once the admitted ones finish — or now, when they
+// already have (or none were admitted).
+export function shrinkUniverseBuilderRun(runId, unadmitted) {
+ const entry = activeRuns.get(runId);
+ if (!entry || !(unadmitted > 0)) return;
+ entry.pending -= unadmitted;
+ if (entry.pending > 0) return;
+ activeRuns.delete(runId);
+ emitRecordUpdated('universe', entry.universeId);
+}
+
// Returns the run's universeId when this terminal closes the batch (pending → 0),
// otherwise null. Callers use the return value as the "fire the final emit" signal.
function noteTerminal(runId) {
diff --git a/server/services/universeBuilderCollectionHook.test.js b/server/services/universeBuilderCollectionHook.test.js
index a7f3ca8f16..673f21eecd 100644
--- a/server/services/universeBuilderCollectionHook.test.js
+++ b/server/services/universeBuilderCollectionHook.test.js
@@ -155,6 +155,23 @@ describe('universeBuilderCollectionHook', () => {
expect(hook.__testing.getActiveRuns().size).toBe(0);
});
+ // #8326: a batch the media queue refused part-way registered more jobs than
+ // it enqueued. Without the shrink the run never reaches zero and every
+ // later completion stays suppressed with no final emit.
+ it('closes a run shrunk after a partial admission once its admitted jobs finish', async () => {
+ const universeId = 'uni-partial';
+ const c = await makeCollection(universeId);
+ hook.registerUniverseBuilderRun({ runId: 'r-partial', universeId, jobCount: 3 });
+ hook.shrinkUniverseBuilderRun('r-partial', 2);
+ expect(hook.__testing.getActiveRuns().size).toBe(1);
+
+ emitCompletion({ runId: 'r-partial', universeId, collectionId: c.id, filename: 'p.png' });
+
+ const unsuppressed = () => updates.filter((u) => u.recordKind === 'universe' && u.recordId === universeId && !u.suppressed);
+ await waitFor(() => hook.__testing.getActiveRuns().size === 0 && unsuppressed().length >= 1);
+ expect(unsuppressed()).toHaveLength(1);
+ });
+
it('falls back to per-image emits when run is not registered', async () => {
const universeId = 'uni-3';
const c = await makeCollection(universeId);
diff --git a/server/services/universeBuilderRender.js b/server/services/universeBuilderRender.js
index 511d6d73ad..7d09dcbe7d 100644
--- a/server/services/universeBuilderRender.js
+++ b/server/services/universeBuilderRender.js
@@ -11,11 +11,11 @@
import { randomUUID } from 'crypto';
import * as svc from './universeBuilder.js';
-import { enqueueJob } from './mediaJobQueue/index.js';
+import { assertMediaQueueRoom, enqueueJob, partialBatchAdmissionError } from './mediaJobQueue/index.js';
import { getSettings } from './settings.js';
import { findOrCreateUniverseCollection } from './mediaCollections.js';
import { buildUniverseRunTag } from './universeRunTag.js';
-import { registerUniverseBuilderRun } from './universeBuilderCollectionHook.js';
+import { registerUniverseBuilderRun, shrinkUniverseBuilderRun } from './universeBuilderCollectionHook.js';
import { IMAGE_GEN_MODE, QUEUEABLE_IMAGE_MODES } from './imageGen/modes.js';
import { resolveRenderTargetConfig } from './imageGen/cloudProviderConfig.js';
import { resolveLocalImageModel } from './imageGen/prepareParams.js';
@@ -94,6 +94,10 @@ export async function renderUniverseJobs(universeId, body, mapServiceError) {
});
}
+ // Refuse a batch the media queue cannot hold (#8326) whole — before the
+ // collection is provisioned or any render lands — rather than half-queue it.
+ assertMediaQueueRoom(compiled.length);
+
// Provision the collection up front so renders can be tagged as they
// complete. The completion hook (universeBuilderCollectionHook) will add
// each finished image's filename to this collection. Resolution is
@@ -148,6 +152,14 @@ export async function renderUniverseJobs(universeId, body, mapServiceError) {
// emitRecordUpdated calls. `compiled.length` is the authoritative expected
// count (each compiled item produces exactly one job below).
registerUniverseBuilderRun({ runId, universeId: universe.id, jobCount: compiled.length });
+ const recordRun = () => svc.recordRun({
+ id: runId,
+ universeId: universe.id,
+ collectionId: collection.id,
+ jobIds,
+ promptCount: compiled.length,
+ createdAt: new Date().toISOString(),
+ });
for (const item of compiled) {
const params = {
...baseParams,
@@ -172,43 +184,30 @@ export async function renderUniverseJobs(universeId, body, mapServiceError) {
entryRef: item.entryRef,
}),
};
- let queued;
// The queue dispatches directly to imageGen/{codex,local}.generateImage,
// bypassing imageGen/index.js's dispatcher that resolves cleaners for
// direct callers. Resolve here so the per-mode cleanC2PA + denoise
// settings apply to Universe Builder batch renders the same way they
// do for /api/image-gen/generate and pipeline renders.
const { cleanC2PA, denoise } = resolveImageCleaners(undefined, settings, mode);
- if (cloud) {
- queued = await enqueueJob({
- kind: 'image',
- params: { ...cloud.jobParams, cleanC2PA, denoise, ...params },
- });
- } else {
+ const jobParams = cloud
+ ? { ...cloud.jobParams, cleanC2PA, denoise, ...params }
// mode === IMAGE_GEN_MODE.LOCAL (validated upfront).
- queued = await enqueueJob({
- kind: 'image',
- params: {
- pythonPath: localModel.pythonPath,
- modelId: localModel.selectedModel.id,
- cleanC2PA,
- denoise,
- ...params,
- },
- });
- }
+ : { pythonPath: localModel.pythonPath, modelId: localModel.selectedModel.id, cleanC2PA, denoise, ...params };
+ const queued = await enqueueJob({ kind: 'image', params: jobParams }).catch(async (err) => {
+ // Refused part-way (another producer filled the queue after the
+ // preflight): the rest will never be enqueued, so release them from the
+ // run's pending count, keep a run record for the renders that DID land,
+ // and say how many that was.
+ shrinkUniverseBuilderRun(runId, compiled.length - jobIds.length);
+ if (jobIds.length) await recordRun();
+ throw partialBatchAdmissionError(err, { admitted: jobIds.length, total: compiled.length, noun: 'renders' });
+ });
jobIds.push(queued.jobId);
if (item.entryRef) entryJobs.push({ jobId: queued.jobId, entryRef: item.entryRef });
}
- const run = await svc.recordRun({
- id: runId,
- universeId: universe.id,
- collectionId: collection.id,
- jobIds,
- promptCount: compiled.length,
- createdAt: new Date().toISOString(),
- });
+ const run = await recordRun();
console.log(`🌍 Universe Builder render — universe=${universe.name} prompts=${compiled.length} mode=${mode} runId=${runId.slice(0, 8)}`);
diff --git a/server/services/universeBuilderRender.test.js b/server/services/universeBuilderRender.test.js
index d3508f2c62..c69bef899b 100644
--- a/server/services/universeBuilderRender.test.js
+++ b/server/services/universeBuilderRender.test.js
@@ -10,6 +10,8 @@ const mocks = vi.hoisted(() => ({
findOrCreateUniverseCollection: vi.fn(),
buildUniverseRunTag: vi.fn(),
registerUniverseBuilderRun: vi.fn(),
+ shrinkUniverseBuilderRun: vi.fn(),
+ assertMediaQueueRoom: vi.fn(),
}));
vi.mock('./universeBuilder.js', () => ({
@@ -18,10 +20,17 @@ vi.mock('./universeBuilder.js', () => ({
recordRun: (...args) => mocks.recordRun(...args),
}));
vi.mock('./settings.js', () => ({ getSettings: (...args) => mocks.getSettings(...args) }));
-vi.mock('./mediaJobQueue/index.js', () => ({ enqueueJob: (...args) => mocks.enqueueJob(...args) }));
+vi.mock('./mediaJobQueue/index.js', async () => ({
+ enqueueJob: (...args) => mocks.enqueueJob(...args),
+ assertMediaQueueRoom: (...args) => mocks.assertMediaQueueRoom(...args),
+ partialBatchAdmissionError: (await import('./mediaJobQueue/admission.js')).partialBatchAdmissionError,
+}));
vi.mock('./mediaCollections.js', () => ({ findOrCreateUniverseCollection: (...args) => mocks.findOrCreateUniverseCollection(...args) }));
vi.mock('./universeRunTag.js', () => ({ buildUniverseRunTag: (...args) => mocks.buildUniverseRunTag(...args) }));
-vi.mock('./universeBuilderCollectionHook.js', () => ({ registerUniverseBuilderRun: (...args) => mocks.registerUniverseBuilderRun(...args) }));
+vi.mock('./universeBuilderCollectionHook.js', () => ({
+ registerUniverseBuilderRun: (...args) => mocks.registerUniverseBuilderRun(...args),
+ shrinkUniverseBuilderRun: (...args) => mocks.shrinkUniverseBuilderRun(...args),
+}));
vi.mock('./imageGen/index.js', () => ({
IMAGE_GEN_MODE: { LOCAL: 'local', EXTERNAL: 'external' },
resolveImageCleaners: () => ({ cleanC2PA: false, denoise: false }),
@@ -44,7 +53,7 @@ beforeEach(() => {
mocks.getUniverse.mockResolvedValue({ id: 'universe-1', name: 'Example Universe' });
mocks.compilePrompts.mockReturnValue([{ prompt: 'render prompt', category: 'character', label: 'Example' }]);
mocks.recordRun.mockImplementation(async (run) => run);
- mocks.enqueueJob.mockReturnValue({ jobId: 'job-1' });
+ mocks.enqueueJob.mockResolvedValue({ jobId: 'job-1' });
mocks.getSettings.mockResolvedValue({
imageGen: { mode: 'local', local: { pythonPath: '/python', modelId: 'pinned-model' } },
});
@@ -76,3 +85,32 @@ describe('renderUniverseJobs local model selection', () => {
expect(mocks.enqueueJob).not.toHaveBeenCalled();
});
});
+
+// #8326: the batch is preflighted against the queue ceiling, but another
+// producer can still fill the queue mid-batch. The renders that landed must be
+// recorded, the rest released from the run's coalescing count (or its final
+// re-export never fires), and the error must say how many landed.
+describe('renderUniverseJobs under a full media queue', () => {
+ const queueFull = () => Object.assign(new Error('The media queue is full'), { status: 429, code: 'MEDIA_QUEUE_FULL' });
+
+ it('refuses an oversized batch before provisioning the collection', async () => {
+ mocks.assertMediaQueueRoom.mockImplementationOnce(() => { throw queueFull(); });
+ await expect(renderUniverseJobs('universe-1', {}, (err) => err)).rejects.toMatchObject({ code: 'MEDIA_QUEUE_FULL' });
+ expect(mocks.findOrCreateUniverseCollection).not.toHaveBeenCalled();
+ expect(mocks.enqueueJob).not.toHaveBeenCalled();
+ });
+
+ it('records the admitted renders and releases the rest when the queue fills mid-batch', async () => {
+ mocks.compilePrompts.mockReturnValue([
+ { prompt: 'first', category: 'character', label: 'A' },
+ { prompt: 'second', category: 'character', label: 'B' },
+ ]);
+ mocks.enqueueJob.mockResolvedValueOnce({ jobId: 'job-1' }).mockRejectedValueOnce(queueFull());
+ await expect(renderUniverseJobs('universe-1', {}, (err) => err)).rejects.toMatchObject({
+ status: 429, code: 'MEDIA_QUEUE_FULL', message: 'Queued 1 of 2 renders — The media queue is full',
+ });
+ const runId = mocks.registerUniverseBuilderRun.mock.calls[0][0].runId;
+ expect(mocks.shrinkUniverseBuilderRun).toHaveBeenCalledWith(runId, 1);
+ expect(mocks.recordRun).toHaveBeenCalledWith(expect.objectContaining({ id: runId, jobIds: ['job-1'], promptCount: 2 }));
+ });
+});