Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

fix(forge): recover NVCF consume-once poll losses instead of failing the job

nirholas3e1bb80b985f
diff --git a/api/_providers/nvidia.js b/api/_providers/nvidia.js
index 6d73ba90d..b6ca79a78 100644
--- a/api/_providers/nvidia.js
+++ b/api/_providers/nvidia.js
@@ -330,7 +330,15 @@ export function createNvidiaProvider() {
// instead of timing out our socket and losing the request id (see above).
'nvcf-poll-seconds': String(NVCF_POLL_SECONDS),
};
- const pollHeaders = { ...authHeader, accept: 'application/json' };
+ // NVCF pexec results are CONSUME-ONCE: the first status GET that receives the
+ // 200 body takes the artifact with it — a later poll 404s. Without an explicit
+ // poll window the gateway may long-hold the status connection until the job
+ // finishes; if our own POLL_TIMEOUT_MS abort fires while that 200 is being
+ // delivered, the result is consumed by a socket nobody read and the job is
+ // unrecoverable ("NVCF request not found or expired"). A short explicit window
+ // makes every status call answer fast (202 or the ready 200) long before the
+ // abort backstop, closing that loss window.
+ const pollHeaders = { ...authHeader, accept: 'application/json', 'nvcf-poll-seconds': '10' };
// Decode a base64 GLB and store it in R2, returning a durable public URL —
// the same persist the Vertex inline-PNG path uses, but for model bytes.
@@ -512,7 +520,12 @@ export function createNvidiaProvider() {
return { status: 'failed', error: 'NVIDIA rejected the API key' };
}
if (res.status === 404) {
- return { status: 'failed', error: 'NVCF request not found or expired' };
+ // The request id is gone: either the consume-once result was taken by a
+ // racing/aborted poll, or NVCF's retention window lapsed. Tagged with a
+ // machine-readable code so the forge poll layer can attempt recovery
+ // (re-check the store for a racing completion, then resubmit) instead of
+ // dead-ending the user's generation.
+ return { status: 'failed', error: 'NVCF request not found or expired', code: 'nvcf_expired' };
}
// 429 / 5xx mid-flight: the job may still be alive — keep polling.
if (res.status === 429) {
diff --git a/api/forge.js b/api/forge.js
index 0b979a7d3..cadb49c04 100644
--- a/api/forge.js
+++ b/api/forge.js
@@ -115,6 +115,7 @@ import {
refundCredits,
} from './_lib/credits.js';
import { markProviderCooldown, providersInCooldown } from './_lib/provider-health.js';
+import { acquireLock, releaseLock, cacheGet, cacheSet } from './_lib/cache.js';
import { sanitizeJobError } from './_lib/provider-job-error.js';
import { normalizeForgeOptions, providerReconstructParams, summarizeForgeOptions } from './_lib/forge-options.js';
import { bindJobToOptions, optionsForJob } from './_lib/forge-job-options.js';
@@ -2196,6 +2197,84 @@ async function startRigJob(req, res) {
}
}
+// ── NVCF poll robustness ─────────────────────────────────────────────────────
+// NVCF pexec results are consume-once: the FIRST status GET that lands after
+// completion receives the artifact and every later GET for that request id
+// 404s. Two production consequences (53 of 134 nvidia jobs in one 36h window
+// failed with "NVCF request not found or expired"):
+// 1. Concurrent polls for the same job (overlapping browser timers, a second
+// tab, a retried request) race — one consumes the result, the other 404s
+// and flips the creation to failed even though the mesh exists.
+// 2. A result that expires out of NVCF's retention window (throttled
+// background tab, closed laptop) is genuinely gone.
+// Recovery below: single-flight the upstream poll per task id so only one
+// request ever touches NVCF at a time; on a 404, first re-check the store for
+// a completion a racing poll already materialized, then — because the prompt
+// is recorded on the creation row — resubmit the SAME generation once and
+// alias the old task id to the new one so the client's existing poll handle
+// keeps working. The alias lives in the shared cache; the creation row keeps
+// its original replicate_job_id, so findByJob/materializeCreation are untouched.
+const NVCF_ALIAS_TTL_S = 3600;
+const NVCF_POLL_LOCK_TTL_S = 70; // > provider poll timeout (60s) so a dead holder can't wedge the job
+
+function nvcfAliasKey(taskId) {
+ return `nvcf:alias:${taskId}`;
+}
+
+async function pollNvidiaStatus({ nv, upstreamId, clientKey }) {
+ // A previous recovery may have resubmitted this job under a new NVCF id.
+ const alias = await cacheGet(nvcfAliasKey(upstreamId)).catch(() => null);
+ const taskId = typeof alias === 'string' && alias ? alias : upstreamId;
+
+ // Single-flight across instances: whoever loses the race reports running and
+ // lets the client's next poll pick up the winner's outcome from the store.
+ const lockKey = `nvcf:poll-lock:${taskId}`;
+ if (!(await acquireLock(lockKey, NVCF_POLL_LOCK_TTL_S))) {
+ return { status: 'running' };
+ }
+
+ let result;
+ try {
+ result = await nv.status({ taskId });
+ } finally {
+ await releaseLock(lockKey);
+ }
+ if (result?.code !== 'nvcf_expired') return result;
+
+ // The request id is dead. A racing poll may have already materialized the
+ // creation — that's a success, not a failure.
+ const row = await findByJob({ replicateJobId: upstreamId, clientKey });
+ if (row?.status === 'done' && row.glb_url) {
+ return { status: 'done', resultGlbUrl: row.glb_url };
+ }
+
+ // Genuinely lost (expired / consumed by an aborted socket). The never-dead-end
+ // rule: regenerate server-side rather than surface a failure the user can only
+ // answer by re-clicking Generate. Once per job — the resub lock outlives the
+ // alias so a second expiry reports the failure honestly.
+ if (!row?.prompt) return result;
+ if (!(await acquireLock(`nvcf:resub:${upstreamId}`, NVCF_ALIAS_TTL_S))) {
+ return { status: 'running' };
+ }
+ try {
+ const tier = resolveTier(row.tier);
+ const resub = await nv.textTo3d({ prompt: row.prompt, tier });
+ if (!resub.taskId && resub.resultGlbUrl) {
+ return { status: 'done', resultGlbUrl: resub.resultGlbUrl };
+ }
+ if (resub.taskId) {
+ await cacheSet(nvcfAliasKey(upstreamId), resub.taskId, NVCF_ALIAS_TTL_S);
+ console.warn(
+ `[forge] NVCF request expired; resubmitted job under a new request id (creation ${row.id})`,
+ );
+ return { status: 'running' };
+ }
+ } catch (err) {
+ console.warn(`[forge] NVCF expiry resubmit failed: ${err?.message || err}`);
+ }
+ return result;
+}
+
async function pollJob(req, res, jobId) {
// A job handle is either a bare Replicate prediction id (legacy / image-
// TRELLIS path) or a forge token encoding the geometry/GCP provider + the
@@ -2282,7 +2361,7 @@ async function pollJob(req, res, jobId) {
message: 'The free NVIDIA NIM 3D lane is not available on this deployment yet.',
});
}
- result = await nv.status({ taskId: upstreamId });
+ result = await pollNvidiaStatus({ nv, upstreamId, clientKey });
} else if (provider === 'gcp') {
// Serves every self-host lane (Hunyuan3D, TripoSG sketch) — the job
// envelope carries the worker URL it was submitted to.
diff --git a/tests/api/forge-nvcf-expiry-recovery.test.js b/tests/api/forge-nvcf-expiry-recovery.test.js
new file mode 100644
index 000000000..dd6e4c05b
--- /dev/null
+++ b/tests/api/forge-nvcf-expiry-recovery.test.js
@@ -0,0 +1,207 @@
+/**
+ * Recovery tests for NVCF "request not found or expired" on the free NVIDIA
+ * NIM poll path (api/forge.js pollNvidiaStatus).
+ *
+ * NVCF pexec results are consume-once: the first status GET after completion
+ * takes the artifact and later GETs 404. In production this failed 53 of 134
+ * nvidia jobs in one 36h window — overlapping polls raced each other, and
+ * results that aged out of NVCF retention were lost outright. The poll layer
+ * now recovers instead of dead-ending:
+ * • the upstream poll is single-flighted per task id (lock losers report
+ * running, never touch NVCF);
+ * • on a 404, a completion already materialized by a racing poll is
+ * returned as done;
+ * • otherwise the SAME generation is resubmitted once (the prompt lives on
+ * the creation row) and the old task id is aliased to the new one so the
+ * client's poll handle keeps working;
+ * • only when no recovery is possible does the failure surface.
+ */
+
+import { describe, it, expect, vi, beforeAll, beforeEach } from 'vitest';
+
+beforeAll(() => {
+ Object.assign(process.env, {
+ APP_ORIGIN: 'https://three.ws',
+ NVIDIA_API_KEY: 'test-nvidia-key',
+ JWT_SECRET: 'test-jwt-secret-at-least-32-characters-long',
+ });
+});
+
+// ── shared cache: in-memory stand-ins for cacheGet/cacheSet/locks ────────────
+const cacheStore = new Map();
+const lockDenials = new Set(); // lock keys that acquireLock must refuse
+const acquireLock = vi.fn(async (key) => !lockDenials.has(key));
+const releaseLock = vi.fn(async () => {});
+const cacheGet = vi.fn(async (key) => (cacheStore.has(key) ? cacheStore.get(key) : null));
+const cacheSet = vi.fn(async (key, value) => {
+ cacheStore.set(key, value);
+});
+vi.mock('../../api/_lib/cache.js', async (importActual) => {
+ const actual = await importActual();
+ return { ...actual, acquireLock, releaseLock, cacheGet, cacheSet };
+});
+
+// ── NVIDIA provider ──────────────────────────────────────────────────────────
+const nvStatus = vi.fn();
+const nvTextTo3d = vi.fn();
+vi.mock('../../api/_providers/nvidia.js', () => ({
+ createNvidiaProvider: () => ({ status: nvStatus, textTo3d: nvTextTo3d }),
+}));
+
+// ── forge store ──────────────────────────────────────────────────────────────
+const findByJob = vi.fn();
+const materializeCreation = vi.fn(async ({ glbUrl }) => ({
+ id: 'creation-1',
+ glbUrl,
+ quality: null,
+ compression: null,
+}));
+const markFailed = vi.fn(async () => {});
+vi.mock('../../api/_lib/forge-store.js', async (importActual) => {
+ const actual = await importActual();
+ return {
+ ...actual,
+ findByJob,
+ materializeCreation,
+ markFailed,
+ hashClient: () => 'client-hash',
+ hashIp: () => 'ip-hash',
+ };
+});
+
+vi.mock('../../api/_lib/rate-limit.js', async (importActual) => {
+ const actual = await importActual();
+ return {
+ ...actual,
+ limits: {
+ ...actual.limits,
+ mcp3dStatus: vi.fn(async () => ({ success: true, reset: Date.now() + 1000 })),
+ },
+ clientIp: () => '203.0.113.9',
+ };
+});
+
+const { default: handler } = await import('../../api/forge.js');
+const { encodeJobToken } = await import('../../api/_lib/forge-job-token.js');
+
+const TASK_ID = 'nvcf-req-0001';
+const EXPIRED = { status: 'failed', error: 'NVCF request not found or expired', code: 'nvcf_expired' };
+const jobToken = () => encodeJobToken({ provider: 'nvidia', kind: 'text-to-3d', taskId: TASK_ID });
+
+function makeReq(url) {
+ return {
+ method: 'GET',
+ url,
+ headers: { 'x-forge-client': 'tester' },
+ on() {},
+ };
+}
+
+function makeRes() {
+ return {
+ statusCode: 200,
+ headers: {},
+ body: null,
+ setHeader(name, value) {
+ this.headers[String(name).toLowerCase()] = value;
+ },
+ end(body) {
+ this.body = body ? JSON.parse(body) : null;
+ },
+ };
+}
+
+async function poll() {
+ const res = makeRes();
+ await handler(makeReq(`/api/forge?job=${encodeURIComponent(jobToken())}`), res);
+ return res;
+}
+
+const baseRow = {
+ id: 'creation-1',
+ status: 'generating',
+ glb_url: null,
+ prompt: 'a small red toy robot',
+ tier: 'standard',
+ backend: 'nvidia',
+ path: 'image',
+};
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ cacheStore.clear();
+ lockDenials.clear();
+});
+
+describe('NVCF expiry recovery on the nvidia poll path', () => {
+ it('returns done when a racing poll already materialized the creation', async () => {
+ nvStatus.mockResolvedValueOnce(EXPIRED);
+ findByJob.mockResolvedValue({ ...baseRow, status: 'done', glb_url: 'https://cdn.example/done.glb' });
+
+ const res = await poll();
+ expect(res.body.status).toBe('done');
+ expect(res.body.glb_url).toBe('https://cdn.example/done.glb');
+ expect(markFailed).not.toHaveBeenCalled();
+ expect(nvTextTo3d).not.toHaveBeenCalled();
+ });
+
+ it('resubmits the same generation once and aliases the new request id', async () => {
+ nvStatus.mockResolvedValueOnce(EXPIRED);
+ findByJob.mockResolvedValue({ ...baseRow });
+ nvTextTo3d.mockResolvedValueOnce({ taskId: 'nvcf-req-0002' });
+
+ const res = await poll();
+ expect(res.body.status).toBe('running');
+ expect(nvTextTo3d).toHaveBeenCalledWith(
+ expect.objectContaining({ prompt: baseRow.prompt }),
+ );
+ expect(cacheStore.get(`nvcf:alias:${TASK_ID}`)).toBe('nvcf-req-0002');
+ expect(markFailed).not.toHaveBeenCalled();
+
+ // The next poll for the ORIGINAL job handle must hit the aliased id.
+ nvStatus.mockResolvedValueOnce({ status: 'done', resultGlbUrl: 'https://cdn.example/resub.glb' });
+ const res2 = await poll();
+ expect(nvStatus).toHaveBeenLastCalledWith({ taskId: 'nvcf-req-0002' });
+ expect(res2.body.status).toBe('done');
+ });
+
+ it('completes inline when the resubmit finishes synchronously', async () => {
+ nvStatus.mockResolvedValueOnce(EXPIRED);
+ findByJob.mockResolvedValue({ ...baseRow });
+ nvTextTo3d.mockResolvedValueOnce({ taskId: null, resultGlbUrl: 'https://cdn.example/sync.glb' });
+
+ const res = await poll();
+ expect(res.body.status).toBe('done');
+ expect(res.body.glb_url).toBe('https://cdn.example/sync.glb');
+ expect(markFailed).not.toHaveBeenCalled();
+ });
+
+ it('reports running (not failed) when another instance owns the resubmit', async () => {
+ nvStatus.mockResolvedValueOnce(EXPIRED);
+ findByJob.mockResolvedValue({ ...baseRow });
+ lockDenials.add(`nvcf:resub:${TASK_ID}`);
+
+ const res = await poll();
+ expect(res.body.status).toBe('running');
+ expect(nvTextTo3d).not.toHaveBeenCalled();
+ expect(markFailed).not.toHaveBeenCalled();
+ });
+
+ it('single-flights the upstream poll: a lock loser never touches NVCF', async () => {
+ lockDenials.add(`nvcf:poll-lock:${TASK_ID}`);
+
+ const res = await poll();
+ expect(res.body.status).toBe('running');
+ expect(nvStatus).not.toHaveBeenCalled();
+ });
+
+ it('surfaces the failure only when no recovery is possible (no stored prompt)', async () => {
+ nvStatus.mockResolvedValueOnce(EXPIRED);
+ findByJob.mockResolvedValue(null);
+
+ const res = await poll();
+ expect(res.body.status).toBe('failed');
+ expect(markFailed).toHaveBeenCalled();
+ expect(nvTextTo3d).not.toHaveBeenCalled();
+ });
+});