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: persist queued media jobs before acknowledging them (#8325)

[._.]/ Adam Eivyfb88cd63698f
diff --git a/docs/STORAGE.md b/docs/STORAGE.md
index e78fd67734..0afa244a16 100644
--- a/docs/STORAGE.md
+++ b/docs/STORAGE.md
@@ -127,7 +127,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. 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. 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.js b/server/routes/imageGen.js
index c1a32d820f..7ee901ecb5 100644
--- a/server/routes/imageGen.js
+++ b/server/routes/imageGen.js
@@ -60,7 +60,7 @@ const routeSource = (req) => ({ route: `${req.baseUrl}${req.route?.path ?? ''}`,
// Event-only pointer: job id in `target`, never the generation prompt (#5596).
async function enqueueLoggedImage(req, job) {
- const queued = enqueueJob(job);
+ const queued = await enqueueJob(job);
try {
const happenedAt = new Date().toISOString();
await recordUserAction({
diff --git a/server/routes/mediaJobs.js b/server/routes/mediaJobs.js
index 7fa1a2983f..bcfc56e752 100644
--- a/server/routes/mediaJobs.js
+++ b/server/routes/mediaJobs.js
@@ -390,7 +390,7 @@ router.post('/:id/retry', asyncHandler(async (req, res) => {
const { cancelRequested: _canceled, reconcile: _reconcile, ...marker } = params.remoteMedia ?? {};
params.remoteMedia = { ...marker, cancelRequested: false, reconcile: false };
}
- const result = enqueueJob({ kind: job.kind, params, owner: job.owner });
+ const result = await enqueueJob({ kind: job.kind, params, owner: job.owner });
// Drop the original failed/canceled row from archive — the new job inherits
// its work, and leaving both visible just lets users keep clicking Retry on
// the dead row and stacking duplicate jobs. If the prune returns false the
diff --git a/server/routes/music.js b/server/routes/music.js
index 002e06c96d..79d4d6a504 100644
--- a/server/routes/music.js
+++ b/server/routes/music.js
@@ -557,7 +557,7 @@ router.post('/generate', asyncHandler(async (req, res) => {
};
}
- const result = enqueueJob({
+ const result = await enqueueJob({
kind: 'audio',
params: {
// Keep only the fixed-vocabulary profile and routing request under the
diff --git a/server/services/bootstrap.js b/server/services/bootstrap.js
index 701c1c1a69..4511cd4f72 100644
--- a/server/services/bootstrap.js
+++ b/server/services/bootstrap.js
@@ -128,7 +128,7 @@ import { ensureSelf } from './instanceIdentity.js';
import { initSyncLog } from './brainSyncLog.js';
import { backfillOriginInstanceId, brainCollectionStores } from './brainStorage.js';
import { initSyncOrchestrator } from './syncOrchestrator.js';
-import { initMediaJobQueue } from './mediaJobQueue/index.js';
+import { initMediaJobQueue, flushMediaJobQueue } from './mediaJobQueue/index.js';
import { initSpriteLocalAnimationHook } from './sprites/localAnimationJobHook.js';
import { initLoraTraining } from './loraTraining/index.js';
import { initSharing } from './sharing/index.js';
@@ -1107,6 +1107,16 @@ export const registerShutdownHandlers = ({ io, httpServer, localHttpServer }) =>
closeServer(localHttpServer, 'Local HTTP mirror')
]);
+ // Flush the media-job queue now that no request can admit another job
+ // (#8325): terminal transitions and the latest progress reach the snapshot a
+ // restart restores from. The file write is independent of Postgres, so it
+ // runs alongside the DB close below and is awaited before exit — bounded by
+ // its own timeout so it spends no budget beyond the DB close's.
+ const mediaQueueFlushed = flushMediaJobQueue().then((outcome) => {
+ if (outcome.ok) console.log('✅ Media job queue flushed');
+ else console.error(`❌ Media job queue flush failed: ${outcome.error}`);
+ });
+
const { close } = await import('../lib/db.js');
if (typeof close === 'function') {
// Bound the DB pool close: pool.end() waits for every checked-out client to
@@ -1119,6 +1129,7 @@ export const registerShutdownHandlers = ({ io, httpServer, localHttpServer }) =>
}
await markerWritten;
+ await mediaQueueFlushed;
clearTimeout(forceExitTimer);
process.exit(0);
};
diff --git a/server/services/bootstrap.shutdown.test.js b/server/services/bootstrap.shutdown.test.js
index 55ed3edc1f..8ce9e61ece 100644
--- a/server/services/bootstrap.shutdown.test.js
+++ b/server/services/bootstrap.shutdown.test.js
@@ -150,3 +150,22 @@ describe('shutdown handler — detached-group teardown (#7496)', () => {
expect(code.indexOf('signalDetachedGroups(')).toBeLessThan(code.indexOf('closeAllConnections'));
});
});
+
+// #8325. An admitted media job is acknowledged only once its snapshot is on
+// disk; shutdown must not exit while that write, a terminal transition, or the
+// final progress snapshot is still in the persist chain.
+describe('shutdown handler — media-job queue flush (#8325)', () => {
+ const code = stripCommentsAndNormalize(extractDeclaration(SRC, 'shutdown') || '');
+
+ it('flushes after admissions stop, before the DB close, and awaits it before exiting', () => {
+ const flushAt = code.indexOf('flushMediaJobQueue(');
+ expect(flushAt, 'flushMediaJobQueue() is not called in shutdown()').toBeGreaterThan(-1);
+ // Started only once the HTTP servers stop accepting requests, so no route
+ // can admit a job the flush misses.
+ expect(flushAt).toBeGreaterThan(code.indexOf("closeServer(httpServer"));
+ expect(flushAt).toBeLessThan(code.indexOf("import('../lib/db.js')"));
+ const awaitAt = code.indexOf('await mediaQueueFlushed');
+ expect(awaitAt).toBeGreaterThan(flushAt);
+ expect(awaitAt).toBeLessThan(code.indexOf('process.exit(0)'));
+ });
+});
diff --git a/server/services/creativeDirector/firstPassMusicGen.js b/server/services/creativeDirector/firstPassMusicGen.js
index aa3c8a4b64..d937b0d960 100644
--- a/server/services/creativeDirector/firstPassMusicGen.js
+++ b/server/services/creativeDirector/firstPassMusicGen.js
@@ -93,7 +93,7 @@ export async function enqueueFirstPassMusicBed(project, { engine } = {}) {
if (!prompt) {
return { mode: resolvedEngine, enqueued: false, reason: 'no-prompt' };
}
- const queued = enqueueJob({
+ const queued = await enqueueJob({
kind: 'audio',
params: {
prompt,
diff --git a/server/services/creativeDirector/videoAudio.js b/server/services/creativeDirector/videoAudio.js
index cfb0a9626f..401ace1539 100644
--- a/server/services/creativeDirector/videoAudio.js
+++ b/server/services/creativeDirector/videoAudio.js
@@ -60,7 +60,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 } = await import('../mediaJobQueue/index.js');
+ const { getJob, enqueueJob, MEDIA_QUEUE_PERSIST_FAILED } = 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));
@@ -70,9 +70,15 @@ export async function prepareVideoSoundtrack(project, isCurrent) {
if (!attempt) return null;
await assertVideoAttemptDispatch(project.id, attempt.id);
// Persist before enqueue; the queue worker checks this receipt again.
- const { jobId } = enqueueJob({ kind: 'audio', owner: `creative-director:${project.id}`,
+ const { jobId } = await enqueueJob({ kind: 'audio', owner: `creative-director:${project.id}`,
params: { engine: audio.providerId, modelId: audio.model, prompt: audio.prompt, durationSec: audio.durationSec,
- videoProduction: { projectId: project.id, attemptId: attempt.id, executionId: attempt.executionId } } });
+ 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' });
+ throw error;
+ });
await settleVideoAttempt(project.id, attempt.id, { status: 'queued', jobId });
attempt = { ...attempt, jobId };
}
diff --git a/server/services/creativeDirector/videoExecution.js b/server/services/creativeDirector/videoExecution.js
index ebb4ac3de0..c626f42c56 100644
--- a/server/services/creativeDirector/videoExecution.js
+++ b/server/services/creativeDirector/videoExecution.js
@@ -301,7 +301,11 @@ 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) {
- const uncertain = error.code !== 'VIDEO_DISPATCH_BLOCKED';
+ // 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';
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 8e866c9d9a..eba8cf182f 100644
--- a/server/services/creativeDirector/videoExecution.test.js
+++ b/server/services/creativeDirector/videoExecution.test.js
@@ -17,7 +17,8 @@ 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)),
- enqueueJob: vi.fn(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 }; }),
+ 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) }));
vi.mock('../pipeline/audioMux.js', () => ({ resolveMusicTrackPath: vi.fn(async filename => filename ? `/fake/music/${filename}` : null) }));
diff --git a/server/services/deckRender.js b/server/services/deckRender.js
index d79f99a54e..f30c2b6e16 100644
--- a/server/services/deckRender.js
+++ b/server/services/deckRender.js
@@ -98,7 +98,12 @@ export async function renderDeckCards(deckId, { cardIds, onlyMissing = false, mo
...(localModel?.selectedModel?.id ? { modelId: localModel.selectedModel.id } : {}),
...base,
};
- const { jobId } = enqueueJob({ kind: 'image', params, owner: 'decks' });
+ // A refused admission (#8325) still stamps the cards already queued, so
+ // the deck shows the renders that WILL land before the error surfaces.
+ const { jobId } = await enqueueJob({ kind: 'image', params, owner: 'decks' }).catch(async (err) => {
+ if (stamps.length) await markCardsRenderQueued(deck.id, stamps);
+ throw err;
+ });
jobs.push({ cardId: card.id, key: card.key, jobId });
stamps.push({ cardId: card.id, render: {
jobId, status: 'queued', queuedAt: new Date().toISOString(), mode,
diff --git a/server/services/deckRender.test.js b/server/services/deckRender.test.js
index 03ccc085fb..ac568ea5bf 100644
--- a/server/services/deckRender.test.js
+++ b/server/services/deckRender.test.js
@@ -1,6 +1,6 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
-const enqueueJob = vi.fn(() => ({ jobId: 'job-1', position: 1, status: 'queued' }));
+const enqueueJob = vi.fn(async () => ({ jobId: 'job-1', position: 1, status: 'queued' }));
const getSettings = vi.fn();
const getDeck = vi.fn();
const markCardsRenderQueued = vi.fn(async () => ({}));
diff --git a/server/services/fableLoom/production.js b/server/services/fableLoom/production.js
index 2b2a4dc12f..c5f926e745 100644
--- a/server/services/fableLoom/production.js
+++ b/server/services/fableLoom/production.js
@@ -831,7 +831,7 @@ async function advanceRun(runId) {
}
const visualConditioning = enrichConditioning(job.params.visualConditioning, job, asset);
if (visualConditioning) job.params.visualConditioning = visualConditioning;
- const enqueued = enqueueJob({
+ const enqueued = await enqueueJob({
kind: job.kind,
params: job.params,
owner: `fableloom:${run.loomId}:${run.episodeId}:${asset.id}`,
diff --git a/server/services/federatedMediaProvider.js b/server/services/federatedMediaProvider.js
index 07468bcb01..39bec3aa85 100644
--- a/server/services/federatedMediaProvider.js
+++ b/server/services/federatedMediaProvider.js
@@ -858,7 +858,7 @@ export async function submitFederatedMediaJob({ callerId, config, input, idempot
idempotencyKey,
requestHash,
};
- const queued = enqueueJob({
+ const queued = await enqueueJob({
kind: input.kind,
owner: jobOwner(callerId),
params: buildQueueParams(input, capability, federatedMedia, inputAssetParams),
diff --git a/server/services/imageGen/cleanGpu.js b/server/services/imageGen/cleanGpu.js
index 499892e032..03a90152fb 100644
--- a/server/services/imageGen/cleanGpu.js
+++ b/server/services/imageGen/cleanGpu.js
@@ -106,7 +106,7 @@ export async function enqueueGpuClean({
// Render to the temp dir with no sidecar so the gallery stays clean.
params.outputTarget = { dir: PATHS.imageCleanTmp, skipSidecar: true };
- const queued = enqueueJob({ kind: 'image', params });
+ const queued = await enqueueJob({ kind: 'image', params });
const jobId = queued.jobId;
// Stage the preserve-region inputs (only when a mask rode along) so the
diff --git a/server/services/loraDatasetGenerate.js b/server/services/loraDatasetGenerate.js
index 7cd9d94d41..9810385e6c 100644
--- a/server/services/loraDatasetGenerate.js
+++ b/server/services/loraDatasetGenerate.js
@@ -318,7 +318,7 @@ export async function generateDatasetImages(datasetId, options = {}) {
const imageId = uuidv4();
const file = `${imageId}.png`;
const { prompt, negativePrompt } = buildDatasetImagePrompt(universe, subject, variation, entryKind);
- const queued = enqueueJob({ kind: 'image', params: { ...base, prompt, negativePrompt } });
+ const queued = await enqueueJob({ kind: 'image', params: { ...base, prompt, negativePrompt } });
const jobId = queued.jobId;
const entry = {
diff --git a/server/services/loraTraining/index.js b/server/services/loraTraining/index.js
index 01dc05076a..4135b6d055 100644
--- a/server/services/loraTraining/index.js
+++ b/server/services/loraTraining/index.js
@@ -219,7 +219,9 @@ export async function startTrainingRun({
};
await runsDb.createRun(run);
- const queued = enqueueJob({
+ // The run row already exists, so a refused admission (#8325) must fail it
+ // rather than leave a 'queued' run no job will ever pick up.
+ const queued = await enqueueJob({
kind: 'training',
owner: 'lora-training',
params: {
@@ -234,6 +236,9 @@ export async function startTrainingRun({
rank: mergedParams.rank,
pythonPath,
},
+ }).catch(async (err) => {
+ await runsDb.updateRun(runId, { status: 'failed', error: err.message, completedAt: new Date().toISOString() });
+ throw err;
});
await runsDb.updateRun(runId, { jobId: queued.jobId });
await stampDatasetTrainingStatus(run, queued.jobId);
@@ -312,7 +317,7 @@ export async function resumeTrainingRun(runId, { auto = false } = {}) {
});
}
- const queued = enqueueJob({
+ const queued = await enqueueJob({
kind: 'training',
owner: 'lora-training',
params: {
diff --git a/server/services/loraTraining/mpsGuard.test.js b/server/services/loraTraining/mpsGuard.test.js
index 34b5da4256..8f56a537b9 100644
--- a/server/services/loraTraining/mpsGuard.test.js
+++ b/server/services/loraTraining/mpsGuard.test.js
@@ -15,7 +15,7 @@ vi.mock('os', async (importActual) => {
const createRunMock = vi.fn(async () => {});
const updateRunMock = vi.fn(async () => {});
-const enqueueJobMock = vi.fn(() => ({ jobId: 'job-1', position: 0 }));
+const enqueueJobMock = vi.fn(async () => ({ jobId: 'job-1', position: 0 }));
const validateDatasetReadyMock = vi.fn(async () => ({
dataset: { character: { entryId: 'c1', universeId: 'u1', name: 'Test Subject' }, triggerWord: 'test_subject' },
manifest: { images: [] },
diff --git a/server/services/mediaJobQueue/index.js b/server/services/mediaJobQueue/index.js
index dd47b654bd..08c90cab36 100644
--- a/server/services/mediaJobQueue/index.js
+++ b/server/services/mediaJobQueue/index.js
@@ -441,7 +441,9 @@ let persistChain = Promise.resolve();
// still runs normally in memory for the life of the process.
let persistBlocked = false;
function persist() {
- if (persistBlocked) return persistChain;
+ // Blocked: nothing is written, but callers awaiting durability (enqueueJob)
+ // must not inherit a stale rejection from a write that predates the latch.
+ if (persistBlocked) return persistChain.catch(() => {});
persistChain = persistChain.then(persistImpl, persistImpl);
return persistChain;
}
@@ -744,7 +746,7 @@ async function drainLoop() {
remote: limits.remote - remoteRunning.length,
};
for (const job of candidates) {
- if (job.status !== 'queued' || job.hold) continue;
+ if (job.status !== 'queued' || job.hold || job.admitting) continue;
const lane = jobLane(job);
if (slots[lane] <= 0) continue;
startLaneJob(job, { lane });
@@ -781,7 +783,7 @@ export function removeArchivedJob(jobId) {
// even if the lane is at its limit. GPU jobs are rejected (single MLX runtime
// would OOM). The rejection code stays 'NOT_CODEX' for client back-compat.
export function runJobNow(jobId) {
- const job = queue.find((j) => j.id === jobId);
+ const job = queue.find((j) => j.id === jobId && !j.admitting);
if (!job) return { ok: false, code: 'NOT_FOUND', error: 'Job not found in queue' };
if (!isCloudImageJob(job)) {
return { ok: false, code: 'NOT_CODEX', error: 'Only cloud-CLI image jobs can be run now; GPU jobs serialize on the MLX runtime' };
@@ -1232,7 +1234,17 @@ async function runJob(job) {
dispatcher.detach();
}
-export function enqueueJob({ kind, params, owner = null }) {
+// 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';
+
+// 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
+// sits in the queue flagged `admitting` (a transient, unserialized field) so the
+// snapshot includes it while drainLoop/runJobNow leave it alone. A failed write
+// withdraws the job and throws, so a caller never holds a job id that a restart
+// would not restore, and no provider work starts for it.
+export async function enqueueJob({ kind, params, owner = null }) {
if (!JOB_KINDS.includes(kind)) {
throw new Error(`enqueueJob: invalid kind '${kind}'`);
}
@@ -1263,11 +1275,30 @@ export function enqueueJob({ kind, params, owner = null }) {
return laneQueue.length + liveCount + 1;
})(),
};
+ job.admitting = true;
queue.push(job);
- const sseEntry = ensureSseEntry(id);
- broadcastSse(sseEntry, { type: 'queued', position: job.position });
+ try {
+ await persist();
+ } catch (err) {
+ // Withdraw before the next snapshot so the rejected job never lands on disk.
+ const idx = queue.indexOf(job);
+ if (idx >= 0) queue.splice(idx, 1);
+ recomputeQueuePositions();
+ // An unrelated write may have landed the admitting job on disk before ours
+ // failed; best-effort rewrite so a restart cannot resurrect a refused job.
+ persist().catch(() => {});
+ console.error(`❌ media-job [${id.slice(0, 8)}] ${kind} not queued — snapshot write failed: ${err.message}`);
+ throw new ServerError(`Could not save the ${kind} job to the media queue: ${err.message}`, {
+ status: 503,
+ code: MEDIA_QUEUE_PERSIST_FAILED,
+ });
+ }
+ delete job.admitting;
+ // A bulk cancel can reach the job while its snapshot is in flight; cancelJob
+ // already archived and announced it, so report that instead of 'queued'.
+ if (job.status !== 'queued') return { jobId: id, position: job.position, status: job.status };
+ broadcastSse(ensureSseEntry(id), { type: 'queued', position: job.position });
mediaJobEvents.emit('enqueued', job);
- persist().catch((e) => console.log(`⚠️ mediaJobQueue persist on enqueue failed: ${e.message}`));
startWorker();
console.log(`📥 media-job [${id.slice(0, 8)}] ${kind} queued (position ${job.position})`);
return { jobId: id, position: job.position, status: 'queued' };
@@ -1462,6 +1493,34 @@ export function attachSseClient(jobId, res) {
return true;
}
+export const MEDIA_QUEUE_FLUSH_TIMEOUT_MS = 2000;
+
+// Graceful-shutdown flush (#8325): let in-flight terminal transitions settle,
+// then write one fresh snapshot — it captures the latest in-memory progress,
+// so a debounced progress write still pending in runJob is not lost — and wait
+// for the whole persist chain behind it. Bounded so a stalled disk cannot eat
+// the shutdown budget; never rejects, reporting the outcome instead.
+export async function flushMediaJobQueue({ timeoutMs = MEDIA_QUEUE_FLUSH_TIMEOUT_MS } = {}) {
+ const drain = (async () => {
+ while (terminalOperations.size > 0) {
+ await Promise.allSettled([...terminalOperations]);
+ }
+ // The lane finalizer schedules its archive snapshot a few microtasks after
+ // the terminal operation settles; yield so most land ahead of our persist.
+ await Promise.resolve();
+ await persist();
+ // A finalizer that still slipped in behind us wrote a newer snapshot.
+ await persistChain;
+ return { ok: true };
+ })().catch((err) => ({ ok: false, error: err.message }));
+ let timer;
+ const timeout = new Promise((resolve) => {
+ timer = setTimeout(() => resolve({ ok: false, timedOut: true, error: `timed out after ${timeoutMs}ms` }), timeoutMs);
+ timer.unref?.();
+ });
+ return Promise.race([drain, timeout]).finally(() => clearTimeout(timer));
+}
+
// Test-only reset hook. Real callers go through enqueueJob/cancelJob.
export function __resetForTests() {
queue.length = 0;
diff --git a/server/services/mediaJobQueue/index.test.js b/server/services/mediaJobQueue/index.test.js
index f0e465e4ce..91eb92e2f6 100644
--- a/server/services/mediaJobQueue/index.test.js
+++ b/server/services/mediaJobQueue/index.test.js
@@ -56,8 +56,7 @@ vi.mock('../../lib/systemCapabilities.js', async (importOriginal) => ({
// 'completed' or 'failed' for the worker to advance — we drive those events
// directly from each test.
const stubs = {
- generateVideo: vi.fn(async () => ({
-tryReadFile: vi.fn().mockResolvedValue(null), jobId: 'whatever' })),
+ generateVideo: vi.fn(async () => ({ jobId: 'whatever' })),
generateVideoGrok: vi.fn(async () => ({ jobId: 'whatever' })),
generateChainedVideo: vi.fn(async () => ({ jobId: 'whatever' })),
generateImage: vi.fn(async () => ({ jobId: 'whatever' })),
@@ -210,12 +209,12 @@ afterEach(async () => {
});
describe('mediaJobQueue', () => {
- it('enqueueJob returns jobId + queued status + position', () => {
+ it('enqueueJob returns jobId + queued status + position', async () => {
// Block the worker so the second enqueue lands behind the first in the
// pipeline rather than entering an empty queue after the first ran.
stubs.generateVideo.mockImplementation(() => new Promise(() => {}));
- const r1 = mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'a' } });
- const r2 = mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'b' } });
+ const r1 = await mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'a' } });
+ const r2 = await mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'b' } });
expect(r1.status).toBe('queued');
expect(r1.jobId).toMatch(/^[0-9a-f-]{36}$/);
expect(r1.position).toBe(1);
@@ -229,8 +228,8 @@ describe('mediaJobQueue', () => {
const upscaleParams = { historyId: 'src-1', sourceFilename: 'src-1.mp4', runtime: 'ltx25', seed: 7 };
it('dispatches to the upscale service and takes the serialized GPU lane', async () => {
- const render = mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'a' } });
- const upscale = mediaJobQueue.enqueueJob({ kind: 'video-upscale', params: upscaleParams });
+ const render = await mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'a' } });
+ const upscale = await mediaJobQueue.enqueueJob({ kind: 'video-upscale', params: upscaleParams });
await waitFor(() => stubs.generateVideo.mock.calls.length === 1);
// The render holds the one GPU slot; the upscale waits behind it rather
@@ -246,7 +245,7 @@ describe('mediaJobQueue', () => {
});
it('settles on the videoGen event bus and cancels through the upscale service', async () => {
- const { jobId } = mediaJobQueue.enqueueJob({ kind: 'video-upscale', params: upscaleParams });
+ const { jobId } = await mediaJobQueue.enqueueJob({ kind: 'video-upscale', params: upscaleParams });
await waitFor(() => stubs.runVideoUpscale.mock.calls.length === 1);
await mediaJobQueue.cancelJob(jobId);
@@ -269,9 +268,9 @@ describe('mediaJobQueue', () => {
// idle peers each read as busy while waiting on the other.
stubs.generateVideo.mockImplementation(() => new Promise(() => {}));
stubs.generateAudioRemote.mockImplementation(() => new Promise(() => {}));
- mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'local' } });
- mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'waiting' } });
- mediaJobQueue.enqueueJob({
+ await mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'local' } });
+ await mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'waiting' } });
+ await mediaJobQueue.enqueueJob({
kind: 'audio',
params: {
prompt: '',
@@ -296,8 +295,8 @@ describe('mediaJobQueue', () => {
it('runs local and Grok video renders in parallel lanes', async () => {
stubs.generateVideo.mockImplementation(() => new Promise(() => {}));
stubs.generateVideoGrok.mockImplementation(() => new Promise(() => {}));
- const local = mediaJobQueue.enqueueJob({ kind: 'video', params: { mode: 'text', prompt: 'local' } });
- const grok = mediaJobQueue.enqueueJob({
+ const local = await mediaJobQueue.enqueueJob({ kind: 'video', params: { mode: 'text', prompt: 'local' } });
+ const grok = await mediaJobQueue.enqueueJob({
kind: 'video',
params: { mode: IMAGE_GEN_MODE.GROK, prompt: 'grok' },
});
@@ -320,9 +319,9 @@ describe('mediaJobQueue', () => {
it('counts queue depth per kind', async () => {
stubs.generateVideo.mockImplementation(() => new Promise(() => {}));
- mediaJobQueue.enqueueJob({ kind: 'video', params: {} });
- mediaJobQueue.enqueueJob({ kind: 'video', params: {} });
- mediaJobQueue.enqueueJob({ kind: 'image', params: {} });
+ await mediaJobQueue.enqueueJob({ kind: 'video', params: {} });
+ await mediaJobQueue.enqueueJob({ kind: 'video', params: {} });
+ await mediaJobQueue.enqueueJob({ kind: 'image', params: {} });
await waitFor(() => stubs.generateVideo.mock.calls.length === 1);
const { byKind } = mediaJobQueue.getQueueCapacity();
@@ -369,8 +368,8 @@ describe('mediaJobQueue', () => {
});
});
- it('rejects unknown kinds', () => {
- expect(() => mediaJobQueue.enqueueJob({ kind: 'bogus', params: {} })).toThrow(/invalid kind/);
+ it('rejects unknown kinds', async () => {
+ await expect(mediaJobQueue.enqueueJob({ kind: 'bogus', params: {} })).rejects.toThrow(/invalid kind/);
});
it('listJobs filters by kind / status / owner', async () => {
@@ -378,9 +377,9 @@ describe('mediaJobQueue', () => {
// the assertions see the queue + running set we expect.
stubs.generateVideo.mockImplementation(() => new Promise(() => {}));
stubs.generateImage.mockImplementation(() => new Promise(() => {}));
- mediaJobQueue.enqueueJob({ kind: 'video', params: {}, owner: 'creative-director:cd-1' });
- mediaJobQueue.enqueueJob({ kind: 'image', params: {}, owner: 'voice' });
- mediaJobQueue.enqueueJob({ kind: 'video', params: {}, owner: 'creative-director:cd-2' });
+ await mediaJobQueue.enqueueJob({ kind: 'video', params: {}, owner: 'creative-director:cd-1' });
+ await mediaJobQueue.enqueueJob({ kind: 'image', params: {}, owner: 'voice' });
+ await mediaJobQueue.enqueueJob({ kind: 'video', params: {}, owner: 'creative-director:cd-2' });
expect(mediaJobQueue.listJobs({ kind: 'video' })).toHaveLength(2);
expect(mediaJobQueue.listJobs({ kind: 'image' })).toHaveLength(1);
expect(mediaJobQueue.listJobs({ owner: 'voice' })).toHaveLength(1);
@@ -405,8 +404,8 @@ describe('mediaJobQueue', () => {
writeFileSync(join(tempDataDir, 'media-jobs.json'), JSON.stringify({ jobs: archived }));
await mediaJobQueue.initMediaJobQueue();
stubs.generateVideo.mockImplementation(() => new Promise(() => {}));
- const first = mediaJobQueue.enqueueJob({ kind: 'video', params: {}, owner: 'example' });
- const second = mediaJobQueue.enqueueJob({ kind: 'video', params: {}, owner: 'example' });
+ const first = await mediaJobQueue.enqueueJob({ kind: 'video', params: {}, owner: 'example' });
+ const second = await mediaJobQueue.enqueueJob({ kind: 'video', params: {}, owner: 'example' });
await flush();
const all = mediaJobQueue.listQueueJobs();
@@ -429,10 +428,10 @@ describe('mediaJobQueue', () => {
// Block the worker so subsequent enqueues stay queued.
let resolveBlocker;
stubs.generateVideo.mockImplementation(() => new Promise((r) => { resolveBlocker = r; }));
- const blocker = mediaJobQueue.enqueueJob({ kind: 'video', params: {} });
- const a = mediaJobQueue.enqueueJob({ kind: 'video', params: {} });
- const b = mediaJobQueue.enqueueJob({ kind: 'image', params: {} });
- const c = mediaJobQueue.enqueueJob({ kind: 'video', params: {} });
+ const blocker = await mediaJobQueue.enqueueJob({ kind: 'video', params: {} });
+ const a = await mediaJobQueue.enqueueJob({ kind: 'video', params: {} });
+ const b = await mediaJobQueue.enqueueJob({ kind: 'image', params: {} });
+ const c = await mediaJobQueue.enqueueJob({ kind: 'video', params: {} });
await flush();
@@ -454,9 +453,9 @@ describe('mediaJobQueue', () => {
it('cancelQueuedJobs respects a kind filter', async () => {
let resolveBlocker;
stubs.generateVideo.mockImplementation(() => new Promise((r) => { resolveBlocker = r; }));
- const blocker = mediaJobQueue.enqueueJob({ kind: 'video', params: {} });
- const v = mediaJobQueue.enqueueJob({ kind: 'video', params: {} });
- const i = mediaJobQueue.enqueueJob({ kind: 'image', params: {} });
+ const blocker = await mediaJobQueue.enqueueJob({ kind: 'video', params: {} });
+ const v = await mediaJobQueue.enqueueJob({ kind: 'video', params: {} });
+ const i = await mediaJobQueue.enqueueJob({ kind: 'image', params: {} });
await flush();
@@ -480,8 +479,8 @@ describe('mediaJobQueue', () => {
// resolves, so subsequent enqueues stay queued for cancellation.
let resolveBlocker;
stubs.generateVideo.mockImplementation(() => new Promise((r) => { resolveBlocker = r; }));
- const blocker = mediaJobQueue.enqueueJob({ kind: 'video', params: {} });
- const target = mediaJobQueue.enqueueJob({ kind: 'video', params: {} });
+ const blocker = await mediaJobQueue.enqueueJob({ kind: 'video', params: {} });
+ const target = await mediaJobQueue.enqueueJob({ kind: 'video', params: {} });
await flush();
@@ -501,7 +500,7 @@ describe('mediaJobQueue', () => {
});
it('worker drains a queued video job and marks it completed on the gen completed event', async () => {
- const job = mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'hi' } });
+ const job = await mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'hi' } });
// Wait until the worker invokes generateVideo. The stub records the call.
await waitFor(() => stubs.generateVideo.mock.calls.length === 1);
// The queue passed our jobId through so the gen module would write to
@@ -526,7 +525,7 @@ describe('mediaJobQueue', () => {
it('progress/status events update the live job record for non-SSE readers', async () => {
const file = join(tempDataDir, 'media-jobs.json');
- const job = mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'progress please' } });
+ const job = await mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'progress please' } });
await waitFor(() => stubs.generateVideo.mock.calls.length === 1);
videoGenEvents.emit('status', { generationId: job.jobId, message: 'Loading pipeline' });
@@ -557,7 +556,7 @@ describe('mediaJobQueue', () => {
});
it('retains the render ETA on the job record so a reload gets it back (#3801)', async () => {
- const job = mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'how long' } });
+ const job = await mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'how long' } });
await waitFor(() => stubs.generateVideo.mock.calls.length === 1);
await waitFor(() => mediaJobQueue.getJob(job.jobId)?.status === 'running');
@@ -578,7 +577,7 @@ describe('mediaJobQueue', () => {
// SSE frames to plot a curve and key sample thumbnails by step. The
// dispatcher must pass those structured fields through (additive — guarded
// by presence so image/video frames that omit them are unaffected).
- const job = mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'metrics' } });
+ const job = await mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'metrics' } });
await waitFor(() => stubs.generateVideo.mock.calls.length === 1);
await waitFor(() => mediaJobQueue.getJob(job.jobId)?.status === 'running');
@@ -622,7 +621,7 @@ describe('mediaJobQueue', () => {
// progress while it does. The phase id is the ONLY thing that lets the page
// say what it is doing, so it has to survive the dispatcher on both frame
// types. Presence-guarded: a frame that carries no phase must not stamp one.
- const job = mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'what are you doing' } });
+ const job = await mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'what are you doing' } });
await waitFor(() => stubs.generateVideo.mock.calls.length === 1);
await waitFor(() => mediaJobQueue.getJob(job.jobId)?.status === 'running');
@@ -656,7 +655,7 @@ describe('mediaJobQueue', () => {
it('debounce-persists live progress before a terminal transition', async () => {
const file = join(tempDataDir, 'media-jobs.json');
- const job = mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'restart snapshot' } });
+ const job = await mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'restart snapshot' } });
await waitFor(() => stubs.generateVideo.mock.calls.length === 1);
// Use a message synthesizeMessage() could NOT produce (it would emit
@@ -690,7 +689,7 @@ describe('mediaJobQueue', () => {
// AGENTS.md forbids. We pin the coalescing by counting atomicWrite calls
// under a burst of N progress events (must be ≪ N within one window).
const file = join(tempDataDir, 'media-jobs.json');
- const job = mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'burst' } });
+ const job = await mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'burst' } });
await waitFor(() => stubs.generateVideo.mock.calls.length === 1);
// Let the enqueue + 'running'-transition writes land first, then zero the
@@ -749,7 +748,7 @@ describe('mediaJobQueue', () => {
});
it('restores cancellation bookkeeping when a provider refuses during finalization', async () => {
- const job = mediaJobQueue.enqueueJob({ kind: 'video', params: {
+ const job = await mediaJobQueue.enqueueJob({ kind: 'video', params: {
mode: 'grok', prompt: 'finishing render', videoProduction: { submissionUncertain: false },
} });
await waitFor(() => stubs.generateVideoGrok.mock.calls.length === 1);
@@ -769,7 +768,7 @@ describe('mediaJobQueue', () => {
});
it.each([true, undefined])('preserves accepted or legacy cancellation results (%s)', async (accepted) => {
- const job = mediaJobQueue.enqueueJob({ kind: 'video', params: { mode: 'grok', prompt: 'cancel render', videoProduction: { projectId: 'example-project', attemptId: 'example-attempt' } } });
+ const job = await mediaJobQueue.enqueueJob({ kind: 'video', params: { mode: 'grok', prompt: 'cancel render', videoProduction: { projectId: 'example-project', attemptId: 'example-attempt' } } });
await waitFor(() => stubs.generateVideoGrok.mock.calls.length === 1);
stubs.cancelVideo.mockImplementationOnce(() => {
videoGenEvents.emit('failed', { generationId: job.jobId, error: 'Stopped' });
@@ -783,7 +782,7 @@ describe('mediaJobQueue', () => {
});
it('cancel during the terminal drain window is refused, not "canceling"', async () => {
- const job = mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'finishing race' } });
+ const job = await mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'finishing race' } });
await waitFor(() => stubs.generateVideo.mock.calls.length === 1);
// Dirty the debounce so terminate() must actually drain (the widened
@@ -925,8 +924,8 @@ describe('mediaJobQueue', () => {
it('persists state to media-jobs.json on enqueue / completion', async () => {
const file = join(tempDataDir, 'media-jobs.json');
- const job = mediaJobQueue.enqueueJob({ kind: 'video', params: {} });
- await waitFor(() => existsSync(file));
+ const job = await mediaJobQueue.enqueueJob({ kind: 'video', params: {} });
+ // Admission is durable (#8325): the acknowledged job is already on disk.
const initial = JSON.parse(readFileSync(file, 'utf-8'));
expect(initial.jobs.find((j) => j.id === job.jobId)).toBeTruthy();
@@ -942,7 +941,7 @@ describe('mediaJobQueue', () => {
});
it('failed gen events propagate to job status', async () => {
- const job = mediaJobQueue.enqueueJob({ kind: 'image', params: { prompt: 'hi' } });
+ const job = await mediaJobQueue.enqueueJob({ kind: 'image', params: { prompt: 'hi' } });
await waitFor(() => stubs.generateImage.mock.calls.length === 1);
imageGenEvents.emit('failed', { generationId: job.jobId, error: 'OOM' });
await waitFor(() => mediaJobQueue.getJob(job.jobId).status === 'failed');
@@ -955,7 +954,7 @@ describe('mediaJobQueue', () => {
it('pre-gen sanitizer nulls uploadedTempPath that resolves outside PATHS.uploads', async () => {
// Any path that is not under the uploads root should be nulled out so the
// gen module never sees it (defense-in-depth against corrupted job params).
- const job = mediaJobQueue.enqueueJob({
+ const job = await mediaJobQueue.enqueueJob({
kind: 'video',
params: { prompt: 'x', uploadedTempPath: '/etc/passwd' },
});
@@ -976,7 +975,7 @@ describe('mediaJobQueue', () => {
// generateVideo hangs forever — never emits completed/failed.
stubs.generateVideo.mockImplementation(() => new Promise(() => {}));
- const job = mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'hang' } });
+ const job = await mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'hang' } });
await waitFor(() => stubs.generateVideo.mock.calls.length === 1);
// The watchdog should fire within 50 ms and fail the job.
@@ -1002,7 +1001,7 @@ describe('mediaJobQueue', () => {
mediaJobQueue.mediaJobEvents.on('failed', (j) => failedEmits.push(j.id));
mediaJobQueue.mediaJobEvents.on('completed', (j) => completedEmits.push(j.id));
- const job = mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'double-terminal' } });
+ const job = await mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'double-terminal' } });
await waitFor(() => stubs.generateVideo.mock.calls.length === 1);
// Let the watchdog fire and confirm the job lands as failed.
@@ -1127,7 +1126,7 @@ describe('mediaJobQueue', () => {
await importFresh();
stubs.generateVideo.mockImplementation(() => new Promise(() => {})); // hang forever
- const job = mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'guard' } });
+ const job = await mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'guard' } });
await waitFor(() => stubs.generateVideo.mock.calls.length === 1);
// Wait a beat — long enough that a NaN-driven watchdog would have fired.
@@ -1140,7 +1139,7 @@ describe('mediaJobQueue', () => {
describe('Audio kind (#1928)', () => {
it('dispatches an audio job to audioGen/local.js#generateAudio and completes', async () => {
- const job = mediaJobQueue.enqueueJob({
+ const job = await mediaJobQueue.enqueueJob({
kind: 'audio',
params: { prompt: 'a moody synth bed', engine: 'musicgen' },
});
@@ -1166,8 +1165,8 @@ describe('Audio kind (#1928)', () => {
stubs.generateVideo.mockImplementation(() => new Promise(() => {}));
stubs.generateAudioRemote.mockImplementation(() => new Promise(() => {}));
- const video = mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'local render' } });
- const remote = mediaJobQueue.enqueueJob({
+ const video = await mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'local render' } });
+ const remote = await mediaJobQueue.enqueueJob({
kind: 'audio',
params: {
prompt: '',
@@ -1195,7 +1194,7 @@ describe('Audio kind (#1928)', () => {
stubs.generateImageRemote.mockImplementation(() => new Promise(() => {}));
// Deliberately hostile input: a caller that passed the local render fields
// straight through, exactly as a forgotten normalization would.
- const remote = mediaJobQueue.enqueueJob({
+ const remote = await mediaJobQueue.enqueueJob({
kind: 'image',
params: {
prompt: 'a harbour',
@@ -1293,11 +1292,11 @@ describe('Audio kind (#1928)', () => {
expect(params.remoteMedia.request.prompt).toBe('a harbour');
});
- it('leaves a training job carrying a stray marker on the local path', () => {
+ it('leaves a training job carrying a stray marker on the local path', async () => {
// Bypass probe for the normalization above: `training` has no federated
// contract, so a marker on one is corrupt state — blanking its params would
// destroy a real local run.
- const job = mediaJobQueue.enqueueJob({
+ const job = await mediaJobQueue.enqueueJob({
kind: 'training',
params: { runId: 'run-1', runtime: 'mflux', modelId: 'dev', remoteMedia: remoteImageMediaParams() },
});
@@ -1307,7 +1306,7 @@ describe('Audio kind (#1928)', () => {
it('persists cancellation intent before signaling a running remote adapter', async () => {
stubs.generateAudioRemote.mockImplementation(() => new Promise(() => {}));
- const remote = mediaJobQueue.enqueueJob({
+ const remote = await mediaJobQueue.enqueueJob({
kind: 'audio',
params: {
prompt: '',
@@ -1362,8 +1361,8 @@ describe('Audio kind (#1928)', () => {
// A local image render occupies the single GPU slot; the federated one must
// still start, because it renders on the peer's hardware.
- const local = mediaJobQueue.enqueueJob({ kind: 'image', params: { prompt: 'local render' } });
- const remote = mediaJobQueue.enqueueJob({
+ const local = await mediaJobQueue.enqueueJob({ kind: 'image', params: { prompt: 'local render' } });
+ const remote = await mediaJobQueue.enqueueJob({
kind: 'image',
params: { prompt: '', modelId: 'dev', remoteMedia: remoteImageMediaParams() },
});
@@ -1387,8 +1386,8 @@ describe('Audio kind (#1928)', () => {
stubs.generateVideo.mockImplementation(() => new Promise(() => {}));
stubs.generateVideoRemote.mockImplementation(() => new Promise(() => {}));
- const local = mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'local render' } });
- const remote = mediaJobQueue.enqueueJob({
+ const local = await mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'local render' } });
+ const remote = await mediaJobQueue.enqueueJob({
kind: 'video',
params: { prompt: '', modelId: null, remoteMedia: remoteVideoMediaParams() },
});
@@ -1450,7 +1449,7 @@ describe('Codex lane', () => {
// Allow the codex job to resolve immediately so the worker can settle.
stubs.generateImageCodex.mockResolvedValue({ jobId: 'whatever' });
- const job = mediaJobQueue.enqueueJob({
+ const job = await mediaJobQueue.enqueueJob({
kind: 'image',
params: { prompt: 'codex test', mode: 'codex' },
});
@@ -1471,8 +1470,8 @@ describe('Codex lane', () => {
stubs.generateVideo.mockImplementation(() => new Promise(() => {}));
stubs.generateImageCodex.mockImplementation(() => new Promise(() => {}));
- const videoJob = mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'video' } });
- const codexJob = mediaJobQueue.enqueueJob({
+ const videoJob = await mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'video' } });
+ const codexJob = await mediaJobQueue.enqueueJob({
kind: 'image',
params: { prompt: 'codex concurrent', mode: 'codex' },
});
@@ -1502,10 +1501,10 @@ describe('Codex lane', () => {
stubs.generateImageCodex.mockImplementation(() => new Promise(() => {}));
// Enqueue one GPU video job (occupies the GPU lane, should not affect Codex positions).
- const videoJob = mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'video blocker' } });
+ const videoJob = await mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'video blocker' } });
// First Codex job: worker picks it up immediately (codexRunning slot).
- const codex1 = mediaJobQueue.enqueueJob({
+ const codex1 = await mediaJobQueue.enqueueJob({
kind: 'image',
params: { prompt: 'codex first', mode: 'codex' },
});
@@ -1514,7 +1513,7 @@ describe('Codex lane', () => {
await waitFor(() => stubs.generateImageCodex.mock.calls.length === 1);
// Second Codex job: lands in queue behind the running Codex job (position 2 in Codex lane).
- const codex2 = mediaJobQueue.enqueueJob({
+ const codex2 = await mediaJobQueue.enqueueJob({
kind: 'image',
params: { prompt: 'codex second', mode: 'codex' },
});
@@ -1537,12 +1536,12 @@ describe('Codex lane', () => {
mediaJobQueue.setCodexParallelLimit(1);
stubs.generateImageCodex.mockImplementation(() => new Promise(() => {}));
- const codex1 = mediaJobQueue.enqueueJob({
+ const codex1 = await mediaJobQueue.enqueueJob({
kind: 'image', params: { prompt: 'codex first', mode: 'codex' },
});
await waitFor(() => stubs.generateImageCodex.mock.calls.length === 1);
- const codex2 = mediaJobQueue.enqueueJob({
+ const codex2 = await mediaJobQueue.enqueueJob({
kind: 'image', params: { prompt: 'codex second', mode: 'codex' },
});
expect(mediaJobQueue.getJob(codex2.jobId).status).toBe('queued');
@@ -1563,9 +1562,9 @@ describe('Codex lane', () => {
// Block the GPU lane with one running job and queue a second so we have a
// queued GPU job to attempt run-now on.
stubs.generateVideo.mockImplementation(() => new Promise(() => {}));
- const v1 = mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'first' } });
+ const v1 = await mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'first' } });
await waitFor(() => stubs.generateVideo.mock.calls.length === 1);
- const v2 = mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'second' } });
+ const v2 = await mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'second' } });
expect(mediaJobQueue.getJob(v2.jobId).status).toBe('queued');
const result = mediaJobQueue.runJobNow(v2.jobId);
@@ -1590,7 +1589,7 @@ describe('audioFilePath sanitization', () => {
it('pre-gen sanitizer nulls audioFilePath that resolves outside PATHS.uploads', async () => {
// audioFilePath must be treated identically to uploadedTempPath: if it
// doesn't resolve under PATHS.uploads, the gen module must never see it.
- const job = mediaJobQueue.enqueueJob({
+ const job = await mediaJobQueue.enqueueJob({
kind: 'video',
params: { prompt: 'x', audioFilePath: '/etc/shadow' },
});
@@ -1605,7 +1604,7 @@ describe('audioFilePath sanitization', () => {
describe('chunks dispatch', () => {
it('video job with chunks > 1 calls generateChainedVideo instead of generateVideo', async () => {
- const job = mediaJobQueue.enqueueJob({
+ const job = await mediaJobQueue.enqueueJob({
kind: 'video',
params: { prompt: 'chained', chunks: 3 },
});
@@ -1622,7 +1621,7 @@ describe('chunks dispatch', () => {
});
it('video job with chunks === 1 calls generateVideo (not generateChainedVideo)', async () => {
- const job = mediaJobQueue.enqueueJob({
+ const job = await mediaJobQueue.enqueueJob({
kind: 'video',
params: { prompt: 'single', chunks: 1 },
});
@@ -1648,7 +1647,7 @@ describe('live pythonPath re-resolution', () => {
join(tempDataDir, 'settings.json'),
JSON.stringify({ imageGen: { local: { pythonPath: '/live/path/python3' } } }),
);
- const job = mediaJobQueue.enqueueJob({
+ const job = await mediaJobQueue.enqueueJob({
kind: 'video',
params: { prompt: 'stale-snapshot', pythonPath: '/stale/anaconda/python3' },
});
@@ -1663,7 +1662,7 @@ describe('live pythonPath re-resolution', () => {
join(tempDataDir, 'settings.json'),
JSON.stringify({ imageGen: { local: { pythonPath: '/live/path/python3' } } }),
);
- const job = mediaJobQueue.enqueueJob({
+ const job = await mediaJobQueue.enqueueJob({
kind: 'image',
params: { prompt: 'codex', mode: 'codex' },
});
@@ -1679,7 +1678,7 @@ describe('cancelJob running-Codex branch', () => {
// Codex job hangs indefinitely so it stays in 'running' for the cancel.
stubs.generateImageCodex.mockImplementation(() => new Promise(() => {}));
- const job = mediaJobQueue.enqueueJob({
+ const job = await mediaJobQueue.enqueueJob({
kind: 'image',
params: { prompt: 'codex running cancel', mode: 'codex' },
});
@@ -1742,7 +1741,7 @@ describe('mediaJobQueue unreadable snapshot (#4115)', () => {
// …and so is every write the running queue would normally make.
stubs.generateVideo.mockImplementation(() => new Promise(() => {}));
- mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'after a bad boot' } });
+ await mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'after a bad boot' } });
await flush();
expect(
readFileSync(file, 'utf8'),
@@ -1757,7 +1756,7 @@ describe('mediaJobQueue unreadable snapshot (#4115)', () => {
await mediaJobQueue.initMediaJobQueue();
stubs.generateVideo.mockImplementation(() => new Promise(() => {}));
- const job = mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'good boot' } });
+ const job = await mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'good boot' } });
await flush();
const written = JSON.parse(readFileSync(file, 'utf8'));
expect(written.jobs.map((j) => j.id)).toContain(job.jobId);
@@ -1844,9 +1843,15 @@ describe('local video failure holds', () => {
await vi.advanceTimersByTimeAsync(150);
await flush();
};
- const submit = (modelId = 'example-mlx', extra = {}) => mediaJobQueue.enqueueJob({
+ const submit = async (modelId = 'example-mlx', extra = {}) => (await mediaJobQueue.enqueueJob({
kind: 'video', owner: 'example-owner', params: { modelId, prompt: 'invented clip', ...extra },
- }).jobId;
+ })).jobId;
+ // Admission is async (#8325); submit in order so queue positions stay FIFO.
+ const submitMany = async (count, make = () => submit()) => {
+ const ids = [];
+ for (let i = 0; i < count; i += 1) ids.push(await make());
+ return ids;
+ };
const finish = async (id, error = 'RuntimeError: shader compilation failed') => {
videoGenEvents.emit(error ? 'failed' : 'completed', { generationId: id, error });
await flush();
@@ -1856,7 +1861,7 @@ describe('local video failure holds', () => {
const upload = join(tempDataDir, 'uploads', 'example.png');
mkdirSync(join(tempDataDir, 'uploads'));
writeFileSync(upload, 'synthetic image');
- const ids = Array.from({ length: 5 }, () => submit(modelId, { uploadedTempPath: upload, seed: 42 }));
+ const ids = await submitMany(5, () => submit(modelId, { uploadedTempPath: upload, seed: 42 }));
for (const id of ids.slice(0, 3)) {
await tick();
expect(mediaJobQueue.getJob(id).status).toBe('running');
@@ -1893,16 +1898,16 @@ describe('local video failure holds', () => {
});
it('refills mixed lanes in FIFO order while skipping holds and oversubscribed cloud capacity', async () => {
- const heldBatch = Array.from({ length: 4 }, () => submit());
+ const heldBatch = await submitMany(4);
for (const id of heldBatch.slice(0, 3)) { await tick(); await finish(id); }
mediaJobQueue.setCodexParallelLimit(1);
stubs.generateImageCodex.mockResolvedValue({});
- const cloudJob = () => mediaJobQueue.enqueueJob({
+ const cloudJob = async () => (await mediaJobQueue.enqueueJob({
kind: 'image', params: { mode: 'codex', prompt: 'example cloud image' },
- }).jobId;
+ })).jobId;
const remoteJob = () => submit('example-mlx', { remoteMedia: remoteVideoMediaParams() });
- const gpu = [submit('example-other')];
- const cloud = [cloudJob()];
+ const gpu = [await submit('example-other')];
+ const cloud = [await cloudJob()];
// Concurrent dynamic imports can bypass the module mock in this test runner;
// without this adapter stub, 19 of 20 dispatches reach the real peer lookup.
const { REMOTE_MEDIA_MODULES } = await import('./remoteMediaJob.js');
@@ -1910,17 +1915,17 @@ describe('local video failure holds', () => {
generateVideo: stubs.generateVideoRemote,
});
const remoteLimit = mediaJobQueue.getQueueCapacity().lanes.remote.limit;
- const remote = Array.from({ length: remoteLimit }, remoteJob);
+ const remote = await submitMany(remoteLimit, remoteJob);
await tick();
- cloud.push(cloudJob());
+ cloud.push(await cloudJob());
expect(mediaJobQueue.runJobNow(cloud[1]).ok).toBe(true);
await tick();
// Interleave waiting jobs behind all three busy lanes and the held cohort.
for (let i = 0; i < 2; i += 1) {
- cloud.push(cloudJob());
- gpu.push(submit('example-other'));
- remote.push(remoteJob());
+ cloud.push(await cloudJob());
+ gpu.push(await submit('example-other'));
+ remote.push(await remoteJob());
}
await tick();
const occupancy = () => {
@@ -1965,11 +1970,11 @@ describe('local video failure holds', () => {
});
it('lets other local models, image, audio, training, cloud and remote work pass a hold', async () => {
- const ids = Array.from({ length: 4 }, () => submit());
+ const ids = await submitMany(4);
for (const id of ids.slice(0, 3)) { await tick(); await finish(id); }
- const cloud = submit('example-mlx', { mode: 'grok' });
- const remote = submit('example-mlx', { remoteMedia: remoteVideoMediaParams() });
- const other = submit('example-other');
+ const cloud = await submit('example-mlx', { mode: 'grok' });
+ const remote = await submit('example-mlx', { remoteMedia: remoteVideoMediaParams() });
+ const other = await submit('example-other');
await tick();
expect(stubs.generateVideoGrok).toHaveBeenCalledWith(expect.objectContaining({ jobId: cloud }));
expect(stubs.generateVideoRemote).toHaveBeenCalledWith(expect.objectContaining({ jobId: remote }));
@@ -1977,7 +1982,7 @@ describe('local video failure holds', () => {
await finish(other, null);
for (const [kind, emitter] of [['image', imageGenEvents], ['audio', audioGenEvents], ['training', (await import('../loraTraining/events.js')).trainingEvents]]) {
stubs.runTraining.mockResolvedValue({});
- const { jobId } = mediaJobQueue.enqueueJob({ kind, params: {} });
+ const { jobId } = await mediaJobQueue.enqueueJob({ kind, params: {} });
await tick();
expect(mediaJobQueue.getJob(jobId).status).toBe('running');
emitter.emit('completed', { generationId: jobId });
@@ -1993,12 +1998,12 @@ describe('local video failure holds', () => {
'RuntimeError: shader failed', 'RuntimeError: shader failed', 'Exit code 1',
'RuntimeError: shape mismatch', 'RuntimeError: shader failed', 'RuntimeError: shader failed'];
for (const error of errors) {
- const id = submit(); await tick(); await finish(id, error);
+ const id = await submit(); await tick(); await finish(id, error);
}
- const canceled = submit(); await tick();
+ const canceled = await submit(); await tick();
await mediaJobQueue.cancelJob(canceled);
await finish(canceled, 'RuntimeError: unrelated cancellation');
- const third = submit(); const retained = submit();
+ const third = await submit(); const retained = await submit();
await tick(); await finish(third, 'RuntimeError: shader failed'); await tick();
expect(mediaJobQueue.getJob(canceled).status).toBe('canceled');
expect(mediaJobQueue.getJob(retained)).toMatchObject({ status: 'queued', hold: { cause: 'shader failed' } });
@@ -2006,13 +2011,13 @@ describe('local video failure holds', () => {
it('counts pre-dispatch rejection once and resumes with a cleared streak', async () => {
stubs.generateVideo.mockRejectedValue(Object.assign(new Error("Example runtime is not installed. Install or repair it from Video Gen's model setup panel."), { code: 'EXAMPLE_VENV_MISSING' }));
- const ids = Array.from({ length: 4 }, () => submit());
+ const ids = await submitMany(4);
for (let i = 0; i < 4; i += 1) await tick();
expect(stubs.generateVideo).toHaveBeenCalledTimes(3);
const held = mediaJobQueue.getJob(ids[3]);
expect(held.status).toBe('queued');
await mediaJobQueue.resumeVideoHold(held.hold.id);
- const next = submit();
+ const next = await submit();
await tick(); await tick();
expect(stubs.generateVideo).toHaveBeenCalledTimes(5);
expect(mediaJobQueue.getJob(next).status).toBe('failed');
@@ -2021,7 +2026,7 @@ describe('local video failure holds', () => {
it('holds repeated quoted-only exceptions while keeping distinct keys separate', async () => {
const errors = ["KeyError: 'Width'", "KeyError: 'width'", "KeyError: 'Width'",
"KeyError: 'width'", "KeyError: 'width'", "KeyError: 'width'"];
- const ids = Array.from({ length: errors.length + 1 }, () => submit());
+ const ids = await submitMany(errors.length + 1);
for (const [i, error] of errors.entries()) {
await tick();
expect(mediaJobQueue.getJob(ids[i]).status).toBe('running');
@@ -2042,9 +2047,9 @@ describe('local video failure holds', () => {
const { getDefaultVideoModelId } = await import('../../lib/mediaModels.js');
getDefaultVideoModelId.mockImplementation((capabilities) => capabilities?.cuda?.maxVramGb === 8
? 'example-cuda' : 'example-large-cuda');
- const ids = Array.from({ length: 4 }, () => mediaJobQueue.enqueueJob({
+ const ids = await submitMany(4, async () => (await mediaJobQueue.enqueueJob({
kind: 'video', params: { prompt: 'invented clip' },
- }).jobId);
+ })).jobId);
for (const id of ids.slice(0, 3)) {
await tick();
expect(stubs.generateVideo).toHaveBeenLastCalledWith(expect.objectContaining({ jobId: id, modelId: 'example-cuda' }));
@@ -2062,7 +2067,7 @@ describe('local video failure holds', () => {
it('uses structured signal evidence and ignores advisory text when no cause was found', async () => {
const { createVideoDiagnosticTail } = await import('../../lib/videoFailure.js');
- const ids = Array.from({ length: 6 }, () => submit());
+ const ids = await submitMany(6);
const causes = ['OutOfMemory', 'InnocentVictim', null, 'Timeout', 'Timeout'];
for (const [i, cause] of causes.entries()) {
await tick();
@@ -2083,7 +2088,7 @@ describe('local video failure holds', () => {
await mediaJobQueue.initMediaJobQueue(); await tick();
expect(mediaJobQueue.getJob('retained-legacy').status).toBe('running');
await finish('retained-legacy');
- const next = submit(); await tick();
+ const next = await submit(); await tick();
expect(mediaJobQueue.getJob(next).status).toBe('running');
});
@@ -2118,7 +2123,7 @@ describe('local video failure holds', () => {
expect(mediaJobQueue.getJob('saved-image').status).toBe('running');
imageGenEvents.emit('completed', { generationId: 'saved-image' });
await flush();
- const newlyQueued = submit('example-other');
+ const newlyQueued = await submit('example-other');
await tick();
const retainedIds = [...savedVideos, newlyQueued];
for (const id of retainedIds) expect(mediaJobQueue.getJob(id)).toMatchObject({ status: 'queued', hold: { scope: 'local-video', heldJobCount: 3 } });
@@ -2137,3 +2142,88 @@ describe('local video failure holds', () => {
expect(readFileSync(file, 'utf8')).toBe(snapshot);
});
});
+
+// #8325: a job id handed to a caller must survive a crash, so admission waits
+// for the snapshot that contains the job — and a failed snapshot refuses it.
+describe('durable admission and shutdown flush', () => {
+ const jobsFile = () => join(tempDataDir, 'media-jobs.json');
+ const persistedIds = () => JSON.parse(readFileSync(jobsFile(), 'utf-8')).jobs.map((j) => j.id);
+ // Hold the NEXT snapshot write until the returned release() is called.
+ const holdNextWrite = () => {
+ const realWrite = atomicWriteSpy.getMockImplementation();
+ let release;
+ const gate = new Promise((resolve) => { release = resolve; });
+ atomicWriteSpy.mockImplementationOnce(async (...args) => {
+ await gate;
+ return realWrite(...args);
+ });
+ return () => release();
+ };
+
+ beforeEach(async () => {
+ stubs.generateVideo.mockImplementation(() => new Promise(() => {}));
+ // Boot starts the worker, so dispatch is live before the job is admitted.
+ await mediaJobQueue.initMediaJobQueue();
+ vi.useFakeTimers();
+ });
+ afterEach(() => { vi.clearAllTimers(); vi.useRealTimers(); });
+
+ it('acknowledges and dispatches a job only once its snapshot is written', async () => {
+ const release = holdNextWrite();
+ const settled = vi.fn();
+ const admission = mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'slow disk' } });
+ admission.then(settled);
+ await vi.advanceTimersByTimeAsync(1000); // several worker passes
+ expect(settled).not.toHaveBeenCalled();
+ expect(stubs.generateVideo).not.toHaveBeenCalled();
+
+ release();
+ const { jobId, status } = await admission;
+ expect(status).toBe('queued');
+ expect(persistedIds()).toContain(jobId);
+ await vi.advanceTimersByTimeAsync(200);
+ await vi.dynamicImportSettled();
+ await vi.waitFor(() => expect(stubs.generateVideo).toHaveBeenCalledWith(expect.objectContaining({ jobId })));
+ });
+
+ it('refuses the submission and starts no provider work when the snapshot fails', async () => {
+ atomicWriteSpy.mockRejectedValueOnce(new Error('disk full'));
+ await expect(mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'no room' } }))
+ .rejects.toMatchObject({ status: 503, code: mediaJobQueue.MEDIA_QUEUE_PERSIST_FAILED });
+ expect(mediaJobQueue.listJobs()).toEqual([]);
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(stubs.generateVideo).not.toHaveBeenCalled();
+
+ // The next admission's snapshot must not resurrect the refused job.
+ const { jobId } = await mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'retry' } });
+ expect(persistedIds()).toEqual([jobId]);
+ });
+
+ it('restores an admitted job exactly once after a crash', async () => {
+ stubs.generateVideo.mockClear();
+ const blocker = await mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'running' } });
+ const { jobId } = await mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'waiting' } });
+ // Crash straight after the acknowledgement — nothing else gets to write.
+ vi.clearAllTimers();
+ mediaJobQueue.__resetForTests();
+ await importFresh();
+ await mediaJobQueue.initMediaJobQueue();
+ const restored = mediaJobQueue.listJobs().filter((j) => j.id === jobId);
+ expect(restored).toHaveLength(1);
+ expect(restored[0].status).toBe('queued');
+ expect(persistedIds().filter((id) => id === jobId)).toHaveLength(1);
+ expect(persistedIds()).toContain(blocker.jobId);
+ });
+
+ it('flushes within its bound and reports a stalled or failed write', async () => {
+ const release = holdNextWrite();
+ const stalled = mediaJobQueue.flushMediaJobQueue({ timeoutMs: 500 });
+ await vi.advanceTimersByTimeAsync(500);
+ await expect(stalled).resolves.toMatchObject({ ok: false, timedOut: true });
+ release();
+
+ atomicWriteSpy.mockRejectedValueOnce(new Error('disk full'));
+ await expect(mediaJobQueue.flushMediaJobQueue()).resolves.toEqual({ ok: false, error: 'disk full' });
+ await expect(mediaJobQueue.flushMediaJobQueue()).resolves.toEqual({ ok: true });
+ });
+});
diff --git a/server/services/pipeline/comicPages.js b/server/services/pipeline/comicPages.js
index 023261505a..60035d1dd7 100644
--- a/server/services/pipeline/comicPages.js
+++ b/server/services/pipeline/comicPages.js
@@ -304,7 +304,7 @@ export async function enqueueVisualComicPage(issueId, options = {}) {
loraTriggerByKey: triggerByKey,
});
- const jobId = enqueueImageJob({
+ const jobId = await enqueueImageJob({
prompt, world, settings, mode, series,
options: { ...options, initImagePath, initImageStrength, ...loraRenderOptions(characterLoras) },
selectedModel,
@@ -486,7 +486,7 @@ export async function refineComicPageRender(issueId, options = {}) {
? Math.min(Math.max(options.initImageStrength, 0), 1)
: REFINE_RENDER_DEFAULT_STRENGTH;
- const jobId = enqueueImageJob({
+ const jobId = await enqueueImageJob({
prompt: refined, world, settings, mode, series,
options: { ...options, initImagePath, initImageStrength },
owner: buildComicPagesOwner({ issueId, target: 'page', pageIndex, variant }),
@@ -554,7 +554,7 @@ export async function enqueueVisualImage(issueId, stageId, options = {}) {
.join(', ');
const prompt = triggerClause ? `${composedPrompt}\n\nFeaturing ${triggerClause}.` : composedPrompt;
- const jobId = enqueueImageJob({
+ const jobId = await enqueueImageJob({
prompt, world, settings, mode, series,
options: { ...options, ...loraRenderOptions(characterLoras) },
selectedModel,
diff --git a/server/services/pipeline/covers.js b/server/services/pipeline/covers.js
index e0016e8d98..dca642543f 100644
--- a/server/services/pipeline/covers.js
+++ b/server/services/pipeline/covers.js
@@ -164,7 +164,7 @@ async function enqueueComicCoverLike(issueId, target, options = {}) {
? composeComicCoverPrompt({ series, world, issue, coverScript: script, extraStyle })
: composeComicBackCoverPrompt({ series, world, issue, backCoverScript: script, extraStyle });
const logTarget = target === 'cover' ? 'cover' : 'back cover';
- const jobId = enqueueImageJob({
+ const jobId = await enqueueImageJob({
prompt, world, settings, mode, series,
options: { ...options, initImagePath, initImageStrength },
owner: buildComicPagesOwner({ issueId, target, variant }),
@@ -360,7 +360,7 @@ async function enqueueVolumeCoverLike(seriesId, seasonId, target, options = {})
? composeVolumeCoverPrompt({ series, world, season, coverScript: script, extraStyle })
: composeVolumeBackCoverPrompt({ series, world, season, backCoverScript: script, extraStyle });
const logTarget = target === 'cover' ? 'cover' : 'back cover';
- const jobId = enqueueImageJob({
+ const jobId = await enqueueImageJob({
prompt, world, settings, mode, series,
options: { ...options, initImagePath, initImageStrength },
owner: buildSeasonCoverOwner({ seriesId, seasonId, target, variant }),
diff --git a/server/services/pipeline/storyboards.js b/server/services/pipeline/storyboards.js
index 32542dbb91..1bce006dbe 100644
--- a/server/services/pipeline/storyboards.js
+++ b/server/services/pipeline/storyboards.js
@@ -140,7 +140,7 @@ export async function enqueueStoryboardSceneVideo(issueId, sceneIndex, options =
}
const negativePrompt = options.negativePrompt || 'text, watermark, blur, motion blur, low quality';
- const { jobId } = enqueueJob({
+ const { jobId } = await enqueueJob({
kind: 'video',
params: {
pythonPath,
@@ -229,7 +229,7 @@ export async function enqueueStoryboardShotStartFrame(issueId, sceneIndex, shotI
characterAppearances: scene.characterAppearances,
});
- const jobId = enqueueImageJob({
+ const jobId = await enqueueImageJob({
prompt, world, settings, options, mode, series,
owner: buildStoryboardsShotOwner({
issueId, sceneIndex: sIdx, shotIndex: tIdx,
diff --git a/server/services/pipeline/visualStageHelpers.js b/server/services/pipeline/visualStageHelpers.js
index da2d76b2d0..5c35296c0f 100644
--- a/server/services/pipeline/visualStageHelpers.js
+++ b/server/services/pipeline/visualStageHelpers.js
@@ -224,7 +224,7 @@ const loadBibleContext = async (issueId) => {
return { ...chain, settings };
};
-const enqueueImageJob = ({ prompt, world, settings, options, mode, owner, logLine, series = null, selectedModel = null }) => {
+const enqueueImageJob = async ({ prompt, world, settings, options, mode, owner, logLine, series = null, selectedModel = null }) => {
// Merge user + world negatives — mirrors composeStyledPrompt's preset
// negative handling so the world's global negative-prompt terms stay in
// effect even when the caller supplies their own additions. Deduplicated
@@ -290,7 +290,7 @@ const enqueueImageJob = ({ prompt, world, settings, options, mode, owner, logLin
denoise,
...baseParams,
};
- const { jobId } = enqueueJob({ kind: 'image', params, owner });
+ const { jobId } = await enqueueJob({ kind: 'image', params, owner });
console.log(`${logLine} mode=${mode} jobId=${jobId.slice(0, 8)}`);
return jobId;
};
diff --git a/server/services/sprites/animationTrackWorkflow.js b/server/services/sprites/animationTrackWorkflow.js
index 9aeb7f8b0d..57edb8bbb1 100644
--- a/server/services/sprites/animationTrackWorkflow.js
+++ b/server/services/sprites/animationTrackWorkflow.js
@@ -369,8 +369,15 @@ async function startTrackGenerationImpl(trackId, recordId, body) {
// boot-registered completion hook stages the clip and runs the attach. See
// the walk lane's note: that is what survives a restart, which matters most
// on this lane because track runs have no wall-clock backstop at all.
- const jobId = enqueueLocalAnimationRender({
+ // A refused admission (#8325) would otherwise leave the run at
+ // `rendering` with no job to finish it — and this lane's in-flight guard
+ // would then refuse every retry — so settle it as an error first.
+ const jobId = await enqueueLocalAnimationRender({
plan: localPlan, canvas, prompt, inputAbs, recordId, runId, track: row.id, direction,
+ }).catch(async (err) => {
+ Object.assign(run, { status: 'error', postprocessError: err.message, completedAt: new Date().toISOString() });
+ await saveRun(recordId, run);
+ throw err;
});
run.jobId = jobId;
await saveRun(recordId, run);
diff --git a/server/services/sprites/localAnimationRender.js b/server/services/sprites/localAnimationRender.js
index faa694d27f..27efc5313b 100644
--- a/server/services/sprites/localAnimationRender.js
+++ b/server/services/sprites/localAnimationRender.js
@@ -329,8 +329,9 @@ export const spriteAnimationJobTag = ({ recordId, runId, track, direction }) =>
});
/**
- * Queue the render. Returns the media-job id synchronously so the caller can
- * stamp it on an already-persisted run record.
+ * Queue the render. Resolves to the media-job id once the queue has durably
+ * admitted it (#8325), so the caller can stamp it on an already-persisted run
+ * record; rejects when the queue could not save the job.
*
* `hidden: true` keeps the clip out of the user's video gallery: it is an
* intermediate the sprite pipeline consumes, not a video they asked to keep.
@@ -338,8 +339,8 @@ export const spriteAnimationJobTag = ({ recordId, runId, track, direction }) =>
* explicitly chose the LOCAL provider, and the unattended helper's default
* routing could send the job to a peer instead.
*/
-export function enqueueLocalAnimationRender({ plan, canvas, prompt, inputAbs, recordId, runId, track, direction }) {
- return enqueueJob({
+export async function enqueueLocalAnimationRender({ plan, canvas, prompt, inputAbs, recordId, runId, track, direction }) {
+ const { jobId } = await enqueueJob({
kind: 'video',
// The owner the client's sprite pending-render hook filters on.
owner: 'sprites',
@@ -354,7 +355,8 @@ export function enqueueLocalAnimationRender({ plan, canvas, prompt, inputAbs, re
hidden: true,
...spriteAnimationJobTag({ recordId, runId, track, direction }),
},
- }).jobId;
+ });
+ return jobId;
}
/**
diff --git a/server/services/sprites/localAnimationRender.test.js b/server/services/sprites/localAnimationRender.test.js
index f2953ca268..0706292784 100644
--- a/server/services/sprites/localAnimationRender.test.js
+++ b/server/services/sprites/localAnimationRender.test.js
@@ -53,7 +53,7 @@ vi.mock('../../lib/hfCache.js', () => ({
const enqueued = [];
let queueJobs = new Map();
vi.mock('../mediaJobQueue/index.js', () => ({
- enqueueJob: (job) => {
+ enqueueJob: async (job) => {
enqueued.push(job);
return { jobId: `job-${enqueued.length}` };
},
@@ -378,8 +378,8 @@ describe('enqueueLocalAnimationRender', () => {
direction: 'east',
});
- it('queues an image-conditioned, hidden render at the planned geometry', () => {
- expect(enqueueWalk()).toBe('job-1');
+ it('queues an image-conditioned, hidden render at the planned geometry', async () => {
+ expect(await enqueueWalk()).toBe('job-1');
expect(enqueued[0]).toMatchObject({ kind: 'video', owner: 'sprites' });
expect(enqueued[0].params).toMatchObject({
modelId: 'minimax_h3_8bit',
@@ -395,18 +395,18 @@ describe('enqueueLocalAnimationRender', () => {
});
});
- it('tags the job so the completion hook can file it with no in-memory state', () => {
- enqueueWalk();
+ it('tags the job so the completion hook can file it with no in-memory state', async () => {
+ await enqueueWalk();
expect(enqueued[0].params.spriteAnimation).toEqual({
recordId: 'hero', runId: 'walk-east-abc12345', track: 'walk', direction: 'east',
});
});
- it('also carries the shipped spriteWalk tag the client rehydrate keys off', () => {
+ it('also carries the shipped spriteWalk tag the client rehydrate keys off', async () => {
// owner 'sprites' + params.spriteWalk.direction is what
// useSpritePendingRenders reads, so a browser reload mid-render still shows
// the direction in flight instead of re-enabling its Generate button.
- enqueueWalk();
+ await enqueueWalk();
expect(enqueued[0].params.spriteWalk).toEqual({ recordId: 'hero', direction: 'east' });
});
diff --git a/server/services/sprites/reference.js b/server/services/sprites/reference.js
index 8c2a011472..99e5d16920 100644
--- a/server/services/sprites/reference.js
+++ b/server/services/sprites/reference.js
@@ -612,7 +612,7 @@ async function startReferenceGenerationImpl(recordId, body, upload = null) {
// read settings and would otherwise fall back to its own default.
: { mode, pythonPath: settings.imageGen?.local?.pythonPath || null, ...(effectiveModel ? { modelId: effectiveModel } : {}), ...baseParams };
- const { jobId } = enqueueJob({ kind: 'image', params, owner: 'sprites' });
+ const { jobId } = await enqueueJob({ kind: 'image', params, owner: 'sprites' });
console.log(`🧍 sprite reference render queued ${recordId}/${anchorId} mode=${mode} jobId=${jobId.slice(0, 8)}`);
return { jobId, mode, target, anchorId };
}
diff --git a/server/services/sprites/walk.js b/server/services/sprites/walk.js
index b850fff62f..d341db5029 100644
--- a/server/services/sprites/walk.js
+++ b/server/services/sprites/walk.js
@@ -1084,8 +1084,14 @@ async function startWalkGenerationImpl(recordId, body) {
// Queued AFTER the record is durable. Nothing here awaits the render: the
// boot-registered completion hook stages the clip and runs the attach, which
// is what lets a render outlive this request, the client, and a restart.
- const jobId = enqueueLocalAnimationRender({
+ // A refused admission (#8325) must not strand the run at `rendering`
+ // with no job behind it — settle it as an error before surfacing.
+ const jobId = await enqueueLocalAnimationRender({
plan: localPlan, canvas, prompt, inputAbs, recordId, runId, track: WALK_TRACK, direction,
+ }).catch(async (err) => {
+ Object.assign(run, { status: 'error', postprocessError: err.message, completedAt: new Date().toISOString() });
+ await saveRunRecord(recordId, run);
+ throw err;
});
// Stamped in a SECOND write so a failure here cannot strand the job: the
// hook already has everything it needs from the job's own params, and a run
diff --git a/server/services/universeBuilderRender.js b/server/services/universeBuilderRender.js
index 96726e7cef..511d6d73ad 100644
--- a/server/services/universeBuilderRender.js
+++ b/server/services/universeBuilderRender.js
@@ -180,13 +180,13 @@ export async function renderUniverseJobs(universeId, body, mapServiceError) {
// do for /api/image-gen/generate and pipeline renders.
const { cleanC2PA, denoise } = resolveImageCleaners(undefined, settings, mode);
if (cloud) {
- queued = enqueueJob({
+ queued = await enqueueJob({
kind: 'image',
params: { ...cloud.jobParams, cleanC2PA, denoise, ...params },
});
} else {
// mode === IMAGE_GEN_MODE.LOCAL (validated upfront).
- queued = enqueueJob({
+ queued = await enqueueJob({
kind: 'image',
params: {
pythonPath: localModel.pythonPath,
diff --git a/server/services/universeCharacterSheet.js b/server/services/universeCharacterSheet.js
index cb4c76142e..5ef9946b02 100644
--- a/server/services/universeCharacterSheet.js
+++ b/server/services/universeCharacterSheet.js
@@ -476,7 +476,7 @@ export async function renderCharacterReferenceSheet(universeId, entryId, options
// Enqueue through mediaJobQueue so the render serializes through the right
// backend lane alongside Image Gen / Universe Builder renders. The queue
// dispatches by `params.mode` (codex → codex lane, local → GPU lane).
- const queued = enqueueJob({ kind: 'image', params });
+ const queued = await enqueueJob({ kind: 'image', params });
const jobId = queued.jobId;
// Claim the latest-pending slot for this character + variant. onSheetComplete
// checks it before stamping — guards against an older-but-slower render
diff --git a/server/services/videoGen/submitJob.js b/server/services/videoGen/submitJob.js
index fd6b568ae3..2394a53f8b 100644
--- a/server/services/videoGen/submitJob.js
+++ b/server/services/videoGen/submitJob.js
@@ -92,7 +92,7 @@ const submitValidatedVideoGenJob = async (body, uploads) => {
request,
inputAssets,
});
- const { jobId, position, status } = enqueueJob({
+ const { jobId, position, status } = await enqueueJob({
kind: 'video',
params: { remoteMedia },
});