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: stop dispatching queued media jobs once server shutdown begins (#8691)

[._.]/ Adam Eivy7e05b5f5914a
diff --git a/docs/STORAGE.md b/docs/STORAGE.md
index 368e6f7412..8b9e5fccd4 100644
--- a/docs/STORAGE.md
+++ b/docs/STORAGE.md
@@ -132,7 +132,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. 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.
+- 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 first stops dispatch (`quiesceMediaJobQueue()`, before its first await — waiting jobs stay queued for the next boot instead of starting during teardown and restoring as interrupted; Run Now answers `503 MEDIA_QUEUE_SHUTTING_DOWN`), then 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/mediaJobs.js b/server/routes/mediaJobs.js
index bcfc56e752..d1b300b601 100644
--- a/server/routes/mediaJobs.js
+++ b/server/routes/mediaJobs.js
@@ -9,7 +9,7 @@ import { Router } from 'express';
import { z } from 'zod';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
import { validateRequest } from '../lib/validation.js';
-import { listJobs, listQueueJobs, getJob, cancelJob, cancelQueuedJobs, enqueueJob, removeArchivedJob, runJobNow, listVideoHolds, resumeVideoHold, JOB_KINDS, JOB_STATUSES } from '../services/mediaJobQueue/index.js';
+import { listJobs, listQueueJobs, getJob, cancelJob, cancelQueuedJobs, enqueueJob, removeArchivedJob, runJobNow, listVideoHolds, resumeVideoHold, JOB_KINDS, JOB_STATUSES, MEDIA_QUEUE_SHUTTING_DOWN } from '../services/mediaJobQueue/index.js';
import { refineMediaPrompt } from '../services/mediaPromptRefiner.js';
import { promptFromMedia } from '../services/mediaPromptFromMedia.js';
import { CODEX_EFFORT_LEVELS } from '../lib/providerModels.js';
@@ -425,7 +425,7 @@ router.delete('/:id', asyncHandler(async (req, res) => {
router.post('/:id/run-now', asyncHandler(async (req, res) => {
const result = runJobNow(req.params.id);
if (!result.ok) {
- const status = result.code === 'NOT_FOUND' ? 404 : 400;
+ const status = result.code === 'NOT_FOUND' ? 404 : result.code === MEDIA_QUEUE_SHUTTING_DOWN ? 503 : 400;
throw new ServerError(result.error || 'Run-now failed', { status, code: result.code });
}
res.json(result);
diff --git a/server/routes/mediaJobs.test.js b/server/routes/mediaJobs.test.js
index fa08e10a44..0ab7c8825c 100644
--- a/server/routes/mediaJobs.test.js
+++ b/server/routes/mediaJobs.test.js
@@ -21,6 +21,7 @@ const stubs = {
vi.mock('../services/mediaJobQueue/index.js', () => ({
JOB_KINDS: ['video', 'image'],
JOB_STATUSES: ['queued', 'running', 'completed', 'failed', 'canceled'],
+ MEDIA_QUEUE_SHUTTING_DOWN: 'MEDIA_QUEUE_SHUTTING_DOWN',
listJobs: () => Array.from(jobStore.values()),
listQueueJobs: (...args) => stubs.listQueueJobs(...args),
getJob: (id) => jobStore.get(id) || null,
@@ -540,6 +541,13 @@ describe('mediaJobs routes', () => {
expect(r.body.code).toBe('NOT_CODEX');
});
+ it('POST /:id/run-now 503s while server shutdown keeps the job queued (#8691)', async () => {
+ stubs.runJobNow.mockReturnValueOnce({ ok: false, code: 'MEDIA_QUEUE_SHUTTING_DOWN', error: 'shutting down' });
+ const r = await request(makeApp()).post('/api/media-jobs/j-codex/run-now').send({});
+ expect(r.status).toBe(503);
+ expect(r.body.code).toBe('MEDIA_QUEUE_SHUTTING_DOWN');
+ });
+
it('POST /:id/run-now 404s for unknown / not-queued ids', async () => {
// Default stub returns NOT_FOUND
const r = await request(makeApp()).post('/api/media-jobs/nope/run-now').send({});
diff --git a/server/services/bootstrap.js b/server/services/bootstrap.js
index 05b7f946d6..6daf4a5142 100644
--- a/server/services/bootstrap.js
+++ b/server/services/bootstrap.js
@@ -135,7 +135,7 @@ import { initSyncLog } from './brainSyncLog.js';
import { backfillOriginInstanceId, brainCollectionStores } from './brainStorage.js';
import { relayUnloggedRecords } from './brainReconcile.js';
import { initSyncOrchestrator } from './syncOrchestrator.js';
-import { initMediaJobQueue, flushMediaJobQueue } from './mediaJobQueue/index.js';
+import { initMediaJobQueue, flushMediaJobQueue, quiesceMediaJobQueue } from './mediaJobQueue/index.js';
import { initSpriteLocalAnimationHook } from './sprites/localAnimationJobHook.js';
import { initLoraTraining } from './loraTraining/index.js';
import { initSharing } from './sharing/index.js';
@@ -1036,6 +1036,10 @@ export const registerShutdownHandlers = ({ io, httpServer, localHttpServer }) =>
// new is accepted while the teardown below runs; requests already accepted
// keep running and are waited on (bounded) just before the HTTP close.
const requestsDrained = httpDrain.begin(HTTP_DRAIN_WINDOW_MS);
+ // Stop media-job dispatch before the first await too (#8691): a lane freed
+ // during teardown must not promote a waiting job the process is about to
+ // abandon — the next boot fails a running record but restores a queued one.
+ quiesceMediaJobQueue();
await import('./tailcatPeer.js').then(({ stopAllForwards }) => stopAllForwards())
.catch((err) => logBootstrapFailure('❌ Tailcat forward shutdown failed', err));
await import('./tailcatServe.js').then(({ stopServeProcess }) => stopServeProcess())
diff --git a/server/services/bootstrap.shutdown.test.js b/server/services/bootstrap.shutdown.test.js
index 5ca65dad2f..0cabb826ba 100644
--- a/server/services/bootstrap.shutdown.test.js
+++ b/server/services/bootstrap.shutdown.test.js
@@ -181,9 +181,18 @@ describe('shutdown handler — detached-group teardown (#7496)', () => {
// #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)', () => {
+describe('shutdown handler — media-job queue quiesce + flush (#8325, #8691)', () => {
const code = stripCommentsAndNormalize(extractDeclaration(SRC, 'shutdown') || '');
+ // #8691: dispatch stops at the signal, not at the flush — a lane freed while
+ // accepted requests drain must not start a waiting job the exit abandons.
+ it('quiesces media-job dispatch before the handler awaits anything', () => {
+ const quiesceAt = code.indexOf('quiesceMediaJobQueue()');
+ expect(quiesceAt, 'quiesceMediaJobQueue() is not called in shutdown()').toBeGreaterThan(-1);
+ expect(quiesceAt).toBeLessThan(code.search(/\bawait\b/));
+ expect(quiesceAt).toBeLessThan(code.indexOf('flushMediaJobQueue('));
+ });
+
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);
diff --git a/server/services/mediaJobQueue/index.js b/server/services/mediaJobQueue/index.js
index 57168f27c6..686633f987 100644
--- a/server/services/mediaJobQueue/index.js
+++ b/server/services/mediaJobQueue/index.js
@@ -289,6 +289,11 @@ const sseJobs = new Map();
let workerStarted = false;
let initPromise = null;
+// Shutdown latch (#8691): once set, nothing promotes a waiting job to running —
+// neither the worker nor Run Now — and nothing re-arms the worker. Waiting jobs
+// stay durably queued for the next process, which restores them untouched.
+let dispatchQuiesced = false;
+export const MEDIA_QUEUE_SHUTTING_DOWN = 'MEDIA_QUEUE_SHUTTING_DOWN';
const terminalOperations = new Set();
function trackTerminalOperation(operation) {
@@ -670,9 +675,9 @@ export async function initMediaJobQueue() {
}
function startWorker() {
- if (workerStarted) return;
+ if (workerStarted || dispatchQuiesced) return;
workerStarted = true;
- // Detach from awaiting so init can return; the loop runs forever.
+ // Detach from awaiting so init can return; the loop runs until shutdown quiesces it.
drainLoop().catch((err) => {
console.error(`❌ mediaJobQueue worker crashed: ${err.message}`, err.stack || '');
workerStarted = false;
@@ -682,6 +687,9 @@ function startWorker() {
// Every lane uses fire-and-forget so the poll loop is never blocked by a
// running job in another lane.
function startLaneJob(job, { lane }) {
+ // The one promotion boundary every dispatch path crosses, so the shutdown
+ // latch holds here even for a caller that raced past its own check.
+ if (dispatchQuiesced) return false;
// If the job isn't in the queue, it was already promoted (e.g. by a parallel
// runJobNow). Skip — promoting again would double-start the job and corrupt
// the lane (push it onto cloudRunning/running twice). Silently splice(-1)
@@ -689,7 +697,7 @@ function startLaneJob(job, { lane }) {
const idx = queue.indexOf(job);
if (idx < 0) {
console.log(`⚠️ media-job [${job.id.slice(0, 8)}] startLaneJob: already removed from queue, skipping`);
- return;
+ return false;
}
queue.splice(idx, 1);
job.status = 'running';
@@ -757,12 +765,15 @@ function startLaneJob(job, { lane }) {
recomputeQueuePositions();
persist().catch((e) => console.log(`⚠️ mediaJobQueue persist on ${label} done failed: ${e.message}`));
})();
+ return true;
}
async function drainLoop() {
- while (true) {
+ while (!dispatchQuiesced) {
const candidates = queue.slice();
await videoHolds.resolveCohorts(candidates);
+ // Shutdown may have begun while cohorts resolved; exit without promoting.
+ if (dispatchQuiesced) break;
videoHolds.updateQueued(queue);
// Single queue scan, promoting work independently into each open lane.
const limits = laneLimits();
@@ -775,7 +786,7 @@ async function drainLoop() {
if (job.status !== 'queued' || job.hold || job.admitting) continue;
const lane = jobLane(job);
if (slots[lane] <= 0) continue;
- startLaneJob(job, { lane });
+ if (!startLaneJob(job, { lane })) continue;
slots[lane] -= 1;
if (Object.values(slots).every((remaining) => remaining <= 0)) break;
}
@@ -783,6 +794,18 @@ async function drainLoop() {
}
}
+// Stop dispatch for server shutdown (#8691). Synchronous and idempotent so the
+// signal handler can call it before its first await. Waiting jobs are neither
+// canceled nor failed — they persist as queued and the next boot restores
+// them; already-running jobs keep their normal completion path, which the
+// shutdown flush then captures. Returns true on the call that latched it.
+export function quiesceMediaJobQueue() {
+ if (dispatchQuiesced) return false;
+ dispatchQuiesced = true;
+ console.log(`⏸️ mediaJobQueue dispatch stopped for shutdown (${queue.length} waiting job(s) kept queued)`);
+ return true;
+}
+
// Drop a job from the archive (e.g. after a successful retry — the old failed
// row shouldn't keep cluttering the recent-reel UI now that a fresh job has
// inherited its work). Returns true if removed, false if the id wasn't found
@@ -814,6 +837,9 @@ export function runJobNow(jobId) {
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' };
}
+ if (dispatchQuiesced) {
+ return { ok: false, code: MEDIA_QUEUE_SHUTTING_DOWN, error: 'The server is shutting down; the job stays queued and resumes after restart' };
+ }
startLaneJob(job, { lane: 'cloud' });
return { ok: true, status: 'running' };
}
@@ -1573,6 +1599,7 @@ export function __resetForTests() {
videoHolds.clear();
sseJobs.clear();
workerStarted = false;
+ dispatchQuiesced = false;
initPromise = null;
// Reset the lane limit too — a test that called setCodexParallelLimit(N)
// otherwise leaks N into subsequent tests and makes ordering matter.
diff --git a/server/services/mediaJobQueue/index.test.js b/server/services/mediaJobQueue/index.test.js
index cc26f624ae..f445483e35 100644
--- a/server/services/mediaJobQueue/index.test.js
+++ b/server/services/mediaJobQueue/index.test.js
@@ -2195,20 +2195,21 @@ describe('local video failure holds', () => {
// #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.
+const persistedJobs = () => JSON.parse(readFileSync(join(tempDataDir, 'media-jobs.json'), 'utf-8')).jobs;
+const persistedIds = () => persistedJobs().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();
+};
+
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(() => {}));
@@ -2278,6 +2279,125 @@ describe('durable admission and shutdown flush', () => {
});
});
+// #8691: once shutdown quiesces the queue, waiting work stays queued on disk for
+// the next process — a running record left behind by the exit is failed on
+// boot (and its staged upload deleted), while a queued one is restored intact.
+describe('shutdown quiesce', () => {
+ const tick = async (ms = 1000) => {
+ await vi.dynamicImportSettled();
+ await vi.advanceTimersByTimeAsync(ms);
+ await flush();
+ };
+ const stageUpload = () => {
+ const upload = join(tempDataDir, 'uploads', 'example.png');
+ mkdirSync(join(tempDataDir, 'uploads'), { recursive: true });
+ writeFileSync(upload, 'synthetic image');
+ return upload;
+ };
+ const restart = async () => {
+ vi.clearAllTimers();
+ mediaJobQueue.__resetForTests();
+ await importFresh();
+ await mediaJobQueue.initMediaJobQueue();
+ };
+
+ beforeEach(() => {
+ // Kickoff resolves; the provider's terminal event arrives when the test emits it.
+ stubs.generateVideo.mockResolvedValue({});
+ vi.useFakeTimers();
+ });
+ afterEach(() => { vi.doUnmock('../videoGen/modelSelection.js'); vi.clearAllTimers(); vi.useRealTimers(); });
+
+ it('keeps a waiting job queued when its lane frees, and restart restores it once with its upload', async () => {
+ await mediaJobQueue.initMediaJobQueue();
+ const blocker = await mediaJobQueue.enqueueJob({ kind: 'video', params: { modelId: 'example-mlx', prompt: 'running' } });
+ await tick();
+ expect(mediaJobQueue.getJob(blocker.jobId).status).toBe('running');
+ const upload = stageUpload();
+ const { jobId } = await mediaJobQueue.enqueueJob({
+ kind: 'video', params: { modelId: 'example-mlx', prompt: 'waiting', uploadedTempPath: upload },
+ });
+
+ expect(mediaJobQueue.quiesceMediaJobQueue()).toBe(true);
+ expect(mediaJobQueue.quiesceMediaJobQueue()).toBe(false);
+ // The running job still completes and its transition is flushed.
+ videoGenEvents.emit('completed', { generationId: blocker.jobId, filename: `${blocker.jobId}.mp4` });
+ await tick();
+ expect(mediaJobQueue.getJob(blocker.jobId).status).toBe('completed');
+ expect(stubs.generateVideo).toHaveBeenCalledTimes(1);
+ expect(mediaJobQueue.getJob(jobId).status).toBe('queued');
+ await expect(mediaJobQueue.flushMediaJobQueue()).resolves.toEqual({ ok: true });
+ expect(persistedJobs().find((j) => j.id === blocker.jobId).status).toBe('completed');
+ expect(persistedJobs().find((j) => j.id === jobId).status).toBe('queued');
+
+ await restart();
+ const restored = mediaJobQueue.listJobs().filter((j) => j.id === jobId);
+ expect(restored).toHaveLength(1);
+ expect(restored[0]).toMatchObject({ status: 'queued', params: { uploadedTempPath: upload } });
+ expect(existsSync(upload)).toBe(true);
+ // The new process dispatches it normally.
+ await tick();
+ await vi.waitFor(() => expect(stubs.generateVideo).toHaveBeenLastCalledWith(expect.objectContaining({ jobId })));
+ });
+
+ it('does not promote when shutdown lands while the worker resolves cohorts', async () => {
+ let releaseCohorts;
+ const cohortsResolved = new Promise((resolve) => { releaseCohorts = resolve; });
+ vi.doMock('../videoGen/modelSelection.js', () => ({
+ resolveVideoModelSelection: vi.fn(async () => {
+ await cohortsResolved;
+ return { model: { id: 'example-mlx', runtime: 'mlx_video' } };
+ }),
+ }));
+ await importFresh();
+ await mediaJobQueue.initMediaJobQueue();
+ const blocker = await mediaJobQueue.enqueueJob({ kind: 'video', params: { modelId: 'example-mlx', prompt: 'running' } });
+ await tick();
+ expect(mediaJobQueue.getJob(blocker.jobId).status).toBe('running');
+ // An omitted modelId makes the next worker pass await the model resolution.
+ const { jobId } = await mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'waiting' } });
+ await tick();
+
+ // The worker is parked on the resolution; free the lane underneath it.
+ videoGenEvents.emit('completed', { generationId: blocker.jobId, filename: `${blocker.jobId}.mp4` });
+ await tick();
+ expect(mediaJobQueue.getRunningJob()).toBeNull();
+ mediaJobQueue.quiesceMediaJobQueue();
+ releaseCohorts();
+ await tick();
+ expect(stubs.generateVideo).toHaveBeenCalledTimes(1);
+ expect(mediaJobQueue.getJob(jobId).status).toBe('queued');
+ });
+
+ it('refuses Run Now without touching the waiting job', async () => {
+ await mediaJobQueue.initMediaJobQueue();
+ mediaJobQueue.setCodexParallelLimit(1);
+ const first = await mediaJobQueue.enqueueJob({ kind: 'image', params: { mode: 'codex', prompt: 'running' } });
+ await tick();
+ expect(mediaJobQueue.getJob(first.jobId).status).toBe('running');
+ const { jobId } = await mediaJobQueue.enqueueJob({ kind: 'image', params: { mode: 'codex', prompt: 'waiting' } });
+
+ mediaJobQueue.quiesceMediaJobQueue();
+ expect(mediaJobQueue.runJobNow(jobId)).toMatchObject({ ok: false, code: mediaJobQueue.MEDIA_QUEUE_SHUTTING_DOWN });
+ await tick();
+ expect(stubs.generateImageCodex).toHaveBeenCalledTimes(1);
+ expect(mediaJobQueue.getJob(jobId)).toMatchObject({ status: 'queued', position: 2 });
+ });
+
+ it('lets an admission settling during shutdown persist without re-arming the worker', async () => {
+ // No boot: the settling admission is what would otherwise start the worker.
+ const release = holdNextWrite();
+ const admission = mediaJobQueue.enqueueJob({ kind: 'video', params: { modelId: 'example-mlx', prompt: 'late' } });
+ mediaJobQueue.quiesceMediaJobQueue();
+ release();
+ const { jobId, status } = await admission;
+ expect(status).toBe('queued');
+ await tick();
+ expect(stubs.generateVideo).not.toHaveBeenCalled();
+ expect(persistedJobs().find((j) => j.id === jobId).status).toBe('queued');
+ });
+});
+
// #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', () => {