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: media queue test drain waits for jobs still dispatching (#9029)

[._.]/ Adam Eivye4a76ef1322d
diff --git a/server/services/mediaJobQueue/index.js b/server/services/mediaJobQueue/index.js
index 870055bb06..e04d05f243 100644
--- a/server/services/mediaJobQueue/index.js
+++ b/server/services/mediaJobQueue/index.js
@@ -296,13 +296,20 @@ let dispatchQuiesced = false;
export const MEDIA_QUEUE_SHUTTING_DOWN = 'MEDIA_QUEUE_SHUTTING_DOWN';
const terminalOperations = new Set();
-function trackTerminalOperation(operation) {
+// A started job crosses async pre-dispatch work (live settings, provider module
+// resolution) before its terminal listeners attach and its provider is invoked.
+// Tracked separately so the test drain can wait for that boundary (#9029).
+const dispatchOperations = new Set();
+
+function trackOperation(operations, operation) {
const tracked = Promise.resolve(operation);
- terminalOperations.add(tracked);
- tracked.finally(() => terminalOperations.delete(tracked)).catch(() => {});
+ operations.add(tracked);
+ tracked.finally(() => operations.delete(tracked)).catch(() => {});
return tracked;
}
+const trackTerminalOperation = (operation) => trackOperation(terminalOperations, operation);
+
function findJob(jobId) {
if (running && running.id === jobId) return running;
const codexHit = cloudRunning.find((j) => j.id === jobId);
@@ -977,7 +984,20 @@ function makeGenDispatcher(emitter, job, handlers) {
};
}
+// The dispatch window closes once the provider has been invoked (not settled —
+// a provider kickoff may legitimately stay pending) or the job failed before
+// reaching it. The finally covers a throw anywhere before that point.
async function runJob(job) {
+ let markDispatched;
+ trackOperation(dispatchOperations, new Promise((resolve) => { markDispatched = resolve; }));
+ try {
+ await runJobLifecycle(job, markDispatched);
+ } finally {
+ markDispatched();
+ }
+}
+
+async function runJobLifecycle(job, markDispatched) {
const sseEntry = ensureSseEntry(job.id);
let resolveTerminalState;
const terminalState = new Promise((resolve) => { resolveTerminalState = resolve; });
@@ -1256,21 +1276,16 @@ async function runJob(job) {
}
// Transient, like terminating: no await between this flag and invocation.
job.providerInvoked = true;
- if (job.kind === 'video' && safeParams.chunks > 1) {
- await mod.generateChainedVideo({ ...safeParams, jobId: job.id });
- } else if (job.kind === 'video') {
- await mod.generateVideo({ ...safeParams, jobId: job.id });
- } else if (job.kind === 'html-composition') {
- await mod.renderComposition({ ...safeParams, jobId: job.id });
- } else if (job.kind === 'video-upscale') {
- await mod.runVideoUpscale({ ...safeParams, jobId: job.id });
- } else if (job.kind === 'training') {
- await mod.runTraining({ ...safeParams, jobId: job.id });
- } else if (job.kind === 'audio') {
- await mod.generateAudio({ ...safeParams, jobId: job.id });
- } else {
- await mod.generateImage({ ...safeParams, jobId: job.id });
- }
+ const request = { ...safeParams, jobId: job.id };
+ const kickoff = job.kind === 'video' && safeParams.chunks > 1 ? mod.generateChainedVideo(request)
+ : job.kind === 'video' ? mod.generateVideo(request)
+ : job.kind === 'html-composition' ? mod.renderComposition(request)
+ : job.kind === 'video-upscale' ? mod.runVideoUpscale(request)
+ : job.kind === 'training' ? mod.runTraining(request)
+ : job.kind === 'audio' ? mod.generateAudio(request)
+ : mod.generateImage(request);
+ markDispatched();
+ await kickoff;
} catch (err) {
// generateVideo / generateChainedVideo / generateImage threw before
// reaching their proc.on cleanup hooks (e.g. PYTHON not configured,
@@ -1279,12 +1294,16 @@ async function runJob(job) {
// safeUnlinkUpload constrains the delete to PATHS.uploads as
// defense-in-depth against corrupted persisted params. audioFilePath
// is the same kind of staged upload (a2v jobs) — clean it up too.
- await safeUnlinkUpload(job.params?.uploadedTempPath);
- await safeUnlinkUpload(job.params?.audioFilePath);
- for (const p of normalizeTempPaths(job.params?.uploadedTempPaths)) {
- await safeUnlinkUpload(p);
- }
- handlers.failed({ error: err.message, code: err.code });
+ // Tracked from the first microtask of the rejection, so a drain that saw
+ // the dispatch window close cannot miss this failure (#9029).
+ await trackTerminalOperation((async () => {
+ await safeUnlinkUpload(job.params?.uploadedTempPath);
+ await safeUnlinkUpload(job.params?.audioFilePath);
+ for (const p of normalizeTempPaths(job.params?.uploadedTempPaths)) {
+ await safeUnlinkUpload(p);
+ }
+ handlers.failed({ error: err.message, code: err.code });
+ })());
}
// The gen modules emit completed/failed asynchronously after kickoff. Await
@@ -1625,8 +1644,11 @@ export function __resetForTests() {
// instead of sleeping for an arbitrary wall-clock window before inspecting or
// removing their temporary data directory.
export async function __drainForTests() {
- while (terminalOperations.size > 0) {
- await Promise.allSettled([...terminalOperations]);
+ // Include open dispatches: a started job reaches its provider (or a pre-dispatch
+ // failure, which becomes a terminal operation) only after real I/O that
+ // neither fake timers nor a microtask yield cover (#9029).
+ while (dispatchOperations.size > 0 || terminalOperations.size > 0) {
+ await Promise.allSettled([...dispatchOperations, ...terminalOperations]);
}
await persistChain.catch(() => {});
// A settled terminal operation can schedule the archive snapshot in the
diff --git a/server/services/mediaJobQueue/index.test.js b/server/services/mediaJobQueue/index.test.js
index acdd4c4fc1..ea74346dd2 100644
--- a/server/services/mediaJobQueue/index.test.js
+++ b/server/services/mediaJobQueue/index.test.js
@@ -2124,6 +2124,31 @@ describe('local video failure holds', () => {
expect(mediaJobQueue.getJob(retained)).toMatchObject({ status: 'queued', hold: { cause: 'shader failed' } });
});
+ // #9029: a started job reaches its provider — and attaches the listeners a
+ // terminal event needs — only after async pre-dispatch work (a cold settings
+ // read is real I/O). A drain that skipped that window let `finish` emit into
+ // nothing, stranding the lane so the retained job above never saw its hold.
+ it('drains a started job through its pre-dispatch window', async () => {
+ const { assertVideoAttemptDispatch } = await import('../creativeDirector/videoExecution.js');
+ let release;
+ const gate = new Promise((resolve) => { release = resolve; });
+ assertVideoAttemptDispatch.mockImplementationOnce(() => gate);
+ const id = await submit('example-mlx', { videoProduction: { projectId: 'example-project', attemptId: 'example-attempt' } });
+ await vi.dynamicImportSettled();
+ await vi.advanceTimersByTimeAsync(150);
+ expect(mediaJobQueue.getJob(id).status).toBe('running');
+ let drained = false;
+ const drain = flush().then(() => { drained = true; });
+ // Every snapshot write and terminal transition has landed; only dispatch is open.
+ await expect(mediaJobQueue.flushMediaJobQueue()).resolves.toEqual({ ok: true });
+ expect(drained).toBe(false);
+ release();
+ await drain;
+ expect(stubs.generateVideo).toHaveBeenCalledWith(expect.objectContaining({ jobId: id }));
+ await finish(id, null);
+ expect(mediaJobQueue.getJob(id).status).toBe('completed');
+ });
+
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 = await submitMany(4);