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(agenc): bound each RPC attempt so a silent lane rotates instead of hanging

nirholasb644c358113a
diff --git a/api/agenc/[action].js b/api/agenc/[action].js
index d20198156..92618f17a 100644
--- a/api/agenc/[action].js
+++ b/api/agenc/[action].js
@@ -159,11 +159,37 @@ export class RpcChainExhausted extends Error {
}
}
+// A lane that ACCEPTS the connection and then never answers is the one failure
+// this rotation could not see. `createAgenCClient` builds a plain
+// `new Connection(rpcUrl)`, so it never gets the rotating fetch's own
+// ATTEMPT_TIMEOUT_MS bound (that only wraps multi-endpoint Connections); undici's
+// defaults then run to minutes with nothing thrown, so `rotateRpc` sat on a dead
+// provider instead of moving to the next one. `getTasksByCreator` is the read
+// that exposed it: it is a getProgramAccounts memcmp scan, the heaviest call
+// shape here and the first any provider stalls or silently drops. Bounding each
+// attempt turns that silence back into a rotate-worthy failure.
+const AGENC_ATTEMPT_TIMEOUT_MS = 10_000;
+
+// Reject with a transient, rotate-worthy error once an attempt outruns its
+// budget. The message is deliberately shaped to match `isTransientRpcError`, so
+// a stall cools the lane exactly like a timeout reported by the provider itself.
+function attemptTimeout(rpcUrl) {
+ let timer;
+ const promise = new Promise((_, reject) => {
+ timer = setTimeout(() => {
+ reject(new Error(`Solana RPC lane timed out after ${AGENC_ATTEMPT_TIMEOUT_MS}ms: ${rpcUrl}`));
+ }, AGENC_ATTEMPT_TIMEOUT_MS);
+ });
+ // Never hold the process open on the loser of the race.
+ timer?.unref?.();
+ return { promise, cancel: () => clearTimeout(timer) };
+}
+
// Run `run` against an AgenC client, rotating to the next endpoint whenever one
// fails in a way the next provider may not share (401/403/404/408/410/429/5xx,
-// timeouts, network blips). A real request error, e.g. a malformed account the
-// chain decodes the same way everywhere, is re-thrown on the first endpoint
-// rather than replayed nine times.
+// timeouts, network blips) or simply stops answering. A real request error, e.g.
+// a malformed account the chain decodes the same way everywhere, is re-thrown on
+// the first endpoint rather than replayed nine times.
export async function rotateRpc({ cluster, endpoints, createClient, run }) {
let last = null;
for (const rpcUrl of endpoints) {
@@ -176,14 +202,19 @@ export async function rotateRpc({ cluster, endpoints, createClient, run }) {
last = err;
continue;
}
+ const bound = attemptTimeout(rpcUrl);
try {
- return await run(client);
+ return await Promise.race([run(client), bound.promise]);
} catch (err) {
const status = rpcStatus(err);
if (!shouldRotate(status) && !isTransientRpcError(err)) throw err;
const ms = markEndpointCooldown(rpcUrl, status || 429, String(err?.message || ''));
console.info(`[agenc] rpc lane failed (${status || 'transient'}), cooling ${Math.round(ms / 1000)}s, rotating`);
last = err;
+ } finally {
+ // Runs on success, rotation, and the re-thrown non-rotatable error alike,
+ // so a won race never leaves a timer pending behind the response.
+ bound.cancel();
}
}
throw new RpcChainExhausted(cluster, endpoints.length, last);
diff --git a/tests/agenc-rpc-failover.test.js b/tests/agenc-rpc-failover.test.js
index 2f0feb0d8..381db2dea 100644
--- a/tests/agenc-rpc-failover.test.js
+++ b/tests/agenc-rpc-failover.test.js
@@ -170,4 +170,74 @@ describe('rotateRpc', () => {
expect(thrown.message).toContain('503 Service Unavailable');
expect(seen).toEqual(endpoints);
});
+
+ // The failure mode the other cases could not see: a lane that accepts the
+ // connection and then answers nothing. `createAgenCClient` builds a plain
+ // `new Connection(rpcUrl)`, which never gets the rotating fetch's own
+ // per-attempt bound, so undici's defaults let a stalled provider hold the
+ // request for minutes with nothing thrown to rotate on. list-tasks surfaced it
+ // first because getTasksByCreator is a getProgramAccounts memcmp scan.
+ it('rotates past a lane that hangs instead of answering', async () => {
+ vi.useFakeTimers();
+ try {
+ const endpoints = lanes(2);
+ const seen = [];
+ const pending = rotateRpc({
+ cluster: 'mainnet',
+ endpoints,
+ createClient: clientFactory,
+ run: async (c) => {
+ seen.push(c.rpcUrl);
+ // The first lane never settles, exactly like a provider that swallows
+ // a heavy getProgramAccounts scan.
+ if (c.rpcUrl === endpoints[0]) return new Promise(() => {});
+ return { ok: true, via: c.rpcUrl };
+ },
+ });
+ await vi.advanceTimersByTimeAsync(10_000);
+ await expect(pending).resolves.toEqual({ ok: true, via: endpoints[1] });
+ expect(seen).toEqual([endpoints[0], endpoints[1]]);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('does not leave the attempt timer pending when a lane answers in time', async () => {
+ vi.useFakeTimers();
+ try {
+ const endpoints = lanes(2);
+ const out = await rotateRpc({
+ cluster: 'mainnet',
+ endpoints,
+ createClient: clientFactory,
+ run: async (c) => ({ ok: true, via: c.rpcUrl }),
+ });
+ expect(out).toEqual({ ok: true, via: endpoints[0] });
+ // A won race must clear its timer, or every served request leaves one
+ // armed behind the response.
+ expect(vi.getTimerCount()).toBe(0);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('exhausts the chain when every lane hangs', async () => {
+ vi.useFakeTimers();
+ try {
+ const endpoints = lanes(3);
+ const pending = rotateRpc({
+ cluster: 'mainnet',
+ endpoints,
+ createClient: clientFactory,
+ run: async () => new Promise(() => {}),
+ }).catch((err) => err);
+ await vi.advanceTimersByTimeAsync(10_000 * 3);
+ const thrown = await pending;
+ expect(thrown).toBeInstanceOf(RpcChainExhausted);
+ expect(thrown.tried).toBe(3);
+ expect(thrown.message).toContain('timed out');
+ } finally {
+ vi.useRealTimers();
+ }
+ });
});