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: circuit-break degraded NVIDIA NIM forge lanes so callers fail over fast

nirholas104e8d8ca922
diff --git a/api/_mcp3d/text-to-image.js b/api/_mcp3d/text-to-image.js
index 0939cdc13..2ffe27ac3 100644
--- a/api/_mcp3d/text-to-image.js
+++ b/api/_mcp3d/text-to-image.js
@@ -18,9 +18,30 @@
// free on the NVIDIA NIM catalog as base64 JPEG (no poll; returns inline).
// Replicate backstop: black-forest-labs/flux-schnell — same family, $0.003/run.
+import { markProviderCooldown, providersInCooldown } from '../_lib/provider-health.js';
+
const REPLICATE_BASE = 'https://api.replicate.com/v1';
const DEFAULT_TXT2IMG_MODEL = 'black-forest-labs/flux-schnell';
+// Circuit-breaker key + window for the free NIM FLUX synthesis lane. When NVCF
+// times out / errors, one slow window otherwise makes every text→image caller
+// (forge text→3D, avatar generation, studio) re-pay the full NIM timeout before
+// failing over. A short cooldown — recorded on a health failure, checked before
+// the lane runs — lets callers skip a degraded NIM lane and go straight to the
+// next configured provider; it expires on its own so a recovered lane is retried
+// promptly. Best-effort via the shared cache: a miss just means "not cooling".
+const NIM_FLUX_COOLDOWN_KEY = 'forge-nim-flux';
+const NIM_FLUX_COOLDOWN_SECONDS = 60;
+
+// Whether a thrown nimFluxImage error means the lane itself is degraded (timeout,
+// unreachable, throttle, or 5xx) — worth a cooldown — as opposed to a 4xx client
+// fault (bad input / key), which a cooldown would wrongly punish a healthy lane for.
+function isNimLaneDegraded(err) {
+ if (err?.code === 'provider_unreachable' || err?.code === 'rate_limited') return true;
+ const status = err?.providerStatus;
+ return typeof status === 'number' && status >= 500;
+}
+
// NVIDIA NIM FLUX.1-schnell — synchronous genai invoke (no 202/poll), returns
// { artifacts: [{ base64, finishReason }] }. flux-schnell is the fast 4-step
// distilled model, so a tight per-attempt timeout is safe: a hung free lane must
@@ -219,18 +240,32 @@ function enhanceFluxPrompt(raw) {
// paid Replicate backstop on any failure — a broken or throttled preferred
// provider must hand off, never take down the whole text→3D pipeline. The last
// configured lane's error is surfaced only when nothing is left to try.
-export async function textToImage(prompt, { aspectRatio = '1:1' } = {}) {
+export async function textToImage(prompt, { aspectRatio = '1:1', skipNim = false } = {}) {
prompt = enhanceFluxPrompt(prompt);
const token = readEnv('REPLICATE_API_TOKEN');
const hasVertex = !!readEnv('GOOGLE_CLOUD_PROJECT');
+ const hasFallback = hasVertex || !!token;
// ── NVIDIA NIM FLUX (free, first) ─────────────────────────────────────────
- if (readEnv('NVIDIA_API_KEY')) {
+ // Skip the NIM lane when a fallback exists AND either the caller just watched a
+ // sibling NVCF lane time out this same request (`skipNim` — the gateway is
+ // degraded now, so a second NIM window would just stack timeouts) or a recent
+ // NIM FLUX failure left it in cooldown. With no fallback, NIM stays the only
+ // lane and is always tried — a degraded lane beats no image at all.
+ const nimCooling =
+ hasFallback &&
+ (skipNim || (await providersInCooldown([NIM_FLUX_COOLDOWN_KEY])).has(NIM_FLUX_COOLDOWN_KEY));
+ if (readEnv('NVIDIA_API_KEY') && !nimCooling) {
try {
return await nimFluxImage(prompt, aspectRatio);
} catch (err) {
+ // A degraded lane (timeout / unreachable / throttle / 5xx) cools down so the
+ // next caller skips it; a clean 4xx (bad input) is not a lane-health fault.
+ if (isNimLaneDegraded(err)) {
+ markProviderCooldown(NIM_FLUX_COOLDOWN_KEY, NIM_FLUX_COOLDOWN_SECONDS).catch(() => {});
+ }
// Nothing downstream to fall through to → surface the NIM error.
- if (!hasVertex && !token) throw err;
+ if (!hasFallback) throw err;
// A handled degradation (Vertex/HF will serve the image), not a fault —
// warn so it doesn't read as an error in the logs like the rest of the
// free-first cascade.
diff --git a/api/forge.js b/api/forge.js
index b66fec5d0..2005bfbb7 100644
--- a/api/forge.js
+++ b/api/forge.js
@@ -86,6 +86,18 @@ import {
getCreditAccount,
refundCredits,
} from './_lib/credits.js';
+import { markProviderCooldown, providersInCooldown } from './_lib/provider-health.js';
+
+// Circuit-breaker key + window for the free NVIDIA NIM TRELLIS text→3D lane. The
+// hosted NVCF gateway can degrade so a submit neither completes nor hands back a
+// pollable id before our timeout — a single slow window otherwise makes every
+// text prompt re-pay that full timeout before failing over to the reconstruct
+// lane. A short cooldown (recorded on a health failure, checked before the lane
+// runs) lets subsequent requests skip a degraded lane and go straight to a
+// working one; it expires on its own so a recovered lane is retried promptly.
+// Best-effort via the shared cache — a miss just means "not cooling".
+const NIM_TRELLIS_COOLDOWN_KEY = 'forge-nim-trellis';
+const NIM_FORGE_COOLDOWN_SECONDS = 60;
// Holder perk (Lever 2): a presented, verified $THREE tier pass lifts the free
// generation ceiling by that tier's multiplier. The pass is pure-HMAC verifiable
@@ -237,6 +249,12 @@ async function runNvidiaTextLane({ req, res, ip, prompt, aspect, tier, path }) {
const nv = await loadNvidiaProvider();
submitted = await nv.textTo3d({ prompt, tier });
} catch (err) {
+ // A timed-out / unreachable / throttled / 5xx NIM lane is degraded — cool it
+ // down so the next request skips the submit-timeout gamble and fails over
+ // fast. A 4xx (bad input / key) is not a lane-health fault, so it never cools.
+ if (isUpstreamUnavailable(err)) {
+ markProviderCooldown(NIM_TRELLIS_COOLDOWN_KEY, NIM_FORGE_COOLDOWN_SECONDS).catch(() => {});
+ }
console.warn(`[forge] free NVIDIA NIM lane unavailable: ${err?.message || err}`);
return false;
}
@@ -470,6 +488,11 @@ async function startJob(req, res) {
// failed (draft already tries nvidia first; standard/high reach it only as a
// last-resort fallback when Replicate is down).
let nvidiaTried = false;
+ // Set once the free NVIDIA NIM TRELLIS lane is known-degraded this request
+ // (skipped on cooldown, or attempted and failed). The text→3D FLUX synthesis
+ // below then skips the sibling NIM image lane too, so a degraded NVCF gateway
+ // can't stack a second submit-timeout window on the same request.
+ let nimGatewayDegraded = false;
// Pay-per-use (Token Utility — consumption lever): set to { paymentId, refId,
// settledAt, redeemed? } once a non-holder's settled $THREE payment is accepted
@@ -993,10 +1016,24 @@ async function startJob(req, res) {
// lane that actually ran (trellis below), so the downgrade is never silent.
if (backendId === 'nvidia') {
nvidiaTried = true;
- if (await runNvidiaTextLane({ req, res, ip, prompt, aspect, tier, path })) return;
- // nvidia failed → fall through to the image-intermediate TRELLIS path
- // below, which gives the prompt a second chance on Replicate.
- backendId = 'trellis';
+ // Skip the submit-timeout gamble when the lane is in a recent-failure
+ // cooldown — go straight to the reconstruct lane instead of re-hanging.
+ const trellisCooling = (await providersInCooldown([NIM_TRELLIS_COOLDOWN_KEY])).has(
+ NIM_TRELLIS_COOLDOWN_KEY,
+ );
+ if (trellisCooling) {
+ console.warn('[forge] NVIDIA NIM TRELLIS lane in cooldown; routing to reconstruct lane');
+ nimGatewayDegraded = true;
+ backendId = 'trellis';
+ } else if (await runNvidiaTextLane({ req, res, ip, prompt, aspect, tier, path })) {
+ return;
+ } else {
+ // nvidia failed → fall through to the image-intermediate TRELLIS path
+ // below, which gives the prompt a second chance on Replicate. The NVCF
+ // gateway is degraded, so the FLUX synthesis below skips its NIM lane too.
+ nimGatewayDegraded = true;
+ backendId = 'trellis';
+ }
}
// ── Image-intermediate path (TRELLIS default, or Hunyuan3D self-host) ────
@@ -1082,7 +1119,7 @@ async function startJob(req, res) {
referenceImageUrl = imageUrls[0];
textToImageModel = null;
} else {
- const synthesized = await textToImage(prompt, { aspectRatio: aspect });
+ const synthesized = await textToImage(prompt, { aspectRatio: aspect, skipNim: nimGatewayDegraded });
referenceImageUrl = synthesized.imageUrl;
textToImageModel = synthesized.model;
views = [referenceImageUrl];
@@ -1341,13 +1378,20 @@ async function startJob(req, res) {
// already failed this request (the draft nvidia→trellis→nvidia loop).
if (isUpstreamUnavailable(err) && !isImageMode && !nvidiaTried && prompt) {
nvidiaTried = true;
- console.warn(
- `[forge] paid TRELLIS lane unavailable (${err?.providerStatus || err?.code}); degrading text→3D to free NVIDIA NIM`,
+ // Don't degrade to NIM when it's already in a recent-failure cooldown — that
+ // would just re-pay the submit timeout on a lane we know is down right now.
+ const trellisCooling = (await providersInCooldown([NIM_TRELLIS_COOLDOWN_KEY])).has(
+ NIM_TRELLIS_COOLDOWN_KEY,
);
- try {
- if (await runNvidiaTextLane({ req, res, ip, prompt, aspect, tier, path })) return;
- } catch (fallbackErr) {
- console.warn(`[forge] NVIDIA NIM fallback also failed: ${fallbackErr?.message || fallbackErr}`);
+ if (!trellisCooling) {
+ console.warn(
+ `[forge] paid TRELLIS lane unavailable (${err?.providerStatus || err?.code}); degrading text→3D to free NVIDIA NIM`,
+ );
+ try {
+ if (await runNvidiaTextLane({ req, res, ip, prompt, aspect, tier, path })) return;
+ } catch (fallbackErr) {
+ console.warn(`[forge] NVIDIA NIM fallback also failed: ${fallbackErr?.message || fallbackErr}`);
+ }
}
}
diff --git a/tests/api/text-to-image.test.js b/tests/api/text-to-image.test.js
index 9e35cf315..b83c96063 100644
--- a/tests/api/text-to-image.test.js
+++ b/tests/api/text-to-image.test.js
@@ -12,6 +12,7 @@
// Imagen PNG's size, so forwarding the data URI breaks reconstruction).
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { cacheDel } from '../../api/_lib/cache.js';
const vertexState = { configured: false, generate: null };
vi.mock('../../api/_mcp3d/vertex-imagen.js', () => ({
@@ -74,11 +75,15 @@ function stubFluxSuccess() {
return stubFetch([['api.replicate.com', () => replicateSuccessResponse()]]);
}
-beforeEach(() => {
+beforeEach(async () => {
vertexState.configured = false;
vertexState.generate = null;
r2State.puts.length = 0;
for (const k of ENV_KEYS) delete process.env[k];
+ // The NIM FLUX circuit breaker persists a short cooldown in the shared in-memory
+ // cache; clear it between tests so one test's induced NIM failure doesn't make a
+ // later test skip the (now healthy) NIM lane it means to exercise.
+ await cacheDel('llm-cooldown:forge-nim-flux');
});
afterEach(() => {
@@ -237,6 +242,52 @@ describe('textToImage — NIM FLUX free lane (first)', () => {
const textToImage = await freshTextToImage();
await expect(textToImage('a red teapot')).rejects.toThrow(/nim flux returned 401/);
});
+
+ it('skipNim bypasses the NIM lane entirely when a fallback exists', async () => {
+ // A caller that just watched a sibling NVCF lane time out passes skipNim so the
+ // degraded gateway never gets a second submit-timeout window this request.
+ process.env.NVIDIA_API_KEY = 'nvapi-test';
+ process.env.REPLICATE_API_TOKEN = 'r8_test_token';
+ const calls = stubFetch([['api.replicate.com', () => replicateSuccessResponse()]]);
+
+ const textToImage = await freshTextToImage();
+ const result = await textToImage('a red teapot', { skipNim: true });
+
+ expect(result.imageUrl).toBe('https://replicate.delivery/out.png');
+ expect(calls.some((c) => c.url.includes('ai.api.nvidia.com'))).toBe(false);
+ });
+
+ it('skipNim still uses NIM when it is the only lane (never skip into a dead end)', async () => {
+ process.env.NVIDIA_API_KEY = 'nvapi-test';
+ const calls = stubFetch([['ai.api.nvidia.com', () => nimSuccessResponse()]]);
+
+ const textToImage = await freshTextToImage();
+ const result = await textToImage('a red teapot', { skipNim: true });
+
+ expect(result.model).toBe('black-forest-labs/flux.1-schnell');
+ expect(calls.filter((c) => c.url.includes('ai.api.nvidia.com'))).toHaveLength(1);
+ });
+
+ it('a degraded NIM failure cools the lane so the next call skips it', async () => {
+ process.env.NVIDIA_API_KEY = 'nvapi-test';
+ process.env.REPLICATE_API_TOKEN = 'r8_test_token';
+ const calls = stubFetch([
+ ['ai.api.nvidia.com', () => new Response('boom', { status: 500 })],
+ ['api.replicate.com', () => replicateSuccessResponse()],
+ ]);
+ vi.spyOn(console, 'warn').mockImplementation(() => {});
+
+ const textToImage = await freshTextToImage();
+ // First call trips the breaker (NIM 500 → cooldown), still serves via Replicate.
+ await textToImage('a red teapot');
+ const nimAfterFirst = calls.filter((c) => c.url.includes('ai.api.nvidia.com')).length;
+ expect(nimAfterFirst).toBe(1);
+
+ // Second call sees the cooldown and skips NIM straight to Replicate — no new NIM hit.
+ await textToImage('a blue teapot');
+ const nimAfterSecond = calls.filter((c) => c.url.includes('ai.api.nvidia.com')).length;
+ expect(nimAfterSecond).toBe(1);
+ });
});
describe('textToImage — Vertex → Replicate fallback', () => {