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: add explicit Music Video shot pools and song conditioning

[._.]/ Adam Eivy608015198214
diff --git a/client/src/components/musicVideo/RenderPoolPicker.jsx b/client/src/components/musicVideo/RenderPoolPicker.jsx
new file mode 100644
index 0000000000..ee2254ee40
--- /dev/null
+++ b/client/src/components/musicVideo/RenderPoolPicker.jsx
@@ -0,0 +1,49 @@
+import { useFederatedMediaTarget } from '../../hooks/useFederatedMediaTarget.js';
+import { federatedMediaModelsForPeer, peerMediaProviderSnapshot, summarizePeerMediaQueue } from '../../lib/federatedMediaReadiness.js';
+
+/** Placement narrows existing peer grants; choosing a row never enables sharing. */
+export default function RenderPoolPicker({ settings, change, disabled }) {
+ const { peers } = useFederatedMediaTarget('video');
+ const pool = settings.renderPool || { mode: 'local', peers: [] };
+ const save = (patch) => change({ renderPool: { ...pool, ...patch } });
+ return (
+ <fieldset disabled={disabled} className="w-full space-y-2 rounded border border-port-border p-2 text-sm">
+ <legend className="px-1">Generated shot render pool</legend>
+ <label htmlFor="mv-render-pool">Run shots on</label>{' '}
+ <select id="mv-render-pool" value={pool.mode} onChange={(event) => save({ mode: event.target.value })}
+ className="bg-port-bg border border-port-border rounded p-2">
+ <option value="local">This Mac</option>
+ <option value="peers" disabled={!pool.peers.length}>Selected peers</option>
+ <option value="both" disabled={!pool.peers.length}>Both</option>
+ </select>
+ <p className="text-xs text-port-text-muted">Select peer models below, then enable the pool. Each shot uses the least occupied eligible selected node; retries keep that node. One GPU job per peer. Final composition export stays on this Mac.</p>
+ {peers.map((peer) => {
+ const selected = pool.peers.find((entry) => entry.peerId === peer.id);
+ const models = federatedMediaModelsForPeer(peer, 'video').filter((entry) => entry.engine === 'local');
+ const snapshot = peerMediaProviderSnapshot(peer);
+ const toggle = (modelId) => save({ peers: [...pool.peers.filter((entry) => entry.peerId !== peer.id),
+ ...(modelId ? [{ peerId: peer.id, modelId }] : [])],
+ ...(selected && pool.peers.length === 1 && !modelId ? { mode: 'local' } : {}) });
+ return <div key={peer.id} className="space-y-1">
+ <label htmlFor={`mv-pool-${peer.id}`}>{peer.name || 'Peer'} model</label>{' '}
+ <select id={`mv-pool-${peer.id}`} value={selected?.modelId || ''} onChange={(event) => toggle(event.target.value)}
+ className="max-w-full bg-port-bg border border-port-border rounded p-2">
+ <option value="">Not selected</option>
+ {selected && !models.some((model) => model.modelId === selected.modelId)
+ && <option value={selected.modelId}>{selected.modelId} · unavailable</option>}
+ {models.map((model) => <option key={model.modelId} value={model.modelId}>
+ {model.modelName} · {model.hardwareEligible !== true ? 'hardware unverified / ineligible' : !model.ready ? model.unavailableReason : 'hardware eligible'}{model.sourceAudio ? ' · supplied audio' : ''}
+ </option>)}
+ </select>
+ <p className="text-xs text-port-text-muted">{summarizePeerMediaQueue(snapshot?.queue).join(' · ') || 'Capacity unknown'}{snapshot?.queue?.maintenanceHeld ? ' · maintenance held' : ''}. Fresh memory and capacity are checked at submission.</p>
+ </div>;
+ })}
+ {!peers.length && <p className="text-xs text-port-text-muted">No opted-in media peers. Configure sharing and model grants in Instances first.</p>}
+ {pool.peers.filter((entry) => !peers.some((peer) => peer.id === entry.peerId)).map((entry) =>
+ <button type="button" key={entry.peerId} onClick={() => save({ mode: 'local', peers: pool.peers.filter((candidate) => candidate !== entry) })}>
+ Remove unavailable selection ({entry.modelId})
+ </button>)}
+ {pool.mode !== 'local' && <p className="text-xs text-port-text-muted">Board shots and revisions only. Production runs, lip-sync, LoRA transfer and continuation require This Mac. Both requires an explicit local model.</p>}
+ </fieldset>
+ );
+}
diff --git a/client/src/components/musicVideo/RenderPoolPicker.test.jsx b/client/src/components/musicVideo/RenderPoolPicker.test.jsx
new file mode 100644
index 0000000000..eed6343fd7
--- /dev/null
+++ b/client/src/components/musicVideo/RenderPoolPicker.test.jsx
@@ -0,0 +1,34 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { cleanup, fireEvent, render, screen } from '@testing-library/react';
+import RenderPoolPicker from './RenderPoolPicker.jsx';
+const state = vi.hoisted(() => ({ peers: [] }));
+vi.mock('../../hooks/useFederatedMediaTarget.js', () => ({ useFederatedMediaTarget: () => state }));
+vi.mock('../../lib/federatedMediaReadiness.js', () => ({
+ federatedMediaModelsForPeer: (peer) => peer.models,
+ peerMediaProviderSnapshot: (peer) => peer.snapshot,
+ summarizePeerMediaQueue: () => ['0 running', '1 queued'],
+}));
+beforeEach(() => { cleanup(); state.peers = []; });
+describe('project shot render pool', () => {
+ it('saves explicit peer/model selection then placement and locks while saving', () => {
+ state.peers = [{ id: 'peer', name: 'Example peer', models: [{ engine: 'local', modelId: 'model', modelName: 'Example model', hardwareEligible: true, ready: true }], snapshot: { queue: { maintenanceHeld: false } } }];
+ const change = vi.fn();
+ const view = render(<RenderPoolPicker settings={{}} change={change} />);
+ expect(screen.getByRole('option', { name: 'Selected peers' }).disabled).toBe(true);
+ fireEvent.change(screen.getByLabelText('Example peer model'), { target: { value: 'model' } });
+ expect(change).toHaveBeenLastCalledWith({ renderPool: { mode: 'local', peers: [{ peerId: 'peer', modelId: 'model' }] } });
+ const settings = { renderPool: { mode: 'local', peers: [{ peerId: 'peer', modelId: 'model' }] } };
+ view.rerender(<RenderPoolPicker settings={settings} change={change} />);
+ fireEvent.change(screen.getByLabelText('Run shots on'), { target: { value: 'both' } });
+ expect(change).toHaveBeenLastCalledWith({ renderPool: { ...settings.renderPool, mode: 'both' } });
+ view.rerender(<RenderPoolPicker settings={settings} change={change} disabled />);
+ expect(screen.getByRole('group').disabled).toBe(true);
+ expect(screen.getByText(/Final composition export stays on this Mac/)).toBeTruthy();
+ });
+ it('shows missing selections without silently replacing their model', () => {
+ render(<RenderPoolPicker settings={{ renderPool: { mode: 'peers', peers: [{ peerId: 'missing', modelId: 'old-model' }] } }} change={vi.fn()} />);
+ expect(screen.getByRole('combobox').value).toBe('peers');
+ expect(screen.getByRole('button', { name: /Remove unavailable selection/ })).toBeTruthy();
+ expect(screen.getByText(/Production runs, lip-sync/)).toBeTruthy();
+ });
+});
diff --git a/client/src/components/musicVideo/VideoRenderSettings.jsx b/client/src/components/musicVideo/VideoRenderSettings.jsx
index 89f9a16ef9..7d4f049b00 100644
--- a/client/src/components/musicVideo/VideoRenderSettings.jsx
+++ b/client/src/components/musicVideo/VideoRenderSettings.jsx
@@ -1,3 +1,4 @@
+import RenderPoolPicker from './RenderPoolPicker.jsx';
import { GROK_VIDEO_DURATIONS } from '../../lib/grokVideoClip.js';
import {
FAL_DEFAULT_IMAGE_VIDEO_MODEL, FAL_IMAGE_VIDEO_MODELS, describeFalVideoRate, falVideoResolutions, getFalVideoModel,
@@ -36,6 +37,7 @@ export default function VideoRenderSettings({ videoSettings, generating }) {
const lipSync = SOURCE_AUDIO_LIPSYNC.fal;
return (
<>
+ <RenderPoolPicker settings={settings} change={change} disabled={locked} />
<label htmlFor="mv-video-backend" className="sr-only">Scene video renderer</label>
<select
id="mv-video-backend"
@@ -77,6 +79,7 @@ export default function VideoRenderSettings({ videoSettings, generating }) {
className="w-full max-w-full bg-port-bg border border-port-border rounded px-1.5 py-1.5 text-sm disabled:opacity-50 min-h-[44px] sm:min-h-0 sm:w-auto"
>
<option value="image">Prompt motion</option>
+ <option value="suppliedAudio">Supplied song audio (cutaway only)</option>
<option value="audioReactive" disabled={!detectedAudioReactiveLora}>Audio reactive</option>
</select>
<label htmlFor="mv-video-model" className="sr-only">Local video model</label>
diff --git a/client/src/hooks/useMusicVideoModelSettings.js b/client/src/hooks/useMusicVideoModelSettings.js
index ce1412c537..00d82a8041 100644
--- a/client/src/hooks/useMusicVideoModelSettings.js
+++ b/client/src/hooks/useMusicVideoModelSettings.js
@@ -56,6 +56,7 @@ export default function useMusicVideoModelSettings({ project, onProjectPatch } =
}, []);
const settings = {
+ renderPool: project?.videoSettings?.renderPool,
// Empty means this peer resolves its own configured Video Gen default.
// Synced projects intentionally arrive without another install's backend
// pin, so do not turn that absence into an explicit local override.
diff --git a/client/src/hooks/useMusicVideoSceneMedia.js b/client/src/hooks/useMusicVideoSceneMedia.js
index bb7eb9b6e8..044bb81f77 100644
--- a/client/src/hooks/useMusicVideoSceneMedia.js
+++ b/client/src/hooks/useMusicVideoSceneMedia.js
@@ -269,7 +269,7 @@ export default function useMusicVideoSceneMedia({ project, videoSettings, applyS
// would force the resolver off a Grok install default. Keep the
// shared pin saved, but omit it until this peer chooses Local.
: { grokDuration: settings.grokDuration, disableAudio: true }),
- mode: audioReactiveSelected ? 'a2v' : 'image',
+ mode: audioReactiveSelected || settings.generationMode === 'suppliedAudio' ? 'a2v' : 'image',
sourceImageFile: scene.referenceImageId,
...(audioReactiveSelected ? {
audioStartSec: scene.startSec || 0,
diff --git a/client/src/pages/MusicVideo.test.jsx b/client/src/pages/MusicVideo.test.jsx
index 4592508803..9228a9feeb 100644
--- a/client/src/pages/MusicVideo.test.jsx
+++ b/client/src/pages/MusicVideo.test.jsx
@@ -8,6 +8,7 @@ import { findEnabledByRole } from '../test/enabledBarrier.js';
import { MemoryRouter, Routes, Route, useNavigate, useLocation } from 'react-router';
import toast from '../components/ui/Toast';
+
const PROJECT_WITH_CLIP = {
id: 'mv-1', name: 'Neon Run', mode: 'director', status: 'ready',
trackId: 't1', uploadedAudioFilename: null, audioAnalysis: null, renderHistoryId: null,
@@ -159,6 +160,7 @@ const pushSocket = (event, payload) => act(async () => {
vi.mock('../services/apiUniverseBuilder.js', () => ({ getUniverse: vi.fn(), listUniverseNames: vi.fn(() => Promise.resolve([])) }));
vi.mock('../lib/downloadBlob.js', () => ({ downloadBlob: vi.fn() }));
vi.mock('../services/apiSystem.js', () => ({
+ getInstances: vi.fn(async () => ({ peers: [] })),
generateImage: vi.fn(async () => ({ status: 'queued', jobId: 'example-frame-job' })),
uploadGalleryImage: vi.fn(),
listImageModels: vi.fn(async () => []),
diff --git a/docs/FEDERATED_MEDIA_PROVIDERS.md b/docs/FEDERATED_MEDIA_PROVIDERS.md
index 37c887ed90..f322b29f93 100644
--- a/docs/FEDERATED_MEDIA_PROVIDERS.md
+++ b/docs/FEDERATED_MEDIA_PROVIDERS.md
@@ -2,7 +2,58 @@
PortOS can opt in to serving local media-generation capacity to another registered PortOS peer. The wire contract, `/api/federation/media/v1`, carries queued **audio, image, and video** generation through the existing durable `mediaJobQueue` and this machine's local engines.
-Provider-side queueing, consumer-side capacity discovery, durable remote execution, and unattended (Creative Director / Commission) routing are available for all three kinds. Interactive provider selection is exposed through the generation APIs and the Music Studio panel; Image Gen / Video Gen pickers, multi-provider scheduling, and input-asset transfer remain later slices of issue #4348.
+Provider-side queueing, consumer-side capacity discovery, durable remote execution, and unattended (Creative Director / Commission) routing are available for all three kinds. Interactive generation can select a peer and transfer supported conditioning images. Music Video also supports an explicit project pool for generated board shots and revisions, as described below.
+
+## Music Video shot pools and supplied song audio
+
+In a project's video settings, select exact models on existing opted-in peers,
+then choose **This Mac**, **Selected peers**, or **Both**. Saving a pool never
+enables a peer, installs a model, or changes a model grant. The pool is local to
+this install and is stripped from project sync. Existing projects keep their
+renderer settings until the pool is configured.
+
+Placement checks fresh provider readiness, known hardware/memory requirements,
+free memory, the existing allowlists and queue capacity, and a known-clear
+maintenance hold. Unknown or insufficient capacity excludes that node. Free
+system memory is a conservative snapshot, not a reservation or a promise about
+reclaimable GPU memory. Both requires an explicit local model. Each shot picks
+the least occupied eligible selected node once; its queued marker preserves that
+peer/model through cancellation and idempotent reconciliation. One remote job
+per peer runs from this consumer at a time; the provider's existing local GPU
+lane still serializes work from all consumers. There is no rerouting on failure
+and no fallback outside the saved pool.
+
+**Supplied song audio** conditions a generated cutaway on an exact window of the
+project recording. This first contract supports LTX-2/2.5 MLX models with native
+A2V support and a source frame. It does not assert verified lip-sync. The frame
+clock is negotiated before the recording is decoded to stereo 48 kHz 16-bit
+PCM. The wire binds original-recording SHA-256, clip SHA-256, start/end sample,
+sample count, rate, channels, fps and frame count. Windows are at most 60 seconds;
+a short source, changed recording, or uncovered scene is refused. No automatic
+padding or subsequent window changes are allowed. The original recording hash
+is consumer provenance; the provider independently verifies only the supplied
+clip bytes and their exact sample/frame span. Admission rechecks the currently
+selected recording hash, including take changes within one linked track; render
+and dependency-repair checks refuse a supplied-audio take from an older recording.
+
+The `sourceAudio` feature and per-model capability must both be negotiated.
+Older peers remain usable for their existing modes, but are ineligible for
+project pools until they report the new capacity, supported-mode and maintenance fields. Audio
+travels through the existing authenticated, caller-scoped, expiring asset store.
+The provider verifies the PCM and copies it into the existing uploads boundary;
+no inbox path exception is added to generator admission. Source clips stay
+available for uncertain remote reconciliation, and owned copies are cleaned up
+only after known settlement. No paths, credentials, prompts, maintenance owner
+or hold reason are added to status responses.
+
+**Scope:** board-generated shots and selective revisions only. Immutable
+production runs require This Mac; their approved model pools and budgets are
+not replaced by mutable project placement. They also refuse supplied song audio
+until immutable grants bind exact audio windows. Performance lip-sync, LoRA transfer,
+continuation/chain state, and remote final composition export are unsupported.
+Final export remains local. These boundaries are enforced before dispatch; the
+existing shot action, capture/evidence, revision, and budget checks still apply.
+See [the routing and audio ADR](decisions/2026-10-04-music-video-render-pools.md).
## Enable a provider
diff --git a/docs/README.md b/docs/README.md
index fa05bc8240..215fdeb26b 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -69,6 +69,7 @@ Comms & voice: [beeper](./features/beeper.md) · [messages-browser-send](./featu
## Point-in-time records
- [Music Video render-grade validation](validation/9302-music-video-grade.md) — synthetic encoder parity, visual references, and remaining generated-shot acceptance.
+- [Explicit Music Video render pools](decisions/2026-10-04-music-video-render-pools.md) — proposed initial shot placement and supplied-audio conditioning; final composition export remains local.
- **[plans/](./plans/README.md)** — dated design plans (`YYYY-MM-DD-<slug>.md`), archived on approval before implementation. Historical records, not living docs. See [provider connections and harnesses](./plans/2026-09-06-provider-connections-and-harnesses.md) for stable executable routes, migration and management flows.
- **decisions/** — ADRs (`YYYY-MM-DD-<slug>.md`), e.g. the [Postgres-as-primary-datastore decision](./decisions/2026-06-07-postgres-as-primary-datastore.md) and what may cross the federation layer ([user-controlled federation](./decisions/2026-09-19-user-controlled-federation.md), [Privacy Center storage](./decisions/2026-08-08-privacy-records-machine-local.md), [federated visual prompts](./decisions/2026-08-20-federated-visual-prompts.md), [conditioning crosses to an allowlisted peer](./decisions/2026-08-22-federated-media-input-assets.md), [AI usage metrics federate on by default](./decisions/2026-09-01-federated-usage-metrics.md), [Eidoverse guest chat](./decisions/2026-09-05-eidoverse-guest-chat.md), [numeric PortOS quality federation](./decisions/2026-09-10-portos-quality-federation.md), [federated Eidoverse foundations](./decisions/2026-09-18-federated-eidoverse-foundations.md)), why H3 [ships the draft-decode gates without an asset](./decisions/2026-08-30-h3-draft-decoder-asset.md), and why closed-set decisions run on a [local entailment model that abstains](./decisions/2026-09-18-local-jev-decision-service.md).
diff --git a/docs/decisions/2026-10-04-music-video-render-pools.md b/docs/decisions/2026-10-04-music-video-render-pools.md
new file mode 100644
index 0000000000..e844f7d667
--- /dev/null
+++ b/docs/decisions/2026-10-04-music-video-render-pools.md
@@ -0,0 +1,57 @@
+# ADR: Explicit Music Video Pools Choose Initial Placement; Retries Keep Their Node
+
+- **Date:** 2026-10-04
+- **Status:** Proposed (draft implementation)
+- **Supersedes in part:** rule 5 of [federated input assets](2026-08-22-federated-media-input-assets.md), only for initial Music Video shot placement inside an explicitly saved pool. Its prohibition on automatic failover remains.
+
+## Context
+
+A Music Video project may use this machine and selected federated instances for
+generated shots without making remote machines a prerequisite. The previous
+contract deliberately declined load balancing because an implicit target change
+could disclose conditioning to a different peer and change the result's model.
+The user now selects the permitted target set in the project itself.
+
+## Decision
+
+The project stores an install-local placement policy: This Mac, Selected peers,
+or Both, with exact peer/model pairs. It narrows existing bilateral opt-in and
+model grants. It never creates credentials, grants, installations or standing
+routes. Project sync strips this policy in both directions.
+
+Before enqueue, select the least occupied eligible member, checking fresh
+capability, known memory floor/free memory, queue capacity and maintenance state.
+Unknown information excludes a node. Persist that selection once. Retries,
+cancellation and reconciliation keep the same peer, model and idempotency key;
+an uncertain response is not permission to dispatch elsewhere. Serialize this
+consumer's GPU jobs per peer, while retaining the separate local GPU lane and
+parallel work on different peers. Initial placement is advisory, not a distributed
+capacity reservation; provider admission remains authoritative.
+
+Source audio is conditioning under the same authentication and asset rules as
+frames. Its separately negotiated feature avoids widening legacy image-role
+enums in status. Bind a canonical PCM window to source/clip hashes and exact
+sample/frame clocks, at most 60 seconds. Only runtimes whose input/output
+controls implement this contract advertise it. Provider validation confirms
+clip bytes, not the unavailable original master. Keep owned inputs through
+uncertain submission or local finalization, then clean them during settlement.
+Admission, staging and cleanup participate in the existing maintenance boundary.
+
+Board shots and revisions use the existing action, capture/evidence and revision
+checks. Production runs retain their immutable approved pool and budget contract
+and refuse nonlocal project policy in this slice. Production runs also refuse
+supplied-audio conditioning until their immutable grants bind exact audio windows.
+Final composition export stays local. Supplied audio does not imply verified
+performance lip-sync.
+
+## Alternatives and limits
+
+- Implicitly choose any discovered peer: rejected because discovery is not consent.
+- Fail over after timeout: rejected because the first render may still exist.
+- Transfer the full master or a URL: rejected in favor of a bounded, hashed,
+ caller-scoped window with no filesystem or fetch authority on the wire.
+- Claim remote final export: rejected until a real composition executor, assets,
+ cancellation and evidence path are implemented and verified.
+
+No hardware render or real peer dispatch is part of this draft's validation.
+Unit and contract tests use synthetic local fixtures and mocked providers.
diff --git a/server/lib/federatedMediaWire.js b/server/lib/federatedMediaWire.js
index feccd25352..596415a817 100644
--- a/server/lib/federatedMediaWire.js
+++ b/server/lib/federatedMediaWire.js
@@ -275,7 +275,6 @@ export const federatedMediaAssetSchema = z.object({
// and any provider-side filename validation. One source so a new result kind
// can't drift the two.
export const FEDERATED_MEDIA_RESULT_EXTENSION = Object.freeze({
- 'audio/wav': 'wav',
'audio/wav': 'wav',
'image/png': 'png',
'video/mp4': 'mp4',
@@ -317,6 +316,7 @@ export const federatedMediaCapabilitySchema = z.object({
label: z.string().trim().max(120).optional(),
})).max(100).nullable().optional(),
inputAssets: federatedMediaInputAssetsSchema,
+ supportedModes: z.array(z.enum(['text', 'image', 'fflf', 'a2v'])).max(4).optional(),
// Supplied audio drives motion; it does not establish verified lip-sync.
sourceAudio: z.object({ requiresImage: z.boolean() }).strict().optional(),
hardwareEligible: z.boolean().optional(),
@@ -342,6 +342,7 @@ const federatedMediaQueueStatusSchema = z.object({
running: z.number().int().nonnegative(),
maxQueuedJobs: z.number().int().positive(),
accepting: z.boolean(),
+ maintenanceHeld: z.boolean().optional(),
// Both added after wire v1 shipped, so both are optional: an older provider
// omits them, and absent must read as UNKNOWN rather than zero. See "Drain
// rate and per-kind occupancy" in docs/FEDERATED_MEDIA_PROVIDERS.md for what
diff --git a/server/lib/federatedMediaWire.test.js b/server/lib/federatedMediaWire.test.js
index 1bf6651d41..9f17c0b477 100644
--- a/server/lib/federatedMediaWire.test.js
+++ b/server/lib/federatedMediaWire.test.js
@@ -136,6 +136,7 @@ describe('federated media status kind projection', () => {
defaultDurationSec: null,
lyrics: false,
autoDuration: false,
+ supportedModes: ['text'],
frameStride: 4,
maxNumFrames: 1017,
frameOptions: [25, 49, 73, 97, 121],
@@ -144,6 +145,8 @@ describe('federated media status kind projection', () => {
};
expect(federatedMediaCapabilitySchema.safeParse(capability).success).toBe(true);
+ expect(federatedMediaCapabilitySchema.parse(capability).supportedModes).toEqual(['text']);
+ expect(federatedMediaCapabilitySchema.safeParse({ ...capability, supportedModes: ['continue'] }).success).toBe(false);
expect(federatedMediaProviderStatusSchema.safeParse(status({
kinds: ['video'],
capabilities: [capability],
@@ -420,7 +423,7 @@ describe('federatedMediaSupports', () => {
});
it('exposes every feature this build emits', () => {
- expect([...FEDERATED_MEDIA_FEATURES]).toEqual(['lyrics', 'inputAssets']);
+ expect([...FEDERATED_MEDIA_FEATURES]).toEqual(['lyrics', 'inputAssets', 'sourceAudio']);
for (const feature of FEDERATED_MEDIA_FEATURES) {
expect(federatedMediaSupports({ features: [...FEDERATED_MEDIA_FEATURES] }, feature)).toBe(true);
}
diff --git a/server/lib/musicVideoValidation.js b/server/lib/musicVideoValidation.js
index b317e31571..1e570fa270 100644
--- a/server/lib/musicVideoValidation.js
+++ b/server/lib/musicVideoValidation.js
@@ -80,6 +80,11 @@ export const musicVideoConceptSchema = z.object({
// is optional because Grok does not consume it; the video-gen route performs
// the authoritative installed-model validation when a local render starts.
export const musicVideoVideoSettingsSchema = z.object({
+ renderPool: z.object({
+ mode: z.enum(['local', 'peers', 'both']),
+ peers: z.array(z.object({ peerId: z.string().uuid(), modelId: z.string().trim().min(1).max(256) }).strict()).max(12),
+ }).strict().refine((v) => v.mode === 'local' || v.peers.length > 0, { message: 'Select at least one peer model' })
+ .refine((v) => new Set(v.peers.map((p) => p.peerId)).size === v.peers.length, { message: 'Choose one model per peer' }).optional(),
// null clears the per-project pin so this install's configured default wins.
// 'fal' is the metered fal.ai queue REST backend (server/services/videoGen/fal.js,
// #8968) — image-to-video only here; the audio-reactive lane stays local-only
@@ -106,7 +111,7 @@ export const musicVideoVideoSettingsSchema = z.object({
// false = lip-sync to the audio alone, without the provider transcribing it
// first (sung words it mishears turn into the wrong mouth shapes).
falLipSyncTranscription: z.boolean().nullable().optional(),
- generationMode: z.enum(['image', 'audioReactive']).optional(),
+ generationMode: z.enum(['image', 'audioReactive', 'suppliedAudio']).optional(),
audioReactiveLora: z.string().max(255).regex(/^[^/\\]+\.safetensors$/i).nullable().optional(),
audioReactiveScale: z.number().min(0).max(2).optional(),
}).strict();
diff --git a/server/lib/pathSafety.js b/server/lib/pathSafety.js
index d128b3ffbc..81ce57ab99 100644
--- a/server/lib/pathSafety.js
+++ b/server/lib/pathSafety.js
@@ -286,7 +286,7 @@ export const resolveImageCleanTmp = makePathResolver(() => PATHS.imageCleanTmp);
* cannot become an arbitrary path argument to the generator.
*/
export const resolveFederatedMediaAsset = makePathResolver(() => PATHS.federatedMediaInbox, {
- extensions: ['png', 'jpg', 'jpeg', 'webp', 'wav'],
+ extensions: ['png', 'jpg', 'jpeg', 'webp'],
});
/**
diff --git a/server/lib/syncWire.js b/server/lib/syncWire.js
index 981d225f89..3582448ce0 100644
--- a/server/lib/syncWire.js
+++ b/server/lib/syncWire.js
@@ -71,6 +71,10 @@ export function stripMusicVideoLocalRenderPins(record, { stripVideoBackend = tru
const { document: _document, documentDraft: _documentDraft, ...composition } = shared.composition;
shared.composition = composition;
}
+ if (shared.videoSettings && typeof shared.videoSettings === 'object' && !Array.isArray(shared.videoSettings)) {
+ const { renderPool: _renderPool, ...settings } = shared.videoSettings;
+ shared.videoSettings = settings;
+ }
if (stripVideoBackend && shared.videoSettings
&& typeof shared.videoSettings === 'object' && !Array.isArray(shared.videoSettings)) {
const { backend: _backend, ...sharedVideoSettings } = shared.videoSettings;
diff --git a/server/lib/validation.js b/server/lib/validation.js
index 918f9c6ed8..2ed4a01f02 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -1403,6 +1403,9 @@ export const federatedMediaVideoJobSubmissionSchema = federatedMediaVideoJobSubm
.refine((v) => Boolean(v.sourceAudio) === Boolean(v.audioConditioning), {
message: 'sourceAudio and audioConditioning must be supplied together',
})
+ .refine((v) => !v.audioConditioning || (v.fps !== undefined && v.numFrames !== undefined), {
+ message: 'Source audio requires explicit fps and numFrames for its exact window',
+ })
.refine((v) => !v.sourceAudio || (!v.lastImage && v.sourceAudio.assetId.endsWith(v.audioConditioning?.clipSha256 || '!')), {
message: 'Source audio must match its clip digest and cannot combine with an end frame',
})
diff --git a/server/routes/federatedMedia.test.js b/server/routes/federatedMedia.test.js
index f0487f615c..91357992d0 100644
--- a/server/routes/federatedMedia.test.js
+++ b/server/routes/federatedMedia.test.js
@@ -1,3 +1,4 @@
+vi.mock('../lib/maintenanceAdmission.js', () => ({ maintenance: { run: (_kind, _resource, fn) => fn() } }));
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
import express from 'express';
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
diff --git a/server/services/federatedMedia/assetStore.js b/server/services/federatedMedia/assetStore.js
index 5a2bff80b0..f8e674b9e0 100644
--- a/server/services/federatedMedia/assetStore.js
+++ b/server/services/federatedMedia/assetStore.js
@@ -1,3 +1,4 @@
+import { maintenance } from '../../lib/maintenanceAdmission.js';
/**
* Provider-side staging for conditioning images an allowlisted peer uploads
* ahead of a federated render (ADR
@@ -21,8 +22,9 @@
*/
import { pcmAudioInfo } from './sourceAudio.js';
-import { readdir, rm, stat, utimes } from 'node:fs/promises';
+import { readdir, rm, stat, utimes, realpath, lstat } from 'node:fs/promises';
import { join } from 'node:path';
+import { isPathInsideDir } from '../../lib/pathSafety.js';
import { ServerError } from '../../lib/errorHandler.js';
import {
atomicWrite,
@@ -78,9 +80,13 @@ export async function findFederatedMediaAsset(callerId, assetId, { now = Date.no
// Through the shared resolver, not join(): it basenames and re-anchors at
// the inbox root, so this stays a single containment check shared with the
// image runner's own re-validation of the same path.
- const path = resolveFederatedMediaAsset(`${parsed.data}.${extension}`);
+ const path = extension === 'wav' ? join(PATHS.federatedMediaInbox, `${parsed.data}.wav`)
+ : resolveFederatedMediaAsset(`${parsed.data}.${extension}`);
if (!path) return null;
- const info = await stat(path).catch(() => null);
+ const info = await lstat(path).catch(() => null);
+ const actual = await realpath(path).catch(() => null);
+ const root = await realpath(PATHS.federatedMediaInbox).catch(() => null);
+ if (!root || !actual || !isPathInsideDir(root, actual) || info?.isSymbolicLink()) return null;
if (!info?.isFile() || now - info.mtimeMs > FEDERATED_MEDIA_ASSET_TTL_MS) return null;
return {
path,
@@ -105,7 +111,9 @@ export async function findFederatedMediaAsset(callerId, assetId, { now = Date.no
* @param {string} args.declaredSha256 - Caller's X-Content-SHA256 header.
* @param {Buffer} args.body
*/
-export async function storeFederatedMediaAsset({ callerId, mimeType, declaredSha256, body }) {
+export const storeFederatedMediaAsset = (args) => maintenance.run('media-input', 'Federated input upload', () => storeAsset(args));
+
+async function storeAsset({ callerId, mimeType, declaredSha256, body }) {
if (!FEDERATED_MEDIA_ASSET_MIME_TYPES.includes(mimeType)) {
reject(
`Unsupported conditioning image type: ${mimeType || 'none'}`,
@@ -150,7 +158,7 @@ export async function storeFederatedMediaAsset({ callerId, mimeType, declaredSha
// so a torn write would leave a file claiming a hash its bytes do not have —
// and the runner would render from a truncated image. It ensures the directory
// itself, so no separate ensureDir.
- const existing = await stat(path).catch(() => null);
+ const existing = await lstat(path).catch(() => null);
if (existing?.isFile() && existing.size === body.length) {
await utimes(path, new Date(), new Date());
} else {
diff --git a/server/services/federatedMedia/assetStore.test.js b/server/services/federatedMedia/assetStore.test.js
index 163e2b8b1d..8fb42c6f0e 100644
--- a/server/services/federatedMedia/assetStore.test.js
+++ b/server/services/federatedMedia/assetStore.test.js
@@ -1,3 +1,4 @@
+vi.mock('../../lib/maintenanceAdmission.js', () => ({ maintenance: { run: (_kind, _resource, fn) => fn() } }));
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { mkdtempSync, rmSync, writeFileSync, existsSync, utimesSync } from 'node:fs';
import { join } from 'node:path';
diff --git a/server/services/federatedMedia/inputAssets.js b/server/services/federatedMedia/inputAssets.js
index c48bce946c..b44ca8a8bb 100644
--- a/server/services/federatedMedia/inputAssets.js
+++ b/server/services/federatedMedia/inputAssets.js
@@ -140,7 +140,7 @@ export function inputAssetRejection(capability, assets = [], status = null) {
return `This render supplies a ${pair.role} with no ${pair.needs} — ${pair.why}. Add one, or render on this instance.`;
}
}
- const unsupported = roles.filter((role) => !limits.roles.includes(role));
+ const unsupported = roles.filter((role) => !(role === 'sourceAudio' ? capability.sourceAudio : limits.roles.includes(role)));
if (unsupported.length) {
return `The selected peer model does not accept ${unsupported.join(' or ')}. Render locally, or clear that input.`;
}
@@ -256,7 +256,7 @@ function createInputAssetStager({ requestJson, emitStatus }) {
// path start a second transfer of the same bytes before the first could
// populate the cache — the exact case the memo exists to collapse.
return function stageInputAsset(localPath, role) {
- const key = `${role}:${localPath}`;
+ const key = `${role === 'sourceAudio' ? 'audio' : 'image'}:${localPath}`;
const pending = uploads.get(key);
if (pending) return pending;
const upload = uploadInputAsset(localPath, role);
diff --git a/server/services/federatedMedia/remoteExecutor.js b/server/services/federatedMedia/remoteExecutor.js
index 854f0901b5..cecd75e327 100644
--- a/server/services/federatedMedia/remoteExecutor.js
+++ b/server/services/federatedMedia/remoteExecutor.js
@@ -536,13 +536,17 @@ export function createRemoteMediaExecutor({
activeJobs.set(params.jobId, state);
try {
const result = await runRemote(state, marker.data);
- events.emit('completed', { generationId: params.jobId, ...result });
+ // This is a transient executor verdict, never a provider/caller field.
+ // The queue may release owned inputs only AFTER its terminal row is durable.
+ events.emit('completed', { generationId: params.jobId, ...result,
+ remoteInputsDisposable: !state.finalizing && (state.remoteTerminal === true || !state.submissionMayExist) });
} catch (error) {
// An unreachable/revoked peer is not proof that its admitted render
// stopped. Keep local ownership until completion can be reconciled.
if ((state.submissionMayExist && !state.remoteTerminal) || state.finalizing) maintenance.markCurrentUnsettled();
events.emit('failed', {
generationId: params.jobId,
+ remoteInputsDisposable: !state.finalizing && (state.remoteTerminal === true || !state.submissionMayExist),
error: error?.canceled
? `Remote ${label} generation canceled`
: (error?.message || `Remote ${label} generation failed`),
diff --git a/server/services/federatedMedia/sourceAudio.js b/server/services/federatedMedia/sourceAudio.js
index 64d7eab785..d2a9bf37a3 100644
--- a/server/services/federatedMedia/sourceAudio.js
+++ b/server/services/federatedMedia/sourceAudio.js
@@ -1,10 +1,31 @@
+import { maintenance } from '../../lib/maintenanceAdmission.js';
/** Exact PCM conditioning windows. Paths stay local; only hashes and sample clocks travel. */
import { randomUUID } from 'node:crypto';
+import { realpathSync } from 'node:fs';
import { readFile, unlink } from 'node:fs/promises';
-import { join, resolve } from 'node:path';
+import { basename, dirname, join, resolve } from 'node:path';
import { PATHS, ensureDir, sha256File } from '../../lib/fileUtils.js';
import { isPathInsideDir } from '../../lib/pathSafety.js';
import { ServerError } from '../../lib/errorHandler.js';
+import { isLtx2FamilyRuntime } from '../../lib/runners.js';
+import { resolveVideoSupportedModes } from '../../lib/videoModeProfiles.js';
+
+// This slice uses the LTX PCM input and --no-audio contract. Other A2V
+// runtimes have different output/window controls and are not negotiated yet.
+export const supportsSourceAudioWindow = (model) => isLtx2FamilyRuntime(model?.runtime)
+ && resolveVideoSupportedModes(model).includes('a2v');
+
+/** Only this feature's owned copies may be released, never a master recording. */
+export async function discardSourceAudioWindow(path) {
+ if (typeof path !== 'string' || dirname(resolve(path)) !== resolve(PATHS.uploads)
+ || !/^(mv-source-audio|federated-audio)-[a-f\d-]{36}\.wav$/.test(basename(path))) return;
+ try { await unlink(path); }
+ catch (error) {
+ if (error.code === 'ENOENT') return;
+ maintenance.markCurrentUnsettled();
+ throw error;
+ }
+}
// A bounded parser, not an audio decoder. The one accepted transport is stereo
// 48 kHz signed 16-bit PCM; RIFF metadata chunks may occur before/after data.
@@ -13,7 +34,8 @@ export function pcmAudioInfo(bytes) {
|| bytes.toString('ascii', 8, 12) !== 'WAVE' || bytes.readUInt32LE(4) + 8 !== bytes.length) return null;
let format = false;
let samples = null;
- for (let at = 12; at + 8 <= bytes.length;) {
+ let at = 12;
+ for (; at + 8 <= bytes.length;) {
const kind = bytes.toString('ascii', at, at + 4);
const size = bytes.readUInt32LE(at + 4);
const start = at + 8;
@@ -31,27 +53,56 @@ export function pcmAudioInfo(bytes) {
}
at = start + size + (size % 2);
}
- return format && samples > 0 && samples <= 48000 * 60
+ return at === bytes.length && format && samples > 0 && samples <= 48000 * 60
? { sampleRate: 48000, channels: 2, sampleCount: samples } : null;
}
export function resolveSourceAudioPath(path) {
if (typeof path !== 'string' || !path.endsWith('.wav')) return null;
const absolute = resolve(path);
- return isPathInsideDir(PATHS.uploads, absolute) ? absolute : null;
+ if (!isPathInsideDir(PATHS.uploads, absolute)) return null;
+ try { return isPathInsideDir(realpathSync(PATHS.uploads), realpathSync(absolute)) ? absolute : null; }
+ catch { return null; }
+}
+
+/** Choose a frame canvas covering the whole authored shot before cutting PCM. */
+export function sourceAudioVideoRequest(scene, capability, request) {
+ const fps = request.fps ?? capability.fpsOptions?.[0] ?? 24;
+ const needed = Math.ceil((scene?.endSec - scene?.startSec) * fps) + 1;
+ const stride = capability.frameStride || 1;
+ const frames = request.numFrames ?? (capability.frameOptions?.length
+ ? [...capability.frameOptions].sort((a, b) => a - b).find((n) => n >= needed)
+ : Math.ceil((needed - 1) / stride) * stride + 1);
+ if (!Number.isFinite(frames) || frames < needed || frames > (capability.maxNumFrames || 1441)) {
+ throw new ServerError('This model cannot cover the scene with one supplied-audio clip; split the scene', { status: 400, code: 'MUSIC_VIDEO_AUDIO_WINDOW_INVALID' });
+ }
+ return { ...request, fps, numFrames: frames };
}
/** Slice a project recording to the model's exact frame span, on a 48 kHz clock. */
-export async function prepareSourceAudioWindow({ project, scene, numFrames, fps }) {
- const startSample = Math.round(scene.startSec * 48000);
+export const prepareSourceAudioWindow = (args) => maintenance.run('media-input', 'Source audio window', () => prepareWindow(args), { continuation: true });
+
+/** A linked track can select another recording without changing project fields. */
+export async function assertCurrentSourceAudioWindow(project, audioConditioning) {
+ const { resolveMasterAudioPath } = await import('../musicVideo/render.js');
+ if (await sha256File(await resolveMasterAudioPath(project)) !== audioConditioning.sourceSha256) {
+ throw new ServerError('The selected recording changed while supplied audio was prepared', { status: 409, code: 'MUSIC_VIDEO_AUDIO_SOURCE_CHANGED' });
+ }
+}
+
+async function prepareWindow({ project, scene, numFrames, fps }) {
+ const startSample = Math.round(scene?.startSec * 48000);
const sampleCount = Math.round(((numFrames - 1) / fps) * 48000);
if (!Number.isSafeInteger(startSample) || startSample < 0 || !Number.isSafeInteger(sampleCount)
- || sampleCount <= 0 || sampleCount > 48000 * 60) {
+ || sampleCount <= 0 || sampleCount > 48000 * 60
+ || (Number.isFinite(scene?.endSec) && sampleCount / 48000 + 1 / 48000 < scene.endSec - scene.startSec)) {
throw new ServerError('Supply a timed scene and a video window of at most 60 seconds', { status: 400, code: 'MUSIC_VIDEO_AUDIO_WINDOW_INVALID' });
}
const [{ resolveMasterAudioPath }, { findFfmpeg, runFfmpegProcess }] = await Promise.all([
import('../musicVideo/render.js'), import('../../lib/ffmpeg.js'),
]);
+ const { captureMusicVideoEvidence } = await import('../../lib/musicVideoDependencies.js');
+ const audioDependencies = captureMusicVideoEvidence(project, { sceneIds: [], composition: false });
const source = await resolveMasterAudioPath(project);
const sourceSha256 = await sha256File(source);
const bin = await findFfmpeg();
@@ -67,10 +118,10 @@ export async function prepareSourceAudioWindow({ project, scene, numFrames, fps
if (info?.sampleCount !== sampleCount || await sha256File(source) !== sourceSha256) {
throw new ServerError('The recording changed or cannot cover the exact requested audio window', { status: 409, code: 'MUSIC_VIDEO_AUDIO_WINDOW_INVALID' });
}
- return { audioFilePath, audioConditioning: { sourceSha256, clipSha256: await sha256File(audioFilePath),
+ return { audioFilePath, audioDependencies, songInterval: { startSec: scene.startSec, endSec: scene.endSec }, audioConditioning: { sourceSha256, clipSha256: await sha256File(audioFilePath),
...info, startSample, endSample } };
} catch (error) {
- await unlink(audioFilePath).catch(() => {});
+ await discardSourceAudioWindow(audioFilePath);
throw error;
}
}
diff --git a/server/services/federatedMedia/sourceAudio.test.js b/server/services/federatedMedia/sourceAudio.test.js
new file mode 100644
index 0000000000..683fcfe049
--- /dev/null
+++ b/server/services/federatedMedia/sourceAudio.test.js
@@ -0,0 +1,102 @@
+vi.mock('../../lib/maintenanceAdmission.js', () => ({ maintenance: { run: (_kind, _resource, fn) => fn() } }));
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { mkdtemp, readFile, rm, symlink, utimes, writeFile } from 'node:fs/promises';
+import { join } from 'node:path';
+import { tmpdir } from 'node:os';
+import { PATHS, sha256Text } from '../../lib/fileUtils.js';
+import { federatedMediaVideoJobSubmissionSchema } from '../../lib/validation.js';
+import { storeFederatedMediaAsset, findFederatedMediaAsset } from './assetStore.js';
+import { assertCurrentSourceAudioWindow, pcmAudioInfo, prepareSourceAudioWindow, resolveSourceAudioPath } from './sourceAudio.js';
+import { applyRemoteInputAssets } from './inputAssets.js';
+
+const mocks = vi.hoisted(() => ({ master: '', run: vi.fn() }));
+vi.mock('../musicVideo/render.js', () => ({ resolveMasterAudioPath: async () => mocks.master }));
+vi.mock('../../lib/ffmpeg.js', () => ({ findFfmpeg: async () => 'fixture-ffmpeg', runFfmpegProcess: mocks.run }));
+
+function wav(samples = 48000) {
+ const bytes = Buffer.alloc(44 + samples * 4);
+ bytes.write('RIFF'); bytes.writeUInt32LE(bytes.length - 8, 4); bytes.write('WAVEfmt ', 8);
+ bytes.writeUInt32LE(16, 16); bytes.writeUInt16LE(1, 20); bytes.writeUInt16LE(2, 22);
+ bytes.writeUInt32LE(48000, 24); bytes.writeUInt32LE(192000, 28); bytes.writeUInt16LE(4, 32);
+ bytes.writeUInt16LE(16, 34); bytes.write('data', 36); bytes.writeUInt32LE(samples * 4, 40);
+ return bytes;
+}
+const saved = { uploads: PATHS.uploads, federatedMediaInbox: PATHS.federatedMediaInbox };
+let root;
+beforeEach(async () => {
+ root = await mkdtemp(join(tmpdir(), 'source-audio-test-'));
+ PATHS.uploads = root; PATHS.federatedMediaInbox = root;
+ mocks.master = join(root, 'master.wav');
+ await writeFile(mocks.master, wav());
+ mocks.run.mockImplementation(async ({ args }) => { await writeFile(args.at(-1), wav()); return { ok: true }; });
+});
+afterEach(async () => { Object.assign(PATHS, saved); await rm(root, { recursive: true, force: true }); vi.clearAllMocks(); });
+
+const provenance = (bytes) => ({ sourceSha256: 'a'.repeat(64), clipSha256: sha256Text(bytes), sampleRate: 48000,
+ channels: 2, startSample: 96000, endSample: 144000, sampleCount: 48000 });
+const request = (bytes, assetId) => ({ kind: 'video', engine: 'local', modelId: 'example-model', prompt: 'Moving light',
+ fps: 24, numFrames: 25, audioConditioning: provenance(bytes), sourceAudio: { assetId } });
+
+describe('supplied-audio transport boundary', () => {
+ it('stages exact PCM with caller-scoped replay, rejects cross-peer, expired, traversal and symlink references', async () => {
+ const body = wav();
+ const upload = () => storeFederatedMediaAsset({ callerId: 'example-peer', body, mimeType: 'audio/wav', declaredSha256: sha256Text(body) });
+ const receipt = await upload();
+ expect((await upload()).assetId).toBe(receipt.assetId);
+ expect(federatedMediaVideoJobSubmissionSchema.parse(request(body, receipt.assetId)).audioConditioning.sampleCount).toBe(48000);
+ expect(await findFederatedMediaAsset('another-peer', receipt.assetId)).toBeNull();
+ expect(await findFederatedMediaAsset('example-peer', `../${receipt.assetId}`)).toBeNull();
+ const path = (await findFederatedMediaAsset('example-peer', receipt.assetId)).path;
+ await utimes(path, new Date(0), new Date(0));
+ expect(await findFederatedMediaAsset('example-peer', receipt.assetId)).toBeNull();
+ await rm(path); await symlink(mocks.master, path);
+ expect(await findFederatedMediaAsset('example-peer', receipt.assetId)).toBeNull();
+ });
+
+ it('refuses truncated or disguised PCM, mismatched hashes and unpaired provenance', async () => {
+ const body = wav();
+ expect(pcmAudioInfo(body.subarray(0, body.length - 1))).toBeNull();
+ const wrongRate = Buffer.from(body); wrongRate.writeUInt32LE(44100, 24);
+ expect(pcmAudioInfo(wrongRate)).toBeNull();
+ await expect(storeFederatedMediaAsset({ callerId: 'p', body, mimeType: 'audio/wav', declaredSha256: '0'.repeat(64) }))
+ .rejects.toMatchObject({ code: 'MEDIA_PROVIDER_ASSET_INTEGRITY' });
+ const value = request(body, `${'b'.repeat(16)}-${sha256Text(body)}`);
+ expect(federatedMediaVideoJobSubmissionSchema.safeParse({ ...value, audioConditioning: undefined }).success).toBe(false);
+ expect(federatedMediaVideoJobSubmissionSchema.safeParse({ ...value, fps: undefined }).success).toBe(false);
+ expect(federatedMediaVideoJobSubmissionSchema.safeParse({ ...value, numFrames: undefined }).success).toBe(false);
+ expect(federatedMediaVideoJobSubmissionSchema.safeParse({ ...value, audioConditioning: { ...value.audioConditioning, endSample: 144001 } }).success).toBe(false);
+ expect(federatedMediaVideoJobSubmissionSchema.safeParse({ ...value, sourceAudio: { assetId: `${'b'.repeat(16)}-${'f'.repeat(64)}` } }).success).toBe(false);
+ });
+
+ it('cuts the requested sample window and refuses a short decode before enqueue', async () => {
+ const audio = await prepareSourceAudioWindow({ project: {}, scene: { startSec: 2 }, numFrames: 25, fps: 24 });
+ expect(mocks.run.mock.calls[0][0].args).toContain('aresample=48000,atrim=start_sample=96000:end_sample=144000,asetpts=PTS-STARTPTS');
+ expect(audio.audioConditioning).toEqual({ ...provenance(await readFile(audio.audioFilePath)), sourceSha256: sha256Text(wav()) });
+ // The recording fixture hashes to the same bytes as the one-second slice.
+ expect(audio.audioConditioning.sourceSha256).toBe(sha256Text(wav()));
+ mocks.run.mockImplementation(async ({ args }) => { await writeFile(args.at(-1), wav(24000)); return { ok: true }; });
+ await expect(prepareSourceAudioWindow({ project: {}, scene: { startSec: 2 }, numFrames: 25, fps: 24 }))
+ .rejects.toMatchObject({ code: 'MUSIC_VIDEO_AUDIO_WINDOW_INVALID' });
+ });
+
+ it('never uploads an audio path outside the approved root, including a symlink', async () => {
+ const outside = await mkdtemp(join(tmpdir(), 'outside-audio-test-'));
+ try {
+ const path = join(outside, 'other.wav'); await writeFile(path, wav());
+ const link = join(root, 'escape.wav'); await symlink(path, link);
+ expect(resolveSourceAudioPath(link)).toBeNull();
+ const requestJson = vi.fn();
+ await expect(applyRemoteInputAssets({}, [{ role: 'sourceAudio', path: link }], { requestJson, emitStatus: vi.fn() }))
+ .rejects.toMatchObject({ code: 'MEDIA_PROVIDER_INPUT_UNREADABLE' });
+ expect(requestJson).not.toHaveBeenCalled();
+ } finally { await rm(outside, { recursive: true, force: true }); }
+ });
+ it('refuses a different selected recording even when the linked track id is unchanged', async () => {
+ const project = { trackId: 'same-track' };
+ const audio = await prepareSourceAudioWindow({ project, scene: { startSec: 0, endSec: 1 }, numFrames: 25, fps: 24 });
+ await expect(assertCurrentSourceAudioWindow(project, audio.audioConditioning)).resolves.toBeUndefined();
+ mocks.master = join(root, 'another-take.wav');
+ await writeFile(mocks.master, wav(96000));
+ await expect(assertCurrentSourceAudioWindow(project, audio.audioConditioning)).rejects.toMatchObject({ code: 'MUSIC_VIDEO_AUDIO_SOURCE_CHANGED' });
+ });
+});
diff --git a/server/services/federatedMediaProvider.js b/server/services/federatedMediaProvider.js
index fbaeba8e5b..88cb19637d 100644
--- a/server/services/federatedMediaProvider.js
+++ b/server/services/federatedMediaProvider.js
@@ -7,15 +7,18 @@
* allowlisted capability/job/result projections cross the peer boundary.
*/
-import { stat, readFile } from 'node:fs/promises';
+import { randomUUID } from 'node:crypto';
+import { join } from 'node:path';
+import { maintenance } from '../lib/maintenanceAdmission.js';
+import { stat, readFile, writeFile } from 'node:fs/promises';
import { totalmem, freemem } from 'node:os';
import { evaluateHardwareRequirements } from '../lib/systemCapabilities.js';
-import { pcmAudioInfo } from './federatedMedia/sourceAudio.js';
+import { discardSourceAudioWindow, pcmAudioInfo, supportsSourceAudioWindow } from './federatedMedia/sourceAudio.js';
import { ServerError } from '../lib/errorHandler.js';
import { createMutex } from '../lib/asyncMutex.js';
import { canonicalStringify } from '../lib/objects.js';
import {
- PATHS, makePathResolver, resolveGalleryImage, sha256File, sha256Text,
+ PATHS, ensureDir, makePathResolver, resolveGalleryImage, sha256File, sha256Text,
} from '../lib/fileUtils.js';
import { findCachedRepoFiles, inspectModelCache } from '../lib/hfCache.js';
import { getImageModels, getVideoModels, isEditOnly, isFlux2, repoForModel, requiredModelCacheGroups } from '../lib/mediaModels.js';
@@ -120,7 +123,7 @@ function federatedInputProfile(kind, model) {
const roles = [];
if (modes.includes('image') || modes.includes('fflf') || modes.includes('a2v')) roles.push('sourceImage');
if (modes.includes('fflf')) roles.push('lastImage');
- if (modes.includes('a2v')) roles.push('sourceAudio');
+
if (!roles.length) return null;
return { roles, required: !modes.includes('text') };
}
@@ -141,8 +144,8 @@ function federatedInputProfile(kind, model) {
// model with declared modes but neither `text` nor a frame slot has no way in.
const supportsFederatedInput = (kind, model) => {
if (kind !== 'video') return true;
- if (resolveVideoSupportedModes(model).includes('text')) return true;
- return !!federatedInputProfile(kind, model);
+ const modes = resolveVideoSupportedModes(model);
+ return modes.some((mode) => ['text', 'image', 'fflf'].includes(mode)) || supportsSourceAudioWindow(model);
};
// The capability's input-asset block. Limits only — never a filename, digest, or
@@ -153,7 +156,7 @@ const federatedInputAssetsBlock = (kind, model) => {
return {
maxBytes: FEDERATED_MEDIA_ASSET_MAX_BYTES,
maxCount: FEDERATED_MEDIA_ASSET_MAX_COUNT,
- mimeTypes: [...FEDERATED_MEDIA_ASSET_MIME_TYPES],
+ mimeTypes: FEDERATED_MEDIA_ASSET_MIME_TYPES.filter((mime) => mime.startsWith('image/')),
roles: profile.roles,
required: profile.required,
};
@@ -215,7 +218,7 @@ async function resolveSubmissionInputAssets({ callerId, input, capability }) {
400,
);
}
- const unsupportedRoles = requested.filter((entry) => !limits.roles.includes(entry.role));
+ const unsupportedRoles = requested.filter((entry) => !(entry.role === 'sourceAudio' ? capability.sourceAudio : limits.roles.includes(entry.role)));
if (unsupportedRoles.length) {
unavailable(
`Requested model does not accept ${unsupportedRoles.map((entry) => entry.role).join(' or ')}`,
@@ -255,7 +258,8 @@ async function resolveSubmissionInputAssets({ callerId, input, capability }) {
if (entry.role === 'sourceAudio') {
const info = pcmAudioInfo(await readFile(found[0].path));
const audio = input.audioConditioning;
- if (!audio || !info || info.sampleCount !== audio.sampleCount
+ if (!audio || !info || !Number.isInteger(input.fps) || !Number.isInteger(input.numFrames)
+ || input.fps <= 0 || input.numFrames <= 1 || info.sampleCount !== audio.sampleCount
|| await sha256File(found[0].path) !== audio.clipSha256
|| Math.abs((input.numFrames - 1) / input.fps - info.sampleCount / info.sampleRate) > 1 / info.sampleRate) {
unavailable('Source audio does not match its exact sample window', 'MEDIA_PROVIDER_ASSET_INTEGRITY', 400);
@@ -465,7 +469,7 @@ async function localGeneratorCapabilities(kind, pythonPath, { models, configured
});
const hardwareEligible = hardware.state === 'available';
const memory = { requiredGb, totalGb: totalmem() / 2 ** 30, freeGb: freemem() / 2 ** 30 };
- const held = kind === 'video' && model && isVideoModelHeld(model.id, model.runtime);
+ const held = kind === 'video' && model && isVideoModelHeld(model.id, model.runtime);
const reason = !isLocal ? 'unknown-engine'
: !model ? 'unknown-model'
: !modelSupportsInput ? 'unsupported-input'
@@ -521,9 +525,11 @@ async function localGeneratorCapabilities(kind, pythonPath, { models, configured
defaultDurationSec: null,
lyrics: false,
inputAssets: federatedInputAssetsBlock(kind, model),
+ ...(kind === 'video' ? { supportedModes: resolveVideoSupportedModes(model).filter((mode) =>
+ ['text', 'image', 'fflf'].includes(mode) || (mode === 'a2v' && supportsSourceAudioWindow(model))) } : {}),
hardwareEligible,
memory,
- ...(kind === 'video' && resolveVideoSupportedModes(model).includes('a2v')
+ ...(kind === 'video' && supportsSourceAudioWindow(model)
? { sourceAudio: { requiresImage: true } } : {}),
autoDuration: false,
frameStride,
@@ -618,7 +624,8 @@ function activeQueueSnapshot(config, kinds) {
queued,
running,
maxQueuedJobs: config.maxQueuedJobs,
- accepting: active.length < config.maxQueuedJobs,
+ accepting: !maintenance.held() && active.length < config.maxQueuedJobs,
+ maintenanceHeld: maintenance.held(),
concurrency: federatedLaneConcurrency(kinds),
byKind,
};
@@ -674,6 +681,13 @@ export async function getFederatedMediaProviderStatus(config, { kinds = ['audio'
*
* @returns {Promise<{image: object[], video: object[]}>}
*/
+/** Project placement checks one explicit local model without enabling sharing. */
+export async function getLocalVideoRenderCapability(modelId) {
+ const pythonPath = await resolveLocalRuntimePythonPath(['video']);
+ const capabilities = await configuredVideoCapabilities(pythonPath, { videoModels: [{ engine: 'local', modelId }] });
+ return capabilities[0] ? publicCapability(capabilities[0]) : null;
+}
+
export async function listLocalMediaShareCandidates() {
const pythonPath = await resolveLocalRuntimePythonPath(['image', 'video']);
const catalogs = { image: getImageModels(), video: getVideoModels() };
@@ -823,6 +837,7 @@ export async function submitFederatedMediaJob({ callerId, config, input, idempot
return { replayed: true, job: await describeFederatedMediaJob(callerId, existing) };
}
+ return maintenance.run('media-input', 'Federated job admission', async () => {
const queue = activeQueueSnapshot(config, [input.kind]);
if (!queue.accepting) {
unavailable('Provider queue is at capacity', 'MEDIA_PROVIDER_BUSY', 429, {
@@ -850,6 +865,12 @@ export async function submitFederatedMediaJob({ callerId, config, input, idempot
if (input.sourceAudio && capability.memory?.requiredGb > capability.memory?.freeGb) {
unavailable('Insufficient free memory for supplied audio generation', 'MEDIA_PROVIDER_BUSY', 429, { retryable: true });
}
+ if (input.kind === 'video') {
+ const mode = input.sourceAudio ? 'a2v' : input.lastImage ? 'fflf' : input.sourceImage ? 'image' : 'text';
+ if (!resolveVideoSupportedModes(capability._model).includes(mode)) {
+ unavailable('Requested model cannot run this conditioning mode', 'MEDIA_PROVIDER_INPUT_UNSUPPORTED', 400);
+ }
+ }
validateFederatedVideoControls(input, capability._model);
// Lyrics reach a lyric-aware model only. `input.lyrics` is checked for a
// non-empty string rather than mere presence: a consumer that renders an
@@ -885,7 +906,8 @@ export async function submitFederatedMediaJob({ callerId, config, input, idempot
// Jobs are passed in so the sweep can PIN an in-flight job's conditioning:
// the TTL alone is a backstop, and a job queued behind a long render can
// outlive it (imageCleanTmpGc.js records the same lesson for its dir).
- sweepFederatedMediaAssets({ jobs: listJobs() }).catch((error) => {
+ await sweepFederatedMediaAssets({ jobs: [...listJobs(), { status: 'queued', params: inputAssetParams }] }).catch((error) => {
+ maintenance.markCurrentUnsettled();
console.error(`❌ Federated media inbox sweep failed: ${error.message}`);
});
@@ -895,11 +917,27 @@ export async function submitFederatedMediaJob({ callerId, config, input, idempot
idempotencyKey,
requestHash,
};
+ let audioUpload = null;
+ if (inputAssetParams.audioFilePath) {
+ audioUpload = join(PATHS.uploads, `federated-audio-${randomUUID()}.wav`);
+ const bytes = await readFile(inputAssetParams.audioFilePath);
+ if (sha256Text(bytes) !== input.audioConditioning.clipSha256) unavailable('Audio changed before admission', 'MEDIA_PROVIDER_ASSET_INTEGRITY', 400);
+ await ensureDir(PATHS.uploads);
+ // This UUID path is unpublished until enqueue succeeds. An exclusive
+ // write owns even a partial file, allowing admission to settle cleanup
+ // without a shared atomic-write helper's unknown temporary sibling.
+ await writeFile(audioUpload, bytes, { flag: 'wx', mode: 0o600 }).catch(async (error) => {
+ if (error.code !== 'EEXIST') await discardSourceAudioWindow(audioUpload);
+ throw error;
+ });
+ inputAssetParams.audioFilePath = audioUpload;
+ }
const queued = await enqueueJob({
kind: input.kind,
owner: jobOwner(callerId),
params: buildQueueParams(input, capability, federatedMedia, inputAssetParams),
- }).catch((error) => {
+ }).catch(async (error) => {
+ if (audioUpload) await discardSourceAudioWindow(audioUpload);
// The shared queue's own pending ceiling (#8326) is the same capacity
// refusal as the provider bound above; answer in the wire's vocabulary so
// the consumer retries later instead of seeing a local queue code.
@@ -912,6 +950,7 @@ export async function submitFederatedMediaJob({ callerId, config, input, idempot
replayed: false,
job: await describeFederatedMediaJob(callerId, queued.jobId),
};
+ });
});
}
diff --git a/server/services/federatedMediaProvider.test.js b/server/services/federatedMediaProvider.test.js
index 60026c7a07..75cff335f4 100644
--- a/server/services/federatedMediaProvider.test.js
+++ b/server/services/federatedMediaProvider.test.js
@@ -1,5 +1,5 @@
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
-import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { mkdtempSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
@@ -13,10 +13,40 @@ const state = vi.hoisted(() => ({
imageModels: [],
videoModels: [],
videoHolds: [],
+ maintenanceHeld: false,
+ failAudioCopy: false,
+ failAudioCleanup: false,
cachedRepos: new Set(),
laneWidthByKind: {},
}));
+vi.mock('node:fs/promises', async (load) => {
+ const fs = await load();
+ return { ...fs,
+ writeFile: async (path, bytes, options) => {
+ if (state.failAudioCopy && String(path).includes('/federated-audio-')) {
+ await fs.writeFile(path, bytes.subarray(0, 12), options);
+ throw Object.assign(new Error('Fixture disk write failure'), { code: 'EIO' });
+ }
+ return fs.writeFile(path, bytes, options);
+ },
+ unlink: async (path) => {
+ if (state.failAudioCleanup && String(path).includes('/federated-audio-')) {
+ throw Object.assign(new Error('Fixture cleanup failure'), { code: 'EIO' });
+ }
+ return fs.unlink(path);
+ },
+ };
+});
+
+vi.mock('../lib/maintenanceAdmission.js', () => ({ maintenance: {
+ held: () => state.maintenanceHeld, markCurrentUnsettled: vi.fn(),
+ run: async (_kind, _resource, fn) => {
+ if (state.maintenanceHeld) throw Object.assign(new Error('Maintenance holds new work'), { code: 'MAINTENANCE_HELD' });
+ return fn();
+ },
+} }));
+
vi.mock('./settings.js', () => ({
getSettings: vi.fn(async () => state.settings),
}));
@@ -156,6 +186,8 @@ beforeEach(() => {
state.settings = { federation: { mediaProvider: config() } };
state.peer = { instanceId: 'peer-example', name: 'Example Peer', enabled: true };
state.jobs = [];
+ state.maintenanceHeld = false;
+ state.failAudioCopy = false; state.failAudioCleanup = false;
state.nextId = 1;
state.capabilities = { engines: [readyEngine()], defaultEngine: 'musicgen' };
state.cancelResult = { ok: true, status: 'canceled' };
@@ -363,7 +395,7 @@ describe('federated media provider capacity and idempotency', () => {
// be distinguishable from a peer whose code predates lyrical federation.
state.capabilities.engines = [readyEngine({ lyrics: false })];
const status = await getFederatedMediaProviderStatus(config());
- expect(status.features).toEqual(['lyrics', 'inputAssets']);
+ expect(status.features).toEqual(['lyrics', 'inputAssets', 'sourceAudio']);
expect(status.capabilities[0].lyrics).toBe(false);
});
@@ -1025,3 +1057,88 @@ describe('federated media provider — prompt-free status and projection payload
expect(cap.resolutionOptions).toEqual([{ label: 'valid', w: 1344, h: 768 }]);
});
});
+
+
+describe('supplied audio provider admission', () => {
+ it('does not negotiate A2V runtimes with a different audio-output contract', async () => {
+ const cfg = { ...config(), videoModels: [{ engine: 'local', modelId: 'other-audio-runtime' }] };
+ state.settings.imageGen = { local: { pythonPath: '/example/python' } };
+ state.videoModels = [{ id: 'other-audio-runtime', runtime: 'minimax_h3_ref2va', repo: 'example/other-audio', supportedModes: ['a2v'] }];
+ state.cachedRepos.add('example/other-audio');
+ const status = await getFederatedMediaProviderStatus(cfg, { kinds: ['video'] });
+ expect(status.capabilities[0]?.sourceAudio).toBeUndefined();
+ expect(status.capabilities[0]).toMatchObject({ ready: false, unavailableReason: 'unsupported-input' });
+ });
+
+ it('keeps maintenance private and idempotent replay available during a hold', async () => {
+ const admitted = await submitFederatedMediaJob({ callerId: 'peer-example', config: config(), input: input(), idempotencyKey: 'before-hold' });
+ state.maintenanceHeld = true;
+ const status = await getFederatedMediaProviderStatus(config());
+ expect(status.queue).toMatchObject({ accepting: false, maintenanceHeld: true });
+ expect(JSON.stringify(status)).not.toMatch(/owner|blockers|requestedAt/);
+ await expect(submitFederatedMediaJob({ callerId: 'peer-example', config: config(), input: input(), idempotencyKey: 'before-hold' }))
+ .resolves.toMatchObject({ replayed: true, job: { id: admitted.job.id } });
+ await expect(submitFederatedMediaJob({ callerId: 'peer-example', config: config(), input: input(), idempotencyKey: 'new-during-hold' }))
+ .rejects.toMatchObject({ code: 'MAINTENANCE_HELD' });
+ expect(enqueueJob).toHaveBeenCalledTimes(1);
+ });
+
+ it('does not advertise a cached runtime as hardware eligible above its memory floor', async () => {
+ const cfg = { ...config(), videoModels: [{ engine: 'local', modelId: 'oversized' }] };
+ state.settings.imageGen = { local: { pythonPath: '/example/python' } };
+ state.videoModels = [{ id: 'oversized', repo: 'example/large', memoryGb: 100000, supportedModes: ['image'] }];
+ state.cachedRepos.add('example/large');
+ const status = await getFederatedMediaProviderStatus(cfg, { kinds: ['video'] });
+ expect(status.capabilities[0]).toMatchObject({ runtimeReady: true, ready: false, hardwareEligible: false, unavailableReason: 'hardware-ineligible' });
+ });
+
+ it('copies only verified caller-owned PCM into the uploads lane and binds idempotency to the audio provenance', async () => {
+ const { storeFederatedMediaAsset } = await import('./federatedMedia/assetStore.js');
+ const { readFileSync } = await import('node:fs');
+ const original = { uploads: PATHS.uploads, federatedMediaInbox: PATHS.federatedMediaInbox };
+ const root = mkdtempSync(join(tmpdir(), 'provider-audio-test-'));
+ PATHS.uploads = join(root, 'uploads'); PATHS.federatedMediaInbox = root;
+ try {
+ const cfg = { ...config(), videoModels: [{ engine: 'local', modelId: 'audio-model' }] };
+ state.settings.imageGen = { local: { pythonPath: '/example/python' } };
+ state.videoModels = [{ id: 'audio-model', runtime: 'ltx2', repo: 'example/audio-video', supportedModes: ['image', 'a2v'] }];
+ state.cachedRepos.add('example/audio-video');
+ const bytes = Buffer.alloc(44 + 48000 * 4);
+ bytes.write('RIFF'); bytes.writeUInt32LE(bytes.length - 8, 4); bytes.write('WAVEfmt ', 8);
+ bytes.writeUInt32LE(16, 16); bytes.writeUInt16LE(1, 20); bytes.writeUInt16LE(2, 22);
+ bytes.writeUInt32LE(48000, 24); bytes.writeUInt32LE(192000, 28); bytes.writeUInt16LE(4, 32);
+ bytes.writeUInt16LE(16, 34); bytes.write('data', 36); bytes.writeUInt32LE(48000 * 4, 40);
+ const upload = (body, mimeType) => storeFederatedMediaAsset({ callerId: 'peer-example', body, mimeType, declaredSha256: sha256Text(body) });
+ const audio = await upload(bytes, 'audio/wav');
+ const frame = await upload(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), 'image/png');
+ const body = { kind: 'video', engine: 'local', modelId: 'audio-model', prompt: 'Example light', fps: 24, numFrames: 25,
+ sourceImage: { assetId: frame.assetId }, sourceAudio: { assetId: audio.assetId },
+ audioConditioning: { sourceSha256: 'b'.repeat(64), clipSha256: audio.sha256, sampleRate: 48000, channels: 2, startSample: 0, endSample: 48000, sampleCount: 48000 } };
+ const args = { callerId: 'peer-example', config: cfg, input: body, idempotencyKey: 'audio-window' };
+ for (const field of ['fps', 'numFrames']) {
+ await expect(submitFederatedMediaJob({ ...args, input: { ...body, [field]: undefined } }))
+ .rejects.toMatchObject({ code: 'MEDIA_PROVIDER_ASSET_INTEGRITY' });
+ }
+ await expect(submitFederatedMediaJob({ ...args, input: { ...body, audioConditioning: { ...body.audioConditioning, sampleCount: 47999 } } }))
+ .rejects.toMatchObject({ code: 'MEDIA_PROVIDER_ASSET_INTEGRITY' });
+ state.failAudioCopy = true;
+ await expect(submitFederatedMediaJob(args)).rejects.toMatchObject({ code: 'EIO' });
+ expect(enqueueJob).not.toHaveBeenCalled();
+ expect(readdirSync(PATHS.uploads)).toEqual([]);
+ state.failAudioCleanup = true;
+ await expect(submitFederatedMediaJob(args)).rejects.toMatchObject({ code: 'EIO' });
+ const { maintenance } = await import('../lib/maintenanceAdmission.js');
+ expect(maintenance.markCurrentUnsettled).toHaveBeenCalled();
+ expect(enqueueJob).not.toHaveBeenCalled();
+ for (const name of readdirSync(PATHS.uploads)) rmSync(join(PATHS.uploads, name));
+ state.failAudioCopy = false; state.failAudioCleanup = false;
+ const result = await submitFederatedMediaJob(args);
+ const params = state.jobs.find((job) => job.id === result.job.id).params;
+ expect(params).toMatchObject({ mode: 'a2v', audioStartSec: 0, disableAudio: true, audioConditioning: body.audioConditioning });
+ expect(params.audioFilePath).toMatch(/federated-audio-.*\.wav$/);
+ expect(readFileSync(params.audioFilePath)).toEqual(bytes);
+ await expect(submitFederatedMediaJob({ ...args, input: { ...body, audioConditioning: { ...body.audioConditioning, startSample: 48000, endSample: 96000 } } }))
+ .rejects.toMatchObject({ code: 'MEDIA_PROVIDER_IDEMPOTENCY_CONFLICT' });
+ } finally { Object.assign(PATHS, original); rmSync(root, { recursive: true, force: true }); }
+ });
+});
diff --git a/server/services/mediaJobQueue/index.js b/server/services/mediaJobQueue/index.js
index 9b7984a553..9f0073dd40 100644
--- a/server/services/mediaJobQueue/index.js
+++ b/server/services/mediaJobQueue/index.js
@@ -793,6 +793,7 @@ function startLaneJob(job, { lane }) {
console.log(`⚠️ media-job [${job.id.slice(0, 8)}] startLaneJob: already removed from queue, skipping`);
return false;
}
+ if (lane === 'remote' && remoteRunning.some((active) => active.params?.remoteMedia?.peerId === job.params?.remoteMedia?.peerId)) return false;
const permit = recoveringJobs.has(job.id)
? maintenance.recoverOwned('media', job.id)
: maintenance.tryAdmit('media', job.id, { reconnect: isRemoteMediaJob(job) && job.params?.remoteMedia?.reconcile === true });
@@ -948,6 +949,9 @@ async function drainLoop() {
if (job.status !== 'queued' || job.hold || job.admitting) continue;
const lane = jobLane(job);
if (slots[lane] <= 0) continue;
+ // One GPU job per peer initially. Different peers and this Mac remain
+ // independent. Reconciliation occupies the same slot until settled.
+ if (lane === 'remote' && !job.params?.remoteMedia?.reconcile && candidates.some((pending) => pending.status === 'queued' && pending.params?.remoteMedia?.reconcile && pending.params.remoteMedia.peerId === job.params?.remoteMedia?.peerId)) continue;
if (!startLaneJob(job, { lane })) continue;
slots[lane] -= 1;
if (Object.values(slots).every((remaining) => remaining <= 0)) break;
@@ -1161,6 +1165,8 @@ async function runJobLifecycle(job, markDispatched) {
let resolveProviderSettlement;
const providerSettlement = new Promise(resolve => { resolveProviderSettlement = resolve; });
let watchdogNeedsProviderSettlement = false;
+ let providerInputsDisposable = false;
+ let inputCleanupAttempted = false;
let progressPersistDirty = false;
let progressPersistTimer = null;
let progressPersisting = null;
@@ -1205,7 +1211,24 @@ async function runJobLifecycle(job, markDispatched) {
// fire a redundant provider cancel. It's a transient in-memory flag
// (excluded from persistImpl's serialized field set).
let watchdogTimer;
- async function terminate(state, apply) {
+ async function releaseRemoteAudioInputs(disposable) {
+ if (!disposable || inputCleanupAttempted || job.kind !== 'video' || !isRemoteMediaJob(job)) return;
+ inputCleanupAttempted = true;
+ try {
+ await maintenance.withResource('media', job.id, async () => {
+ const { discardSourceAudioWindow } = await import('../federatedMedia/sourceAudio.js');
+ for (const asset of job.params?.remoteMedia?.inputAssets || []) {
+ if (asset.role === 'sourceAudio' && normalizeTempPaths(job.params?.uploadedTempPaths).includes(asset.path)) {
+ await discardSourceAudioWindow(asset.path);
+ }
+ }
+ });
+ } catch (error) {
+ maintenance.markResourceUnsettled('media', job.id);
+ console.error(`❌ Remote video input cleanup needs recovery for ${job.id}: ${error.message}`);
+ }
+ }
+ async function terminate(state, apply, remoteInputsDisposable = false) {
if (!claimTerminalOutcome(job)) return;
// setInterval now (was setTimeout) — using clearInterval to match the new
// API. (Node accepts either clearTimeout or clearInterval on the same
@@ -1214,10 +1237,10 @@ async function runJobLifecycle(job, markDispatched) {
emitter.off?.('activity', onActivity);
emitter.off?.('progress', onActivity);
await drainProgressPersist();
- await admitCompletion(state, () => publishTerminalTransition(state, apply));
+ await admitCompletion(state, () => publishTerminalTransition(state, apply, remoteInputsDisposable));
}
- async function publishTerminalTransition(state, apply) {
+ async function publishTerminalTransition(state, apply, remoteInputsDisposable) {
stageTerminalTransition(job, (job) => {
apply(job);
job.status = state;
@@ -1230,6 +1253,11 @@ async function runJobLifecycle(job, markDispatched) {
// so the residual values are not displayed for terminal jobs.
job.completedAt = new Date().toISOString();
}, async () => {
+ // The terminal snapshot is durable now; a restart no longer rebuilds
+ // this request. Absence of the executor verdict retains all inputs.
+ // A shared persist can acknowledge another job: restore THAT job's
+ // maintenance context, and never let cleanup failure lose this callback.
+ await releaseRemoteAudioInputs(remoteInputsDisposable);
if (job.params?.videoProduction) {
const tag = job.params.videoProduction;
const { settleVideoAttempt } = await import('../creativeDirector/videoExecution.js');
@@ -1279,8 +1307,9 @@ async function runJobLifecycle(job, markDispatched) {
broadcastSse(sseEntry, payload);
},
completed: (payload) => {
+ const { remoteInputsDisposable, ...result } = payload;
trackTerminalOperation(
- terminate('completed', (j) => { j.result = payload; })
+ terminate('completed', (j) => { j.result = result; }, remoteInputsDisposable === true)
.catch((e) => console.log(`⚠️ media-job [${job.id.slice(0, 8)}] terminal handler failed: ${e.message}`)),
);
},
@@ -1295,7 +1324,7 @@ async function runJobLifecycle(job, markDispatched) {
// is cleaned up still gets a meaningful terminal frame from the
// archived state, rather than the generic "Canceled" fallback.
j.error = 'Canceled while running';
- }).catch((e) => console.log(`⚠️ media-job [${job.id.slice(0, 8)}] terminal handler failed: ${e.message}`)),
+ }, payload.remoteInputsDisposable === true).catch((e) => console.log(`⚠️ media-job [${job.id.slice(0, 8)}] terminal handler failed: ${e.message}`)),
);
return;
}
@@ -1303,7 +1332,7 @@ async function runJobLifecycle(job, markDispatched) {
terminate('failed', (j) => {
j.error = payload.error || 'unknown error';
videoHolds.captureFailure(j, j.error, payload);
- })
+ }, payload.remoteInputsDisposable === true)
.catch((e) => console.log(`⚠️ media-job [${job.id.slice(0, 8)}] terminal handler failed: ${e.message}`)),
);
},
@@ -1349,8 +1378,8 @@ async function runJobLifecycle(job, markDispatched) {
// provider terminal event can release that additional wait.
const dispatcher = makeGenDispatcher(emitter, job, {
...handlers,
- completed: payload => { resolveProviderSettlement(); handlers.completed(payload); },
- failed: payload => { resolveProviderSettlement(); handlers.failed(payload); },
+ completed: payload => { providerInputsDisposable = payload.remoteInputsDisposable === true; resolveProviderSettlement(); handlers.completed(payload); },
+ failed: payload => { providerInputsDisposable = payload.remoteInputsDisposable === true; resolveProviderSettlement(); handlers.failed(payload); },
});
dispatcher.attach();
@@ -1495,10 +1524,12 @@ async function runJobLifecycle(job, markDispatched) {
// 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);
+ if (!(isRemoteMediaJob(job) && job.params?.remoteMedia?.reconcile === true)) {
+ 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 });
})());
@@ -1509,6 +1540,10 @@ async function runJobLifecycle(job, markDispatched) {
// lane release immediate and gives tests a deterministic lifecycle to drain.
await terminalState;
if (watchdogNeedsProviderSettlement) await providerSettlement;
+ // A watchdog can win the terminal row before the real provider responds.
+ // Keep its later trusted verdict through physical settlement, then release
+ // inputs under the still-owned lane after that row is durable.
+ await releaseRemoteAudioInputs(providerInputsDisposable);
dispatcher.detach();
}
diff --git a/server/services/mediaJobQueue/index.test.js b/server/services/mediaJobQueue/index.test.js
index 092f675b6f..b2da27b597 100644
--- a/server/services/mediaJobQueue/index.test.js
+++ b/server/services/mediaJobQueue/index.test.js
@@ -1498,6 +1498,25 @@ describe('Audio kind (#1928)', () => {
expect(settled.result).toEqual({ generationId: job.jobId, filename: `${job.jobId}.wav`, durationSec: 12 });
});
+ it('serializes jobs per peer while distinct peers and local GPU run together, releasing the peer after cancellation', async () => {
+ stubs.generateVideo.mockImplementation(() => new Promise(() => {}));
+ const finish = new Map();
+ stubs.generateVideoRemote.mockImplementation(({ jobId }) => new Promise((resolve) => finish.set(jobId, resolve)));
+ const submit = (peerId) => mediaJobQueue.enqueueJob({ kind: 'video', params: { remoteMedia: { ...remoteVideoMediaParams(), peerId } } });
+ const local = await mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'local' } });
+ const first = await submit('11111111-1111-4111-8111-111111111111');
+ const second = await submit('11111111-1111-4111-8111-111111111111');
+ const other = await submit('22222222-2222-4222-8222-222222222222');
+ await waitFor(() => mediaJobQueue.getJob(other.jobId)?.status === 'running');
+ expect(mediaJobQueue.getJob(local.jobId).status).toBe('running');
+ expect(mediaJobQueue.getJob(first.jobId).status).toBe('running');
+ expect(mediaJobQueue.getJob(second.jobId).status).toBe('queued');
+ await mediaJobQueue.cancelJob(first.jobId);
+ videoGenEvents.emit('failed', { generationId: first.jobId, error: 'Canceled' });
+ finish.get(first.jobId)();
+ await waitFor(() => mediaJobQueue.getJob(second.jobId)?.status === 'running');
+ });
+
it('runs remote audio in its own lane without occupying the local GPU', async () => {
stubs.generateVideo.mockImplementation(() => new Promise(() => {}));
stubs.generateAudioRemote.mockImplementation(() => new Promise(() => {}));
@@ -2298,7 +2317,8 @@ describe('local video failure holds', () => {
const cloudJob = async () => (await mediaJobQueue.enqueueJob({
kind: 'image', params: { mode: 'codex', prompt: 'example cloud image' },
})).jobId;
- const remoteJob = () => submit('example-mlx', { remoteMedia: remoteVideoMediaParams() });
+ let peerSequence = 0;
+ const remoteJob = () => submit('example-mlx', { remoteMedia: { ...remoteVideoMediaParams(), peerId: `11111111-1111-4111-8111-${String(++peerSequence).padStart(12, '0')}` } });
const gpu = [await submit('example-other')];
const cloud = [await cloudJob()];
// Concurrent dynamic imports can bypass the module mock in this test runner;
@@ -2721,6 +2741,111 @@ const holdNextWrite = () => {
return () => release();
};
+describe('durable remote source-audio settlement', () => {
+ const startAudioJob = async (suffix = '001', directory = false) => {
+ const path = join(tempDataDir, 'uploads', `mv-source-audio-00000000-0000-4000-8000-000000000${suffix}.wav`);
+ mkdirSync(join(tempDataDir, 'uploads'), { recursive: true });
+ if (directory) mkdirSync(path); else writeFileSync(path, 'owned fixture');
+ const remoteMedia = { ...remoteVideoMediaParams(), peerId: `00000000-0000-4000-8000-000000000${suffix}`,
+ inputAssets: [{ role: 'sourceAudio', path }] };
+ const job = await mediaJobQueue.enqueueJob({ kind: 'video', params: { remoteMedia, uploadedTempPaths: [path] } });
+ await waitFor(() => stubs.generateVideoRemote.mock.calls.some(([params]) => params.jobId === job.jobId));
+ return { ...job, path };
+ };
+
+ it('retains the slice until a durable terminal snapshot, then cleans before publishing completion', async () => {
+ const job = await startAudioJob();
+ const release = holdNextWrite();
+ const published = vi.fn(() => expect(existsSync(job.path)).toBe(false));
+ mediaJobQueue.mediaJobEvents.once('completed', published);
+ videoGenEvents.emit('completed', { generationId: job.jobId, remoteInputsDisposable: true });
+ await new Promise(resolve => setImmediate(resolve));
+ expect(existsSync(job.path)).toBe(true);
+ expect(persistedJobs().find(entry => entry.id === job.jobId).status).toBe('running');
+ release();
+ await waitFor(() => published.mock.calls.length === 1);
+ expect(persistedJobs().find(entry => entry.id === job.jobId).status).toBe('completed');
+ expect(mediaJobQueue.getJob(job.jobId).result).not.toHaveProperty('remoteInputsDisposable');
+ });
+
+ it('retains uncertain inputs when the executor gives no safe-disposal verdict', async () => {
+ const job = await startAudioJob();
+ videoGenEvents.emit('failed', { generationId: job.jobId, error: 'Uncertain remote outcome', remoteInputsDisposable: false });
+ await waitFor(() => mediaJobQueue.getJob(job.jobId).status === 'failed');
+ expect(existsSync(job.path)).toBe(true);
+ });
+
+ it('keeps Run now from bypassing the per-peer GPU cap', async () => {
+ const first = await startAudioJob();
+ const second = await mediaJobQueue.enqueueJob({ kind: 'video', params: { remoteMedia: remoteVideoMediaParams() } });
+ expect(mediaJobQueue.runJobNow(second.jobId)).toMatchObject({ ok: false, code: 'NOT_CODEX' });
+ expect(mediaJobQueue.getJob(second.jobId).status).toBe('queued');
+ videoGenEvents.emit('completed', { generationId: first.jobId, remoteInputsDisposable: true });
+ });
+
+ it('retains the real provider cleanup verdict after a watchdog wins the durable terminal outcome', async () => {
+ process.env.MEDIA_JOB_WATCHDOG_VIDEO_MS = '50';
+ await importFresh();
+ stubs.generateVideoRemote.mockResolvedValue({});
+ const job = await startAudioJob();
+ const { maintenance } = await import('../../lib/maintenanceAdmission.js');
+ const { hold } = maintenance.begin({ reason: 'Await peer settlement', owner: 'Operator' });
+ vi.useFakeTimers();
+ try {
+ await vi.advanceTimersByTimeAsync(100);
+ await vi.waitFor(() => expect(mediaJobQueue.getJob(job.jobId).status).toBe('failed'));
+ expect(existsSync(job.path)).toBe(true);
+ expect(maintenance.status().state).toBe('draining');
+ videoGenEvents.emit('failed', { generationId: job.jobId, error: 'Peer confirms terminal', remoteInputsDisposable: true });
+ await vi.waitFor(() => expect(existsSync(job.path)).toBe(false));
+ await vi.waitFor(() => expect(maintenance.status().state).toBe('ready'));
+ expect(persistedJobs().find(entry => entry.id === job.jobId).status).toBe('failed');
+ } finally {
+ videoGenEvents.emit('failed', { generationId: job.jobId, error: 'Fixture teardown' });
+ maintenance.resume({ id: hold.id, revision: hold.revision });
+ delete process.env.MEDIA_JOB_WATCHDOG_VIDEO_MS;
+ vi.clearAllTimers(); vi.useRealTimers();
+ }
+ });
+
+ it('preserves replay bytes across a failed terminal write and releases them on storage recovery', async () => {
+ const job = await startAudioJob();
+ const write = atomicWriteSpy.getMockImplementation();
+ let failing = true;
+ atomicWriteSpy.mockImplementation((path, data) => failing && data?.jobs?.some(entry => entry.id === job.jobId && entry.status === 'completed')
+ ? Promise.reject(new Error('fixture storage unavailable')) : write(path, data));
+ try {
+ videoGenEvents.emit('completed', { generationId: job.jobId, remoteInputsDisposable: true });
+ await waitFor(() => mediaJobQueue.getJob(job.jobId).persistenceError === true);
+ expect(existsSync(job.path)).toBe(true);
+ expect(persistedJobs().find(entry => entry.id === job.jobId).status).toBe('running');
+ failing = false;
+ await mediaJobQueue.flushMediaJobQueue();
+ await waitFor(() => !existsSync(job.path));
+ expect(stubs.generateVideoRemote).toHaveBeenCalledTimes(1);
+ } finally { atomicWriteSpy.mockImplementation(write); }
+ });
+
+ it('attributes failed cleanup to the correct job during shared terminal persistence and still publishes both outcomes', async () => {
+ const bad = await startAudioJob('001', true);
+ const good = await startAudioJob('002');
+ const { maintenance } = await import('../../lib/maintenanceAdmission.js');
+ const published = [];
+ const receive = job => published.push(job.id);
+ mediaJobQueue.mediaJobEvents.on('completed', receive);
+ try {
+ videoGenEvents.emit('completed', { generationId: good.jobId, remoteInputsDisposable: true });
+ videoGenEvents.emit('completed', { generationId: bad.jobId, remoteInputsDisposable: true });
+ await waitFor(() => published.length === 2);
+ const blockers = maintenance.status().blockers;
+ expect(blockers).toContainEqual(expect.objectContaining({ resource: bad.jobId, unsettled: true }));
+ expect(blockers.filter(entry => entry.resource === good.jobId && entry.unsettled)).toEqual([]);
+ expect(existsSync(good.path)).toBe(false);
+ expect(existsSync(bad.path)).toBe(true);
+ } finally { mediaJobQueue.mediaJobEvents.off('completed', receive); }
+ });
+});
+
describe('durable admission and shutdown flush', () => {
beforeEach(async () => {
diff --git a/server/services/musicVideo/performanceShot.js b/server/services/musicVideo/performanceShot.js
index f67aedda1d..0b242ad9fa 100644
--- a/server/services/musicVideo/performanceShot.js
+++ b/server/services/musicVideo/performanceShot.js
@@ -156,14 +156,22 @@ function legacyMasterLookup(project, masterPath) {
async function reviewPerformanceTakes(project, masterPath) {
const results = [];
const selected = [];
+ let sha256 = null;
for (const scene of Array.isArray(project?.scenes) ? project.scenes : []) {
+ const supplied = (scene.takes || []).find((take) => take.kind === 'video' && take.assetId === scene.videoHistoryId)?.shotInstruction;
+ if (scene.videoHistoryId && !['still', 'card'].includes(scene.visualLayer) && supplied?.audioConditioning) {
+ sha256 ??= await hashFile(masterPath);
+ if (supplied.audioConditioning.sourceSha256 !== sha256) results.push({ sceneId: scene.sceneId, reason: 'source-audio-changed', stale: true });
+ else if (Math.round(scene.startSec * 48000) !== supplied.audioConditioning.startSample
+ || scene.endSec !== supplied.songInterval?.endSec) results.push({ sceneId: scene.sceneId, reason: 'retimed', stale: true });
+ }
if (!isPerformanceScene(scene) || !scene.videoHistoryId) continue;
const instruction = selectedPerformanceInstruction(scene);
if (instruction) selected.push({ scene, instruction });
else results.push({ sceneId: scene.sceneId, reason: 'not-lip-synced', stale: true });
}
if (selected.length === 0) return results;
- const sha256 = await hashFile(masterPath);
+ sha256 ??= await hashFile(masterPath);
let currentEnvelope = null;
const oldEnvelope = legacyMasterLookup(project, masterPath);
const windowUnchanged = async (instruction) => {
@@ -213,6 +221,13 @@ export async function assertCurrentPerformanceTakes(project, masterPath) {
if (rehashed > 0) console.log(`🎵 Music Video: ${rehashed} lip-sync take${rehashed === 1 ? '' : 's'} still match${rehashed === 1 ? 'es' : ''} the re-mastered song in ${rehashed === 1 ? 'its' : 'their'} sung window`);
const stale = reviewed.filter((r) => r.stale).map(({ sceneId, reason }) => ({ sceneId, reason }));
if (stale.length === 0) return;
+ if (stale.some(({ sceneId }) => {
+ const scene = project.scenes.find((entry) => entry.sceneId === sceneId);
+ return scene?.takes?.some((take) => take.assetId === scene.videoHistoryId && take.shotInstruction?.audioConditioning);
+ })) {
+ throw new ServerError('A supplied-audio shot no longer matches the selected recording or scene interval; regenerate it before rendering',
+ { status: 422, code: 'MUSIC_VIDEO_STALE_SOURCE_AUDIO_TAKES', context: { stale } });
+ }
const counts = new Map();
for (const { reason } of stale) counts.set(reason, (counts.get(reason) || 0) + 1);
const why = [...counts].map(([reason, n]) => `${n} ${STALE_REASON_LABELS[reason] || reason}`).join(', ');
diff --git a/server/services/musicVideo/performanceShot.test.js b/server/services/musicVideo/performanceShot.test.js
index 973057a345..3439bbf33f 100644
--- a/server/services/musicVideo/performanceShot.test.js
+++ b/server/services/musicVideo/performanceShot.test.js
@@ -103,6 +103,33 @@ beforeEach(async () => {
afterAll(() => cleanupTempDataRoots());
+it('blocks composition and exposes a repair when supplied audio used an older take of the same track', async () => {
+ const { assertCurrentPerformanceTakes } = await import('./performanceShot.js');
+ const { resolveMasterAudioPath } = await import('./render.js');
+ const { getDependencyImpact } = await import('./revisionService.js');
+ const sourceSha256 = createHash('sha256').update(songWav()).digest('hex');
+ const supplied = { ...project({ shotMode: 'cutaway' }), trackId: 'same-track', uploadedAudioFilename: null };
+ const shot = supplied.scenes[0];
+ shot.videoHistoryId = 'supplied-take';
+ shot.takes = [{ kind: 'video', assetId: shot.videoHistoryId, shotInstruction: {
+ shotMode: 'cutaway', songInterval: { startSec: shot.startSec, endSec: shot.endSec },
+ audioConditioning: { sourceSha256, startSample: shot.startSec * RATE },
+ } }];
+ getProject.mockResolvedValue(supplied);
+ getTrack.mockResolvedValue({ audioFilename: 'song.wav' });
+ await expect(assertCurrentPerformanceTakes(supplied, await resolveMasterAudioPath(supplied))).resolves.toBeUndefined();
+ await writeFile(join(PATHS.music, 'another-take.wav'), songWav({ markerAmp: 10000 }));
+ getTrack.mockResolvedValue({ audioFilename: 'another-take.wav' });
+ await expect(assertCurrentPerformanceTakes(supplied, await resolveMasterAudioPath(supplied))).rejects.toMatchObject({ code: 'MUSIC_VIDEO_STALE_SOURCE_AUDIO_TAKES' });
+ const impact = await getDependencyImpact(supplied.id);
+ expect(impact.shots).toEqual(expect.arrayContaining([expect.objectContaining({ sceneId: shot.sceneId, reasons: expect.arrayContaining(['source-audio-changed']) })]));
+ for (const visualLayer of ['still', 'card']) {
+ shot.visualLayer = visualLayer;
+ await expect(assertCurrentPerformanceTakes(supplied, await resolveMasterAudioPath(supplied))).resolves.toBeUndefined();
+ expect((await getDependencyImpact(supplied.id)).shots).toEqual([]);
+ }
+});
+
describe.skipIf(!ffmpeg)('music-video performance shot through the fal lip-sync lane (#8977)', () => {
it('slices the exact song window, submits it once, and trims the delivered take at its edit points', async () => {
getProject.mockResolvedValue(project());
diff --git a/server/services/musicVideo/productionService.js b/server/services/musicVideo/productionService.js
index fc3c9c8f00..cea305818c 100644
--- a/server/services/musicVideo/productionService.js
+++ b/server/services/musicVideo/productionService.js
@@ -626,6 +626,12 @@ async function cancelOwnedJobs(runId, { includeRunning = false, jobIds = null }
*/
export async function startProduction(projectId, { directive, pool: requested, limits, reviewer, authoring: requestedAuthoring }) {
const project = await requireProject(projectId);
+ if (project.videoSettings?.renderPool && project.videoSettings.renderPool.mode !== 'local') {
+ throw new ServerError('Production runs require This Mac until immutable run pools support peer placement', { status: 409, code: 'MUSIC_VIDEO_RENDER_POOL_UNAVAILABLE' });
+ }
+ if (project.videoSettings?.generationMode === 'suppliedAudio') {
+ throw new ServerError('Production runs do not yet bind supplied-audio windows in their immutable pool; use Prompt motion', { status: 409, code: 'MUSIC_VIDEO_RENDER_POOL_UNAVAILABLE' });
+ }
const assets = codeFirstProductionAssets(project);
const authoring = assets ? await deps.resolveAuthoring(requestedAuthoring) : null;
const pool = normalizeProductionPool(requested, { allowEmpty: !!assets });
diff --git a/server/services/musicVideo/productionService.test.js b/server/services/musicVideo/productionService.test.js
index 13af1426ad..f44a574210 100644
--- a/server/services/musicVideo/productionService.test.js
+++ b/server/services/musicVideo/productionService.test.js
@@ -182,6 +182,20 @@ beforeEach(() => {
afterEach(settle);
describe('music video production run (#9066)', () => {
+ it('refuses mutable peer placement before starting an immutable production budget', async () => {
+ seedProject({ videoSettings: { renderPool: { mode: 'both', peers: [{ peerId: 'example-peer', modelId: 'example-model' }] } } });
+ await expect(start()).rejects.toMatchObject({ code: 'MUSIC_VIDEO_RENDER_POOL_UNAVAILABLE' });
+ expect(dispatch).not.toHaveBeenCalled();
+ expect(current().productionRuns).toBeUndefined();
+ });
+
+ it('refuses unbound supplied-audio windows before starting or spending a production budget', async () => {
+ seedProject({ videoSettings: { generationMode: 'suppliedAudio', renderPool: { mode: 'local', peers: [] } } });
+ await expect(start()).rejects.toMatchObject({ code: 'MUSIC_VIDEO_RENDER_POOL_UNAVAILABLE' });
+ expect(dispatch).not.toHaveBeenCalled();
+ expect(current().productionRuns).toBeUndefined();
+ });
+
it('produces a reviewed draft from one Start: frames, then clips, then the continuous-excerpt review', async () => {
seedProject();
await start();
diff --git a/server/services/musicVideo/projectsLogic.js b/server/services/musicVideo/projectsLogic.js
index d7f3b61edd..caf21f23aa 100644
--- a/server/services/musicVideo/projectsLogic.js
+++ b/server/services/musicVideo/projectsLogic.js
@@ -122,6 +122,7 @@ export function buildProjectRecord(input, { id, now }) {
visualSpec: input.visualSpec ? normalizeVisualSpec(input.visualSpec) : null,
...(input.styleReferences ? { styleReferences: input.styleReferences } : {}),
videoSettings: {
+ ...(videoSettings.renderPool ? { renderPool: videoSettings.renderPool } : {}),
backend: videoSettings.backend ?? 'local',
modelId: videoSettings.modelId ?? null,
grokDuration: videoSettings.grokDuration ?? 10,
@@ -772,10 +773,11 @@ export function mergeProjectRecord(local, remoteRaw) {
};
}
if (local.videoSettings && typeof local.videoSettings === 'object'
- && !Array.isArray(local.videoSettings) && Object.hasOwn(local.videoSettings, 'backend')) {
+ && !Array.isArray(local.videoSettings) && ['backend', 'renderPool'].some((key) => Object.hasOwn(local.videoSettings, key))) {
const remoteVideoSettings = remote.videoSettings && typeof remote.videoSettings === 'object'
&& !Array.isArray(remote.videoSettings) ? remote.videoSettings : {};
- remote.videoSettings = { ...remoteVideoSettings, backend: local.videoSettings.backend };
+ remote.videoSettings = { ...remoteVideoSettings,
+ ...Object.fromEntries(['backend', 'renderPool'].filter((key) => Object.hasOwn(local.videoSettings, key)).map((key) => [key, local.videoSettings[key]])) };
}
const remoteWins = compareNewerWins(remote.updatedAt, local.updatedAt);
const next = remoteWins ? remote : local;
diff --git a/server/services/musicVideo/renderPool.js b/server/services/musicVideo/renderPool.js
new file mode 100644
index 0000000000..dbc950236f
--- /dev/null
+++ b/server/services/musicVideo/renderPool.js
@@ -0,0 +1,88 @@
+/** Project-scoped shot placement. A saved pool narrows existing grants; it never enables one. */
+import { ServerError } from '../../lib/errorHandler.js';
+import { isPerformanceScene } from '../../lib/musicVideoShotTiming.js';
+
+const refuse = (message, reasons = []) => {
+ throw new ServerError(message, { status: 409, code: 'MUSIC_VIDEO_RENDER_POOL_UNAVAILABLE', context: { reasons } });
+};
+
+export async function applyProjectRenderPool(body) {
+ const { getProject } = await import('./projects.js');
+ const project = await getProject(body.musicVideo.projectId);
+ const pool = project?.videoSettings?.renderPool;
+ if (body.musicVideo.productionRunId && project?.videoSettings?.generationMode === 'suppliedAudio') {
+ refuse('Production runs do not yet bind supplied-audio windows in their immutable pool; use Prompt motion');
+ }
+ // Existing projects retain their renderer pins until a pool is saved.
+ if (!pool || pool.mode === 'local') {
+ if (body.mediaProviderPeerId) refuse('Select a peer in the saved project render pool first');
+ if (project?.videoSettings?.generationMode === 'suppliedAudio' && body.backend && body.backend !== 'local') {
+ refuse('Supplied song audio requires Local video; choose that renderer explicitly');
+ }
+ return project?.videoSettings?.generationMode === 'suppliedAudio'
+ ? { ...body, backend: 'local', mode: 'a2v', _suppliedAudio: true } : body;
+ }
+ const scene = project.scenes?.find((entry) => entry.sceneId === body.musicVideo.sceneId);
+ if (!scene) refuse('The requested scene is no longer in this project');
+ if (isPerformanceScene(scene)) refuse('Remote performance lip-sync has not been verified; choose This Mac and a supported lip-sync renderer');
+ if (body.musicVideo.productionRunId) {
+ // Production runs already carry an immutable backend/model budget pool.
+ // Replacing it with this mutable placement policy would violate that grant.
+ refuse('Project render pools currently support board-generated shots and revisions; production runs require This Mac');
+ }
+ if (body.backend && body.backend !== 'local') refuse('Peer pools support local GPU models only; choose Local video');
+ if (body.mediaProviderPeerId) refuse('Choose peers in the saved project pool, not in the individual request');
+ if (!['image', 'suppliedAudio'].includes(project.videoSettings.generationMode || 'image')) {
+ refuse('Audio-reactive LoRA weights cannot cross to peers; use Prompt motion or Supplied song audio');
+ }
+ if (body.mode && !['image', 'a2v'].includes(body.mode)) refuse('Peer pools do not support video continuation or chain state');
+ const suppliedAudio = project.videoSettings.generationMode === 'suppliedAudio';
+ const requestedMode = suppliedAudio ? 'a2v' : 'image';
+ const [{ getPeers }, { resolveFederatedMediaProvider }, { listJobs }] = await Promise.all([
+ import('../instances.js'), import('../federatedMediaConsumer.js'), import('../mediaJobQueue/index.js'),
+ ]);
+ const peers = await getPeers();
+ const jobs = listJobs().filter((job) => ['queued', 'running'].includes(job.status));
+ const candidates = [];
+ const reasons = [];
+ if (pool.mode === 'both') {
+ const modelId = project.videoSettings.modelId;
+ if (!modelId) reasons.push('This Mac: select an explicit local model');
+ else {
+ const { getLocalVideoRenderCapability } = await import('../federatedMediaProvider.js');
+ const capability = await getLocalVideoRenderCapability(modelId);
+ if (capability?.ready !== true || capability.hardwareEligible !== true || !capability.memory?.requiredGb
+ || capability.memory.requiredGb > capability.memory.freeGb || !capability.inputAssets?.roles?.includes('sourceImage')
+ || !capability.supportedModes?.includes(requestedMode)
+ || (suppliedAudio && !capability.sourceAudio)) reasons.push('This Mac: model, memory capacity or supplied-audio support is unavailable');
+ else candidates.push({ modelId, peerId: null, load: jobs.filter((job) => !job.params?.remoteMedia && !['grok', 'fal', 'reactor', 'codex', 'agy'].includes(job.params?.mode)).length });
+ }
+ }
+ // Probe only explicitly selected and already allowlisted peers. Status alone
+ // is advisory; prepareRemoteMediaJob and provider admission recheck it.
+ for (const selected of pool.peers) {
+ try {
+ const { capability, status } = await resolveFederatedMediaProvider(peers.find((peer) => peer.id === selected.peerId),
+ { kind: 'video', engine: 'local', modelId: selected.modelId });
+ if (capability.hardwareEligible !== true || !capability.memory?.requiredGb
+ || capability.memory.requiredGb > capability.memory.totalGb || capability.memory.requiredGb > capability.memory.freeGb) {
+ throw new Error('Measured memory capacity is insufficient or unknown');
+ }
+ if (!capability.inputAssets?.roles?.includes('sourceImage')) throw new Error('This model cannot consume the selected frame');
+ if (!capability.supportedModes?.includes(requestedMode)) throw new Error('The requested shot mode is unavailable or unknown');
+ if (suppliedAudio && (!status.features?.includes('sourceAudio') || !capability.sourceAudio)) throw new Error('Supplied audio is not negotiated');
+ if (status.queue.maintenanceHeld !== false) throw new Error('Maintenance state is held or unknown; update the peer');
+ const assigned = jobs.filter((job) => job.params?.remoteMedia?.peerId === selected.peerId).length;
+ candidates.push({ ...selected, load: Math.max(assigned, status.queue.totalActive) });
+ } catch (error) { reasons.push(`${selected.modelId}: ${error.message}`); }
+ }
+ candidates.sort((a, b) => a.load - b.load); // stable ties follow the saved order
+ const selected = candidates[0];
+ if (!selected) refuse('No selected render node is eligible; no job was submitted', reasons);
+ return { ...body, backend: 'local', modelId: selected.modelId,
+ ...(selected.peerId ? { mediaProviderPeerId: selected.peerId } : {}),
+ mode: suppliedAudio ? 'a2v' : 'image',
+ _suppliedAudio: suppliedAudio,
+ // Chosen once before enqueue; retries keep this exact node/model.
+ };
+}
diff --git a/server/services/musicVideo/renderPool.test.js b/server/services/musicVideo/renderPool.test.js
new file mode 100644
index 0000000000..9fa22a4c37
--- /dev/null
+++ b/server/services/musicVideo/renderPool.test.js
@@ -0,0 +1,92 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { applyProjectRenderPool } from './renderPool.js';
+import { musicVideoVideoSettingsSchema } from '../../lib/musicVideoValidation.js';
+import { stripMusicVideoLocalRenderPins } from '../../lib/syncWire.js';
+import { mergeProjectRecord } from './projectsLogic.js';
+
+const m = vi.hoisted(() => ({ project: null, jobs: [], local: null, resolve: vi.fn() }));
+vi.mock('./projects.js', () => ({ getProject: async () => m.project }));
+vi.mock('../instances.js', () => ({ getPeers: async () => [{ id: 'peer-a' }, { id: 'peer-b' }] }));
+vi.mock('../federatedMediaConsumer.js', () => ({ resolveFederatedMediaProvider: (...args) => m.resolve(...args) }));
+vi.mock('../mediaJobQueue/index.js', () => ({ listJobs: () => m.jobs }));
+vi.mock('../federatedMediaProvider.js', () => ({ getLocalVideoRenderCapability: async () => m.local }));
+const body = () => ({ prompt: 'Example shot', backend: 'local', mode: 'image', musicVideo: { projectId: 'project', sceneId: 'scene' } });
+const ready = () => ({ capability: { hardwareEligible: true, ready: true, memory: { requiredGb: 12, totalGb: 48, freeGb: 32 },
+ inputAssets: { roles: ['sourceImage'] }, supportedModes: ['image', 'a2v'], sourceAudio: { requiresImage: true } },
+status: { features: ['sourceAudio'], queue: { totalActive: 0, maintenanceHeld: false } } });
+beforeEach(() => {
+ m.project = { id: 'project', scenes: [{ sceneId: 'scene', startSec: 0, endSec: 1 }],
+ videoSettings: { backend: 'local', generationMode: 'image', renderPool: { mode: 'peers', peers: [
+ { peerId: 'peer-a', modelId: 'model-a' }, { peerId: 'peer-b', modelId: 'model-b' },
+ ] } } };
+ m.local = null; m.jobs = []; m.resolve.mockReset().mockResolvedValue(ready());
+});
+describe('project render-pool submission policy', () => {
+ it('assigns the least occupied explicit peer/model and never modifies grants', async () => {
+ m.jobs = [{ status: 'queued', params: { remoteMedia: { peerId: 'peer-a' } } }];
+ expect(await applyProjectRenderPool(body())).toMatchObject({ mediaProviderPeerId: 'peer-b', modelId: 'model-b' });
+ expect(m.resolve).toHaveBeenCalledWith({ id: 'peer-b' }, { kind: 'video', engine: 'local', modelId: 'model-b' });
+ });
+ it('refuses ready-but-too-large models, unknown maintenance and missing audio negotiation', async () => {
+ const fail = ready(); fail.capability.memory.requiredGb = 96;
+ m.resolve.mockResolvedValue(fail);
+ await expect(applyProjectRenderPool(body())).rejects.toMatchObject({ code: 'MUSIC_VIDEO_RENDER_POOL_UNAVAILABLE' });
+ const unknown = ready(); delete unknown.status.queue.maintenanceHeld;
+ m.resolve.mockResolvedValue(unknown);
+ await expect(applyProjectRenderPool(body())).rejects.toThrow(/No selected render node/);
+ m.project.videoSettings.generationMode = 'suppliedAudio';
+ const oldPeer = ready(); oldPeer.status.features = [];
+ m.resolve.mockResolvedValue(oldPeer);
+ await expect(applyProjectRenderPool(body())).rejects.toThrow(/No selected render node/);
+ });
+ it('allows Both to choose an eligible selected peer when this Mac is ineligible, never an unselected fallback', async () => {
+ m.project.videoSettings.renderPool.mode = 'both'; m.project.videoSettings.modelId = 'local-model';
+ expect(await applyProjectRenderPool(body())).toMatchObject({ mediaProviderPeerId: 'peer-a' });
+ m.resolve.mockRejectedValue(new Error('not allowlisted'));
+ await expect(applyProjectRenderPool(body())).rejects.toThrow(/No selected render node/);
+ });
+ it('chooses a ready explicit local model in Both and excludes it when its installed runtime is unavailable', async () => {
+ m.project.videoSettings.renderPool.mode = 'both'; m.project.videoSettings.modelId = 'local-model';
+ m.local = ready().capability;
+ const busyPeer = ready(); busyPeer.status.queue.totalActive = 1;
+ m.resolve.mockResolvedValue(busyPeer);
+ const local = await applyProjectRenderPool(body());
+ expect(local.modelId).toBe('local-model');
+ expect(local.mediaProviderPeerId).toBeUndefined();
+ m.local.ready = false;
+ expect(await applyProjectRenderPool(body())).toMatchObject({ mediaProviderPeerId: 'peer-a', modelId: 'model-a' });
+ });
+ it('excludes a frame-capable node that cannot run the requested shot mode, including Both local placement', async () => {
+ m.project.videoSettings.renderPool.mode = 'both'; m.project.videoSettings.modelId = 'local-model';
+ m.local = ready().capability; m.local.supportedModes = ['text', 'fflf'];
+ m.resolve.mockImplementation(async (peer) => {
+ const result = ready();
+ if (peer.id === 'peer-a') result.capability.supportedModes = ['text', 'fflf'];
+ return result;
+ });
+ expect(await applyProjectRenderPool(body())).toMatchObject({ mediaProviderPeerId: 'peer-b', modelId: 'model-b' });
+ m.resolve.mockImplementation(async () => { const result = ready(); delete result.capability.supportedModes; return result; });
+ await expect(applyProjectRenderPool(body())).rejects.toThrow(/No selected render node/);
+ });
+ it('refuses performance, production-budget substitutions, and individual target overrides', async () => {
+ m.project.scenes[0].shotMode = 'performance';
+ await expect(applyProjectRenderPool(body())).rejects.toThrow(/lip-sync/);
+ m.project.scenes[0].shotMode = 'cutaway';
+ await expect(applyProjectRenderPool({ ...body(), musicVideo: { ...body().musicVideo, productionRunId: 'run' } })).rejects.toThrow(/production runs/);
+ m.project.videoSettings.renderPool.mode = 'local';
+ await expect(applyProjectRenderPool({ ...body(), mediaProviderPeerId: 'peer-a' })).rejects.toThrow(/saved project/);
+ m.project.videoSettings.generationMode = 'suppliedAudio';
+ await expect(applyProjectRenderPool({ ...body(), backend: 'fal' })).rejects.toThrow(/explicitly/);
+ });
+ it('rejects an empty or duplicated remote pool at the project write schema', () => {
+ expect(musicVideoVideoSettingsSchema.safeParse({ renderPool: { mode: 'peers', peers: [] } }).success).toBe(false);
+ });
+ it('keeps node selections machine-local on outbound and inbound project sync', () => {
+ const pool = m.project.videoSettings.renderPool;
+ expect(stripMusicVideoLocalRenderPins(m.project, { stripVideoBackend: false }).videoSettings.renderPool).toBeUndefined();
+ const remote = { ...m.project, updatedAt: '2026-10-02T00:00:00.000Z' };
+ expect(mergeProjectRecord(null, remote).next.videoSettings.renderPool).toBeUndefined();
+ const local = { ...m.project, updatedAt: '2026-10-01T00:00:00.000Z' };
+ expect(mergeProjectRecord(local, remote).next.videoSettings.renderPool).toEqual(pool);
+ });
+});
diff --git a/server/services/musicVideo/revisionService.js b/server/services/musicVideo/revisionService.js
index 2daea47537..9bb8c51226 100644
--- a/server/services/musicVideo/revisionService.js
+++ b/server/services/musicVideo/revisionService.js
@@ -157,7 +157,9 @@ export async function cancelRevision(projectId, revisionId, { alsoOnProject = nu
async function dependencyImpactFor(project) {
- const performanceScenes = (project.scenes || []).filter((scene) => scene.shotMode === 'performance' && scene.videoHistoryId);
+ const performanceScenes = (project.scenes || []).filter((scene) => scene.videoHistoryId
+ && (scene.shotMode === 'performance' || (!['still', 'card'].includes(scene.visualLayer)
+ && scene.takes?.some((take) => take.assetId === scene.videoHistoryId && take.shotInstruction?.audioConditioning))));
let performanceChanges = [];
if (performanceScenes.length) {
const { resolveMasterAudioPath } = await import('./render.js');
diff --git a/server/services/videoGen/generateVideo.js b/server/services/videoGen/generateVideo.js
index 2ce69c1e43..f75534e511 100644
--- a/server/services/videoGen/generateVideo.js
+++ b/server/services/videoGen/generateVideo.js
@@ -20,6 +20,7 @@ import { randomUUID } from 'crypto';
import { ensureDir, PATHS, rmGuarded } from '../../lib/fileUtils.js';
import { ServerError } from '../../lib/errorHandler.js';
import { maintenance } from '../../lib/maintenanceAdmission.js';
+import { federatedSourceAudioSchema } from '../../lib/federatedMediaWire.js';
import { wan22FrameCountError } from './wan22Controls.js';
import {
isDefaultI2vReferenceMode, normalizeI2vReferenceMode, resolveI2vReferenceStrength,
@@ -151,7 +152,8 @@ export const listVideoModels = () => getVideoModels().map(decorateVideoModel);
export const defaultVideoModelId = (capabilities, preferredId) => getDefaultVideoModelId(capabilities, preferredId);
-export async function generateVideo({ pythonPath, prompt, negativePrompt = '', modelId, width = null, height = null, numFrames = null, fps = 24, steps, guidanceScale, seed, batchSize = 1, tiling = 'auto', disableAudio = false, sourceImagePath = null, uploadedTempPath = null, uploadedTempPaths = [], lastImagePath = null, keyframes = null, extendFromVideoPath = null, audioFilePath = null, audioStartSec = null, mode = null, imageStrength = null, i2vReferenceMode = null, loras = null, icReferencePaths = null, icStrength = null, icAttentionStrength = null, icSkipStage2 = false, textEncoderId = null, speedProfileId = null, draftDecode = null, streamingMode = null, visualConditioning = null, hidden = false, displaySleep = null, jobId: providedJobId = null }) {
+export async function generateVideo({ pythonPath, prompt, negativePrompt = '', modelId, width = null, height = null, numFrames = null, fps = 24, steps, guidanceScale, seed, batchSize = 1, tiling = 'auto', disableAudio = false, sourceImagePath = null, uploadedTempPath = null, uploadedTempPaths = [], lastImagePath = null, keyframes = null, extendFromVideoPath = null, audioFilePath = null, audioStartSec = null, audioConditioning = null, mode = null, imageStrength = null, i2vReferenceMode = null, loras = null, icReferencePaths = null, icStrength = null, icAttentionStrength = null, icSkipStage2 = false, textEncoderId = null, speedProfileId = null, draftDecode = null, streamingMode = null, visualConditioning = null, hidden = false, displaySleep = null, jobId: providedJobId = null }) {
+ const sourceAudioProvenance = audioConditioning == null ? null : federatedSourceAudioSchema.parse(audioConditioning);
uploadedTempPaths = Array.isArray(uploadedTempPaths) ? uploadedTempPaths : [];
if (!prompt?.trim()) throw new ServerError('Prompt is required', { status: 400, code: 'VALIDATION_ERROR' });
// Single-flight is now enforced by the mediaJobQueue worker upstream — only
@@ -513,6 +515,7 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m
guidanceScale: actualGuidance,
tiling,
disableAudio,
+ ...(sourceAudioProvenance ? { audioConditioning: sourceAudioProvenance } : {}),
// Which prompt conditioner read this prompt. Only recorded when it wasn't
// the stock one, so pre-feature history and every unswapped render stay
// byte-identical — and so a Remix of a stock render can't resurrect an
diff --git a/server/services/videoGen/local.test.js b/server/services/videoGen/local.test.js
index 97d53a9e1b..5b90037a62 100644
--- a/server/services/videoGen/local.test.js
+++ b/server/services/videoGen/local.test.js
@@ -5799,6 +5799,18 @@ describe('generateVideo — LTX-2.5 speed profile (#4875)', () => {
expect(meta.stage2Steps).toBeUndefined();
});
+ it('preserves the exact supplied-audio provenance in renderer history metadata', async () => {
+ const audioConditioning = { sourceSha256: 'a'.repeat(64), clipSha256: 'b'.repeat(64),
+ sampleRate: 48000, channels: 2, startSample: 96000, endSample: 144000, sampleCount: 48000 };
+ const meta = await metaFor('supplied-audio-provenance', {
+ mode: 'a2v', audioFilePath: '/mock/data/uploads/example.wav', audioStartSec: 0, audioConditioning,
+ });
+ expect(meta.audioConditioning).toEqual(audioConditioning);
+ expect(meta.mode).toBe('a2v');
+ await expect(metaFor('supplied-audio-malformed', { audioConditioning: { ...audioConditioning, endSample: 144001 } }))
+ .rejects.toThrow();
+ });
+
it('stamps nothing when the profile was declined', async () => {
const meta = await metaFor('sp-meta-declined', { speedProfileId: 'turbo' });
expect(meta.speedProfileId).toBeUndefined();
diff --git a/server/services/videoGen/remote.js b/server/services/videoGen/remote.js
index 5918a8b0f1..458b88d5e8 100644
--- a/server/services/videoGen/remote.js
+++ b/server/services/videoGen/remote.js
@@ -96,6 +96,7 @@ const executor = createRemoteMediaExecutor({
// the federation, never a hostname, address, or credential.
federatedPeerId: peerId,
federatedJobId: remoteJob.id,
+ ...(request.audioConditioning ? { audioConditioning: request.audioConditioning } : {}),
createdAt,
provenance: provenanceForRender({
model: {
diff --git a/server/services/videoGen/remote.test.js b/server/services/videoGen/remote.test.js
index 8fe3f18068..1e7bbf99d0 100644
--- a/server/services/videoGen/remote.test.js
+++ b/server/services/videoGen/remote.test.js
@@ -186,6 +186,7 @@ describe('federated video consumer adapter', () => {
type: 'completed',
event: {
generationId: LOCAL_JOB_ID,
+ remoteInputsDisposable: true,
filename: `${LOCAL_JOB_ID}.mp4`,
path: `/data/videos/${LOCAL_JOB_ID}.mp4`,
thumbnail: `${LOCAL_JOB_ID}.jpg`,
@@ -269,4 +270,34 @@ describe('federated video consumer adapter', () => {
expect(outcome.event.error).toMatch(/chained video renders cannot run on a federated media provider/i);
expect(transport.fetch).not.toHaveBeenCalled();
});
+
+ it.each(['failed', 'canceled'])('marks inputs disposable only after a known provider %s outcome', async (status) => {
+ transport.fetch.mockResolvedValue(jsonResponse(providerJob(status), 200));
+ const terminal = captureTerminal(LOCAL_JOB_ID);
+ await generateVideo(params());
+ expect(await terminal).toMatchObject({ type: 'failed', event: { remoteInputsDisposable: true } });
+ });
+
+ it('retains replay inputs after an uncertain submission or malformed recovery metadata', async () => {
+ transport.fetch.mockRejectedValue(new Error('Uncertain transport response'));
+ let terminal = captureTerminal(LOCAL_JOB_ID);
+ await generateVideo(params());
+ expect(await terminal).toMatchObject({ type: 'failed', event: { remoteInputsDisposable: false } });
+ terminal = captureTerminal(LOCAL_JOB_ID);
+ await generateVideo(params({ remoteMedia: { reconcile: true } }));
+ expect((await terminal).event.remoteInputsDisposable).not.toBe(true);
+ });
+
+ it('retains inputs when local finalization fails after downloading a verified remote result', async () => {
+ const mp4 = Buffer.from('fixture verified video');
+ const digest = sha256(mp4);
+ transport.fetch.mockImplementation(async (url) => url.endsWith('/jobs')
+ ? jsonResponse(providerJob('completed', { result: { available: true, mimeType: 'video/mp4', sizeBytes: mp4.length,
+ sha256: digest, downloadUrl: '/ignored', engine: 'local', modelId: 'ltx2', durationSec: 5 } }))
+ : new Response(mp4, { headers: { 'Content-Length': String(mp4.length), 'Content-Type': 'video/mp4', 'X-Content-SHA256': digest } }));
+ ffmpeg.faststart.mockRejectedValueOnce(new Error('fixture finalization failed'));
+ const terminal = captureTerminal(LOCAL_JOB_ID);
+ await generateVideo(params());
+ expect(await terminal).toMatchObject({ type: 'failed', event: { remoteInputsDisposable: false } });
+ });
});
diff --git a/server/services/videoGen/submitJob.js b/server/services/videoGen/submitJob.js
index ccc963cd6a..f670d047c0 100644
--- a/server/services/videoGen/submitJob.js
+++ b/server/services/videoGen/submitJob.js
@@ -5,6 +5,8 @@
*/
import { unlink } from 'fs/promises';
+import { maintenance } from '../../lib/maintenanceAdmission.js';
+import { discardSourceAudioWindow } from '../federatedMedia/sourceAudio.js';
import { ServerError } from '../../lib/errorHandler.js';
import { buildFederatedMediaRequest } from '../../lib/federatedMediaRequest.js';
import { asFableLoomRenderSettings } from '../../lib/fableLoomProduction.js';
@@ -15,7 +17,7 @@ import { isDefaultI2vReferenceMode } from '../../lib/videoReferenceModes.js';
import { isDefaultSpeedProfile } from '../../lib/videoSpeedProfiles.js';
import { isStockTextEncoder } from '../../lib/videoTextEncoders.js';
import { collectRemoteInputAssets } from '../federatedMedia/inputAssets.js';
-import { prepareRemoteMediaJob } from '../federatedMedia/remoteSubmission.js';
+import { prepareRemoteMediaJob, negotiateVideoConstraints } from '../federatedMedia/remoteSubmission.js';
import { getLoom } from '../fableLoom/records.js';
import {
compileFableLoomVisualRequest,
@@ -44,6 +46,11 @@ const submitValidatedVideoGenJob = async (body, uploads) => {
}
}
+ if (body.musicVideo) {
+ const { applyProjectRenderPool } = await import('../musicVideo/renderPool.js');
+ body = await applyProjectRenderPool(body);
+ }
+ let prepared;
// Federated render (#4348): submit to the selected peer instead of running
// locally. Handled before local preparation, which resolves this machine's
// backend and stages uploads a remote render can never use.
@@ -65,7 +72,6 @@ const submitValidatedVideoGenJob = async (body, uploads) => {
// Inspire is a per-runtime capability the caller cannot prove for a peer.
// Refuse it instead of returning an anchored clip under an Inspire label.
['a loose reference mode', !isDefaultI2vReferenceMode(body.i2vReferenceMode)],
- ['a music-video scene tag', body.musicVideo],
].filter(([, present]) => present).map(([label]) => label);
if (unsupported.length) {
throw new ServerError(
@@ -75,7 +81,7 @@ const submitValidatedVideoGenJob = async (body, uploads) => {
}
const inputAssets = collectRemoteInputAssets('video', body);
- const impliedMode = body.lastImageFile ? 'fflf' : body.sourceImageFile ? 'image' : 'text';
+ const impliedMode = body._suppliedAudio ? 'a2v' : body.lastImageFile ? 'fflf' : body.sourceImageFile ? 'image' : 'text';
if (body.mode !== undefined && body.mode !== impliedMode) {
throw new ServerError(
`A federated render mode must match its conditioning — this request asks for '${body.mode}' but supplies ${impliedMode === 'text' ? 'no frames' : `a ${impliedMode} frame set`}. Render locally instead.`,
@@ -89,34 +95,64 @@ const submitValidatedVideoGenJob = async (body, uploads) => {
);
}
+ const { resolveGalleryImage } = await import('../../lib/pathSafety.js');
const request = buildFederatedMediaRequest({ kind: 'video', params: body });
- const { peer, remoteMedia } = await prepareRemoteMediaJob({
- peerId: body.mediaProviderPeerId,
- kind: 'video',
- request,
- inputAssets,
- });
- const { jobId, position, status } = await enqueueJob({
- kind: 'video',
- params: { remoteMedia },
+ // Negotiate dimensions/frames before slicing audio. Audio is never padded,
+ // truncated, or silently dropped to fit a different peer after submission.
+ if (body._suppliedAudio) inputAssets.push({ role: 'sourceAudio', path: 'pending.wav' });
+ const selected = await prepareRemoteMediaJob({ peerId: body.mediaProviderPeerId, kind: 'video', request, inputAssets });
+ const sourceImagePath = body.sourceImageFile ? resolveGalleryImage(body.sourceImageFile) : null;
+ let audio = null;
+ if (body._suppliedAudio) {
+ const [{ getProject }, { prepareSourceAudioWindow, sourceAudioVideoRequest }] = await Promise.all([
+ import('../musicVideo/projects.js'), import('../federatedMedia/sourceAudio.js'),
+ ]);
+ const project = await getProject(body.musicVideo.projectId);
+ const scene = project?.scenes?.find((entry) => entry.sceneId === body.musicVideo.sceneId);
+ selected.request = negotiateVideoConstraints(sourceAudioVideoRequest(scene, selected.capability, selected.request), selected.capability);
+ selected.remoteMedia.request = selected.request;
+ audio = await prepareSourceAudioWindow({ project, scene, ...selected.request });
+ selected.remoteMedia.request.audioConditioning = audio.audioConditioning;
+ selected.remoteMedia.inputAssets = collectRemoteInputAssets('video', { ...body, ...audio });
+ }
+ prepared = { backend: 'remote', sourceImagePath, remoteMedia: selected.remoteMedia, audio,
+ cleanupStaged: async () => { if (audio) await discardSourceAudioWindow(audio.audioFilePath); } };
+ } else {
+ if (body._suppliedAudio) {
+ const [{ getProject }, { resolveVideoModelSelection }, { sourceAudioVideoRequest, supportsSourceAudioWindow }] = await Promise.all([
+ import('../musicVideo/projects.js'), import('./modelSelection.js'), import('../federatedMedia/sourceAudio.js'),
+ ]);
+ const project = await getProject(body.musicVideo.projectId);
+ const scene = project?.scenes?.find((entry) => entry.sceneId === body.musicVideo.sceneId);
+ const { model, modelId } = await resolveVideoModelSelection(body.modelId);
+ if (!supportsSourceAudioWindow(model)) {
+ throw new ServerError('Supplied song windows currently require an LTX MLX model with audio conditioning', { status: 400, code: 'MUSIC_VIDEO_AUDIO_UNSUPPORTED' });
+ }
+ body = sourceAudioVideoRequest(scene, model, { ...body, modelId });
+ }
+ prepared = await prepareVideoGenParams({ body, uploads, localOnlyParamKeys: VIDEO_GEN_LOCAL_ONLY_FIELD_NAMES });
+ }
+ if (body._suppliedAudio && prepared.backend === 'local') {
+ const [{ getProject }, { prepareSourceAudioWindow, supportsSourceAudioWindow }] = await Promise.all([
+ import('../musicVideo/projects.js'), import('../federatedMedia/sourceAudio.js'),
+ ]);
+ if (!supportsSourceAudioWindow(prepared.effectiveModel)) {
+ await prepared.cleanupStaged();
+ throw new ServerError('Supplied song windows currently require an LTX MLX model with audio conditioning', { status: 400, code: 'MUSIC_VIDEO_AUDIO_UNSUPPORTED' });
+ }
+ const project = await getProject(body.musicVideo.projectId);
+ const scene = project?.scenes?.find((entry) => entry.sceneId === body.musicVideo.sceneId);
+ const audio = await prepareSourceAudioWindow({ project, scene,
+ numFrames: prepared.effectiveNumFrames, fps: body.fps || 24 }).catch(async (error) => {
+ await prepared.cleanupStaged(); throw error;
});
- return {
- jobId,
- generationId: jobId,
- filename: `${jobId}.mp4`,
- model: request.modelId,
- mode: null,
- mediaProviderPeerId: peer.id,
- status,
- position,
- };
+ prepared.audio = audio;
+ prepared.audioFilePath = audio.audioFilePath;
+ prepared.uploadedTempPaths = [...(prepared.uploadedTempPaths || []), audio.audioFilePath];
+ const priorCleanup = prepared.cleanupStaged;
+ prepared.cleanupStaged = async () => { await priorCleanup(); await discardSourceAudioWindow(audio.audioFilePath); };
+ body.audioStartSec = 0;
}
-
- const prepared = await prepareVideoGenParams({
- body,
- uploads,
- localOnlyParamKeys: VIDEO_GEN_LOCAL_ONLY_FIELD_NAMES,
- });
const { backend, cleanupStaged } = prepared;
if (body.fableLoom) {
@@ -224,7 +260,10 @@ const submitValidatedVideoGenJob = async (body, uploads) => {
const scene = project?.scenes?.find((entry) => entry.sceneId === body.musicVideo.sceneId);
assertShotActionContract(scene);
params.prompt = withShotActionPrompt(params.prompt, project, scene, { offsetSec: performance?.shotInstruction?.edit?.inSec || 0 });
- const interval = performance?.shotInstruction?.songInterval;
+ const interval = performance?.shotInstruction?.songInterval || prepared.audio?.songInterval;
+ if (params.audioConditioning && Math.round(scene?.startSec * 48000) !== params.audioConditioning.startSample) {
+ throw new ServerError('Scene timing changed while source audio was prepared', { status: 409, code: 'MUSIC_VIDEO_SHOT_TIMING_CHANGED' });
+ }
if (interval && (interval.startSec !== scene?.startSec || interval.endSec !== scene?.endSec)) {
throw new ServerError('The shot timing changed while its performance audio was prepared — submit again', { status: 409, code: 'MUSIC_VIDEO_SHOT_TIMING_CHANGED' });
}
@@ -241,9 +280,19 @@ const submitValidatedVideoGenJob = async (body, uploads) => {
actionContract: structuredClone(scene.direction.actionContract),
};
}
- const { captureTakeDependencies } = await import('../../lib/musicVideoDependencies.js');
+ const { captureTakeDependencies, musicVideoDependencyChanges } = await import('../../lib/musicVideoDependencies.js');
+ if (prepared.audio && musicVideoDependencyChanges(project, prepared.audio.audioDependencies).length) {
+ throw new ServerError('The source song changed while supplied audio was prepared', { status: 409, code: 'MUSIC_VIDEO_AUDIO_SOURCE_CHANGED' });
+ }
+ if (prepared.audio) {
+ const { assertCurrentSourceAudioWindow } = await import('../federatedMedia/sourceAudio.js');
+ await assertCurrentSourceAudioWindow(project, prepared.audio.audioConditioning);
+ }
const { basename } = await import('path');
- if (scene) params.musicVideoDependencies = captureTakeDependencies(scene, prepared.sourceImagePath ? basename(prepared.sourceImagePath) : null);
+ if (scene) {
+ params.musicVideoDependencies = captureTakeDependencies(scene, prepared.sourceImagePath ? basename(prepared.sourceImagePath) : null);
+ if (prepared.audio) params.musicVideoDependencies.references.push(...prepared.audio.audioDependencies.references);
+ }
// #10157: a board-started (manual or auto-review) fal clip records the
// estimate it was priced at so project spend counts it. A production-run
// step is already charged to the run's own usage, so it is skipped.
@@ -268,10 +317,28 @@ const submitValidatedVideoGenJob = async (body, uploads) => {
await assertRevisionOpen(body.musicVideo.projectId, body.musicVideo.revisionId, { sceneId: body.musicVideo.sceneId, kind: 'video' });
repairReserved = Boolean(performance?.shotInstruction?.repair);
}
+ if (params.remoteMedia && params.musicVideo) {
+ // Prompt augmentation still passes the strict wire boundary before any upload.
+ params.remoteMedia.request = buildFederatedMediaRequest({ kind: 'video', params: { ...params.remoteMedia.request, prompt: params.prompt } });
+ }
+ if (params.remoteMedia && !params.musicVideo) delete params.prompt;
return enqueueJob({ kind: 'video', params });
},
);
+ if (backend === 'remote') {
+ const { remoteMedia, audio } = prepared;
+ const { jobId, position, status } = await enqueue({
+ prompt: body.prompt, remoteMedia, ...(body.musicVideo ? { musicVideo: body.musicVideo } : {}),
+ ...(body.musicVideo && prepared.sourceImagePath ? { sourceImagePath: prepared.sourceImagePath } : {}),
+ ...(body.musicVideo ? { ...remoteMedia.request } : {}),
+ ...(audio ? { audioConditioning: audio.audioConditioning, uploadedTempPaths: [audio.audioFilePath],
+ shotInstruction: { version: 1, shotMode: 'cutaway', songInterval: audio.songInterval, audioConditioning: audio.audioConditioning } } : {}),
+ });
+ return { jobId, generationId: jobId, filename: `${jobId}.mp4`, model: remoteMedia.request.modelId,
+ mode: null, mediaProviderPeerId: remoteMedia.peerId, status, position };
+ }
+
const hosted = HOSTED_VIDEO_SUBMISSIONS[backend];
if (hosted) {
const { sourceImagePath, uploadedTempPath } = prepared;
@@ -339,6 +406,8 @@ const submitValidatedVideoGenJob = async (body, uploads) => {
sourceImagePath,
audioFilePath,
audioStartSec: body.audioStartSec,
+ ...(prepared.audio ? { audioConditioning: prepared.audio.audioConditioning,
+ shotInstruction: { version: 1, shotMode: 'cutaway', songInterval: prepared.audio.songInterval, audioConditioning: prepared.audio.audioConditioning } } : {}),
uploadedTempPath,
uploadedTempPaths,
lastImagePath,
@@ -377,6 +446,7 @@ const submitValidatedVideoGenJob = async (body, uploads) => {
* @param {object} uploads - multipart uploads keyed by field name
*/
export async function submitVideoGenJob(body, uploads) {
+ const submit = async () => {
try {
return await submitValidatedVideoGenJob(body, uploads);
} catch (err) {
@@ -386,4 +456,8 @@ export async function submitVideoGenJob(body, uploads) {
await cleanupMultipartTemp(uploads).catch(() => {});
throw err;
}
+ };
+ return body.musicVideo
+ ? maintenance.run('media-input', 'Music Video submission', submit, { continuation: true })
+ : submit();
}
diff --git a/server/services/videoGen/submitJob.test.js b/server/services/videoGen/submitJob.test.js
index a618bd2ad7..3a879bf956 100644
--- a/server/services/videoGen/submitJob.test.js
+++ b/server/services/videoGen/submitJob.test.js
@@ -1,5 +1,7 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
+vi.mock('../../lib/maintenanceAdmission.js', () => ({ maintenance: { run: (_kind, _resource, fn) => fn() } }));
+
const mocks = vi.hoisted(() => ({
buildFederatedMediaRequest: vi.fn(),
cleanupMultipartTemp: vi.fn(async () => {}),
diff --git a/server/services/videoGen/submitMusicVideoPool.test.js b/server/services/videoGen/submitMusicVideoPool.test.js
new file mode 100644
index 0000000000..74a20d9f02
--- /dev/null
+++ b/server/services/videoGen/submitMusicVideoPool.test.js
@@ -0,0 +1,80 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { submitVideoGenJob } from './submitJob.js';
+import { captureMusicVideoEvidence, musicVideoDependencyChanges } from '../../lib/musicVideoDependencies.js';
+
+const peerId = '00000000-0000-4000-8000-000000000123';
+const m = vi.hoisted(() => ({ project: null, enqueue: vi.fn(), slice: vi.fn(), discard: vi.fn(), revision: vi.fn(), currentAudio: vi.fn() }));
+vi.mock('../../lib/maintenanceAdmission.js', () => ({ maintenance: { run: (_kind, _resource, fn) => fn() } }));
+vi.mock('../musicVideo/projects.js', () => ({ getProject: async () => m.project }));
+vi.mock('../instances.js', () => ({ getPeers: async () => [{ id: '00000000-0000-4000-8000-000000000123' }] }));
+vi.mock('../mediaJobQueue/index.js', () => ({ listJobs: () => [], enqueueJob: (...args) => m.enqueue(...args) }));
+vi.mock('../federatedMediaConsumer.js', () => ({ resolveFederatedMediaProvider: async () => ({
+ capability: { hardwareEligible: true, memory: { requiredGb: 1, totalGb: 64, freeGb: 48 },
+ inputAssets: { roles: ['sourceImage'] }, supportedModes: ['image', 'a2v'], sourceAudio: { requiresImage: true } },
+ status: { features: ['sourceAudio'], queue: { totalActive: 0, maintenanceHeld: false } },
+}) }));
+vi.mock('../federatedMedia/remoteSubmission.js', async (load) => ({ ...await load(),
+ prepareRemoteMediaJob: async ({ peerId, request, inputAssets }) => ({ request,
+ capability: { fpsOptions: [24], frameStride: 8, maxNumFrames: 121 },
+ remoteMedia: { wireVersion: 1, peerId, request, inputAssets },
+ }),
+}));
+vi.mock('../federatedMedia/sourceAudio.js', async (load) => ({ ...await load(),
+ prepareSourceAudioWindow: (...args) => m.slice(...args), discardSourceAudioWindow: (...args) => m.discard(...args),
+ assertCurrentSourceAudioWindow: (...args) => m.currentAudio(...args),
+}));
+vi.mock('../musicVideo/performanceShot.js', () => ({ preparePerformanceShot: async () => null }));
+vi.mock('../musicVideo/revisionService.js', () => ({ assertRevisionOpen: (...args) => m.revision(...args) }));
+
+const audio = { audioFilePath: '/example/uploads/mv-source-audio-00000000-0000-4000-8000-000000000456.wav',
+ songInterval: { startSec: 2, endSec: 3 },
+ audioConditioning: { sourceSha256: 'a'.repeat(64), clipSha256: 'b'.repeat(64), sampleRate: 48000,
+ channels: 2, startSample: 96000, endSample: 144000, sampleCount: 48000 } };
+const body = () => ({ prompt: 'A lighthouse in fog', backend: 'local', mode: 'a2v', sourceImageFile: 'example-frame.png',
+ fps: 24, numFrames: 25, musicVideo: { projectId: 'project', sceneId: 'scene', revisionId: 'revision' } });
+beforeEach(() => {
+ vi.clearAllMocks();
+ m.project = { id: 'project', videoSettings: { generationMode: 'suppliedAudio',
+ renderPool: { mode: 'peers', peers: [{ peerId, modelId: 'ltx-example' }] } },
+ scenes: [{ sceneId: 'scene', referenceImageId: 'example-frame.png', prompt: 'A lighthouse in fog', startSec: 2, endSec: 3, shotMode: 'cutaway' }] };
+ m.slice.mockResolvedValue({ ...structuredClone(audio), audioDependencies: captureMusicVideoEvidence(m.project, { sceneIds: [], composition: false }) });
+ m.enqueue.mockResolvedValue({ jobId: 'job', status: 'queued', position: 1 });
+ m.revision.mockResolvedValue(undefined);
+ m.currentAudio.mockResolvedValue(undefined);
+});
+
+describe('Music Video supplied-audio submission integration', () => {
+ it('keeps the selected target, exact provenance, scene binding and revision guard in the normal queue path', async () => {
+ await expect(submitVideoGenJob(body(), {})).resolves.toMatchObject({ mediaProviderPeerId: peerId, status: 'queued' });
+ expect(m.slice).toHaveBeenCalledWith(expect.objectContaining({ fps: 24, numFrames: 25 }));
+ expect(m.revision).toHaveBeenCalledWith('project', 'revision', { sceneId: 'scene', kind: 'video' });
+ const { params } = m.enqueue.mock.calls[0][0];
+ expect(params).toMatchObject({ musicVideo: body().musicVideo, audioConditioning: audio.audioConditioning,
+ shotInstruction: { songInterval: audio.songInterval },
+ remoteMedia: { peerId, request: { modelId: 'ltx-example', fps: 24, numFrames: 25, audioConditioning: audio.audioConditioning } },
+ uploadedTempPaths: [audio.audioFilePath] });
+ expect(params.musicVideoDependencies.references).toEqual(expect.arrayContaining([expect.objectContaining({ role: 'song' })]));
+ expect(musicVideoDependencyChanges({ ...m.project, trackId: 'changed-song' }, params.musicVideoDependencies)).toEqual(expect.arrayContaining([expect.objectContaining({ role: 'song' })]));
+ expect(params.remoteMedia.inputAssets).toContainEqual({ role: 'sourceAudio', path: audio.audioFilePath });
+ expect(m.discard).not.toHaveBeenCalled();
+ });
+ it('releases the owned slice when a revision closes before the queue write', async () => {
+ m.revision.mockRejectedValueOnce(Object.assign(new Error('Revision closed'), { code: 'REVISION_CLOSED' }));
+ await expect(submitVideoGenJob(body(), {})).rejects.toMatchObject({ code: 'REVISION_CLOSED' });
+ expect(m.enqueue).not.toHaveBeenCalled();
+ expect(m.discard).toHaveBeenCalledWith(audio.audioFilePath);
+ });
+ it('refuses changed scene timing after audio preparation without dispatching', async () => {
+ m.slice.mockImplementationOnce(async () => { m.project.scenes[0].startSec = 2.5; return structuredClone(audio); });
+ await expect(submitVideoGenJob(body(), {})).rejects.toMatchObject({ code: 'MUSIC_VIDEO_SHOT_TIMING_CHANGED' });
+ expect(m.enqueue).not.toHaveBeenCalled();
+ expect(m.discard).toHaveBeenCalledWith(audio.audioFilePath);
+ });
+ it('refuses a source song changed during audio preparation and releases the owned window', async () => {
+ const audioDependencies = captureMusicVideoEvidence(m.project, { sceneIds: [], composition: false });
+ m.slice.mockImplementationOnce(async () => { m.project.trackId = 'changed-song'; return { ...structuredClone(audio), audioDependencies }; });
+ await expect(submitVideoGenJob(body(), {})).rejects.toMatchObject({ code: 'MUSIC_VIDEO_AUDIO_SOURCE_CHANGED' });
+ expect(m.enqueue).not.toHaveBeenCalled();
+ expect(m.discard).toHaveBeenCalledWith(audio.audioFilePath);
+ });
+});