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(solana-rpc): name the transport errno, re-sweep once when every lane dies at the wire, and serve last-good reads instead of a 502

nirholas801be9857238
diff --git a/api/_lib/solana/connection.js b/api/_lib/solana/connection.js
index 3673a92d2..d4f7a924b 100644
--- a/api/_lib/solana/connection.js
+++ b/api/_lib/solana/connection.js
@@ -201,6 +201,165 @@ const RATE_LIMIT_COOLDOWN_MS = 10 * 60_000; // 10m, transient 429
const AUTH_COOLDOWN_MS = 30 * 60_000; // 30m: bad/expired key on this provider only
const SERVER_COOLDOWN_MS = 2 * 60_000; // 2m: provider 5xx
const NETWORK_COOLDOWN_MS = 30_000; // 30s: fetch threw (DNS/connection blip)
+
+// ---------------------------------------------------------------------------
+// Whole-chain transport failure: re-sweep, then serve last-good
+// ---------------------------------------------------------------------------
+// On 2026-08-27 the fleet logged "[solana-rpc] all 10 endpoints failed this
+// request, fetch failed" roughly 2,000 times an hour while a direct probe of the
+// same lanes from the same region answered fine. Ten unrelated hosts do not die
+// in the same millisecond; when every lane fails with a transport error (DNS,
+// refused socket, reset) inside one request, the weather is on OUR side of the
+// wire (instance egress, resolver, socket pool), and it clears in well under a
+// second. Three fallbacks stack here, cheapest first:
+// 1. The error carries the undici cause code (ECONNRESET, EAI_AGAIN, ...).
+// "fetch failed" alone told nobody where to look for a week.
+// 2. One jittered re-sweep of every lane after a short pause, only when the
+// first sweep was transport-only (an HTTP 429 or a quota body is a verdict
+// about the lane, not the wire, and never triggers it).
+// 3. Idempotent READ methods answer from the last body a lane returned for the
+// identical call, marked stale in a response header, instead of a 502. A
+// holdings list from a few minutes ago is what the wallet hub should show
+// during a thirty-second egress blip; "could not read the wallet balance"
+// is not. Blockhash and slot reads are excluded on purpose: a stale
+// blockhash produces a transaction that fails later and worse.
+const RESWEEP_DELAY_MIN_MS = 250;
+const RESWEEP_DELAY_MAX_MS = 700;
+const LAST_GOOD_TTL_SECONDS = 15 * 60;
+const LAST_GOOD_MAX_BYTES = 256 * 1024;
+// A success re-publishes its body at most this often per call shape, so the
+// steady state costs one cache write a minute per distinct read, not one per
+// RPC call.
+const LAST_GOOD_WRITE_INTERVAL_MS = 60_000;
+const LAST_GOOD_WRITE_MEMO_MAX = 4000;
+const LAST_GOOD_READ_METHODS = new Set([
+ 'getBalance',
+ 'getAccountInfo',
+ 'getMultipleAccounts',
+ 'getTokenAccountBalance',
+ 'getTokenAccountsByOwner',
+ 'getTokenAccountsByDelegate',
+ 'getTokenSupply',
+ 'getTokenLargestAccounts',
+ 'getProgramAccounts',
+ 'getSignaturesForAddress',
+ 'getTransaction',
+ 'getMinimumBalanceForRentExemption',
+ 'getAsset',
+ 'getAssetsByOwner',
+ 'getAssetsByGroup',
+ 'getTokenAccounts',
+]);
+
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+
+/**
+ * The network-level cause behind a thrown fetch, or '' when the error was not a
+ * transport failure (an abort, a timeout, an HTTP verdict already classified).
+ * undici wraps every socket/DNS failure as `TypeError: fetch failed` with the
+ * errno on `cause`; that code is the only diagnostic worth having.
+ */
+export function transportCause(err) {
+ if (!err) return '';
+ const code = err.cause?.code || err.code;
+ if (typeof code === 'string' && code) return code;
+ const msg = String(err.message || err);
+ if (/fetch failed|socket hang up|ECONNRESET|ECONNREFUSED|ETIMEDOUT|EAI_AGAIN|ENOTFOUND|network error/i.test(msg)) {
+ return 'transport';
+ }
+ return '';
+}
+
+/** djb2 over a string. Keys the last-good cache; collisions are made harmless by including the method and length in the key. */
+function hashText(text) {
+ let h = 5381;
+ for (let i = 0; i < text.length; i++) h = ((h * 33) ^ text.charCodeAt(i)) >>> 0;
+ return h.toString(36);
+}
+
+/**
+ * The last-good cache key for a single (non-batch) read call, or null when the
+ * body is a batch, a write, a subscription, or anything not on the read list.
+ * The JSON-RPC id is excluded so every caller of the same read shares one entry.
+ */
+export function lastGoodKey(body) {
+ if (typeof body !== 'string' || !body || body.length > LAST_GOOD_MAX_BYTES) return null;
+ let parsed;
+ try {
+ parsed = JSON.parse(body);
+ } catch {
+ return null;
+ }
+ if (!parsed || Array.isArray(parsed) || typeof parsed !== 'object') return null;
+ if (!LAST_GOOD_READ_METHODS.has(parsed.method)) return null;
+ const shape = JSON.stringify({ method: parsed.method, params: parsed.params ?? [] });
+ return `rpclastgood:v1:${parsed.method}:${shape.length}:${hashText(shape)}`;
+}
+
+const _lastGoodWrittenAt = new Map(); // key → epoch ms of the last publish
+async function publishLastGood(key, okBody) {
+ if (!key || okBody.length > LAST_GOOD_MAX_BYTES) return;
+ const now = Date.now();
+ if (now - (_lastGoodWrittenAt.get(key) || 0) < LAST_GOOD_WRITE_INTERVAL_MS) return;
+ let parsed;
+ try {
+ parsed = JSON.parse(okBody);
+ } catch {
+ return;
+ }
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed) || parsed.error || !('result' in parsed)) return;
+ if (_lastGoodWrittenAt.size >= LAST_GOOD_WRITE_MEMO_MAX) _lastGoodWrittenAt.clear();
+ _lastGoodWrittenAt.set(key, now);
+ try {
+ const cache = await sharedCache();
+ if (!cache) return;
+ await cache.cacheSet(key, { result: parsed.result, at: now }, LAST_GOOD_TTL_SECONDS);
+ } catch {
+ /* best effort: the live answer already went out */
+ }
+}
+
+/**
+ * The last body a lane returned for this exact read, re-addressed to the
+ * caller's request id, or null. Returned as a Response so the rotation can hand
+ * it to web3.js unchanged; `x-solana-rpc-stale` carries the age in ms so a
+ * proxy or handler can surface "as of" to the user.
+ */
+async function serveLastGood(key, body) {
+ if (!key) return null;
+ try {
+ const cache = await sharedCache();
+ if (!cache) return null;
+ const hit = await cache.cacheGet(key);
+ if (!hit || typeof hit !== 'object' || !('result' in hit)) return null;
+ const id = JSON.parse(body).id ?? null;
+ return new Response(JSON.stringify({ jsonrpc: '2.0', id, result: hit.result }), {
+ status: 200,
+ headers: {
+ 'content-type': 'application/json',
+ 'x-solana-rpc-stale': String(Math.max(0, Date.now() - (Number(hit.at) || 0))),
+ },
+ });
+ } catch {
+ return null;
+ }
+}
+
+const _staleLogAt = new Map(); // method → epoch ms of the last stale-serve log
+function logStaleServe(method, ageMs, cause) {
+ const now = Date.now();
+ if (now - (_staleLogAt.get(method) || 0) < 30_000) return;
+ _staleLogAt.set(method, now);
+ console.warn(
+ `[solana-rpc] every lane failed ${method} (${cause}); serving last-good from ${formatCooldown(ageMs)} ago`,
+ );
+}
+
+/** Test hook: forget every last-good publish timestamp so a fresh write is observable. */
+export function _resetLastGoodMemo() {
+ _lastGoodWrittenAt.clear();
+ _staleLogAt.clear();
+}
// A lane refusing ONE call shape is demoted for that method alone, never for the
// lane. Short, because a policy block is a provider setting that can change and
// re-probing costs exactly one request that transparently fails over, unlike a
@@ -1365,6 +1524,7 @@ export function makeRotatingFetch(endpoints) {
'content-type': resp.headers.get('content-type') || 'application/json',
},
}),
+ okBody,
};
} catch (err) {
const disposition = throwDisposition({
@@ -1377,6 +1537,15 @@ export function makeRotatingFetch(endpoints) {
} else if (disposition === 'cool-lane') {
_endpointCooldown.set(url, Date.now() + NETWORK_COOLDOWN_MS);
}
+ // A transport failure is re-thrown with its errno and the lane on the
+ // message, so the exhausted-chain warning names the real fault
+ // (EAI_AGAIN is a resolver problem, ECONNRESET a socket one) instead of
+ // undici's bare "fetch failed". The original stays on `cause`.
+ const cause = disposition === 'cool-lane' ? transportCause(err) : '';
+ if (cause) {
+ const tagged = new Error(`${err?.message || 'fetch failed'} (${cause}) @ ${maskUrl(url)}`, { cause: err });
+ return { error: tagged, transport: true };
+ }
return { error: err };
}
};
@@ -1389,6 +1558,15 @@ export function makeRotatingFetch(endpoints) {
else hydrateEndpointCooldowns();
let lastErr = null;
+ // The last-good key for this call (null for a batch, a write, or a read not
+ // on the list), and whether every failed attempt so far was a transport
+ // error. Both feed the two whole-chain fallbacks after the passes.
+ const staleKey = lastGoodKey(typeof init?.body === 'string' ? init.body : '');
+ let transportOnly = true;
+ const succeed = (out) => {
+ if (out.okBody !== undefined) publishLastGood(staleKey, out.okBody);
+ return out.response;
+ };
// Passes widen the candidate set only when the narrower one had nothing to
// try. Pass 1 skips both lane cooldowns and lanes demoted for this call shape.
// Pass 2 forgives cooldowns so a just-recovered node still gets exercised but
@@ -1411,14 +1589,40 @@ export function makeRotatingFetch(endpoints) {
if (!pass.ignoreCapability && isAnyMethodDemoted(url, methods)) continue;
attempted = true;
const out = await tryEndpoint(url);
- if (out.response) return out.response;
+ if (out.response) return succeed(out);
lastErr = out.error;
+ if (!out.transport) transportOnly = false;
}
// This pass actually exercised at least one candidate and they all failed
// this request: the chain is genuinely down for it right now, so don't
// force a wider sweep that would just re-hammer known-bad lanes.
if (attempted) break;
}
+ // Every lane died at the transport layer inside one request. That is not
+ // ten providers failing, it is this instance's egress hiccuping, and it is
+ // usually over before the caller's own timeout: one jittered re-sweep of
+ // every lane (the cooldowns just set were set by THIS request, so they are
+ // ignored) turns most of those into a normal answer. Never for a caller
+ // that has already walked away.
+ if (transportOnly && lastErr && init?.signal?.aborted !== true) {
+ await sleep(RESWEEP_DELAY_MIN_MS + Math.random() * (RESWEEP_DELAY_MAX_MS - RESWEEP_DELAY_MIN_MS));
+ for (const url of endpoints) {
+ if (init?.signal?.aborted === true) break;
+ if (isAnyMethodDemoted(url, methods)) continue;
+ const out = await tryEndpoint(url);
+ if (out.response) return succeed(out);
+ lastErr = out.error;
+ }
+ }
+ // Still nothing. A read that a lane answered recently is served from that
+ // answer, stale-marked, rather than as a 502: the page keeps its data and
+ // the caller can say "as of N minutes ago". Writes and blockhash reads fall
+ // through to the error, because a stale answer to those is worse than none.
+ const stale = await serveLastGood(staleKey, init?.body);
+ if (stale) {
+ logStaleServe(methods[0] || 'read', Number(stale.headers.get('x-solana-rpc-stale')) || 0, lastErr?.message || 'unknown error');
+ return stale;
+ }
// Reached the end with every provider failing in this one request, the caller
// gets a thrown error (→ a clean 502 from the proxy), never garbage. THIS is
// worth a warning: the whole failover chain is down, not just one lane.
diff --git a/api/solana-rpc.js b/api/solana-rpc.js
index cb0026175..af9c0e7c0 100644
--- a/api/solana-rpc.js
+++ b/api/solana-rpc.js
@@ -181,5 +181,13 @@ export default wrap(async function handler(req, res) {
res.statusCode = upstream.status;
res.setHeader('content-type', 'application/json; charset=utf-8');
res.setHeader('cache-control', 'no-store');
+ // The rotation answers an idempotent read from its last-good body when every
+ // lane is down (api/_lib/solana/connection.js); pass the age through so a
+ // browser can render "as of N minutes ago" instead of trusting it as live.
+ const staleMs = upstream.headers.get('x-solana-rpc-stale');
+ if (staleMs) {
+ res.setHeader('x-solana-rpc-stale', staleMs);
+ res.setHeader('access-control-expose-headers', 'x-solana-rpc-stale');
+ }
res.end(text);
});
diff --git a/tests/solana-rpc-method-capability.test.js b/tests/solana-rpc-method-capability.test.js
index 2d982b0a9..4d89a43de 100644
--- a/tests/solana-rpc-method-capability.test.js
+++ b/tests/solana-rpc-method-capability.test.js
@@ -266,12 +266,17 @@ describe('makeRotatingFetch: a method refusal demotes the method, never the lane
global.fetch = vi.fn(async () => (refuse ? resp(PUBLICNODE_403_BODY, 403) : resp(OK)));
const rf = makeRotatingFetch([a, b]);
- await expect(rf(null, rpc('getTokenAccountsByOwner'))).rejects.toThrow();
+ // A distinct owner: the rotation now answers an idempotent read from its
+ // last-good body when every lane fails, and an earlier test already fed it
+ // the parameterless shape. This test is about the demotion bookkeeping, so
+ // it must ask something no lane has ever answered.
+ const ask = rpc('getTokenAccountsByOwner', ['cap-g-owner']);
+ await expect(rf(null, ask)).rejects.toThrow();
expect(isMethodDemoted(a, 'getTokenAccountsByOwner')).toBe(true);
expect(isMethodDemoted(b, 'getTokenAccountsByOwner')).toBe(true);
refuse = false;
- const out = await rf(null, rpc('getTokenAccountsByOwner'));
+ const out = await rf(null, ask);
expect((await out.json()).result).toEqual({ ok: true });
});
diff --git a/tests/solana-rpc-transport-fallback.test.js b/tests/solana-rpc-transport-fallback.test.js
new file mode 100644
index 000000000..8f5dd88fc
--- /dev/null
+++ b/tests/solana-rpc-transport-fallback.test.js
@@ -0,0 +1,150 @@
+// Whole-chain transport fallbacks in the Solana RPC rotation: the cause code on
+// the exhausted-chain error, the jittered re-sweep when every lane died at the
+// wire, and last-good serving for idempotent reads when the chain stays down.
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import {
+ makeRotatingFetch,
+ transportCause,
+ lastGoodKey,
+ _resetLastGoodMemo,
+} from '../api/_lib/solana/connection.js';
+
+const body = (method, params = [], id = 7) => JSON.stringify({ jsonrpc: '2.0', id, method, params });
+const ok = (result, id = 7) =>
+ new Response(JSON.stringify({ jsonrpc: '2.0', id, result }), {
+ status: 200,
+ headers: { 'content-type': 'application/json' },
+ });
+const netFail = (code) => {
+ const err = new TypeError('fetch failed');
+ err.cause = Object.assign(new Error(code), { code });
+ return err;
+};
+
+let origFetch;
+beforeEach(() => {
+ origFetch = global.fetch;
+ _resetLastGoodMemo();
+});
+afterEach(() => {
+ global.fetch = origFetch;
+ vi.restoreAllMocks();
+});
+
+describe('transportCause', () => {
+ it('surfaces the undici errno behind "fetch failed"', () => {
+ expect(transportCause(netFail('ECONNRESET'))).toBe('ECONNRESET');
+ expect(transportCause(netFail('EAI_AGAIN'))).toBe('EAI_AGAIN');
+ });
+ it('names a bare transport failure without an errno, and ignores everything else', () => {
+ expect(transportCause(new TypeError('fetch failed'))).toBe('transport');
+ expect(transportCause(new Error('solana rpc 429 @ https://x'))).toBe('');
+ const abort = new Error('This operation was aborted');
+ abort.name = 'AbortError';
+ expect(transportCause(abort)).toBe('');
+ expect(transportCause(null)).toBe('');
+ });
+});
+
+describe('lastGoodKey', () => {
+ it('keys an idempotent read by method and params, never by request id', () => {
+ const a = lastGoodKey(body('getBalance', ['abc'], 1));
+ const b = lastGoodKey(body('getBalance', ['abc'], 99));
+ expect(a).toBeTruthy();
+ expect(a).toBe(b);
+ expect(lastGoodKey(body('getBalance', ['xyz']))).not.toBe(a);
+ });
+ it('refuses writes, blockhash and slot reads, batches, and junk', () => {
+ expect(lastGoodKey(body('sendTransaction', ['sig']))).toBeNull();
+ expect(lastGoodKey(body('getLatestBlockhash'))).toBeNull();
+ expect(lastGoodKey(body('getSlot'))).toBeNull();
+ expect(lastGoodKey(JSON.stringify([JSON.parse(body('getBalance', ['a']))]))).toBeNull();
+ expect(lastGoodKey('not json')).toBeNull();
+ expect(lastGoodKey('')).toBeNull();
+ });
+});
+
+describe('makeRotatingFetch whole-chain transport fallbacks', () => {
+ it('re-sweeps every lane once after a transport-only first sweep and returns the live answer', async () => {
+ const eps = ['https://resweep-a.test/', 'https://resweep-b.test/'];
+ let calls = 0;
+ global.fetch = vi.fn(async () => {
+ calls += 1;
+ if (calls <= 2) throw netFail('ECONNRESET');
+ return ok({ value: 42 });
+ });
+ const resp = await makeRotatingFetch(eps)(eps[0], { method: 'POST', body: body('getSlot') });
+ expect(await resp.json()).toMatchObject({ result: { value: 42 } });
+ expect(calls).toBe(3);
+ });
+
+ it('does not re-sweep when a lane failed with an HTTP verdict rather than at the wire', async () => {
+ const eps = ['https://verdict-a.test/', 'https://verdict-b.test/'];
+ let calls = 0;
+ global.fetch = vi.fn(async (url) => {
+ calls += 1;
+ if (String(url).includes('verdict-a')) return new Response('slow down', { status: 429 });
+ throw netFail('ECONNREFUSED');
+ });
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ await expect(
+ makeRotatingFetch(eps)(eps[0], { method: 'POST', body: body('getSlot') }),
+ ).rejects.toThrow(/ECONNREFUSED/);
+ expect(calls).toBe(2);
+ expect(warn.mock.calls.some(([m]) => /all 2 endpoints failed .*ECONNREFUSED/.test(m))).toBe(true);
+ });
+
+ it('names the errno on the exhausted-chain error instead of a bare "fetch failed"', async () => {
+ const eps = ['https://errno-a.test/'];
+ global.fetch = vi.fn(async () => {
+ throw netFail('EAI_AGAIN');
+ });
+ vi.spyOn(console, 'warn').mockImplementation(() => {});
+ await expect(
+ makeRotatingFetch(eps)(eps[0], { method: 'POST', body: body('getSlot') }),
+ ).rejects.toThrow(/fetch failed \(EAI_AGAIN\) @ https:\/\/errno-a\.test/);
+ });
+
+ it('serves the last-good body for an idempotent read when the whole chain stays down', async () => {
+ const eps = ['https://stale-a.test/'];
+ let down = false;
+ global.fetch = vi.fn(async () => {
+ if (down) throw netFail('ECONNRESET');
+ return ok({ context: { slot: 1 }, value: 1234 }, 7);
+ });
+ const rotate = makeRotatingFetch(eps);
+ const live = await rotate(eps[0], { method: 'POST', body: body('getBalance', ['wallet1'], 7) });
+ expect(await live.json()).toMatchObject({ id: 7, result: { value: 1234 } });
+ // The publish is fire-and-forget; let it land.
+ await new Promise((r) => setTimeout(r, 20));
+
+ down = true;
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const stale = await rotate(eps[0], { method: 'POST', body: body('getBalance', ['wallet1'], 31) });
+ expect(stale.status).toBe(200);
+ expect(Number(stale.headers.get('x-solana-rpc-stale'))).toBeGreaterThanOrEqual(0);
+ // Re-addressed to the caller's own request id so web3.js matches it.
+ expect(await stale.json()).toMatchObject({ id: 31, result: { value: 1234 } });
+ expect(warn.mock.calls.some(([m]) => /serving last-good/.test(m))).toBe(true);
+
+ // A different wallet has no last-good and still fails honestly.
+ await expect(
+ rotate(eps[0], { method: 'POST', body: body('getBalance', ['wallet2'], 32) }),
+ ).rejects.toThrow(/ECONNRESET/);
+ });
+
+ it('never serves a stale blockhash', async () => {
+ const eps = ['https://hash-a.test/'];
+ let down = false;
+ global.fetch = vi.fn(async () => {
+ if (down) throw netFail('ECONNRESET');
+ return ok({ value: { blockhash: 'abc', lastValidBlockHeight: 1 } });
+ });
+ const rotate = makeRotatingFetch(eps);
+ await rotate(eps[0], { method: 'POST', body: body('getLatestBlockhash') });
+ await new Promise((r) => setTimeout(r, 20));
+ down = true;
+ vi.spyOn(console, 'warn').mockImplementation(() => {});
+ await expect(rotate(eps[0], { method: 'POST', body: body('getLatestBlockhash') })).rejects.toThrow(/ECONNRESET/);
+ });
+});