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 self-host 404s instead of failing image→3D on the first miss

nirholas167081fea2a0
diff --git a/api/_lib/forge-selfhost-recovery.js b/api/_lib/forge-selfhost-recovery.js
new file mode 100644
index 000000000..833ca41bf
--- /dev/null
+++ b/api/_lib/forge-selfhost-recovery.js
@@ -0,0 +1,82 @@
+// @ts-check
+// Self-host (GCP worker) poll recovery — the fix for the platform's single
+// largest generation-failure class.
+//
+// Evidence (forge_creations, 7-day window): image→3D failed ~48% of the time,
+// and 410 of 425 `trellis_selfhost` failures were the literal string
+// "task not found on gcp service" — a 404 from the worker's /tasks/:id or
+// /jobs/:id poll. Every one of those was on path='image'.
+//
+// Why a 404 is NOT a real failure (usually):
+// The worker persists each task's `queued` state to GCS synchronously before
+// returning its 202, and every poll re-reads GCS for non-terminal records
+// (workers/model-trellis/main.py `_resolve_task`). So a 404 means the durable
+// record is not visible to the instance this poll happened to land on. With the
+// worker at containerConcurrency 80 / maxScale 3 and no session affinity, a poll
+// fired seconds after submit can hit a different instance before the just-written
+// record is consistently readable, or a completion write can be racing. Treating
+// that first 404 as terminal — which the router did — throws away a job that is
+// almost always fine, then burns a failover hop recovering it.
+//
+// The rule the rest of the forge already follows (see the NVCF recovery in
+// api/forge.js `pollNvidiaStatus`): never dead-end on a RECOVERABLE signal.
+// This module is the GCP twin of that decision, kept pure so the grace/terminal
+// state machine is unit-testable without a worker or a DB.
+//
+// Decision, given a 404-class ("gcp_task_missing") poll result:
+// 1. Store re-check — if the creation row already materialized (done + a glb),
+// a racing poll or the worker's completion write beat us; that's a success.
+// 2. Grace window — if the job is younger than GRACE, the 404 is the
+// post-submit cross-instance/visibility window; report `running` so the
+// client keeps polling. The durable record resolves within seconds.
+// 3. Terminal — past the window a still-missing task is genuinely orphaned
+// (its runner instance died mid-job); surface the failure so the poll
+// handler's lane failover redispatches to a healthy lane.
+//
+// GRACE is 90s: comfortably covers the post-submit visibility window and a cold
+// instance, while leaving the client's ~300s poll budget room for a failover
+// hop plus a real generation if the task is truly lost.
+
+export const GCP_TASK_MISSING_GRACE_MS = 90_000;
+
+// The recoverable code the GCP provider tags onto a 404 result (api/_providers/
+// gcp.js). Matching on a code, not the human error string, keeps the operator-
+// facing message free to change without breaking recovery.
+export const GCP_TASK_MISSING_CODE = 'gcp_task_missing';
+
+/**
+ * Decide what a "task not found" (404-class) self-host poll should become.
+ * Pure: no clock, no I/O — the caller supplies the resolved row and the job age.
+ *
+ * @param {{
+ * code?: string,
+ * row?: { status?: string, glb_url?: string|null } | null,
+ * ageMs?: number,
+ * graceMs?: number,
+ * }} input
+ * @returns {{ action: 'passthrough' } | { action: 'done', glbUrl: string }
+ * | { action: 'running' } | { action: 'fail' }}
+ * - passthrough: not the recoverable class; use the provider result unchanged.
+ * - done: a durable result already exists; resolve the job as complete.
+ * - running: within grace; keep the client polling.
+ * - fail: genuinely lost; let the caller surface failure + failover.
+ */
+export function decideSelfhostMissing({ code, row, ageMs, graceMs = GCP_TASK_MISSING_GRACE_MS } = {}) {
+ if (code !== GCP_TASK_MISSING_CODE) return { action: 'passthrough' };
+
+ // A racing poll or the worker's own completion write already materialized the
+ // mesh — the 404 we just got is stale. That's a success, not a loss.
+ if (row && row.status === 'done' && row.glb_url) {
+ return { action: 'done', glbUrl: row.glb_url };
+ }
+
+ // Young job: the durable record is written but not yet visible to the instance
+ // this poll reached. Keep waiting; the next poll resolves it.
+ if (Number.isFinite(ageMs) && /** @type {number} */ (ageMs) < graceMs) {
+ return { action: 'running' };
+ }
+
+ // Old enough (or age unknowable): a still-missing task is orphaned. Surface
+ // the failure so lane failover can redispatch.
+ return { action: 'fail' };
+}
diff --git a/api/_providers/gcp.js b/api/_providers/gcp.js
index afeb56240..d8673967e 100644
--- a/api/_providers/gcp.js
+++ b/api/_providers/gcp.js
@@ -518,7 +518,12 @@ export function createRegenProvider({ reconstructUrl } = {}) {
}
if (response.status === 404) {
- return { status: 'failed', error: 'task not found on gcp service' };
+ // A 404 means the durable task record isn't visible to the instance
+ // this poll landed on — usually the post-submit cross-instance window
+ // (worker at high concurrency, no session affinity), not a real loss.
+ // Tag it recoverable so the router can grace/recover instead of failing
+ // on the first miss (see _lib/forge-selfhost-recovery.js).
+ return { status: 'failed', error: 'task not found on gcp service', code: 'gcp_task_missing' };
}
const data = await response.json().catch(() => ({}));
diff --git a/api/forge.js b/api/forge.js
index 7e2b14023..50c42e0ed 100644
--- a/api/forge.js
+++ b/api/forge.js
@@ -137,6 +137,7 @@ import {
submitFailoverJob,
MAX_FAILOVER_HOPS,
} from './_lib/forge-failover.js';
+import { decideSelfhostMissing } from './_lib/forge-selfhost-recovery.js';
import { directPrompt } from './_mcp-studio/forge-client.js';
import { MESH_DIRECTOR, resolveLogoPrompt } from './_lib/forge-director-prompts.js';
@@ -2648,6 +2649,32 @@ async function pollNvidiaStatus({ nv, upstreamId, clientKey }) {
return result;
}
+// ── Self-host (GCP worker) poll recovery ─────────────────────────────────────
+// A self-host /tasks/:id or /jobs/:id poll can 404 ("task not found on gcp
+// service") when the durable task record isn't visible to the instance this
+// poll reached — the post-submit cross-instance window (worker at high
+// concurrency, no session affinity) or a completion write racing us. That was
+// the platform's single largest failure class (410 of 425 trellis failures, all
+// path='image'), and the router used to treat the FIRST 404 as terminal. The
+// GCP twin of pollNvidiaStatus: never dead-end on a recoverable signal —
+// re-check the store, grace a young job, and only surface failure once a missing
+// task is genuinely orphaned, where the poll handler's lane failover takes over.
+async function pollGcpStatus({ gcp, upstreamId, clientKey, createdAt }) {
+ const result = await gcp.status(upstreamId);
+ if (result?.code !== 'gcp_task_missing') return result;
+
+ const row = await findByJob({ replicateJobId: upstreamId, clientKey }).catch(() => null);
+ const ageMs = createdAt ? Date.now() - Date.parse(createdAt) : Infinity;
+ const decision = decideSelfhostMissing({ code: result.code, row, ageMs });
+ if (decision.action === 'done') {
+ return { status: 'done', resultGlbUrl: decision.glbUrl };
+ }
+ if (decision.action === 'running') {
+ return { status: 'running' };
+ }
+ return result; // genuinely orphaned → existing failover path acts on it
+}
+
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
@@ -2756,7 +2783,7 @@ async function pollJob(req, res, jobId) {
message: 'Self-hosted generation is not configured on this deployment.',
});
}
- result = await gcp.status(upstreamId);
+ result = await pollGcpStatus({ gcp, upstreamId, clientKey, createdAt: meta?.created_at });
} else {
let rep;
try {
diff --git a/docs/forge-background-generation.md b/docs/forge-background-generation.md
index 08931d53b..4fad5be5a 100644
--- a/docs/forge-background-generation.md
+++ b/docs/forge-background-generation.md
@@ -50,6 +50,32 @@ Three cooperating pieces:
completions). Email delivery uses the platform Resend pipeline and skips
undeliverable placeholder addresses.
+## Self-host poll recovery (the "task not found" grace)
+
+A self-host worker poll (`/tasks/:id` or `/jobs/:id`) can 404 when the durable
+task record is not yet visible to the instance the poll load-balanced to — the
+brief post-submit cross-instance window (workers run at high concurrency with no
+session affinity), or a completion write racing the poll. The worker persists
+each task's `queued` state to GCS before returning its 202 and re-reads GCS for
+non-terminal records, so a 404 is almost never a real loss.
+
+The router used to treat that first 404 as terminal, which made
+`task not found on gcp service` the platform's single largest generation-failure
+class (image→3D). Recovery now mirrors the NVCF path (never dead-end on a
+recoverable signal): the GCP provider tags a 404 with `code: 'gcp_task_missing'`
+([api/_providers/gcp.js](../api/_providers/gcp.js)) and the poll handler runs a
+pure decision ([api/_lib/forge-selfhost-recovery.js](../api/_lib/forge-selfhost-recovery.js)):
+
+1. **Store re-check** — if the creation row already materialized (`done` + a
+ glb), a racing poll or the completion write beat us; resolve as complete.
+2. **Grace window** — a job younger than `GCP_TASK_MISSING_GRACE_MS` (90s)
+ reports `running` so the client keeps polling; the durable record resolves
+ within seconds.
+3. **Terminal** — past the window a still-missing task is genuinely orphaned;
+ the failure surfaces and the existing lane failover redispatches to a healthy
+ lane. Nothing here disables failover — it just stops firing it on transient
+ 404s.
+
## Operational notes
- The finalizer needs `CRON_SECRET` (standard cron auth), `DATABASE_URL`, the
diff --git a/tests/api/forge-selfhost-recovery.test.js b/tests/api/forge-selfhost-recovery.test.js
new file mode 100644
index 000000000..6f3501caa
--- /dev/null
+++ b/tests/api/forge-selfhost-recovery.test.js
@@ -0,0 +1,77 @@
+import { describe, it, expect } from 'vitest';
+import {
+ decideSelfhostMissing,
+ GCP_TASK_MISSING_GRACE_MS,
+ GCP_TASK_MISSING_CODE,
+} from '../../api/_lib/forge-selfhost-recovery.js';
+
+// The recovery for the platform's largest generation-failure class: a self-host
+// worker 404 ("task not found on gcp service") — 410 of 425 trellis failures,
+// all image→3D — that the router used to treat as terminal on the first poll.
+
+describe('decideSelfhostMissing — never dead-end on a recoverable 404', () => {
+ const glbUrl = 'https://cdn.three.ws/forge/abc.glb';
+
+ it('passes through any result that is not the recoverable 404 class', () => {
+ expect(decideSelfhostMissing({ code: undefined, ageMs: 0 }).action).toBe('passthrough');
+ expect(decideSelfhostMissing({ code: 'some_other_error', ageMs: 0 }).action).toBe('passthrough');
+ // A genuine done/failed result never carries the missing code, so it flows
+ // through untouched.
+ expect(decideSelfhostMissing({}).action).toBe('passthrough');
+ });
+
+ it('resolves DONE when a durable result already materialized (racing poll / completion write)', () => {
+ const d = decideSelfhostMissing({
+ code: GCP_TASK_MISSING_CODE,
+ row: { status: 'done', glb_url: glbUrl },
+ ageMs: GCP_TASK_MISSING_GRACE_MS + 10_000, // even past grace, a real result wins
+ });
+ expect(d).toEqual({ action: 'done', glbUrl });
+ });
+
+ it('keeps the client polling (RUNNING) for a young job — the post-submit cross-instance window', () => {
+ const d = decideSelfhostMissing({
+ code: GCP_TASK_MISSING_CODE,
+ row: { status: 'running', glb_url: null },
+ ageMs: 5_000, // 5s after submit: the durable record just isn't visible yet
+ });
+ expect(d.action).toBe('running');
+ });
+
+ it('keeps polling even with no store row yet, while young', () => {
+ const d = decideSelfhostMissing({ code: GCP_TASK_MISSING_CODE, row: null, ageMs: 1_000 });
+ expect(d.action).toBe('running');
+ });
+
+ it('FAILS once the job is older than grace — a still-missing task is genuinely orphaned', () => {
+ const d = decideSelfhostMissing({
+ code: GCP_TASK_MISSING_CODE,
+ row: { status: 'running', glb_url: null },
+ ageMs: GCP_TASK_MISSING_GRACE_MS + 1,
+ });
+ expect(d.action).toBe('fail');
+ });
+
+ it('FAILS when age is unknowable (no created_at) — conservative, preserves prior behavior', () => {
+ expect(decideSelfhostMissing({ code: GCP_TASK_MISSING_CODE, row: null, ageMs: Infinity }).action).toBe('fail');
+ expect(decideSelfhostMissing({ code: GCP_TASK_MISSING_CODE, row: null, ageMs: NaN }).action).toBe('fail');
+ expect(decideSelfhostMissing({ code: GCP_TASK_MISSING_CODE, row: null }).action).toBe('fail');
+ });
+
+ it('boundary: exactly at grace is terminal, just under is still running', () => {
+ expect(decideSelfhostMissing({ code: GCP_TASK_MISSING_CODE, ageMs: GCP_TASK_MISSING_GRACE_MS }).action).toBe('fail');
+ expect(decideSelfhostMissing({ code: GCP_TASK_MISSING_CODE, ageMs: GCP_TASK_MISSING_GRACE_MS - 1 }).action).toBe('running');
+ });
+
+ it('a done row missing its glb url is not treated as done (falls to grace/fail)', () => {
+ const young = decideSelfhostMissing({ code: GCP_TASK_MISSING_CODE, row: { status: 'done', glb_url: null }, ageMs: 1_000 });
+ expect(young.action).toBe('running');
+ const old = decideSelfhostMissing({ code: GCP_TASK_MISSING_CODE, row: { status: 'done', glb_url: null }, ageMs: GCP_TASK_MISSING_GRACE_MS + 1 });
+ expect(old.action).toBe('fail');
+ });
+
+ it('grace window is a sane length (covers the visibility window, fits the client poll budget)', () => {
+ expect(GCP_TASK_MISSING_GRACE_MS).toBeGreaterThanOrEqual(30_000);
+ expect(GCP_TASK_MISSING_GRACE_MS).toBeLessThanOrEqual(180_000);
+ });
+});