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

feat: dispatch the generative video upscale as a queued media job (#6511)

[._.]/ Adam Eivyb446358ff50c
diff --git a/server/routes/videoGen.js b/server/routes/videoGen.js
index 6e1487b3a6..555bdfc3f0 100644
--- a/server/routes/videoGen.js
+++ b/server/routes/videoGen.js
@@ -51,6 +51,7 @@ import {
// provider surface would make every suite that mocks local.js responsible for
// re-declaring it just so this file's route schemas can be built.
import { UPSCALE_METHODS, DEFAULT_UPSCALE_METHOD } from '../services/videoGen/upscalePlan.js';
+import { enqueueLtxUpscale } from '../services/videoGen/upscaleJob.js';
import { cleanupMultipartTemp } from '../services/videoGen/prepareParams.js';
import { submitVideoGenJob } from '../services/videoGen/submitJob.js';
import { resolveReactorApiKey, mintReactorToken } from '../services/videoGen/reactor.js';
@@ -1200,11 +1201,21 @@ router.get('/upscale/:id/plan', asyncHandler(async (req, res) => {
res.json({ ok: true, plan: await planUpscaleHistoryItem(parsed.data, query.data) });
}));
+// The two methods answer with materially different things, so they answer with
+// different KEYS rather than one overloaded field. Lanczos is an inline ffmpeg
+// pass that returns the finished row; the generative method is a multi-minute
+// GPU render, so it returns the queued job to watch and the row appears in
+// history when it lands (#6511). Every pre-#6511 client omits `method`, gets
+// Lanczos, and still reads `video` exactly as before.
router.post('/upscale/:id', asyncHandler(async (req, res) => {
const parsed = historyIdSchema.safeParse(req.params.id);
if (!parsed.success) failValidation(parsed);
const body = upscaleMethodSchema.safeParse(req.body ?? {});
if (!body.success) failValidation(body);
+ if (body.data.method === 'ltx') {
+ res.json({ ok: true, job: await enqueueLtxUpscale(parsed.data) });
+ return;
+ }
const entry = await upscaleHistoryItem(parsed.data, body.data);
res.json({ ok: true, video: entry });
}));
diff --git a/server/routes/videoGen.test.js b/server/routes/videoGen.test.js
index 75a1884c4a..af3918f9a1 100644
--- a/server/routes/videoGen.test.js
+++ b/server/routes/videoGen.test.js
@@ -101,6 +101,12 @@ vi.mock('../lib/pythonSetup.js', () => ({
detectVenvBasePythonSync: vi.fn(() => null),
}));
+// The generative upscale is queued, not run inline (#6511), so it lives in
+// its own service module and the route reaches it directly.
+vi.mock('../services/videoGen/upscaleJob.js', () => ({
+ enqueueLtxUpscale: vi.fn(),
+}));
+
vi.mock('../services/videoGen/local.js', () => ({
// The route checks `runtime` on the default model when validating a2v —
// include it so the a2v happy-path tests don't trip the runtime capability
@@ -284,6 +290,7 @@ vi.mock('fs/promises', () => ({
import { copyFile, unlink } from 'fs/promises';
import * as videoGenService from '../services/videoGen/local.js';
+import * as upscaleJobService from '../services/videoGen/upscaleJob.js';
import * as mediaJobQueue from '../services/mediaJobQueue/index.js';
import { prepareRemoteMediaJob } from '../services/federatedMedia/remoteSubmission.js';
import { getProject as getMusicVideoProject } from '../services/musicVideo/projects.js';
@@ -2857,11 +2864,16 @@ describe('videoGen routes', () => {
expect(explicit).toEqual(noBody);
});
- it('forwards the generative method to the service', async () => {
- videoGenService.upscaleHistoryItem.mockResolvedValue({ id: otherValidId });
+ // The generative method answers with a QUEUED JOB, not a finished row: it
+ // is a multi-minute GPU render, so running it inline would hold the request
+ // open and skip cancellation/watchdog/partial-output cleanup (#6511).
+ it('queues the generative method instead of running it inline', async () => {
+ upscaleJobService.enqueueLtxUpscale.mockResolvedValue({ jobId: 'job-1', position: 2, status: 'queued' });
const r = await request(app).post(`/api/video-gen/upscale/${validHistoryId}`).send({ method: 'ltx' });
expect(r.status).toBe(200);
- expect(videoGenService.upscaleHistoryItem).toHaveBeenCalledWith(validHistoryId, { method: 'ltx' });
+ expect(r.body).toEqual({ ok: true, job: { jobId: 'job-1', position: 2, status: 'queued' } });
+ expect(upscaleJobService.enqueueLtxUpscale).toHaveBeenCalledWith(validHistoryId);
+ expect(videoGenService.upscaleHistoryItem).not.toHaveBeenCalled();
});
it('rejects an unknown method with a 400 and never reaches the service', async () => {
@@ -2871,7 +2883,7 @@ describe('videoGen routes', () => {
});
it('surfaces the 501 capability error the service raises for an unavailable runtime', async () => {
- videoGenService.upscaleHistoryItem.mockRejectedValue(
+ upscaleJobService.enqueueLtxUpscale.mockRejectedValue(
Object.assign(new Error('needs LTX-2.5 MLX (ltx25)'), { status: 501, code: 'UNSUPPORTED_RUNTIME' }),
);
const r = await request(app).post(`/api/video-gen/upscale/${validHistoryId}`).send({ method: 'ltx' });
diff --git a/server/services/mediaJobQueue/index.js b/server/services/mediaJobQueue/index.js
index ebfb297958..bf34ab5c62 100644
--- a/server/services/mediaJobQueue/index.js
+++ b/server/services/mediaJobQueue/index.js
@@ -148,7 +148,13 @@ async function safeUnlinkUpload(path) {
await unlink(path).catch(() => {});
}
-export const JOB_KINDS = Object.freeze(['video', 'image', 'training', 'audio']);
+// 'video-upscale' (#6511) is its OWN kind rather than a 'video' mode so the
+// generative upscale can never be offered to a peer: the federation layer's
+// kind maps (REMOTE_MEDIA_MODULES here, ROUTABLE_MEDIA_KINDS and
+// KNOWN_MEDIA_KINDS in federatedMedia/) are closed lists that do not name it,
+// so shipping a user's source video across the wire would take a deliberate
+// edit to one of them rather than a mode string slipping through.
+export const JOB_KINDS = Object.freeze(['video', 'video-upscale', 'image', 'training', 'audio']);
export const JOB_STATUSES = Object.freeze(['queued', 'running', 'completed', 'failed', 'canceled']);
// Returns a Promise that resolves to the gen module for the given job's
@@ -161,6 +167,7 @@ function getGenModuleForJob(job) {
// later local branch would happily claim it and render a second time on this
// machine.
if (isRemoteMediaJob(job)) return REMOTE_MEDIA_MODULES[job.kind]();
+ if (job.kind === 'video-upscale') return import('../videoGen/upscaleJob.js');
if (job.kind === 'video' && job.params?.mode === IMAGE_GEN_MODE.GROK) return import('../videoGen/grok.js');
if (job.kind === 'video' && job.params?.mode === VIDEO_GEN_MODE.FAL) return import('../videoGen/fal.js');
if (job.kind === 'video' && job.params?.mode === VIDEO_GEN_MODE.REACTOR) return import('../videoGen/reactor.js');
@@ -806,7 +813,7 @@ function recomputeQueuePositions() {
// the queue, even though the underlying emitters don't supply one.
function synthesizeMessage(e, kind) {
if (typeof e.step === 'number' && typeof e.totalSteps === 'number' && e.totalSteps > 0) {
- const verb = kind === 'video' ? 'Rendering' : kind === 'training' ? 'Training' : 'Generating';
+ const verb = kind === 'video' ? 'Rendering' : kind === 'video-upscale' ? 'Upscaling' : kind === 'training' ? 'Training' : 'Generating';
return `${verb} step ${e.step}/${e.totalSteps}`;
}
return undefined;
@@ -1054,7 +1061,7 @@ async function runJob(job) {
await resolveLiveParams(job, safeParams);
- const emitter = job.kind === 'video' ? videoGenEvents
+ const emitter = job.kind === 'video' || job.kind === 'video-upscale' ? videoGenEvents
: job.kind === 'training' ? trainingEvents
: job.kind === 'audio' ? audioGenEvents
: imageGenEvents;
@@ -1074,6 +1081,9 @@ async function runJob(job) {
// the chunk-scaled local-video one (the provider emits 'activity' on
// stdout so a long-but-active render never trips the idle cap).
if (isCloudImageJob(job)) return WATCHDOG_CODEX_MS;
+ // An upscale is a single GPU render with no chunking, so it takes the
+ // video idle window flat rather than the chunk-scaled one.
+ if (job.kind === 'video-upscale') return WATCHDOG_VIDEO_MS;
if (job.kind === 'video') return WATCHDOG_VIDEO_MS * Math.max(1, Number(safeParams.chunks) || 1);
if (job.kind === 'training') return WATCHDOG_TRAINING_MS;
if (job.kind === 'audio') return WATCHDOG_AUDIO_MS;
@@ -1150,6 +1160,8 @@ async function runJob(job) {
await mod.generateChainedVideo({ ...safeParams, jobId: job.id });
} else if (job.kind === 'video') {
await mod.generateVideo({ ...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') {
diff --git a/server/services/mediaJobQueue/index.test.js b/server/services/mediaJobQueue/index.test.js
index 95a9ae670f..ad193b2b26 100644
--- a/server/services/mediaJobQueue/index.test.js
+++ b/server/services/mediaJobQueue/index.test.js
@@ -78,6 +78,8 @@ tryReadFile: vi.fn().mockResolvedValue(null), jobId: 'whatever' })),
// re-attach decision is testable without loading the real trainer module.
runTraining: vi.fn(() => new Promise(() => {})),
hasSurvivingTrainer: vi.fn(async () => false),
+ runVideoUpscale: vi.fn(() => new Promise(() => {})),
+ cancelVideoUpscale: vi.fn(),
};
vi.mock('../videoGen/local.js', () => ({
@@ -86,6 +88,11 @@ vi.mock('../videoGen/local.js', () => ({
cancel: (...args) => stubs.cancelVideo(...args),
}));
+vi.mock('../videoGen/upscaleJob.js', () => ({
+ runVideoUpscale: (...args) => stubs.runVideoUpscale(...args),
+ cancel: (...args) => stubs.cancelVideoUpscale(...args),
+}));
+
vi.mock('../videoGen/grok.js', () => ({
generateVideo: (...args) => stubs.generateVideoGrok(...args),
cancel: (...args) => stubs.cancelVideo(...args),
@@ -185,6 +192,7 @@ beforeEach(async () => {
// 'running'). Individual tests override hasSurvivingTrainer as needed.
stubs.runTraining.mockImplementation(() => new Promise(() => {}));
stubs.hasSurvivingTrainer.mockResolvedValue(false);
+ stubs.runVideoUpscale.mockImplementation(() => new Promise(() => {}));
await importFresh();
});
@@ -209,6 +217,46 @@ describe('mediaJobQueue', () => {
expect(r2.position).toBe(2);
});
+ // The generative video upscale (#6511) rides the queue as its own kind, on
+ // the serialized GPU lane and the videoGen event bus, so it can be watched,
+ // cancelled and watchdogged exactly like a render.
+ describe('video-upscale kind', () => {
+ 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 });
+ await waitFor(() => stubs.generateVideo.mock.calls.length === 1);
+
+ // The render holds the one GPU slot; the upscale waits behind it rather
+ // than starting a second heavy child on the same accelerator.
+ expect(mediaJobQueue.getJob(render.jobId).status).toBe('running');
+ expect(mediaJobQueue.getJob(upscale.jobId).status).toBe('queued');
+ expect(stubs.runVideoUpscale).not.toHaveBeenCalled();
+ expect(mediaJobQueue.laneConcurrencyFor({ kind: 'video-upscale', params: upscaleParams })).toBe(1);
+
+ videoGenEvents.emit('completed', { generationId: render.jobId });
+ await waitFor(() => stubs.runVideoUpscale.mock.calls.length === 1);
+ expect(stubs.runVideoUpscale).toHaveBeenCalledWith({ ...upscaleParams, chunks: 1, uploadedTempPaths: [], jobId: upscale.jobId });
+ });
+
+ it('settles on the videoGen event bus and cancels through the upscale service', async () => {
+ const { jobId } = mediaJobQueue.enqueueJob({ kind: 'video-upscale', params: upscaleParams });
+ await waitFor(() => stubs.runVideoUpscale.mock.calls.length === 1);
+
+ await mediaJobQueue.cancelJob(jobId);
+ expect(stubs.cancelVideoUpscale).toHaveBeenCalledWith(jobId);
+ // The service reports the kill as a failure; the queue maps a requested
+ // cancel to 'canceled' so the source-preserving outcome reads correctly.
+ videoGenEvents.emit('failed', { generationId: jobId, error: 'Canceled while running' });
+ await waitFor(() => mediaJobQueue.getJob(jobId)?.status === 'canceled');
+ });
+
+ it('reports the kind in queue capacity so it is never invisible', () => {
+ expect(Object.keys(mediaJobQueue.getQueueCapacity().byKind)).toContain('video-upscale');
+ });
+ });
+
describe('getQueueCapacity', () => {
it('separates the serialized GPU lane from the parallel remote lane', async () => {
// Both lanes run concurrently, so a remote job must NOT be reported as
diff --git a/server/services/videoGen/renderArgs.js b/server/services/videoGen/renderArgs.js
index f80807778a..2e01566c61 100644
--- a/server/services/videoGen/renderArgs.js
+++ b/server/services/videoGen/renderArgs.js
@@ -53,8 +53,11 @@ import {
FASTVIDEO_REPO_DIR,
FASTVIDEO_MLX_CHECKPOINT_DIR,
FASTVIDEO_PROMPT_CACHE_DIR,
+ LTX25_VENV_PYTHON,
+ LTX25_UPSCALE_HELPER_SCRIPT,
LTX25_CUDA_VENV_PYTHON,
LTX25_CUDA_HELPER_SCRIPT,
+ LTX25_CUDA_UPSCALE_HELPER_SCRIPT,
WAN22_CUDA_VENV_PYTHON,
WAN22_CUDA_HELPER_SCRIPT,
BYOV_RUNTIME_INFO,
@@ -968,6 +971,99 @@ const buildLtx25CudaArgs = ({ model, prompt, negativePrompt, width, height, numF
return { bin: LTX25_CUDA_VENV_PYTHON, args };
};
+// Which helper script + interpreter carries a generative upscale on each BYOV
+// runtime. Keyed by runtime id (NOT platform) so the caller's resolved runtime
+// is the single decision — `upscalePlan.ltxUpscaleRuntimeId()` already made it.
+const LTX_UPSCALE_RUNNERS = Object.freeze({
+ ltx25: { bin: LTX25_VENV_PYTHON, script: LTX25_UPSCALE_HELPER_SCRIPT },
+ ltx25_cuda: { bin: LTX25_CUDA_VENV_PYTHON, script: LTX25_CUDA_UPSCALE_HELPER_SCRIPT },
+});
+
+/**
+ * Argv for the generative 2× video upscale (#6511).
+ *
+ * The pass is an IC-LoRA render whose single reference is the clip being
+ * upscaled, so it reuses the IC flag alphabet (`--ic-lora-path`,
+ * `--ic-reference`, `--ic-min-references`, `--ic-max-references`) rather than
+ * inventing a second one. The bounds are passed EXPLICITLY for the same reason
+ * `icLoraArgs` passes them: the weight registry is the single source of truth
+ * across both languages, and `run_ic_lora` requires them — a Python-side
+ * default would be a second table free to drift from `icLoraWeights.js`.
+ *
+ * There is deliberately no model id here. The base LTX-2.5 checkpoint is the
+ * runner's own pinned dependency (#6512 / #6513), not a user-selectable render
+ * model, so naming one would invite an upscale conditioned on a checkpoint the
+ * adapter was never trained against.
+ *
+ * `width`/`height`/`numFrames` are the ALIGNED target the caller already padded
+ * its source up to, so this builder asserts the grid rather than re-deriving it.
+ */
+export const buildLtxUpscaleArgs = ({
+ runtime, sourceVideoPath, icLoraWeightPath, icMinReferences, icMaxReferences,
+ width, height, numFrames, fps, seed, outputPath,
+}) => {
+ const runner = LTX_UPSCALE_RUNNERS[runtime];
+ if (!runner) {
+ throw new ServerError(
+ `No generative upscale runner exists for runtime "${runtime || 'unknown'}".`,
+ { status: 400, code: 'UPSCALE_RUNTIME_UNSUPPORTED' },
+ );
+ }
+ assertByovRuntimeInstalled(runtime);
+ if (!icLoraWeightPath) {
+ throw new ServerError(
+ 'The Pixel Spatial Upscaler weight is not downloaded — download it from the model panel first.',
+ { status: 400, code: 'IC_LORA_WEIGHT_UNRESOLVED' },
+ );
+ }
+ if (!sourceVideoPath || !existsSync(sourceVideoPath)) {
+ throw new ServerError(
+ `Upscale source clip not found on disk: ${sourceVideoPath || '(missing)'}`,
+ { status: 400, code: 'IC_LORA_REFERENCE_MISSING' },
+ );
+ }
+ // The bounds ride in the job params so a persisted/replayed job stays
+ // self-describing. A job written before they did — or hand-edited out of
+ // media-jobs.json — must fail rather than silently borrow the helper's
+ // default, which is the exact drift this contract exists to prevent.
+ const bound = (value, flag) => {
+ const n = Number(value);
+ if (!Number.isInteger(n) || n < 1) {
+ throw new ServerError(
+ `Generative upscale requires an explicit ${flag} from the weight registry; got ${value}.`,
+ { status: 400, code: 'IC_LORA_REFERENCE_BOUNDS_MISSING' },
+ );
+ }
+ return String(n);
+ };
+ const positive = (value, flag) => {
+ const n = Number(value);
+ if (!Number.isFinite(n) || n <= 0) {
+ throw new ServerError(
+ `Generative upscale requires a positive ${flag}; got ${value}.`,
+ { status: 400, code: 'UPSCALE_TARGET_INVALID' },
+ );
+ }
+ return String(n);
+ };
+ return {
+ bin: runner.bin,
+ args: [
+ runner.script,
+ '--ic-lora-path', icLoraWeightPath,
+ '--ic-reference', sourceVideoPath,
+ '--ic-min-references', bound(icMinReferences, '--ic-min-references'),
+ '--ic-max-references', bound(icMaxReferences, '--ic-max-references'),
+ '--width', positive(width, 'width'),
+ '--height', positive(height, 'height'),
+ '--num-frames', positive(numFrames, 'frame count'),
+ '--fps', positive(fps, 'frame rate'),
+ '--seed', String(Number(seed) >>> 0),
+ '--output', outputPath,
+ ],
+ };
+};
+
export const buildMiniMaxH3Ref2vaArgs = ({
model, ref2vaModelPath, prompt, negativePrompt, width, height, numFrames, fps,
steps, seed, sourceImagePath, audioFilePath, audioStartSec, mode, tiling,
@@ -1019,7 +1115,12 @@ export const buildMiniMaxH3Ref2vaArgs = ({
return { bin: process.execPath, args };
};
-export const buildArgs = ({ pythonPath, modelId, model, wanModelPath, wanRequiredWeights, ltxModelPath, ref2vaModelPath, prompt, negativePrompt, width, height, numFrames, fps, steps, stage2Steps, guidance, seed, tiling, disableAudio, sourceImagePath, lastImagePath, keyframes, extendFromVideoPath, audioFilePath, audioStartSec, mode, imageStrength, i2vReferenceMode, textEncoderRepo, textEncoder, outputPath, previewDir, loras, icReferencePaths, icLoraWeightPath, icStrength, icAttentionStrength, icSkipStage2, speedProfile, draftDecoder, streamingMode, ffmpegPath, ffprobePath }) => {
+export const buildArgs = ({ upscale, pythonPath, modelId, model, wanModelPath, wanRequiredWeights, ltxModelPath, ref2vaModelPath, prompt, negativePrompt, width, height, numFrames, fps, steps, stage2Steps, guidance, seed, tiling, disableAudio, sourceImagePath, lastImagePath, keyframes, extendFromVideoPath, audioFilePath, audioStartSec, mode, imageStrength, i2vReferenceMode, textEncoderRepo, textEncoder, outputPath, previewDir, loras, icReferencePaths, icLoraWeightPath, icStrength, icAttentionStrength, icSkipStage2, speedProfile, draftDecoder, streamingMode, ffmpegPath, ffprobePath }) => {
+ // Generative upscale (#6511) declines FIRST. It is not a text/image render:
+ // it carries no video model, no prompt and no reference mode, so every guard
+ // below would either dereference a model it was never given or reject it for
+ // lacking a conditioning contract it does not have.
+ if (upscale) return buildLtxUpscaleArgs({ ...upscale, outputPath });
// Reference-mode promise (#4874) — checked HERE rather than inside
// buildLtx2Args because every runtime reaches this function and only one can
// honor a loose reference. A wan22/mlx_video/H3 render that fell through to its
diff --git a/server/services/videoGen/renderArgsUpscale.test.js b/server/services/videoGen/renderArgsUpscale.test.js
new file mode 100644
index 0000000000..d39de6fba6
--- /dev/null
+++ b/server/services/videoGen/renderArgsUpscale.test.js
@@ -0,0 +1,110 @@
+import { describe, expect, it, vi } from 'vitest';
+
+// The generative-upscale runtimes are BYO-venv checkouts that do not exist on
+// CI (and are the capability gate that keeps #6511 off until #6512/#6513 land),
+// so the install assertion is stubbed for the argv tests and exercised on its
+// own below. Paths are fixtures, never a real install's layout.
+vi.mock('./runtimes.js', async (importOriginal) => ({
+ ...(await importOriginal()),
+ assertByovRuntimeInstalled: vi.fn(),
+ LTX25_VENV_PYTHON: '/fixture/ltx-2.5-mlx/.venv/bin/python3',
+ LTX25_UPSCALE_HELPER_SCRIPT: '/fixture/scripts/upscale_ltx25.py',
+ LTX25_CUDA_VENV_PYTHON: '/fixture/ltx-2.5-cuda/.venv/bin/python3',
+ LTX25_CUDA_UPSCALE_HELPER_SCRIPT: '/fixture/scripts/upscale_ltx25_cuda.py',
+}));
+
+const { buildArgs, buildLtxUpscaleArgs } = await import('./renderArgs.js');
+const runtimes = await import('./runtimes.js');
+
+// An existing file the builder can stat as the IC reference. `import.meta.url`
+// resolves to this test itself, so nothing about the developer's install leaks
+// into the fixture.
+const REFERENCE = new URL(import.meta.url).pathname;
+
+const upscale = (extra = {}) => ({
+ runtime: 'ltx25',
+ sourceVideoPath: REFERENCE,
+ icLoraWeightPath: '/fixture/cache/pixel-spatial-upscaler.safetensors',
+ icMinReferences: 1,
+ icMaxReferences: 1,
+ width: 1728,
+ height: 1024,
+ numFrames: 121,
+ fps: 24,
+ seed: 4242,
+ ...extra,
+});
+
+describe('buildLtxUpscaleArgs (#6511)', () => {
+ it('builds the exact MLX argv, with the reference bounds passed explicitly', () => {
+ expect(buildLtxUpscaleArgs({ ...upscale(), outputPath: '/fixture/out.mp4' })).toEqual({
+ bin: '/fixture/ltx-2.5-mlx/.venv/bin/python3',
+ args: [
+ '/fixture/scripts/upscale_ltx25.py',
+ '--ic-lora-path', '/fixture/cache/pixel-spatial-upscaler.safetensors',
+ '--ic-reference', REFERENCE,
+ '--ic-min-references', '1',
+ '--ic-max-references', '1',
+ '--width', '1728',
+ '--height', '1024',
+ '--num-frames', '121',
+ '--fps', '24',
+ '--seed', '4242',
+ '--output', '/fixture/out.mp4',
+ ],
+ });
+ });
+
+ it('routes the CUDA runtime to its own interpreter and helper', () => {
+ const { bin, args } = buildLtxUpscaleArgs({ ...upscale({ runtime: 'ltx25_cuda' }), outputPath: '/fixture/out.mp4' });
+ expect(bin).toBe('/fixture/ltx-2.5-cuda/.venv/bin/python3');
+ expect(args[0]).toBe('/fixture/scripts/upscale_ltx25_cuda.py');
+ });
+
+ // The bounds are `run_ic_lora`'s contract and the weight registry is their
+ // single source of truth across both languages. A job that lost them (an old
+ // persisted job, a hand-edited media-jobs.json) must fail rather than let the
+ // Python helper supply a second, drifting table.
+ it.each([
+ ['icMinReferences', { icMinReferences: undefined }],
+ ['icMaxReferences', { icMaxReferences: null }],
+ ['a non-integer bound', { icMinReferences: 1.5 }],
+ ])('refuses to render when %s is missing', (_label, extra) => {
+ expect(() => buildLtxUpscaleArgs({ ...upscale(extra), outputPath: '/fixture/out.mp4' }))
+ .toThrow(expect.objectContaining({ code: 'IC_LORA_REFERENCE_BOUNDS_MISSING' }));
+ });
+
+ it('refuses an un-downloaded adapter rather than handing the pipeline a repo id', () => {
+ expect(() => buildLtxUpscaleArgs({ ...upscale({ icLoraWeightPath: null }), outputPath: '/fixture/out.mp4' }))
+ .toThrow(expect.objectContaining({ code: 'IC_LORA_WEIGHT_UNRESOLVED' }));
+ });
+
+ it('refuses a source clip that is not on disk', () => {
+ expect(() => buildLtxUpscaleArgs({ ...upscale({ sourceVideoPath: '/fixture/gone.mp4' }), outputPath: '/fixture/out.mp4' }))
+ .toThrow(expect.objectContaining({ code: 'IC_LORA_REFERENCE_MISSING' }));
+ });
+
+ it('refuses a runtime with no upscale runner', () => {
+ expect(() => buildLtxUpscaleArgs({ ...upscale({ runtime: 'ltx2' }), outputPath: '/fixture/out.mp4' }))
+ .toThrow(expect.objectContaining({ code: 'UPSCALE_RUNTIME_UNSUPPORTED' }));
+ });
+
+ // The capability gate #6511 ships behind: with no venv installed there is no
+ // generative upscale on this machine, whatever else the request carries.
+ it('asserts the BYOV runtime is installed before building anything', () => {
+ runtimes.assertByovRuntimeInstalled.mockImplementationOnce(() => {
+ throw Object.assign(new Error('LTX-2.5 MLX runtime is not installed.'), { code: 'LTX25_VENV_MISSING' });
+ });
+ expect(() => buildLtxUpscaleArgs({ ...upscale(), outputPath: '/fixture/out.mp4' }))
+ .toThrow(expect.objectContaining({ code: 'LTX25_VENV_MISSING' }));
+ });
+});
+
+describe('buildArgs upscale dispatch', () => {
+ // The upscale carries no video model, no prompt and no reference mode, so it
+ // has to decline before any of buildArgs' render guards dereference one.
+ it('routes an upscale request without a model or prompt', () => {
+ expect(buildArgs({ upscale: upscale(), outputPath: '/fixture/out.mp4' }))
+ .toEqual(buildLtxUpscaleArgs({ ...upscale(), outputPath: '/fixture/out.mp4' }));
+ });
+});
diff --git a/server/services/videoGen/runtimes.js b/server/services/videoGen/runtimes.js
index 5b3fa556bc..97ca20c4a7 100644
--- a/server/services/videoGen/runtimes.js
+++ b/server/services/videoGen/runtimes.js
@@ -41,6 +41,14 @@ export const LTX25_EXPECTED_REVISION = '57952288076766abe27dda3a774b2c24f7346977
// would read as untracked in that pin verification.
export const LTX25_ENCODER_SHIM_DIR = join(homedir(), '.portos', 'ltx25-encoder-shims');
+// Generative video upscale (#6511). A spatial-upscale pass fuses the LTX-2.5
+// Pixel Spatial Upscaler IC-LoRA over a source clip, which is a different
+// entry point from a text/image render — so it gets its own helper script per
+// runtime rather than another mode flag on the generation script. Both scripts
+// land with the Python backends (#6512 MLX / #6513 CUDA); until then the
+// runtime's venv is absent, which is what gates the feature off.
+export const LTX25_UPSCALE_HELPER_SCRIPT = join(PATHS.root, 'scripts', 'upscale_ltx25.py');
+
// Wan 2.2 MLX runtime — pinned MLX-Gen checkout provisioned on demand.
export const WAN22_VENV_PYTHON = join(homedir(), '.portos', 'mlx-gen', '.venv', 'bin', 'python3');
export const WAN22_HELPER_SCRIPT = join(PATHS.root, 'scripts', 'generate_wan22.py');
@@ -127,6 +135,7 @@ export const LTX25_CUDA_VENV_PYTHON = process.platform === 'win32'
? join(LTX25_CUDA_REPO_DIR, '.venv', 'Scripts', 'python.exe')
: join(LTX25_CUDA_REPO_DIR, '.venv', 'bin', 'python3');
export const LTX25_CUDA_HELPER_SCRIPT = join(PATHS.root, 'scripts', 'generate_ltx25_cuda.py');
+export const LTX25_CUDA_UPSCALE_HELPER_SCRIPT = join(PATHS.root, 'scripts', 'upscale_ltx25_cuda.py');
// Wan 2.2 TI2V 5B on CUDA — official Diffusers checkpoint.
export const WAN22_CUDA_REPO_DIR = join(homedir(), '.portos', 'wan2.2-cuda');
diff --git a/server/services/videoGen/upscaleFfmpeg.js b/server/services/videoGen/upscaleFfmpeg.js
new file mode 100644
index 0000000000..262bd51666
--- /dev/null
+++ b/server/services/videoGen/upscaleFfmpeg.js
@@ -0,0 +1,110 @@
+/**
+ * The two ffmpeg passes that bracket a generative video upscale (#6511).
+ *
+ * The model renders on a fixed grid, so a source that does not already sit on
+ * it has to be padded up before the render and cropped back after it. #6509
+ * computes that plan; these apply exactly it and nothing else:
+ *
+ * source ─padSourceForUpscale─▶ aligned copy ─(GPU render)─▶ padded output
+ * ─finalizeUpscaleOutput─▶ deliverable (cropped, trimmed, audio muxed)
+ *
+ * Both write to a NEW path and never touch their input — the source clip is the
+ * user's original and the whole contract is that a failed or cancelled upscale
+ * leaves it exactly as it was.
+ *
+ * These live beside the upscale service rather than in `lib/ffmpeg.js` because
+ * their arguments are the alignment plan, not a general video operation: the
+ * pad geometry, the crop-back geometry and the audio re-mux are one contract
+ * that only makes sense together.
+ */
+
+import {
+ findFfmpeg, runFfmpegProcess, bt709TagFilter,
+ H264_ENCODE_ARGS, BT709_CONTAINER_ARGS,
+} from '../../lib/ffmpeg.js';
+
+// Right/bottom pad + tail-frame extension, in one filter chain. `tpad`'s
+// `stop_mode=clone` repeats the LAST frame rather than inserting black, so the
+// padding the model sees is a still hold of the final image instead of a hard
+// cut to black that it would try to synthesize detail into.
+const alignFilter = ({ width, height, padFrames, fps }) => {
+ const chain = [`pad=${width}:${height}:0:0:color=black`];
+ if (padFrames > 0) chain.push(`tpad=stop_mode=clone:stop_duration=${(padFrames / fps).toFixed(6)}`);
+ return chain;
+};
+
+const withColorTag = async (chain) => {
+ const tag = await bt709TagFilter();
+ return (tag ? [...chain, tag] : chain).join(',');
+};
+
+/**
+ * Write an aligned copy of `sourcePath` to `outPath`.
+ *
+ * Video only (`-an`): the source audio is re-muxed onto the FINAL deliverable
+ * from the original file, so carrying it through the render input would only
+ * risk the padded tail stretching it.
+ *
+ * @returns {{ok: true} | {ok: false, reason: string}}
+ */
+export const padSourceForUpscale = async (sourcePath, outPath, {
+ width, height, padFrames = 0, fps, signal,
+} = {}) => {
+ const ffmpeg = await findFfmpeg();
+ if (!ffmpeg) return { ok: false, reason: 'ffmpeg not found' };
+ if (!(Number(fps) > 0)) return { ok: false, reason: 'source frame rate unknown' };
+ return runFfmpegProcess({
+ bin: ffmpeg,
+ signal,
+ args: [
+ '-i', sourcePath,
+ '-vf', await withColorTag(alignFilter({ width, height, padFrames, fps })),
+ ...H264_ENCODE_ARGS,
+ ...BT709_CONTAINER_ARGS,
+ '-an',
+ '-y', outPath,
+ ],
+ });
+};
+
+/**
+ * Turn the model's padded output into the deliverable.
+ *
+ * Crops the alignment padding back off (top-left origin, matching how
+ * `padSourceForUpscale` added it), trims the cloned tail frames back to the
+ * source's own frame count, and muxes the ORIGINAL clip's audio track back on
+ * at offset zero — the adapter is a spatial upscaler, so the timeline it was
+ * handed is the timeline that comes back.
+ *
+ * `-map 1:a:0?` is optional-by-suffix: a source with no audio track yields a
+ * silent output rather than an ffmpeg failure, which is the #6511 contract.
+ *
+ * @returns {{ok: true} | {ok: false, reason: string}}
+ */
+export const finalizeUpscaleOutput = async (renderedPath, outPath, {
+ width, height, frameCount, audioSourcePath, signal,
+} = {}) => {
+ const ffmpeg = await findFfmpeg();
+ if (!ffmpeg) return { ok: false, reason: 'ffmpeg not found' };
+ if (!(Number(width) > 0) || !(Number(height) > 0) || !(Number(frameCount) > 0)) {
+ return { ok: false, reason: 'upscale output geometry unknown' };
+ }
+ return runFfmpegProcess({
+ bin: ffmpeg,
+ signal,
+ args: [
+ '-i', renderedPath,
+ '-i', audioSourcePath,
+ '-filter_complex', `[0:v]${await withColorTag([`crop=${width}:${height}:0:0`])}[v]`,
+ '-map', '[v]',
+ '-map', '1:a:0?',
+ ...H264_ENCODE_ARGS,
+ ...BT709_CONTAINER_ARGS,
+ '-c:a', 'copy',
+ '-frames:v', String(Math.round(frameCount)),
+ '-shortest',
+ '-movflags', '+faststart',
+ '-y', outPath,
+ ],
+ });
+};
diff --git a/server/services/videoGen/upscaleFfmpeg.test.js b/server/services/videoGen/upscaleFfmpeg.test.js
new file mode 100644
index 0000000000..cb29457893
--- /dev/null
+++ b/server/services/videoGen/upscaleFfmpeg.test.js
@@ -0,0 +1,79 @@
+import { describe, expect, it, vi, beforeEach } from 'vitest';
+
+// Pure argv construction over a stubbed ffmpeg — the passes themselves are
+// exercised through upscaleJob, and running real ffmpeg here would make the
+// suite depend on a binary CI does not guarantee.
+const ffmpeg = vi.hoisted(() => ({ runs: [] }));
+
+vi.mock('../../lib/ffmpeg.js', () => ({
+ findFfmpeg: vi.fn(async () => '/fixture/bin/ffmpeg'),
+ runFfmpegProcess: vi.fn(async (call) => { ffmpeg.runs.push(call); return { ok: true }; }),
+ bt709TagFilter: vi.fn(async () => null),
+ H264_ENCODE_ARGS: ['-c:v', 'libx264'],
+ BT709_CONTAINER_ARGS: ['-color_primaries', 'bt709'],
+}));
+
+const { padSourceForUpscale, finalizeUpscaleOutput } = await import('./upscaleFfmpeg.js');
+
+const argFor = (flag) => {
+ const args = ffmpeg.runs.at(-1).args;
+ return args[args.indexOf(flag) + 1];
+};
+
+beforeEach(() => { ffmpeg.runs.length = 0; });
+
+describe('padSourceForUpscale', () => {
+ it('pads right/bottom and clones the tail for exactly the planned frames', async () => {
+ await padSourceForUpscale('/fixture/src.mp4', '/fixture/aligned.mp4', {
+ width: 864, height: 512, padFrames: 4, fps: 25,
+ });
+ // 4 frames at 25fps = 0.16s of held final frame. `stop_mode=clone` rather
+ // than black so the model is not asked to synthesize detail into a cut.
+ expect(argFor('-vf')).toBe('pad=864:512:0:0:color=black,tpad=stop_mode=clone:stop_duration=0.160000');
+ expect(ffmpeg.runs.at(-1).args).toContain('-an');
+ });
+
+ it('omits the tail filter entirely when no frames need padding', async () => {
+ await padSourceForUpscale('/fixture/src.mp4', '/fixture/aligned.mp4', {
+ width: 768, height: 512, padFrames: 0, fps: 24,
+ });
+ expect(argFor('-vf')).toBe('pad=768:512:0:0:color=black');
+ });
+
+ it('refuses rather than guessing when the source frame rate is unknown', async () => {
+ const result = await padSourceForUpscale('/fixture/src.mp4', '/fixture/aligned.mp4', {
+ width: 768, height: 512, padFrames: 8, fps: null,
+ });
+ expect(result).toEqual({ ok: false, reason: 'source frame rate unknown' });
+ expect(ffmpeg.runs).toHaveLength(0);
+ });
+});
+
+describe('finalizeUpscaleOutput', () => {
+ const finalize = (extra = {}) => finalizeUpscaleOutput('/fixture/rendered.mp4', '/fixture/final.mp4', {
+ width: 1536, height: 1024, frameCount: 121, audioSourcePath: '/fixture/src.mp4', ...extra,
+ });
+
+ it('crops the padding back off at the origin it was added and trims the tail', async () => {
+ await finalize();
+ expect(argFor('-filter_complex')).toBe('[0:v]crop=1536:1024:0:0[v]');
+ expect(argFor('-frames:v')).toBe('121');
+ });
+
+ it('maps the source audio OPTIONALLY, so a silent source is a silent output rather than a failure', async () => {
+ await finalize();
+ const args = ffmpeg.runs.at(-1).args;
+ // The trailing `?` is the whole no-audio contract: ffmpeg skips a missing
+ // stream instead of exiting non-zero.
+ expect(args.join(' ')).toContain('-map [v] -map 1:a:0?');
+ expect(args.join(' ')).toContain('-c:a copy');
+ // The original clip is the audio INPUT and is never an output target.
+ expect(args.filter((a) => a === '/fixture/src.mp4')).toHaveLength(1);
+ expect(args.at(-1)).toBe('/fixture/final.mp4');
+ });
+
+ it('refuses rather than writing a wrong-sized deliverable when the geometry is unknown', async () => {
+ expect(await finalize({ frameCount: null })).toEqual({ ok: false, reason: 'upscale output geometry unknown' });
+ expect(ffmpeg.runs).toHaveLength(0);
+ });
+});
diff --git a/server/services/videoGen/upscaleJob.js b/server/services/videoGen/upscaleJob.js
new file mode 100644
index 0000000000..6d3bc014b5
--- /dev/null
+++ b/server/services/videoGen/upscaleJob.js
@@ -0,0 +1,414 @@
+/**
+ * Generative video upscale — the media-job lifecycle (#6511).
+ *
+ * The Lanczos pass is an inline ffmpeg filter, so `upscaleVideo.js` runs it
+ * during the request. A generative pass is a multi-minute GPU render, so it
+ * goes through `mediaJobQueue` instead: `enqueueLtxUpscale` validates and
+ * queues, `runVideoUpscale` is what the queue worker invokes, and `cancel` is
+ * the hook `cancelJob` reaches through `getGenModuleForJob`.
+ *
+ * Two contracts govern everything here:
+ *
+ * - **The source is never touched.** Cancellation, a probe failure, a render
+ * failure and a mux failure all leave the source clip and its history row
+ * byte-identical and remove every partial output. That mirrors the Lanczos
+ * path's copy-then-transform shape: the deliverable is a NEW file and a NEW
+ * history row, or it does not exist at all.
+ * - **Local only.** `LTX_UPSCALE_JOB_KIND` is deliberately absent from the
+ * federation layer's kind maps, so the source video cannot be offered to a
+ * peer. See the privacy rules in AGENTS.md.
+ */
+
+import { existsSync } from 'fs';
+import { randomUUID, randomInt } from 'crypto';
+import { join } from 'path';
+import { tmpdir } from 'os';
+import { PATHS, unlinkGuarded } from '../../lib/fileUtils.js';
+import { ServerError } from '../../lib/errorHandler.js';
+import {
+ safeUnder, generateThumbnail, probeVideoStreamInfo, probeVideoDuration,
+} from '../../lib/ffmpeg.js';
+import { createLineReader } from '../../lib/streamLines.js';
+import { spawnDetached } from '../../lib/detachedSpawn.js';
+import { killWithEscalation } from '../../lib/killWithEscalation.js';
+import { safeChildProcessEnv } from '../../lib/processEnv.js';
+import { PYTHON_NOISE_RE } from '../../lib/sseUtils.js';
+import { omitRenderTiming, renderTimingFields } from '../../lib/renderTiming.js';
+import { resolveIcLoraWeightByKey } from '../../lib/icLoraWeights.js';
+import { hfChildEnv } from '../hfToken.js';
+import { enqueueJob } from '../mediaJobQueue/index.js';
+import { videoGenEvents } from './events.js';
+import { getHistoryItem, loadHistory, mutateVideoHistory } from './history.js';
+import { buildArgs } from './renderArgs.js';
+import { runtimeIsCacheOnly, runtimeNeedsProcessGroupKill } from './runtimes.js';
+import { padSourceForUpscale, finalizeUpscaleOutput } from './upscaleFfmpeg.js';
+import { planUpscaleHistoryItem } from './upscaleVideo.js';
+import {
+ LTX_UPSCALE_JOB_KIND, LTX_UPSCALE_WEIGHT_KEY, UPSCALE_SCALE,
+ ltxAlignmentBlocker, ltxAlignmentIsNoop,
+} from './upscalePlan.js';
+
+const MAX_SEED = 2 ** 32 - 1;
+const STAGE_RE = /^STAGE:\s*(\S+)\s*(.*)$/;
+const STDERR_TAIL_LINES = 20;
+
+// jobId → the in-flight run's cancel handles. Module-local rather than the
+// shared `videoJobState`, because an upscale child is not a render child: the
+// GPU lane already serializes the two, and mixing them would let a plain
+// `videoGen.cancel()` kill an upscale (and vice versa) with no job id to
+// discriminate on.
+const activeUpscales = new Map();
+
+// Same suffix convention the Lanczos pass uses, so the gallery reads
+// "<original prompt> (2×)" whichever method produced the row.
+const upscaledPrompt = (prompt) => (prompt ? `${prompt} (2×)` : '(upscaled 2×)');
+
+/**
+ * Validate an upscale request and queue it. Everything that can be known
+ * before a GPU is committed is checked HERE — an unsupported/uninstalled
+ * runtime, a missing adapter, and a source the model grid cannot take without
+ * losing duration — so a refusal is an immediate 4xx/501 rather than a job that
+ * fails minutes later.
+ */
+export async function enqueueLtxUpscale(historyId) {
+ const plan = await planUpscaleHistoryItem(historyId, { method: 'ltx' });
+ if (plan.alreadyUpscaled) {
+ throw new ServerError('Cannot upscale an already-upscaled video', { status: 400, code: 'ALREADY_UPSCALED' });
+ }
+ if (!plan.runtime.supported || !plan.runtime.installed) {
+ throw new ServerError(
+ `Generative upscale is not available on this install: ${plan.runtime.reason}`,
+ { status: 501, code: 'UNSUPPORTED_RUNTIME' },
+ );
+ }
+ // Cache-only resolve (#6508): a `requiresPreDownload` weight never falls back
+ // to a repo id, so an un-cached adapter is a refusal here rather than a
+ // silent multi-hundred-MB pull inside the render.
+ const adapter = await resolveIcLoraWeightByKey(LTX_UPSCALE_WEIGHT_KEY);
+ if (!adapter?.path) {
+ throw new ServerError(
+ `${plan.adapter.label} is not downloaded — download it from the model panel before upscaling.`,
+ { status: 400, code: 'IC_LORA_WEIGHT_UNRESOLVED' },
+ );
+ }
+ const blocker = ltxAlignmentBlocker(plan.alignment);
+ if (blocker) {
+ throw new ServerError(blocker, { status: 400, code: 'UPSCALE_SOURCE_UNALIGNABLE' });
+ }
+ // The frame rate is not part of the spatial grid, but the plan cannot be
+ // APPLIED without it: it sets the duration of the padded tail and is a
+ // required runner argument. An unmeasured rate is the same refusal.
+ if (!(Number(plan.source.fps) > 0)) {
+ throw new ServerError(
+ 'The source frame rate could not be measured, so the padded tail and the render frame rate cannot be set.',
+ { status: 400, code: 'UPSCALE_SOURCE_UNALIGNABLE' },
+ );
+ }
+ // Read back for the two fields the plan projection deliberately omits (it is
+ // a geometry/capability disclosure, not a row dump).
+ const item = await getHistoryItem(plan.id);
+ if (!item) throw new ServerError('Video not found', { status: 404, code: 'NOT_FOUND' });
+ return enqueueJob({
+ kind: LTX_UPSCALE_JOB_KIND,
+ params: {
+ historyId: plan.id,
+ // The FILENAME, not an absolute path: job params are persisted and
+ // replayed, and `runVideoUpscale` re-resolves them through `safeUnder`
+ // so a hand-edited media-jobs.json cannot point the render (or the
+ // audio re-mux) at a file outside data/videos.
+ sourceFilename: item.filename,
+ method: 'ltx',
+ runtime: plan.runtime.id,
+ adapterKey: plan.adapter.key,
+ adapterPath: adapter.path,
+ // Explicit, from the weight registry — the Python helper is never allowed
+ // to carry its own copy of these bounds (see buildLtxUpscaleArgs).
+ icMinReferences: adapter.spec.minReferences,
+ icMaxReferences: adapter.spec.maxReferences,
+ seed: randomInt(0, MAX_SEED + 1),
+ source: plan.source,
+ alignment: plan.alignment,
+ target: plan.target,
+ // Projected by sanitizeJob, so the Render Queue names what is being
+ // upscaled instead of showing an unlabeled row.
+ prompt: upscaledPrompt(item.prompt),
+ width: plan.target.width,
+ height: plan.target.height,
+ numFrames: plan.target.frameCount,
+ fps: plan.source.fps,
+ },
+ });
+}
+
+// Cancel the running upscale for `jobId`. Called by mediaJobQueue's cancelJob
+// and by its idle watchdog; both then read the resulting child death as the
+// job's terminal state.
+export function cancel(jobId) {
+ const entry = activeUpscales.get(jobId);
+ if (!entry) return false;
+ entry.canceled = true;
+ entry.abort.abort();
+ if (entry.proc) {
+ killWithEscalation(entry.proc, {
+ label: 'video upscale child',
+ stillRunning: () => activeUpscales.get(jobId)?.proc === entry.proc,
+ });
+ }
+ return true;
+}
+
+// Build the child env for the upscale runner, mirroring the render path: no
+// inherited PYTHONPATH (the venv owns its site-packages), unbuffered stdio so
+// STAGE lines reach the watchdog as they happen, and no ambient HF credential
+// for a cache-only runtime that must never reach the network.
+const upscaleChildEnv = async (runtime) => {
+ const cacheOnly = runtimeIsCacheOnly(runtime);
+ const env = cacheOnly ? safeChildProcessEnv() : await hfChildEnv();
+ delete env.PYTHONPATH;
+ env.PYTHONUNBUFFERED = '1';
+ if (cacheOnly) {
+ delete env.HF_TOKEN;
+ delete env.HUGGING_FACE_HUB_TOKEN;
+ env.HF_HUB_DISABLE_IMPLICIT_TOKEN = '1';
+ env.HF_HUB_OFFLINE = '1';
+ env.TRANSFORMERS_OFFLINE = '1';
+ }
+ return env;
+};
+
+/**
+ * Spawn the upscale runner and settle when it exits.
+ *
+ * Resolves `{ ok }` rather than rejecting so every terminal path in
+ * `runVideoUpscale` converges on the same cleanup. Non-noise child output is
+ * forwarded as `activity` so the queue's idle watchdog measures real silence,
+ * and `STAGE:` markers become status frames the UI can name.
+ */
+const runUpscaleChild = async ({ jobId, bin, args, runtime, entry }) => {
+ // A cancel that landed while the alignment pass was still running has no
+ // child to kill yet, so it is honored HERE rather than letting the runner
+ // start and burn a GPU on work nobody is waiting for.
+ if (entry.canceled) return { ok: false, reason: 'canceled before the runner started' };
+ const proc = await spawnDetached(bin, args, {
+ env: await upscaleChildEnv(runtime),
+ controlDir: join(PATHS.videos, '.detached', jobId),
+ cleanup: true,
+ killProcessGroup: runtimeNeedsProcessGroupKill(runtime),
+ });
+ entry.proc = proc;
+ // …and a cancel that landed during the spawn itself: the handle exists now,
+ // so signal it immediately instead of waiting for a render nobody wants.
+ if (entry.canceled) cancel(jobId);
+ const stderrTail = [];
+ const onLine = (line, isStderr) => {
+ const text = String(line).trim();
+ if (!text || PYTHON_NOISE_RE.test(text)) return;
+ if (isStderr) {
+ stderrTail.push(text);
+ if (stderrTail.length > STDERR_TAIL_LINES) stderrTail.shift();
+ }
+ videoGenEvents.emit('activity', { generationId: jobId });
+ const stage = STAGE_RE.exec(text);
+ if (stage) {
+ videoGenEvents.emit('status', { generationId: jobId, phase: stage[1], message: stage[2] || stage[1] });
+ }
+ };
+ const outReader = createLineReader((l) => onLine(l, false));
+ const errReader = createLineReader((l) => onLine(l, true));
+ proc.stdout.on('data', (c) => outReader.push(c));
+ proc.stderr.on('data', (c) => errReader.push(c));
+ return new Promise((resolve) => {
+ let settled = false;
+ const settle = (result) => {
+ if (settled) return;
+ settled = true;
+ outReader.flush();
+ errReader.flush();
+ resolve(result);
+ };
+ proc.on('error', (err) => settle({ ok: false, reason: `spawn failed: ${err.message}` }));
+ proc.on('close', (code, signal) => {
+ if (code === 0) { settle({ ok: true }); return; }
+ const tail = stderrTail.slice(-4).join(' | ');
+ const how = signal ? `killed (${signal})` : `exit ${code}`;
+ settle({ ok: false, reason: tail ? `upscale runner ${how}: ${tail}` : `upscale runner ${how}` });
+ });
+ });
+};
+
+/**
+ * The queue worker's entry point. Never throws — every outcome is reported on
+ * `videoGenEvents` as `completed` or `failed`, which is the terminal signal
+ * `mediaJobQueue`'s dispatcher awaits. A `failed` on a job whose cancel was
+ * requested is mapped to `canceled` by the queue, so this does not need to
+ * distinguish them on the wire.
+ */
+export async function runVideoUpscale({
+ jobId, historyId, sourceFilename, runtime, adapterPath, adapterKey,
+ icMinReferences, icMaxReferences, seed, source, alignment, target,
+}) {
+ const entry = { canceled: false, proc: null, abort: new AbortController() };
+ activeUpscales.set(jobId, entry);
+ const renderStartedAtMs = Date.now();
+ // Every path this run might create, so a failure at ANY step removes all of
+ // them. The source clip is never in this list.
+ const scratch = [];
+ let deliverablePath = null;
+ let thumbnailPath = null;
+ try {
+ // Re-read the row rather than trusting the enqueue-time snapshot: a queued
+ // job can wait behind a long render, and the user may have deleted or
+ // already upscaled the source in the meantime.
+ const history = await loadHistory();
+ const item = history.find((h) => h.id === historyId);
+ if (!item) throw new ServerError('Video not found', { status: 404, code: 'NOT_FOUND' });
+ if (item.upscaledFrom) {
+ throw new ServerError('Cannot upscale an already-upscaled video', { status: 400, code: 'ALREADY_UPSCALED' });
+ }
+ // Re-resolve the queued filename through safeUnder rather than trusting the
+ // persisted string: media-jobs.json is replayed on boot and hand-editable,
+ // and this path is handed to both the render and the audio re-mux.
+ if (item.filename !== sourceFilename) {
+ throw new ServerError('The source clip was replaced while this upscale was queued.', { status: 409, code: 'UPSCALE_SOURCE_CHANGED' });
+ }
+ const sourcePath = safeUnder(PATHS.videos, sourceFilename);
+ if (!sourcePath || !existsSync(sourcePath)) {
+ throw new ServerError('Video file not found on disk', { status: 404, code: 'NOT_FOUND' });
+ }
+
+ videoGenEvents.emit('started', {
+ generationId: jobId,
+ id: jobId,
+ upscaledFrom: historyId,
+ upscaleMethod: 'ltx',
+ upscaleRuntime: runtime,
+ width: target.width,
+ height: target.height,
+ numFrames: target.frameCount,
+ fps: source.fps,
+ seed,
+ etaMs: null,
+ });
+ console.log(`🔍 Upscaling video [${historyId.slice(0, 8)}] on ${runtime}: ${source.width}×${source.height} → ${target.width}×${target.height}`);
+
+ // Apply exactly #6509's plan: pad to the grid, never crop, never trim. A
+ // conforming source skips the pass entirely and is READ in place.
+ let referencePath = sourcePath;
+ if (!ltxAlignmentIsNoop(alignment)) {
+ referencePath = join(tmpdir(), `portos-upscale-src-${jobId}.mp4`);
+ scratch.push(referencePath);
+ const padded = await padSourceForUpscale(sourcePath, referencePath, {
+ width: alignment.paddedSource.width,
+ height: alignment.paddedSource.height,
+ padFrames: alignment.padFrames,
+ fps: source.fps,
+ signal: entry.abort.signal,
+ });
+ if (!padded.ok) {
+ throw new ServerError(`Failed to align the source clip: ${padded.reason}`, { status: 500, code: 'UPSCALE_ALIGN_FAILED' });
+ }
+ }
+
+ const renderPath = join(tmpdir(), `portos-upscale-out-${jobId}.mp4`);
+ scratch.push(renderPath);
+ const { bin, args } = buildArgs({
+ upscale: {
+ runtime,
+ sourceVideoPath: referencePath,
+ icLoraWeightPath: adapterPath,
+ icMinReferences,
+ icMaxReferences,
+ width: target.width,
+ height: target.height,
+ numFrames: target.frameCount,
+ fps: source.fps,
+ seed,
+ },
+ outputPath: renderPath,
+ });
+ const rendered = await runUpscaleChild({ jobId, bin, args, runtime, entry });
+ if (!rendered.ok) {
+ throw new ServerError(rendered.reason, { status: 500, code: 'UPSCALE_RENDER_FAILED' });
+ }
+ if (entry.canceled) {
+ throw new ServerError('Upscale canceled', { status: 499, code: 'UPSCALE_CANCELED' });
+ }
+ if (!existsSync(renderPath)) {
+ throw new ServerError('The upscale runner exited cleanly but wrote no video.', { status: 500, code: 'UPSCALE_RENDER_FAILED' });
+ }
+
+ // Crop the alignment padding back off, trim the cloned tail frames, and
+ // re-mux the ORIGINAL clip's audio at offset zero. A source with no audio
+ // track yields a silent deliverable, not a failure.
+ const newId = randomUUID();
+ const newFilename = `${newId}.mp4`;
+ deliverablePath = join(PATHS.videos, newFilename);
+ const finalized = await finalizeUpscaleOutput(renderPath, deliverablePath, {
+ width: source.width * UPSCALE_SCALE,
+ height: source.height * UPSCALE_SCALE,
+ frameCount: source.frameCount,
+ audioSourcePath: sourcePath,
+ signal: entry.abort.signal,
+ });
+ if (!finalized.ok) {
+ throw new ServerError(`Failed to finish the upscaled clip: ${finalized.reason}`, { status: 500, code: 'UPSCALE_MUX_FAILED' });
+ }
+
+ // Provenance is MEASURED off the deliverable, not assumed from the plan —
+ // a generative render is the one upscale method whose output can legally
+ // differ from 2× the source, so a recorded guess would be a lie.
+ const [measured, duration] = await Promise.all([
+ probeVideoStreamInfo(deliverablePath),
+ probeVideoDuration(deliverablePath),
+ ]);
+ const thumbnail = await generateThumbnail(deliverablePath, newId);
+ // Tracked so a failure between here and the history write cannot leave a
+ // poster for a clip that does not exist.
+ thumbnailPath = thumbnail ? safeUnder(PATHS.videoThumbnails, thumbnail) : null;
+ const newEntry = {
+ ...omitRenderTiming(item),
+ id: newId,
+ filename: newFilename,
+ thumbnail,
+ createdAt: new Date().toISOString(),
+ width: measured.width ?? source.width * UPSCALE_SCALE,
+ height: measured.height ?? source.height * UPSCALE_SCALE,
+ fps: measured.fps ?? source.fps,
+ numFrames: measured.frameCount ?? source.frameCount,
+ duration,
+ seed,
+ upscaledFrom: item.id,
+ upscaleMethod: 'ltx',
+ upscaleRuntime: runtime,
+ upscaleAdapter: adapterKey,
+ // What the grid actually required of this source, kept beside the result
+ // so a reader can tell a padded render from a conforming one.
+ upscaleAlignment: {
+ padWidth: alignment.padWidth,
+ padHeight: alignment.padHeight,
+ padFrames: alignment.padFrames,
+ trimFrames: alignment.trimFrames,
+ },
+ prompt: upscaledPrompt(item.prompt),
+ hidden: false,
+ ...renderTimingFields(renderStartedAtMs),
+ };
+ await mutateVideoHistory((h) => { h.unshift(newEntry); return h; });
+ console.log(`✅ Upscaled [${newId.slice(0, 8)}]: ${newFilename} (${newEntry.width}×${newEntry.height}, ${Math.round((newEntry.renderMs ?? 0) / 1000)}s)`);
+ videoGenEvents.emit('completed', { generationId: jobId, ...newEntry });
+ return newEntry;
+ } catch (err) {
+ // The history row is written LAST, so nothing here can orphan one — only a
+ // partial file can exist, and it is removed before the failure is reported.
+ for (const path of [deliverablePath, thumbnailPath]) {
+ if (path) await unlinkGuarded(path).catch(() => {});
+ }
+ const reason = entry.canceled ? 'Canceled while running' : (err.message || 'Upscale failed');
+ console.log(`❌ Video upscale ${entry.canceled ? 'canceled' : 'failed'} [${jobId.slice(0, 8)}]: ${reason}`);
+ videoGenEvents.emit('failed', { generationId: jobId, error: reason });
+ return null;
+ } finally {
+ for (const path of scratch) await unlinkGuarded(path).catch(() => {});
+ activeUpscales.delete(jobId);
+ }
+}
diff --git a/server/services/videoGen/upscaleJob.test.js b/server/services/videoGen/upscaleJob.test.js
new file mode 100644
index 0000000000..1c1863d9ce
--- /dev/null
+++ b/server/services/videoGen/upscaleJob.test.js
@@ -0,0 +1,450 @@
+import { describe, it, expect, beforeEach, afterAll, vi } from 'vitest';
+import { EventEmitter } from 'events';
+import { existsSync, mkdirSync, writeFileSync } from 'fs';
+import { join } from 'path';
+import { tmpdir } from 'os';
+import { makePathsProxy, lazyTempDataRoot, cleanupTempDataRoots } from '../../lib/mockPathsDataRoot.js';
+
+// The lifecycle really creates and removes files, so PATHS must point at a temp
+// tree — the install's data/ is the developer's live gallery.
+vi.mock('../../lib/fileUtils.js', async (importOriginal) =>
+ makePathsProxy(await importOriginal(), { dataRoot: () => lazyTempDataRoot('portos-upscale-job-') }));
+afterAll(cleanupTempDataRoots);
+
+const state = vi.hoisted(() => ({
+ history: [],
+ plan: null,
+ adapter: null,
+ enqueued: [],
+ padResult: { ok: true },
+ finalizeResult: { ok: true },
+ measured: { width: 1536, height: 1024, fps: 24, frameCount: 121 },
+ duration: 5.04,
+ child: null,
+ // Whether the fake runner writes the file it was told to produce.
+ writesOutput: true,
+ buildArgsCalls: [],
+}));
+
+vi.mock('./upscaleVideo.js', () => ({
+ planUpscaleHistoryItem: vi.fn(async () => state.plan),
+}));
+
+vi.mock('../mediaJobQueue/index.js', () => ({
+ enqueueJob: vi.fn((job) => {
+ state.enqueued.push(job);
+ return { jobId: 'queued-job', position: 1, status: 'queued' };
+ }),
+}));
+
+vi.mock('./history.js', () => ({
+ getHistoryItem: vi.fn(async (id) => state.history.find((h) => h.id === id) || null),
+ loadHistory: vi.fn(async () => state.history),
+ mutateVideoHistory: vi.fn(async (mutator) => mutator(state.history)),
+}));
+
+vi.mock('../../lib/icLoraWeights.js', () => ({
+ resolveIcLoraWeightByKey: vi.fn(async () => state.adapter),
+}));
+
+vi.mock('../../lib/ffmpeg.js', () => ({
+ safeUnder: vi.fn((base, name) => (name ? join(base, name) : null)),
+ generateThumbnail: vi.fn(async () => 'thumb.jpg'),
+ probeVideoStreamInfo: vi.fn(async () => state.measured),
+ probeVideoDuration: vi.fn(async () => state.duration),
+}));
+
+vi.mock('./upscaleFfmpeg.js', () => ({
+ padSourceForUpscale: vi.fn(async (_src, out) => {
+ if (state.padResult.ok) writeFileSync(out, 'aligned');
+ return state.padResult;
+ }),
+ finalizeUpscaleOutput: vi.fn(async (_rendered, out) => {
+ // A real ffmpeg run leaves a partial file behind on failure, which is
+ // exactly what the cleanup contract has to remove.
+ writeFileSync(out, 'final');
+ return state.finalizeResult;
+ }),
+}));
+
+vi.mock('./renderArgs.js', () => ({
+ buildArgs: vi.fn((args) => {
+ state.buildArgsCalls.push(args);
+ return { bin: '/fixture/python3', args: ['/fixture/upscale.py'] };
+ }),
+}));
+
+vi.mock('../../lib/detachedSpawn.js', () => ({
+ spawnDetached: vi.fn(async () => state.child),
+}));
+
+vi.mock('../hfToken.js', () => ({ hfChildEnv: vi.fn(async () => ({})) }));
+vi.mock('../../lib/killWithEscalation.js', () => ({ killWithEscalation: vi.fn((proc) => proc.kill('SIGTERM')) }));
+
+const { enqueueLtxUpscale, runVideoUpscale, cancel } = await import('./upscaleJob.js');
+const { enqueueJob } = await import('../mediaJobQueue/index.js');
+const { mutateVideoHistory } = await import('./history.js');
+const { padSourceForUpscale, finalizeUpscaleOutput } = await import('./upscaleFfmpeg.js');
+const { videoGenEvents } = await import('./events.js');
+const { PATHS } = await import('../../lib/fileUtils.js');
+const { LTX_UPSCALE_JOB_KIND, LTX_PROVENANCE_FIELDS } = await import('./upscalePlan.js');
+
+const SOURCE_ID = '11111111-1111-4111-8111-111111111111';
+const JOB_ID = 'job-11112222-3333';
+const SOURCE_FILE = `${SOURCE_ID}.mp4`;
+
+// A source already on the 32px grid with a conforming frame count: no padding,
+// so the plan is a no-op and the render reads the original clip in place.
+const conformingPlan = () => ({
+ id: SOURCE_ID,
+ method: 'ltx',
+ scale: 2,
+ alreadyUpscaled: false,
+ source: { width: 768, height: 512, fps: 24, frameCount: 121, durationSeconds: 5.04, hasAudio: true },
+ target: { width: 1536, height: 1024, frameCount: 121 },
+ alignment: {
+ padWidth: 0, padHeight: 0, padFrames: 0, trimFrames: 0,
+ paddedSource: { width: 768, height: 512, frameCount: 121 },
+ conforming: true,
+ },
+ runtime: { id: 'ltx25', label: 'LTX-2.5 MLX', supported: true, installed: true, reason: null },
+ adapter: { key: 'pixel-upscale', label: 'Pixel Spatial Upscaler', cached: true },
+});
+
+const sourceRow = (extra = {}) => ({
+ id: SOURCE_ID, filename: SOURCE_FILE, prompt: 'a lighthouse',
+ modelId: 'ltx2_unified', width: 768, height: 512, numFrames: 121, fps: 24, seed: 7,
+ renderMs: 90_000, renderStartedAt: '2026-01-01T00:00:00.000Z', ...extra,
+});
+
+const makeChild = () => {
+ const child = new EventEmitter();
+ child.stdout = new EventEmitter();
+ child.stderr = new EventEmitter();
+ child.kill = vi.fn(() => { child.emit('close', null, 'SIGTERM'); return true; });
+ return child;
+};
+
+const jobParams = (overrides = {}) => ({
+ jobId: JOB_ID,
+ historyId: SOURCE_ID,
+ sourceFilename: SOURCE_FILE,
+ runtime: 'ltx25',
+ adapterPath: '/cache/pixel-upscale.safetensors',
+ adapterKey: 'pixel-upscale',
+ icMinReferences: 1,
+ icMaxReferences: 1,
+ seed: 4242,
+ source: conformingPlan().source,
+ alignment: conformingPlan().alignment,
+ target: conformingPlan().target,
+ ...overrides,
+});
+
+const renderOutputPath = join(tmpdir(), `portos-upscale-out-${JOB_ID}.mp4`);
+const alignedSourcePath = join(tmpdir(), `portos-upscale-src-${JOB_ID}.mp4`);
+const sourcePath = () => join(PATHS.videos, SOURCE_FILE);
+
+// Drive the fake runner: it writes the file the real one would, then exits.
+const finishChild = (code = 0, signal = null) => {
+ if (state.writesOutput && code === 0) writeFileSync(renderOutputPath, 'rendered');
+ state.child.emit('close', code, signal);
+};
+
+// Run the job and settle the child once the spawn has happened.
+const runWith = async (drive, params = {}) => {
+ const run = runVideoUpscale(jobParams(params));
+ await vi.waitFor(() => expect(state.child.listenerCount('close')).toBeGreaterThan(0));
+ drive();
+ return run;
+};
+
+beforeEach(() => {
+ mkdirSync(PATHS.videos, { recursive: true });
+ writeFileSync(sourcePath(), 'source-bytes');
+ state.history = [sourceRow()];
+ state.plan = conformingPlan();
+ state.adapter = { path: '/cache/pixel-upscale.safetensors', cached: true, spec: { minReferences: 1, maxReferences: 1 } };
+ state.enqueued = [];
+ state.padResult = { ok: true };
+ state.finalizeResult = { ok: true };
+ state.measured = { width: 1536, height: 1024, fps: 24, frameCount: 121 };
+ state.writesOutput = true;
+ state.buildArgsCalls = [];
+ state.child = makeChild();
+ vi.clearAllMocks();
+});
+
+describe('enqueueLtxUpscale', () => {
+ it('queues the generative pass as its own job kind with the resolved render inputs', async () => {
+ const result = await enqueueLtxUpscale(SOURCE_ID);
+ expect(result).toEqual({ jobId: 'queued-job', position: 1, status: 'queued' });
+ expect(enqueueJob).toHaveBeenCalledTimes(1);
+ const [job] = state.enqueued;
+ expect(job.kind).toBe(LTX_UPSCALE_JOB_KIND);
+ expect(job.params).toEqual({
+ historyId: SOURCE_ID,
+ sourceFilename: SOURCE_FILE,
+ method: 'ltx',
+ runtime: 'ltx25',
+ adapterKey: 'pixel-upscale',
+ adapterPath: '/cache/pixel-upscale.safetensors',
+ icMinReferences: 1,
+ icMaxReferences: 1,
+ seed: expect.any(Number),
+ source: conformingPlan().source,
+ alignment: conformingPlan().alignment,
+ target: conformingPlan().target,
+ prompt: 'a lighthouse (2×)',
+ width: 1536,
+ height: 1024,
+ numFrames: 121,
+ fps: 24,
+ });
+ });
+
+ it('records a seed so the pass is reproducible', async () => {
+ await enqueueLtxUpscale(SOURCE_ID);
+ const { seed } = state.enqueued[0].params;
+ expect(Number.isInteger(seed)).toBe(true);
+ expect(seed).toBeGreaterThanOrEqual(0);
+ expect(seed).toBeLessThanOrEqual(2 ** 32 - 1);
+ });
+
+ // Every refusal below has to happen BEFORE a GPU is committed — that is the
+ // whole reason the plan endpoint exists.
+ it('refuses a source that cannot be aligned without losing duration', async () => {
+ state.plan.alignment.trimFrames = 3;
+ await expect(enqueueLtxUpscale(SOURCE_ID))
+ .rejects.toMatchObject({ status: 400, code: 'UPSCALE_SOURCE_UNALIGNABLE' });
+ expect(enqueueJob).not.toHaveBeenCalled();
+ });
+
+ it('refuses a source whose geometry could not be measured rather than guessing', async () => {
+ state.plan.alignment.padFrames = null;
+ await expect(enqueueLtxUpscale(SOURCE_ID))
+ .rejects.toMatchObject({ status: 400, code: 'UPSCALE_SOURCE_UNALIGNABLE' });
+ expect(enqueueJob).not.toHaveBeenCalled();
+ });
+
+ it('refuses a source whose frame rate could not be measured', async () => {
+ state.plan.source.fps = null;
+ await expect(enqueueLtxUpscale(SOURCE_ID))
+ .rejects.toMatchObject({ status: 400, code: 'UPSCALE_SOURCE_UNALIGNABLE' });
+ expect(enqueueJob).not.toHaveBeenCalled();
+ });
+
+ it('refuses when this machine has no installed generative backend', async () => {
+ state.plan.runtime = { id: 'ltx25', label: 'LTX-2.5 MLX', supported: true, installed: false, reason: 'The LTX-2.5 MLX runtime is not installed on this machine.' };
+ await expect(enqueueLtxUpscale(SOURCE_ID))
+ .rejects.toMatchObject({ status: 501, code: 'UNSUPPORTED_RUNTIME' });
+ expect(enqueueJob).not.toHaveBeenCalled();
+ });
+
+ // #6508: the adapter is `requiresPreDownload`, so an un-cached weight has no
+ // repo-id fallback — queueing would strand the render on a 401 or a 708 GB pull.
+ it('refuses when the upscale adapter is not downloaded', async () => {
+ state.adapter = { path: null, cached: false, spec: { minReferences: 1, maxReferences: 1 } };
+ await expect(enqueueLtxUpscale(SOURCE_ID))
+ .rejects.toMatchObject({ status: 400, code: 'IC_LORA_WEIGHT_UNRESOLVED' });
+ expect(enqueueJob).not.toHaveBeenCalled();
+ });
+
+ it('keeps the already-upscaled guard, matching the inline path', async () => {
+ state.plan.alreadyUpscaled = true;
+ await expect(enqueueLtxUpscale(SOURCE_ID))
+ .rejects.toMatchObject({ status: 400, code: 'ALREADY_UPSCALED' });
+ expect(enqueueJob).not.toHaveBeenCalled();
+ });
+});
+
+describe('local-only (#6511 item 7)', () => {
+ // The privacy rule in AGENTS.md is enforced structurally: the federation
+ // layer's kind maps are closed lists, so a source video can only cross to a
+ // peer if someone adds this kind to one of them.
+ it('is absent from every federation kind map', async () => {
+ const { REMOTE_MEDIA_MODULES, isRemoteMediaJob } = await import('../mediaJobQueue/remoteMediaJob.js');
+ const { ROUTABLE_MEDIA_KINDS } = await import('../federatedMedia/routingPolicy.js');
+ const { KNOWN_MEDIA_KINDS } = await import('../../lib/federatedMediaWire.js');
+ expect(Object.keys(REMOTE_MEDIA_MODULES)).not.toContain(LTX_UPSCALE_JOB_KIND);
+ expect(ROUTABLE_MEDIA_KINDS).not.toContain(LTX_UPSCALE_JOB_KIND);
+ expect(KNOWN_MEDIA_KINDS).not.toContain(LTX_UPSCALE_JOB_KIND);
+ // Even a hand-planted marker cannot make it routed — the predicate gates on
+ // the kind map, not on the marker alone.
+ expect(isRemoteMediaJob({ kind: LTX_UPSCALE_JOB_KIND, params: { remoteMedia: {} } })).toBe(false);
+ });
+});
+
+describe('runVideoUpscale — success', () => {
+ it('writes a new history row carrying the full provenance contract', async () => {
+ const completed = [];
+ videoGenEvents.on('completed', (e) => completed.push(e));
+ const entry = await runWith(() => finishChild(0));
+ videoGenEvents.removeAllListeners('completed');
+
+ for (const field of LTX_PROVENANCE_FIELDS) expect(entry[field]).toBeDefined();
+ expect(entry).toMatchObject({
+ upscaledFrom: SOURCE_ID,
+ upscaleMethod: 'ltx',
+ upscaleRuntime: 'ltx25',
+ upscaleAdapter: 'pixel-upscale',
+ // MEASURED off the deliverable, not assumed from the plan.
+ width: 1536,
+ height: 1024,
+ fps: 24,
+ numFrames: 121,
+ duration: 5.04,
+ seed: 4242,
+ prompt: 'a lighthouse (2×)',
+ hidden: false,
+ });
+ expect(entry.renderMs).toBeGreaterThanOrEqual(0);
+ // The source render's timing must not ride along on a row that only paid
+ // for the upscale.
+ expect(entry.renderStartedAt).not.toBe('2026-01-01T00:00:00.000Z');
+ expect(mutateVideoHistory).toHaveBeenCalledTimes(1);
+ expect(state.history[0].id).toBe(entry.id);
+ expect(completed).toHaveLength(1);
+ });
+
+ it('leaves the source clip and its history row untouched', async () => {
+ const entry = await runWith(() => finishChild(0));
+ expect(existsSync(sourcePath())).toBe(true);
+ const source = state.history.find((h) => h.id === SOURCE_ID);
+ expect(source).toEqual(sourceRow());
+ expect(entry.filename).not.toBe(SOURCE_FILE);
+ });
+
+ it('removes every scratch file it created', async () => {
+ await runWith(() => finishChild(0));
+ expect(existsSync(renderOutputPath)).toBe(false);
+ expect(existsSync(alignedSourcePath)).toBe(false);
+ });
+
+ it('reads a conforming source in place instead of writing a padded copy', async () => {
+ await runWith(() => finishChild(0));
+ expect(padSourceForUpscale).not.toHaveBeenCalled();
+ expect(state.buildArgsCalls[0].upscale.sourceVideoPath).toBe(sourcePath());
+ });
+
+ // The plan is APPLIED, not approximated: the render sees the padded geometry
+ // and the deliverable is cropped back to 2x the SOURCE, so no duration or
+ // framing is silently lost.
+ it('pads a non-conforming source to exactly the plan and crops back to 2x the source', async () => {
+ const alignment = {
+ padWidth: 16, padHeight: 0, padFrames: 4, trimFrames: 0,
+ paddedSource: { width: 864, height: 512, frameCount: 121 },
+ conforming: false,
+ };
+ await runWith(() => finishChild(0), {
+ source: { width: 848, height: 512, fps: 24, frameCount: 117, durationSeconds: 4.875, hasAudio: true },
+ alignment,
+ target: { width: 1728, height: 1024, frameCount: 121 },
+ });
+ expect(padSourceForUpscale).toHaveBeenCalledWith(sourcePath(), alignedSourcePath, {
+ width: 864, height: 512, padFrames: 4, fps: 24, signal: expect.anything(),
+ });
+ expect(state.buildArgsCalls[0].upscale).toMatchObject({
+ sourceVideoPath: alignedSourcePath, width: 1728, height: 1024, numFrames: 121,
+ });
+ expect(finalizeUpscaleOutput).toHaveBeenCalledWith(renderOutputPath, expect.any(String), {
+ width: 1696, height: 1024, frameCount: 117, audioSourcePath: sourcePath(), signal: expect.anything(),
+ });
+ });
+
+ // The adapter is a spatial upscaler, so the source's own track is re-muxed
+ // at offset zero either way — a silent source takes the identical path and
+ // yields a silent deliverable rather than a failure.
+ it.each([true, false])('takes the identical path for a source with audio=%s', async (hasAudio) => {
+ const entry = await runWith(() => finishChild(0), {
+ source: { ...conformingPlan().source, hasAudio },
+ });
+ expect(entry.upscaleMethod).toBe('ltx');
+ expect(finalizeUpscaleOutput).toHaveBeenCalledWith(renderOutputPath, expect.any(String), {
+ width: 1536, height: 1024, frameCount: 121, audioSourcePath: sourcePath(), signal: expect.anything(),
+ });
+ });
+});
+
+describe('runVideoUpscale — failure and cancellation leave the source alone', () => {
+ const expectSourceIntact = () => {
+ expect(existsSync(sourcePath())).toBe(true);
+ expect(state.history).toEqual([sourceRow()]);
+ expect(mutateVideoHistory).not.toHaveBeenCalled();
+ };
+ const deliverables = () => state.history.filter((h) => h.upscaledFrom);
+
+ it('reports a non-zero runner exit and orphans no history entry', async () => {
+ const failures = [];
+ videoGenEvents.on('failed', (e) => failures.push(e));
+ state.writesOutput = false;
+ await runWith(() => finishChild(3));
+ videoGenEvents.removeAllListeners('failed');
+ expectSourceIntact();
+ expect(deliverables()).toHaveLength(0);
+ expect(failures).toHaveLength(1);
+ expect(failures[0].error).toMatch(/exit 3/);
+ });
+
+ it('fails when the runner exits clean but writes nothing', async () => {
+ state.writesOutput = false;
+ await runWith(() => finishChild(0));
+ expectSourceIntact();
+ expect(finalizeUpscaleOutput).not.toHaveBeenCalled();
+ });
+
+ it('removes the partial deliverable when the audio mux fails', async () => {
+ state.finalizeResult = { ok: false, reason: 'ffmpeg exit 1' };
+ const failures = [];
+ videoGenEvents.on('failed', (e) => failures.push(e));
+ await runWith(() => finishChild(0));
+ videoGenEvents.removeAllListeners('failed');
+ expectSourceIntact();
+ // finalizeUpscaleOutput wrote a partial file; nothing may survive it.
+ const written = finalizeUpscaleOutput.mock.calls[0][1];
+ expect(existsSync(written)).toBe(false);
+ expect(failures[0].error).toMatch(/ffmpeg exit 1/);
+ });
+
+ it('fails before spawning when the source cannot be aligned on disk', async () => {
+ state.padResult = { ok: false, reason: 'ffmpeg not found' };
+ await runVideoUpscale(jobParams({
+ alignment: { ...conformingPlan().alignment, padWidth: 16, paddedSource: { width: 784, height: 512, frameCount: 121 }, conforming: false },
+ }));
+ expectSourceIntact();
+ expect(state.buildArgsCalls).toHaveLength(0);
+ });
+
+ it('leaves the source and every row untouched when the job is cancelled mid-render', async () => {
+ const failures = [];
+ videoGenEvents.on('failed', (e) => failures.push(e));
+ const run = runVideoUpscale(jobParams());
+ await vi.waitFor(() => expect(state.child.listenerCount('close')).toBeGreaterThan(0));
+ expect(cancel(JOB_ID)).toBe(true);
+ await run;
+ videoGenEvents.removeAllListeners('failed');
+ expectSourceIntact();
+ expect(deliverables()).toHaveLength(0);
+ expect(existsSync(renderOutputPath)).toBe(false);
+ expect(failures[0].error).toBe('Canceled while running');
+ });
+
+ it('reports no cancel handle once the run has settled', async () => {
+ await runWith(() => finishChild(0));
+ expect(cancel(JOB_ID)).toBe(false);
+ });
+
+ it('refuses to re-upscale a source that was already upscaled while queued', async () => {
+ state.history = [sourceRow({ upscaledFrom: 'aaaaaaaa-aaaa-4aaa-aaaa-aaaaaaaaaaa1' })];
+ await runVideoUpscale(jobParams());
+ expect(mutateVideoHistory).not.toHaveBeenCalled();
+ expect(state.buildArgsCalls).toHaveLength(0);
+ });
+
+ it('refuses when the source row was replaced under the queued job', async () => {
+ state.history = [sourceRow({ filename: 'something-else.mp4' })];
+ await runVideoUpscale(jobParams());
+ expect(mutateVideoHistory).not.toHaveBeenCalled();
+ expect(state.buildArgsCalls).toHaveLength(0);
+ });
+});
diff --git a/server/services/videoGen/upscalePlan.js b/server/services/videoGen/upscalePlan.js
index b172122d44..20881c8065 100644
--- a/server/services/videoGen/upscalePlan.js
+++ b/server/services/videoGen/upscalePlan.js
@@ -186,3 +186,47 @@ export const LANCZOS_PROVENANCE_FIELDS = Object.freeze([
// runtime, and naming it explicitly keeps `upscaleRuntime` non-null on every
// upscaled row.
export const LANCZOS_RUNTIME_ID = 'ffmpeg';
+
+// The media-job kind the generative pass is dispatched as (#6511). It is its
+// OWN kind rather than a `video` mode so the local-only rule is structural: the
+// federation layer's kind maps (`REMOTE_MEDIA_MODULES`, `ROUTABLE_MEDIA_KINDS`,
+// `KNOWN_MEDIA_KINDS`) are closed lists that do not contain it, so a source clip
+// can never be offered to a peer without someone adding it to one of them.
+export const LTX_UPSCALE_JOB_KIND = 'video-upscale';
+
+/**
+ * Why this source cannot be aligned to the model grid, or `null` when it can.
+ *
+ * #6502 forbids silent cropping and silent duration loss, so an alignment plan
+ * is only usable when every axis was measurable and the plan pads rather than
+ * trims. Both refusals are stated as a reason the caller can show, and both
+ * happen BEFORE the job is queued — a multi-minute GPU render that ends in a
+ * shorter clip than the user submitted is exactly what this prevents.
+ */
+export const ltxAlignmentBlocker = (alignment) => {
+ if (!alignment) return 'The source could not be measured, so the model grid alignment is unknown.';
+ const unmeasured = ['padWidth', 'padHeight', 'padFrames'].filter((key) => alignment[key] === null);
+ if (unmeasured.length > 0) {
+ const axes = unmeasured.map((key) => key.replace('pad', '').toLowerCase()).join(', ');
+ return `The source ${axes} could not be measured, so it cannot be aligned to the model grid without guessing.`;
+ }
+ if (alignment.trimFrames > 0) {
+ return `Aligning this source to the model grid would trim ${alignment.trimFrames} frame(s) off the end, losing duration.`;
+ }
+ return null;
+};
+
+// Whether the aligned source differs from the source at all. `false` means the
+// render can read the ORIGINAL clip as its IC reference — no padded temp copy,
+// and nothing to crop back off the output.
+export const ltxAlignmentIsNoop = (alignment) => (
+ ltxAlignmentBlocker(alignment) === null
+ && alignment.padWidth === 0 && alignment.padHeight === 0 && alignment.padFrames === 0
+);
+
+// The provenance the generative pass writes ITSELF. Unlike Lanczos — which
+// inherits fps/numFrames/duration/seed from the source row it spreads — a
+// generative render measures its own output and rolls its own seed, so it owns
+// the whole contract. Asserted against a real ltx entry so dropping one fails a
+// test rather than shipping a row a reader cannot tell apart from a legacy one.
+export const LTX_PROVENANCE_FIELDS = UPSCALE_PROVENANCE_FIELDS;
diff --git a/server/services/videoGen/upscaleVideo.js b/server/services/videoGen/upscaleVideo.js
index 893866e319..34d49792bf 100644
--- a/server/services/videoGen/upscaleVideo.js
+++ b/server/services/videoGen/upscaleVideo.js
@@ -158,9 +158,8 @@ export async function planUpscaleHistoryItem(historyId, options = {}) {
//
// `options.method` selects the pass: `'lanczos'` (the default, and what every
// pre-#6509 caller gets by omitting the bag) runs the historical ffmpeg filter
-// inline. `'ltx'` is accepted by the contract but has no dispatch path until
-// #6511 lands, so it fails fast with a capability error naming the runtime it
-// would need rather than silently falling back to Lanczos.
+// inline. `'ltx'` belongs to the queued dispatch path (upscaleJob.js, #6511)
+// and is refused here rather than silently falling back to Lanczos.
//
// Returns the new history entry on success; throws ServerError on any
// missing-input / ffmpeg / file-system failure so the route can map it to
@@ -172,11 +171,15 @@ export async function upscaleHistoryItem(historyId, options = {}) {
throw new ServerError('Cannot upscale an already-upscaled video', { status: 400, code: 'ALREADY_UPSCALED' });
}
if (method === 'ltx') {
- const runtime = describeLtxRuntime();
- const named = runtime.id ? `${runtime.label} (${runtime.id})` : `no runtime for ${process.platform}`;
+ // This is the INLINE pass. A generative upscale is a multi-minute GPU
+ // render and must go through the media job queue (#6511), so running it
+ // here would block the request and bypass cancellation, the watchdog and
+ // the partial-output cleanup. Callers use enqueueLtxUpscale instead; the
+ // route already dispatches on the method, so reaching this is a bug, not a
+ // capability gap.
throw new ServerError(
- `Generative upscale is not available on this install: it needs ${named}, which has no upscale dispatch path yet.`,
- { status: 501, code: 'UNSUPPORTED_RUNTIME' },
+ 'Generative upscale runs through the media job queue — submit it with enqueueLtxUpscale, not the inline pass.',
+ { status: 400, code: 'UPSCALE_METHOD_NOT_INLINE' },
);
}
const sourcePath = resolveSourcePath(item);
diff --git a/server/services/videoGen/upscaleVideo.test.js b/server/services/videoGen/upscaleVideo.test.js
index e2a9fd8b18..25844c9fe8 100644
--- a/server/services/videoGen/upscaleVideo.test.js
+++ b/server/services/videoGen/upscaleVideo.test.js
@@ -10,8 +10,8 @@ vi.mock('../../lib/fileUtils.js', async (importOriginal) =>
afterAll(cleanupTempDataRoots);
// The method contract (#6509): an absent options bag is exactly the historical
-// Lanczos pass, `ltx` is accepted by the contract but has no dispatch path
-// until #6511, and the plan endpoint is read-only.
+// Lanczos pass, `ltx` belongs to the queued dispatch path (#6511) and is
+// refused by the inline entry point, and the plan endpoint is read-only.
const state = vi.hoisted(() => ({
history: [],
@@ -124,18 +124,18 @@ describe('upscaleHistoryItem — method selection', () => {
expect(loadHistory).not.toHaveBeenCalled();
});
- it('fails the generative method with a capability error naming the runtime', async () => {
+ it('refuses to run the generative method inline — it belongs to the queue (#6511)', async () => {
await expect(upscaleHistoryItem(SOURCE_ID, { method: 'ltx' }))
- .rejects.toMatchObject({ status: 501, code: 'UNSUPPORTED_RUNTIME' });
+ .rejects.toMatchObject({ status: 400, code: 'UPSCALE_METHOD_NOT_INLINE' });
});
- it('queues nothing and writes nothing when the generative method is refused', async () => {
+ it('runs nothing and writes nothing when the generative method is refused inline', async () => {
await upscaleHistoryItem(SOURCE_ID, { method: 'ltx' }).catch(() => {});
expect(ffmpeg.upscaleVideo2x).not.toHaveBeenCalled();
expect(mutateVideoHistory).not.toHaveBeenCalled();
});
- it('keeps the already-upscaled guard ahead of the capability error', async () => {
+ it('keeps the already-upscaled guard ahead of the method-dispatch error', async () => {
// Otherwise adding a method would change the status code an existing client
// sees for a source it must not re-upscale.
state.history = [sourceRow({ upscaledFrom: 'aaaaaaaa-aaaa-4aaa-aaaa-aaaaaaaaaaa1' })];