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): put the reference-image step on the shared paint budget so a stalled Vertex call cannot hold a submit for minutes

nirholasc479081a4bd6
diff --git a/api/_lib/forge-reference-image.js b/api/_lib/forge-reference-image.js
index e6354206f..6fbb1e1b8 100644
--- a/api/_lib/forge-reference-image.js
+++ b/api/_lib/forge-reference-image.js
@@ -59,7 +59,7 @@ import { getGcpAccessToken } from './gcp-auth.js';
import { persistImageBase64 } from './image-persist.js';
import { subjectNegativePrompt } from '../forge-enhance.js';
import { isProviderRefusal } from './ai-image-lanes.js';
-import { textToImage } from '../_mcp3d/text-to-image.js';
+import { textToImage, ladderBudgetMs, laneTimeoutMs } from '../_mcp3d/text-to-image.js';
import { parseJsonLoose } from './vision.js';
import { getRedis } from './redis.js';
@@ -182,7 +182,14 @@ export function buildReferenceInstruction(prompt, negativePrompt) {
// without imageConfig.imageSize if the tier rejects that field (defensive: the
// field is accepted today, but a tier change must degrade to a valid request
// rather than a hard failure that skips the whole Vertex lane).
-async function generateViaVertex({ instruction, aspectRatio }) {
+// `deadline` (epoch ms) bounds EVERY request this makes, the retry-without-size
+// and the no-image re-roll included. Before it, each request had its own 60 s
+// window and a single call could chain up to four of them.
+const VERTEX_REQUEST_CEILING_MS = 60_000;
+function msLeft(deadline) {
+ return deadline ? deadline - Date.now() : VERTEX_REQUEST_CEILING_MS;
+}
+async function generateViaVertex({ instruction, aspectRatio, deadline = null }) {
const project = process.env.GOOGLE_CLOUD_PROJECT;
const location = DEFAULT_LOCATION;
const model = DEFAULT_MODEL;
@@ -203,7 +210,7 @@ async function generateViaVertex({ instruction, aspectRatio }) {
contents: [{ role: 'user', parts: [{ text: instruction }] }],
generationConfig: { responseModalities: ['IMAGE'], imageConfig },
}),
- signal: AbortSignal.timeout(60_000),
+ signal: AbortSignal.timeout(Math.max(1_000, Math.min(VERTEX_REQUEST_CEILING_MS, msLeft(deadline)))),
});
return res;
};
@@ -214,7 +221,7 @@ async function generateViaVertex({ instruction, aspectRatio }) {
// Peek at the error: only retry-without-size when it is specifically about
// imageConfig/imageSize, so a genuine bad request still fails fast.
const detail = await res.text().catch(() => '');
- if (/imageSize|imageConfig/i.test(detail)) {
+ if (/imageSize|imageConfig/i.test(detail) && msLeft(deadline) > 5_000) {
res = await request(false);
} else {
throw Object.assign(new Error(`Vertex reference image 400: ${detail.slice(0, 200)}`), {
@@ -252,7 +259,7 @@ async function generateViaVertex({ instruction, aspectRatio }) {
// than a second attempt at this lane. Refusals and HTTP errors re-throw
// unchanged so genuine blocks and outages still fail fast.
const noImage = /produced no image/i.test(String(err?.message || ''));
- if (!noImage || isProviderRefusal(err)) throw err;
+ if (!noImage || isProviderRefusal(err) || msLeft(deadline) < 10_000) throw err;
return await attempt();
}
}
@@ -343,8 +350,17 @@ async function scoreReferenceImage({ b64, mime, prompt }) {
// every lane is exhausted, exactly as textToImage does today.
export async function generateReferenceImage(
prompt,
- { aspectRatio = '1:1', negativePrompt = null, seed, skipNim = false } = {},
+ { aspectRatio = '1:1', negativePrompt = null, seed, skipNim = false, budgetMs } = {},
) {
+ // One budget for the whole reference step, shared with the fallthrough
+ // ladder: the Vertex lane gets the leader's share (it has a fallback behind
+ // it), QA scoring and the corrective retry only run while there is real time
+ // left, and whatever remains is handed to textToImage. Measured 2026-08-25:
+ // with no budget this step held a submit open for minutes before any job
+ // existed, on every text prompt.
+ const budget = ladderBudgetMs(budgetMs);
+ const startedAt = Date.now();
+ const remaining = () => budget - (Date.now() - startedAt);
const negatives =
negativePrompt && String(negativePrompt).trim()
? String(negativePrompt).trim()
@@ -363,8 +379,14 @@ export async function generateReferenceImage(
if (vertexImageEnabled()) {
try {
const instruction = buildReferenceInstruction(prompt, negatives);
- let generated = await generateViaVertex({ instruction, aspectRatio });
- let verdict = await scoreReferenceImage({ b64: generated.b64, mime: generated.mime, prompt });
+ const leaderMs = laneTimeoutMs(VERTEX_REQUEST_CEILING_MS, { budgetMs: budget, remainingMs: remaining(), laneRemains: true });
+ let generated = await generateViaVertex({ instruction, aspectRatio, deadline: Date.now() + leaderMs });
+ // Scoring is cheap insurance, not a gate: with the budget mostly spent
+ // the image ships unscored rather than blocking on one more call.
+ let verdict =
+ remaining() > budget * 0.25
+ ? await scoreReferenceImage({ b64: generated.b64, mime: generated.mime, prompt })
+ : null;
// One retry with corrective feedback on a scoring failure: fold the
// vision model's own named issue into the instruction as an explicit
@@ -372,11 +394,11 @@ export async function generateReferenceImage(
// of the two attempts scored higher (best-of-2). GPU reconstruction
// time dwarfs the cost of one extra vision call, so this is cheap
// insurance against a bad reference wasting the expensive step downstream.
- if (verdict && verdict.score < QA_PASS_SCORE) {
+ if (verdict && verdict.score < QA_PASS_SCORE && remaining() > budget * 0.5) {
const issue = verdict.issue || 'the subject was incomplete, off-center, not photoreal, or the background was cluttered';
const retryInstruction = `${instruction} IMPORTANT: a previous attempt at this shot failed on: ${issue}. Fix that specifically this time.`;
try {
- const retried = await generateViaVertex({ instruction: retryInstruction, aspectRatio });
+ const retried = await generateViaVertex({ instruction: retryInstruction, aspectRatio, deadline: Date.now() + Math.floor(remaining() * 0.6) });
const retryVerdict = await scoreReferenceImage({ b64: retried.b64, mime: retried.mime, prompt });
if (!verdict || (retryVerdict && retryVerdict.score > verdict.score)) {
generated = retried;
@@ -411,6 +433,6 @@ export async function generateReferenceImage(
// Fallthrough: the current reference-image provider (NIM FLUX free → Vertex
// Imagen → Replicate). Same call the router makes today, so this can only ever
// add the Vertex-reference lane in front, never remove a path.
- const served = await textToImage(prompt, { aspectRatio, skipNim, seed });
+ const served = await textToImage(prompt, { aspectRatio, skipNim, seed, budgetMs: Math.max(5_000, remaining()) });
return { ...served, lane: served.lane || (served.predictionId ? 'replicate' : 'fallthrough') };
}
diff --git a/api/gpt-forge.js b/api/gpt-forge.js
index d586f013a..00ca217ca 100644
--- a/api/gpt-forge.js
+++ b/api/gpt-forge.js
@@ -62,7 +62,7 @@
import { randomUUID } from 'node:crypto';
import { cors, json, method, readJson, wrap, rateLimited } from './_lib/http.js';
import { limits, clientIp } from './_lib/rate-limit.js';
-import { textToImage, synthesizeTurnaroundViews } from './_mcp3d/text-to-image.js';
+import { textToImage, synthesizeTurnaroundViews, ladderBudgetMs } from './_mcp3d/text-to-image.js';
import { createRegenProvider } from './_providers/replicate.js';
import { createRegenProvider as createGcpProvider } from './_providers/gcp.js';
import { BYOK_PROVIDER_FACTORIES } from './_providers/byok-registry.js';
@@ -382,6 +382,15 @@ function readForgeEnv(name) {
// the module is absent or Vertex is unavailable. Returns { imageUrl, model } -
// exactly textToImage()'s shape: so the call site is a drop-in swap.
export async function seedReferenceImage({ prompt, aspect, seed, skipNim }) {
+ // The reference step and the text-to-image ladder share ONE budget
+ // (TEXT_TO_IMAGE_BUDGET_MS, default 60 s). The reference module is bounded
+ // internally; the race below is the backstop for anything it awaits that is
+ // not (a token mint, a cache read), so a submit can never outlive the
+ // caller's socket before a job exists. On a cap the ladder gets what is
+ // left, which is nothing, and answers a fast retryable 429.
+ const budget = ladderBudgetMs();
+ const startedAt = Date.now();
+ const remaining = () => budget - (Date.now() - startedAt);
if (readForgeEnv('FORGE_REFERENCE_IMAGE') !== 'off') {
try {
const mod = await import('./_lib/forge-reference-image.js');
@@ -394,7 +403,19 @@ export async function seedReferenceImage({ prompt, aspect, seed, skipNim }) {
// Positional signature: (prompt, { aspectRatio, seed, skipNim }). The module
// itself falls through to the standing text→image provider on a Vertex
// failure, so a returned result already reflects the best available lane.
- const out = await fn(prompt, { aspectRatio: aspect, seed, skipNim });
+ let capTimer;
+ const cap = new Promise((_, reject) => {
+ capTimer = setTimeout(
+ () => reject(Object.assign(new Error(`reference image step exceeded its ${budget}ms budget`), { code: 'rate_limited', queued: true, retryAfter: 15 })),
+ Math.max(1_000, remaining()),
+ );
+ });
+ let out;
+ try {
+ out = await Promise.race([fn(prompt, { aspectRatio: aspect, seed, skipNim, budgetMs: budget }), cap]);
+ } finally {
+ clearTimeout(capTimer);
+ }
const imageUrl = out && (out.imageUrl || out.image_url || out.url);
if (imageUrl) {
return { imageUrl, model: out.model || 'vertex-reference', referenceModule: true };
@@ -406,7 +427,7 @@ export async function seedReferenceImage({ prompt, aspect, seed, skipNim }) {
console.warn(`[forge] reference-image module unavailable, using standing provider: ${err?.message || err}`);
}
}
- const synthesized = await textToImage(prompt, { aspectRatio: aspect, skipNim, seed });
+ const synthesized = await textToImage(prompt, { aspectRatio: aspect, skipNim, seed, budgetMs: Math.max(5_000, remaining()) });
return { imageUrl: synthesized.imageUrl, model: synthesized.model, referenceModule: false };
}
diff --git a/tests/forge-reference-image-budget.test.js b/tests/forge-reference-image-budget.test.js
new file mode 100644
index 000000000..8df1273fa
--- /dev/null
+++ b/tests/forge-reference-image-budget.test.js
@@ -0,0 +1,85 @@
+/**
+ * The reference-image step (api/_lib/forge-reference-image.js) runs BEFORE the
+ * text-to-image ladder on every text prompt and, until now, had no budget: one
+ * Vertex call could chain a 60 s request, a 60 s retry-without-size, a 60 s
+ * no-image re-roll, a QA score, then the same again as a corrective retry,
+ * then the ladder. Measured live on 2026-08-25: text submits hung 95 s+ with
+ * the ladder fix already deployed, because this step sits in front of it.
+ */
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+process.env.GOOGLE_CLOUD_PROJECT = 'test-project';
+delete process.env.VERTEX_IMAGEN_ENABLED;
+delete process.env.TEXT_TO_IMAGE_BUDGET_MS;
+
+vi.mock('../api/_lib/gcp-auth.js', () => ({ getGcpAccessToken: async () => 'tok' }));
+vi.mock('../api/_lib/redis.js', () => ({ getRedis: () => null }));
+vi.mock('../api/_lib/image-persist.js', () => ({ persistImageBase64: async () => 'https://cdn.test/ref.png' }));
+vi.mock('../api/_lib/vision.js', () => ({ parseJsonLoose: (t) => JSON.parse(t) }));
+vi.mock('../api/forge-enhance.js', () => ({ subjectNegativePrompt: () => 'blurry' }));
+vi.mock('../api/_lib/ai-image-lanes.js', () => ({ isProviderRefusal: () => false }));
+
+const ladder = vi.hoisted(() => ({ calls: [] }));
+vi.mock('../api/_mcp3d/text-to-image.js', async (importOriginal) => {
+ const real = await importOriginal();
+ return {
+ ...real,
+ textToImage: async (prompt, opts) => {
+ ladder.calls.push(opts);
+ return { imageUrl: 'https://cdn.test/ladder.png', model: 'nim/flux' };
+ },
+ };
+});
+
+const { generateReferenceImage } = await import('../api/_lib/forge-reference-image.js');
+
+// Vertex: a fetch that stalls until its abort signal fires (a stalled
+// upstream), recording the timeout each request was given.
+const vertex = { requests: [] };
+globalThis.fetch = vi.fn(
+ (url, init) =>
+ new Promise((_, reject) => {
+ vertex.requests.push(Date.now());
+ init?.signal?.addEventListener('abort', () =>
+ reject(Object.assign(new Error('The operation was aborted due to timeout'), { name: 'TimeoutError' })),
+ );
+ }),
+);
+
+beforeEach(() => {
+ ladder.calls.length = 0;
+ vertex.requests.length = 0;
+});
+
+describe('the reference step shares the paint budget', () => {
+ it('cuts a stalled Vertex reference request at the leader share and hands the rest to the ladder', async () => {
+ const started = Date.now();
+ const out = await generateReferenceImage('a low-poly fox', { budgetMs: 5_000 });
+ const elapsed = Date.now() - started;
+ // Served by the fallthrough, inside the budget, not after minutes.
+ expect(out.imageUrl).toBe('https://cdn.test/ladder.png');
+ expect(elapsed).toBeLessThan(5_000);
+ // Exactly one Vertex request: no retry-without-size, no re-roll, no QA
+ // retry once the leader share (60% of 5 s = 3 s) was gone.
+ expect(vertex.requests).toHaveLength(1);
+ expect(elapsed).toBeGreaterThanOrEqual(2_900);
+ // The ladder was handed what was left, never a fresh full budget. The
+ // ladder floors its own budget at 5 s, so that is the most it can get
+ // here; with a real 60 s budget this is the ~24 s remainder.
+ expect(ladder.calls).toHaveLength(1);
+ expect(ladder.calls[0].budgetMs).toBeLessThanOrEqual(5_000);
+ expect(ladder.calls[0].budgetMs).toBeGreaterThanOrEqual(1_000);
+ }, 15_000);
+
+ it('defaults to the shared 60 s ladder budget when the caller passes none', async () => {
+ process.env.TEXT_TO_IMAGE_BUDGET_MS = '4000';
+ try {
+ const started = Date.now();
+ await generateReferenceImage('a low-poly fox');
+ expect(Date.now() - started).toBeLessThan(4_000);
+ expect(vertex.requests).toHaveLength(1);
+ } finally {
+ delete process.env.TEXT_TO_IMAGE_BUDGET_MS;
+ }
+ }, 15_000);
+});