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(quality-bench): bound a poll by the caller's remaining runway

nirholascb5d2906c53a
diff --git a/api/_lib/quality-bench.js b/api/_lib/quality-bench.js
index 1517be0fc..a62e414bc 100644
--- a/api/_lib/quality-bench.js
+++ b/api/_lib/quality-bench.js
@@ -147,8 +147,16 @@ export async function submitForge(baseUrl, { prompt, mode, referenceImageUrl, ti
return data;
}
-export async function pollForge(baseUrl, jobId, { timeoutMs = 10 * 60 * 1000, intervalMs = 4000 } = {}) {
- const deadline = Date.now() + timeoutMs;
+// Two independent ceilings bound the wait: this poll's own patience (timeoutMs,
+// how long one generation is worth waiting for) and `deadlineAt`, an absolute
+// wall-clock instant the CALLER must return inside. Whichever lands first wins,
+// so a caller with 40s of runway left never sits out a 10-minute poll. Callers
+// that pass no deadline (the by-hand full bench) keep the old unbounded-patience
+// behavior exactly.
+export async function pollForge(baseUrl, jobId, { timeoutMs = 10 * 60 * 1000, intervalMs = 4000, deadlineAt = Infinity } = {}) {
+ const ownDeadline = Date.now() + timeoutMs;
+ const budgetBound = deadlineAt < ownDeadline;
+ const deadline = budgetBound ? deadlineAt : ownDeadline;
while (Date.now() < deadline) {
const res = await fetch(`${baseUrl}/api/forge?job=${encodeURIComponent(jobId)}`);
const data = await res.json().catch(() => ({}));
@@ -159,15 +167,22 @@ export async function pollForge(baseUrl, jobId, { timeoutMs = 10 * 60 * 1000, in
err.code = 'generation_failed';
throw err;
}
- await sleep(intervalMs);
+ // Never sleep past the deadline: the last nap decides how far the caller
+ // overshoots its budget.
+ await sleep(Math.max(0, Math.min(intervalMs, deadline - Date.now())));
+ }
+ if (budgetBound) {
+ const err = new Error('run budget exhausted while waiting for generation');
+ err.code = 'budget_exhausted';
+ throw err;
}
throw new Error(`poll timed out after ${timeoutMs}ms`);
}
-export async function generate(baseUrl, params) {
+export async function generate(baseUrl, params, { deadlineAt = Infinity } = {}) {
const submitted = await submitForge(baseUrl, params);
if (submitted.status === 'done' && submitted.glb_url) return submitted;
- if (submitted.job_id) return pollForge(baseUrl, submitted.job_id);
+ if (submitted.job_id) return pollForge(baseUrl, submitted.job_id, { deadlineAt });
throw new Error(`unexpected forge response shape: ${JSON.stringify(submitted).slice(0, 300)}`);
}
@@ -175,7 +190,12 @@ export async function generate(baseUrl, params) {
// judge each view twice -> average. Never throws for a generation/scoring
// failure — returns a result object with status set instead, so a caller
// iterating many combos never has one bad lane abort the whole sweep.
-export async function runOne(baseUrl, promptEntry, lane, tier) {
+// `deadlineAt` is an absolute wall-clock instant this combo must be finished by.
+// A caller running under a request budget passes it so generation waits and the
+// per-view render/judge loop both stop at the line instead of running on past a
+// response nobody is listening to any more. Omitting it keeps the unbounded
+// behavior the by-hand bench relies on.
+export async function runOne(baseUrl, promptEntry, lane, tier, { deadlineAt = Infinity } = {}) {
const result = { promptId: promptEntry.id, subjectClass: promptEntry.subjectClass, lane, tier, startedAt: new Date().toISOString() };
try {
const gen = await generate(baseUrl, {
@@ -184,7 +204,7 @@ export async function runOne(baseUrl, promptEntry, lane, tier) {
referenceImageUrl: promptEntry.referenceImageUrl,
tier,
backend: lane,
- });
+ }, { deadlineAt });
result.glbUrl = gen.glb_url;
result.creationId = gen.creation_id ?? null;
// /api/forge falls back between lanes internally (a cooling NIM gateway
@@ -197,6 +217,10 @@ export async function runOne(baseUrl, promptEntry, lane, tier) {
result.cached = gen.cached === true;
result.views = [];
for (const view of CANONICAL_VIEWS) {
+ if (Date.now() >= deadlineAt) {
+ result.budgetExhausted = true;
+ break;
+ }
const viewResult = { view: view.label };
try {
const { png } = await renderClip({
@@ -216,12 +240,30 @@ export async function runOne(baseUrl, promptEntry, lane, tier) {
result.views.push(viewResult);
}
const okViews = result.views.filter((v) => v.avg);
- result.status = okViews.length ? 'ok' : 'scoring_failed';
- result.meanScore = okViews.length ? okViews.reduce((s, v) => s + v.avg.mean, 0) / okViews.length : null;
+ if (result.budgetExhausted) {
+ // A combo whose view sweep was cut short is not a comparable data point:
+ // scoring it against a baseline built from complete sweeps would read a
+ // short clock as a quality change. Keep the partial views for diagnosis
+ // and withhold the score.
+ result.status = 'budget_exhausted';
+ result.meanScore = null;
+ } else {
+ result.status = okViews.length ? 'ok' : 'scoring_failed';
+ result.meanScore = okViews.length ? okViews.reduce((s, v) => s + v.avg.mean, 0) / okViews.length : null;
+ }
} catch (genErr) {
- result.status = 'lane_failed';
- result.error = genErr.message;
- result.meanScore = 0;
+ if (genErr.code === 'budget_exhausted') {
+ // Same reasoning: out of time is not the same finding as a broken lane,
+ // so it must not be scored as a zero.
+ result.status = 'budget_exhausted';
+ result.budgetExhausted = true;
+ result.error = genErr.message;
+ result.meanScore = null;
+ } else {
+ result.status = 'lane_failed';
+ result.error = genErr.message;
+ result.meanScore = 0;
+ }
}
result.finishedAt = new Date().toISOString();
return result;
diff --git a/api/cron/quality-bench.js b/api/cron/quality-bench.js
index 75780baa0..792a82a50 100644
--- a/api/cron/quality-bench.js
+++ b/api/cron/quality-bench.js
@@ -22,9 +22,21 @@ import { requireCron } from '../_lib/cron-auth.js';
export const maxDuration = 300;
+// Nothing enforces `maxDuration` here. It is a Vercel declaration, and this runs
+// on Cloud Run, where the only ceilings are the Cloud Scheduler job's 320s
+// attempt deadline and Cloud Run's own 900s request timeout. So the sweep has to
+// bound itself. Until it did, "kept deliberately short" was an intention rather
+// than a limit: the 2026-08-10 run spent 900s, collected a 504 from Cloud Run,
+// left Scheduler recording the job as DEADLINE_EXCEEDED, and then logged its
+// summary 21 minutes later into a request nobody was reading.
+const RESPONSE_RESERVE_MS = 20_000;
+const BUDGET_MS = maxDuration * 1000 - RESPONSE_RESERVE_MS;
+// Starting another prompt with less runway than this just burns forge capacity
+// on a result that cannot land, so the sweep skips it and says so instead.
+const MIN_PROMPT_MS = 45_000;
+
// A small, fixed, cheap-to-run cross-section of the full bench: one
// people/organic subject, one hard-surface subject, one architecture subject.
-// Kept deliberately short so the whole sweep fits inside maxDuration.
const SMOKE_PROMPT_IDS = ['qb01', 'qb09', 'qb12'];
const SMOKE_TIER = 'standard';
const REGRESSION_THRESHOLD = 1.0;
@@ -65,6 +77,10 @@ export default wrapCron(async (req, res) => {
if (!method(req, res, ['GET'])) return;
if (!requireCron(req, res)) return;
+ // Clock starts before the catalog fetch: loading the catalog is part of the
+ // budget, not free time in front of it.
+ const startedAt = Date.now();
+ const deadlineAt = startedAt + BUDGET_MS;
const baseUrl = `https://${req.headers.host || 'three.ws'}`;
let catalog;
@@ -84,14 +100,24 @@ export default wrapCron(async (req, res) => {
const prompts = SMOKE_PROMPT_IDS.map((id) => allPrompts.find((p) => p.id === id)).filter(Boolean);
const results = [];
+ const skippedForBudget = [];
for (const p of prompts) {
- results.push(await runOne(baseUrl, p, lane, SMOKE_TIER));
+ if (Date.now() + MIN_PROMPT_MS > deadlineAt) {
+ skippedForBudget.push(p.id);
+ continue;
+ }
+ results.push(await runOne(baseUrl, p, lane, SMOKE_TIER, { deadlineAt }));
}
const scored = results.filter((r) => typeof r.meanScore === 'number');
const smokeMean = scored.length ? scored.reduce((s, r) => s + r.meanScore, 0) / scored.length : null;
const baseline = await baselineMean(lane, SMOKE_TIER);
+ // A sweep that ran out of clock covers fewer prompts than the baseline it
+ // would be compared against, so its delta measures the budget, not the
+ // models. Report it loudly and do not let it trip the regression alarm.
+ const complete = !skippedForBudget.length && !results.some((r) => r.status === 'budget_exhausted');
+
const summary = {
kind: 'quality-bench-smoke',
lane,
@@ -100,12 +126,18 @@ export default wrapCron(async (req, res) => {
smokeMean,
baselineMean: baseline,
delta: smokeMean != null && baseline != null ? smokeMean - baseline : null,
+ complete,
+ skippedForBudget,
+ budgetMs: BUDGET_MS,
+ elapsedMs: Date.now() - startedAt,
perPrompt: results.map((r) => ({ promptId: r.promptId, status: r.status, meanScore: r.meanScore, error: r.error || null })),
};
- const regressed = summary.delta != null && summary.delta < -REGRESSION_THRESHOLD;
+ const regressed = complete && summary.delta != null && summary.delta < -REGRESSION_THRESHOLD;
if (regressed) {
console.error('[cron] quality-bench REGRESSION', summary);
+ } else if (!complete) {
+ console.warn('[cron] quality-bench INCOMPLETE (ran out of budget)', summary);
} else {
console.log('[cron] quality-bench smoke run', summary);
}
diff --git a/tests/quality-bench-budget.test.js b/tests/quality-bench-budget.test.js
new file mode 100644
index 000000000..434ba1461
--- /dev/null
+++ b/tests/quality-bench-budget.test.js
@@ -0,0 +1,112 @@
+/**
+ * quality-bench run budget (pollForge / runOne `deadlineAt`).
+ *
+ * The weekly /api/cron/quality-bench sweep runs on Cloud Run, where nothing
+ * enforces the handler's `maxDuration`. With no self-imposed ceiling the
+ * 2026-08-10 run spent 900s on three sequential generations, took a 504 from
+ * Cloud Run, left Cloud Scheduler recording DEADLINE_EXCEEDED, and logged its
+ * summary 21 minutes after anyone could read it. `deadlineAt` is the fix.
+ * Contracts under test:
+ * 1. A caller's wall-clock deadline beats pollForge's own patience, and the
+ * failure is tagged `budget_exhausted` rather than a generic poll timeout.
+ * 2. No deadline means the old unbounded-patience behavior, unchanged, so the
+ * by-hand full bench in scripts/quality-bench.mjs is untouched.
+ * 3. Running out of clock during generation is NOT scored as a zero the way a
+ * broken lane is: it yields a null meanScore, so a short clock can never be
+ * read as a quality regression.
+ * 4. The per-view render/judge loop stops at the deadline too, instead of
+ * running on past a response nobody is listening to.
+ */
+
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+
+const renderClip = vi.fn();
+vi.mock('../api/_lib/render-clip.js', () => ({ renderClip: (...a) => renderClip(...a) }));
+vi.mock('../api/_lib/vertex-gemini.js', () => ({
+ vertexGeminiAvailable: () => false,
+ vertexGeminiChatUrl: () => 'https://vertex.invalid/chat',
+ vertexGeminiHeaders: async () => ({}),
+}));
+
+import { pollForge, runOne } from '../api/_lib/quality-bench.js';
+
+const BASE = 'https://three.ws';
+const PROMPT = { id: 'qb01', subjectClass: 'people', prompt: 'a stone bust', mode: 'text' };
+
+// Forge stand-in: POST /api/forge submits, GET /api/forge?job= reports status.
+// `submitResponse` decides whether generation resolves instantly or has to poll.
+function stubForge({ submitResponse, pollStatus = 'running' }) {
+ return vi.fn(async (url, init) => {
+ const method = init?.method || 'GET';
+ if (method === 'POST') return { ok: true, json: async () => submitResponse };
+ return { ok: true, json: async () => ({ status: pollStatus }) };
+ });
+}
+
+let realFetch;
+beforeEach(() => {
+ realFetch = globalThis.fetch;
+ renderClip.mockReset();
+});
+afterEach(() => {
+ globalThis.fetch = realFetch;
+ vi.restoreAllMocks();
+});
+
+describe('pollForge deadlineAt', () => {
+ it('stops at the caller budget instead of waiting out its own timeout', async () => {
+ globalThis.fetch = stubForge({ submitResponse: { job_id: 'j1' } });
+ const started = Date.now();
+ await expect(
+ pollForge(BASE, 'j1', { timeoutMs: 10 * 60 * 1000, intervalMs: 10, deadlineAt: Date.now() + 60 }),
+ ).rejects.toMatchObject({ code: 'budget_exhausted' });
+ // It must give up on the budget, nowhere near the 10-minute patience.
+ expect(Date.now() - started).toBeLessThan(5000);
+ });
+
+ it('keeps the plain timeout error when no budget is passed', async () => {
+ globalThis.fetch = stubForge({ submitResponse: { job_id: 'j1' } });
+ await expect(pollForge(BASE, 'j1', { timeoutMs: 40, intervalMs: 10 })).rejects.toThrow(
+ /poll timed out after 40ms/,
+ );
+ });
+
+ it('returns the finished job when it lands inside the budget', async () => {
+ globalThis.fetch = stubForge({ submitResponse: { job_id: 'j1' }, pollStatus: 'done' });
+ await expect(pollForge(BASE, 'j1', { intervalMs: 10, deadlineAt: Date.now() + 5000 })).resolves.toMatchObject({
+ status: 'done',
+ });
+ });
+});
+
+describe('runOne under a budget', () => {
+ it('reports an exhausted budget without scoring it as a zero', async () => {
+ globalThis.fetch = stubForge({ submitResponse: { job_id: 'j1' } });
+ const result = await runOne(BASE, PROMPT, 'lane-a', 'standard', { deadlineAt: Date.now() + 60 });
+ expect(result.status).toBe('budget_exhausted');
+ // A broken lane scores 0 and drags the mean down. Out of time must not:
+ // null keeps it out of the comparison entirely.
+ expect(result.meanScore).toBeNull();
+ expect(renderClip).not.toHaveBeenCalled();
+ });
+
+ it('still scores a lane failure as a zero', async () => {
+ globalThis.fetch = vi.fn(async (url, init) => {
+ if ((init?.method || 'GET') === 'POST') return { ok: false, json: async () => ({ error: 'lane down' }) };
+ return { ok: true, json: async () => ({ status: 'running' }) };
+ });
+ const result = await runOne(BASE, PROMPT, 'lane-a', 'standard', { deadlineAt: Date.now() + 5000 });
+ expect(result.status).toBe('lane_failed');
+ expect(result.meanScore).toBe(0);
+ });
+
+ it('stops the view sweep at the deadline once generation is done', async () => {
+ globalThis.fetch = stubForge({ submitResponse: { status: 'done', glb_url: 'https://cdn.invalid/a.glb' } });
+ const result = await runOne(BASE, PROMPT, 'lane-a', 'standard', { deadlineAt: Date.now() - 1 });
+ expect(result.glbUrl).toBe('https://cdn.invalid/a.glb');
+ expect(result.status).toBe('budget_exhausted');
+ expect(result.meanScore).toBeNull();
+ expect(result.views).toEqual([]);
+ expect(renderClip).not.toHaveBeenCalled();
+ });
+});