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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: cancel abandoned fal.ai video renders on polling failure or deadline (#8340)
[._.]/ Adam Eivye7cea1e0ab01
diff --git a/server/services/videoGen/fal.js b/server/services/videoGen/fal.jsindex e154d3dac9..0eb8597808 100644--- a/server/services/videoGen/fal.js+++ b/server/services/videoGen/fal.js@@ -47,6 +47,10 @@ export const FAL_DEFAULT_IMAGE_MODEL = 'fal-ai/minimax/hailuo-02/standard/image-const FAL_SUBMIT_TIMEOUT_MS = 30_000;const FAL_POLL_TIMEOUT_MS = 15_000;const FAL_POLL_INTERVAL_MS = 3000;+// A transient status-fetch failure (network blip, fal.ai 5xx) gets this many+// additional attempts — on the same FAL_POLL_INTERVAL_MS cadence, never+// resubmitting the paid generation — before the run is abandoned (#8340).+const FAL_MAX_STATUS_RETRIES = 2;// Bounds the WHOLE download — headers and every byte of the video — now that// `fetchWithTimeout` holds its deadline through body consumption. It used to// bound only the headers, which left the multi-MB transfer itself with no@@ -87,6 +91,28 @@ export function resolveFalApiKey(settings) {return fromEnv || null;}+// Best-effort, idempotent cancellation of the remote fal.ai request — shared+// by explicit user cancellation (cancel()/cancelAll()) and every local+// abandonment path (exhausted status retries, the render deadline) so an+// already-known cancel_url is never left unsent (#8340). A caught failure is+// logged for diagnosis but never rethrown: the local job still finalizes as+// failed/canceled either way. Guarded so it never re-sends once fired, and+// never fires once the remote request already reached a fal-reported+// terminal state (COMPLETED/ERROR) — there is nothing left to cancel there.+async function cancelFalRequest(entry) {+ if (!entry || entry.canceledRemote || entry.remoteTerminal || !entry.cancelUrl || !entry.apiKey) return;+ entry.canceledRemote = true;+ try {+ const res = await fetchWithTimeout(entry.cancelUrl, {+ method: 'PUT',+ headers: { Authorization: `Key ${entry.apiKey}` },+ }, FAL_POLL_TIMEOUT_MS);+ if (!res.ok) console.error(`❌ fal.ai cancellation request failed: HTTP ${res.status}`);+ } catch (err) {+ console.error(`❌ fal.ai cancellation request failed: ${err?.message || err}`);+ }+}+export const cancel = (jobId) => {if (!jobId) {throw new Error("videoGen/fal.cancel requires a jobId — use cancelAll() to terminate every in-flight render");@@ -94,12 +120,7 @@ export const cancel = (jobId) => {const entry = activeRequests.get(jobId);if (!entry) return false;entry.aborted = true;- if (entry.cancelUrl && entry.apiKey) {- fetchWithTimeout(entry.cancelUrl, {- method: 'PUT',- headers: { Authorization: `Key ${entry.apiKey}` },- }, FAL_POLL_TIMEOUT_MS).catch(() => {});- }+ cancelFalRequest(entry);return true;};@@ -225,7 +246,9 @@ export async function generateVideo({}async function runFalVideo(job, jobId, { apiKey, modelId, prompt, negativePrompt, duration, aspectRatio, sourceImagePath, outputPath, filename, meta }) {- const entry = { apiKey, aborted: false, cancelUrl: null };+ const entry = {+ apiKey, aborted: false, cancelUrl: null, canceledRemote: false, remoteTerminal: false,+ };activeRequests.set(jobId, entry);const deadline = Date.now() + FAL_RENDER_TIMEOUT_MS;try {@@ -236,12 +259,29 @@ async function runFalVideo(job, jobId, { apiKey, modelId, prompt, negativePromptconst statusUrl = submitted.status_url || `${FAL_QUEUE_BASE}/${modelId}/requests/${submitted.request_id}/status`;const responseUrl = submitted.response_url || `${FAL_QUEUE_BASE}/${modelId}/requests/${submitted.request_id}`;+ let statusFailures = 0;while (Date.now() < deadline) {if (entry.aborted) return finalizeCanceled(job, jobId);videoGenEvents.emit('activity', { generationId: jobId });- const status = await pollFalStatus({ statusUrl, apiKey });- if (status.status === 'COMPLETED') break;+ let status;+ try {+ status = await pollFalStatus({ statusUrl, apiKey });+ } catch (err) {+ statusFailures += 1;+ if (statusFailures > FAL_MAX_STATUS_RETRIES) {+ await cancelFalRequest(entry);+ return finalizeJobFailure(job, jobId, null, `fal.ai status checks failed ${statusFailures} times in a row: ${err?.message || err}`);+ }+ await new Promise((r) => setTimeout(r, FAL_POLL_INTERVAL_MS));+ continue;+ }+ statusFailures = 0;+ if (status.status === 'COMPLETED') {+ entry.remoteTerminal = true;+ break;+ }if (status.status === 'ERROR') {+ entry.remoteTerminal = true;return finalizeJobFailure(job, jobId, null, `fal.ai render failed: ${status.error || 'unknown error'}`);}// fal's own queue maps to SUBMIT rather than to the queued step: the@@ -253,6 +293,7 @@ async function runFalVideo(job, jobId, { apiKey, modelId, prompt, negativePrompt}if (entry.aborted) return finalizeCanceled(job, jobId);if (Date.now() >= deadline) {+ await cancelFalRequest(entry);return finalizeJobFailure(job, jobId, null, `fal.ai did not finish within ${Math.round(FAL_RENDER_TIMEOUT_MS / 1000)}s`);}@@ -275,12 +316,20 @@ async function runFalVideo(job, jobId, { apiKey, modelId, prompt, negativePromptawait finalizeGeneratedVideo({ job, jobId, outputPath, filename, meta, actualSeed: null, mutateHistory: mutateVideoHistory });closeJobAfterDelay(jobs, jobId);} catch (err) {+ // Best-effort: an unanticipated throw (e.g. from fetchFalResult or the+ // download) may still leave the remote render queued or running — cancel+ // it before finalizing. `cancelFalRequest` already no-ops once+ // entry.remoteTerminal is set (fal reported COMPLETED/ERROR) or the+ // request was never submitted (no cancelUrl yet), so this never sends a+ // stray cancel for a job that already finished on fal.ai's side (#8340).+ //// finalizeGeneratedVideo marks job.status='complete' BEFORE its async// post-processing (faststart/thumbnail/history), and the request slot is// already released above — a throw there must still surface as a terminal// failure or the queue's job stays 'running' until the watchdog and the// client never gets a terminal frame. Force past the idempotence guard,// same as videoGen/grok.js's post-exit catch and reactor.js's catch-all (#6831).+ await cancelFalRequest(entry);finalizeJobFailure(job, jobId, null, `fal.ai video generation failed: ${err?.message || err}`, { force: true });}}diff --git a/server/services/videoGen/fal.test.js b/server/services/videoGen/fal.test.jsindex ca46b196a9..1b5b33a2a3 100644--- a/server/services/videoGen/fal.test.js+++ b/server/services/videoGen/fal.test.js@@ -329,3 +329,195 @@ describe('videoGen/fal — generateVideo', () => {expect(frames.at(-1)).toEqual({ type: 'error', error: expect.stringContaining('faststart remux failed') });}, 10000);});++// #8340 — a remote fal.ai render must not keep consuming metered compute+// after PortOS locally abandons it. These cover: recovering from a transient+// status-fetch failure without resubmitting, cancelling once retries are+// exhausted, cancelling at the local render deadline, and never sending a+// redundant cancel once fal.ai already reported a terminal status.+describe('videoGen/fal — cancel abandoned renders (#8340)', () => {+ afterEach(() => {+ vi.useRealTimers();+ });++ it('retries a transient status-fetch failure up to twice, never resubmits, and still completes', async () => {+ vi.useFakeTimers();+ const requestId = 'req-retry';+ const statusUrl = `https://queue.fal.run/fal-ai/x/requests/${requestId}/status`;+ const responseUrl = `https://queue.fal.run/fal-ai/x/requests/${requestId}`;+ const cancelUrl = `https://queue.fal.run/fal-ai/x/requests/${requestId}/cancel`;+ let submitCalls = 0;+ let statusCalls = 0;+ const fetchMock = vi.fn(async (url) => {+ if (url === 'https://queue.fal.run/fal-ai/x') {+ submitCalls += 1;+ return jsonResponse({ request_id: requestId, status_url: statusUrl, cancel_url: cancelUrl, response_url: responseUrl });+ }+ if (url === statusUrl) {+ statusCalls += 1;+ if (statusCalls <= 2) return { ok: false, status: 502, json: async () => null };+ return jsonResponse({ status: 'COMPLETED' });+ }+ if (url === responseUrl) return jsonResponse({ video: { url: 'https://cdn.fal.ai/out.mp4' } });+ if (url === 'https://cdn.fal.ai/out.mp4') {+ return { ok: true, status: 200, arrayBuffer: async () => Uint8Array.from(Buffer.from('bytes')).buffer };+ }+ throw new Error(`unexpected fetch: ${url}`);+ });+ vi.stubGlobal('fetch', fetchMock);++ const completed = vi.fn();+ videoGenEvents.on('completed', completed);+ const job = await fal.generateVideo({ apiKey: 'test-key', modelId: 'fal-ai/x', prompt: 'retry me' });++ // Two failed status attempts, each separated by the normal poll interval,+ // then a third attempt that reports COMPLETED.+ await vi.advanceTimersByTimeAsync(3000);+ await vi.advanceTimersByTimeAsync(3000);+ // Let the completion path (fetchFalResult + download + finalize) settle.+ await vi.advanceTimersByTimeAsync(0);+ await vi.waitFor(() => expect(completed).toHaveBeenCalledTimes(1), { timeout: 5000 });++ expect(submitCalls).toBe(1);+ expect(statusCalls).toBe(3);+ expect(fetchMock.mock.calls.some(([url]) => url === cancelUrl)).toBe(false);+ });++ it('cancels the remote render once status retries are exhausted', async () => {+ vi.useFakeTimers();+ const requestId = 'req-exhausted';+ const statusUrl = `https://queue.fal.run/fal-ai/x/requests/${requestId}/status`;+ const cancelUrl = `https://queue.fal.run/fal-ai/x/requests/${requestId}/cancel`;+ let submitCalls = 0;+ let statusCalls = 0;+ let cancelCalls = 0;+ const fetchMock = vi.fn(async (url, opts) => {+ if (url === 'https://queue.fal.run/fal-ai/x') {+ submitCalls += 1;+ return jsonResponse({ request_id: requestId, status_url: statusUrl, cancel_url: cancelUrl, response_url: `https://queue.fal.run/fal-ai/x/requests/${requestId}` });+ }+ if (url === statusUrl) {+ statusCalls += 1;+ return { ok: false, status: 502, json: async () => null };+ }+ if (url === cancelUrl) {+ cancelCalls += 1;+ expect(opts.method).toBe('PUT');+ expect(opts.headers.Authorization).toBe('Key test-key');+ return jsonResponse({});+ }+ throw new Error(`unexpected fetch: ${url}`);+ });+ vi.stubGlobal('fetch', fetchMock);++ const failed = vi.fn();+ videoGenEvents.on('failed', failed);+ const job = await fal.generateVideo({ apiKey: 'test-key', modelId: 'fal-ai/x', prompt: 'x' });++ // Initial attempt + two retries, each separated by the poll interval.+ await vi.advanceTimersByTimeAsync(3000);+ await vi.advanceTimersByTimeAsync(3000);+ await vi.advanceTimersByTimeAsync(0);+ await vi.waitFor(() => expect(failed).toHaveBeenCalledTimes(1), { timeout: 5000 });++ expect(submitCalls).toBe(1);+ expect(statusCalls).toBe(3);+ expect(cancelCalls).toBe(1);+ expect(failed).toHaveBeenCalledWith(expect.objectContaining({+ generationId: job.jobId,+ error: expect.stringContaining('status checks failed'),+ }));+ });++ it('cancels the remote render when the local render deadline expires while fal.ai still reports nonterminal', async () => {+ vi.useFakeTimers();+ const requestId = 'req-deadline';+ const statusUrl = `https://queue.fal.run/fal-ai/x/requests/${requestId}/status`;+ const cancelUrl = `https://queue.fal.run/fal-ai/x/requests/${requestId}/cancel`;+ let cancelCalls = 0;+ const fetchMock = vi.fn(async (url, opts) => {+ if (url === 'https://queue.fal.run/fal-ai/x') {+ return jsonResponse({ request_id: requestId, status_url: statusUrl, cancel_url: cancelUrl, response_url: `https://queue.fal.run/fal-ai/x/requests/${requestId}` });+ }+ if (url === statusUrl) return jsonResponse({ status: 'IN_PROGRESS' });+ if (url === cancelUrl) {+ cancelCalls += 1;+ expect(opts.method).toBe('PUT');+ expect(opts.headers.Authorization).toBe('Key test-key');+ return jsonResponse({});+ }+ throw new Error(`unexpected fetch: ${url}`);+ });+ vi.stubGlobal('fetch', fetchMock);++ const failed = vi.fn();+ videoGenEvents.on('failed', failed);+ const job = await fal.generateVideo({ apiKey: 'test-key', modelId: 'fal-ai/x', prompt: 'x' });++ // Drive well past the 20-minute default render deadline.+ await vi.advanceTimersByTimeAsync(20 * 60 * 1000 + 6000);+ await vi.waitFor(() => expect(failed).toHaveBeenCalledTimes(1), { timeout: 5000 });++ expect(cancelCalls).toBe(1);+ expect(failed).toHaveBeenCalledWith(expect.objectContaining({+ generationId: job.jobId,+ error: expect.stringContaining('did not finish within'),+ }));+ });++ it('never sends a cancellation once fal.ai already reported ERROR', async () => {+ const requestId = 'req-no-redundant-cancel';+ const statusUrl = `https://queue.fal.run/fal-ai/x/requests/${requestId}/status`;+ const cancelUrl = `https://queue.fal.run/fal-ai/x/requests/${requestId}/cancel`;+ const fetchMock = vi.fn(async (url) => {+ if (url === 'https://queue.fal.run/fal-ai/x') {+ return jsonResponse({ request_id: requestId, status_url: statusUrl, cancel_url: cancelUrl, response_url: `https://queue.fal.run/fal-ai/x/requests/${requestId}` });+ }+ if (url === statusUrl) return jsonResponse({ status: 'ERROR', error: 'model overloaded' });+ throw new Error(`unexpected fetch: ${url}`);+ });+ vi.stubGlobal('fetch', fetchMock);++ const failed = vi.fn();+ videoGenEvents.on('failed', failed);+ const job = await fal.generateVideo({ apiKey: 'test-key', modelId: 'fal-ai/x', prompt: 'x' });+ expect(await waitForTerminal(job.jobId)).toMatchObject({ type: 'failed' });+ expect(fetchMock.mock.calls.some(([url]) => url === cancelUrl)).toBe(false);+ });++ it('is idempotent with explicit cancellation — a second cancel() does not resend the PUT', async () => {+ vi.useFakeTimers();+ const requestId = 'req-explicit-cancel';+ const statusUrl = `https://queue.fal.run/fal-ai/x/requests/${requestId}/status`;+ const cancelUrl = `https://queue.fal.run/fal-ai/x/requests/${requestId}/cancel`;+ let cancelCalls = 0;+ const fetchMock = vi.fn(async (url, opts) => {+ if (url === 'https://queue.fal.run/fal-ai/x') {+ return jsonResponse({ request_id: requestId, status_url: statusUrl, cancel_url: cancelUrl, response_url: `https://queue.fal.run/fal-ai/x/requests/${requestId}` });+ }+ if (url === statusUrl) return jsonResponse({ status: 'IN_PROGRESS' });+ if (url === cancelUrl) {+ cancelCalls += 1;+ expect(opts.method).toBe('PUT');+ return jsonResponse({});+ }+ throw new Error(`unexpected fetch: ${url}`);+ });+ vi.stubGlobal('fetch', fetchMock);++ const failed = vi.fn();+ videoGenEvents.on('failed', failed);+ const job = await fal.generateVideo({ apiKey: 'test-key', modelId: 'fal-ai/x', prompt: 'x' });+ // Let the run reach its first poll iteration (submit + one status check)+ // before cancelling, so entry.cancelUrl is populated.+ await vi.advanceTimersByTimeAsync(0);++ expect(fal.cancel(job.jobId)).toBe(true);+ expect(fal.cancel(job.jobId)).toBe(true);+ // The poll loop notices `entry.aborted` on its next iteration.+ await vi.advanceTimersByTimeAsync(3000);+ await vi.waitFor(() => expect(failed).toHaveBeenCalledTimes(1), { timeout: 5000 });++ expect(cancelCalls).toBe(1);+ });+});