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(agent-index): stop the Solana sweep on an RPC brownout and report EVM backlog honestly when a crawl fails

nirholas26d560f0bf75
diff --git a/api/_lib/ops/index-lag.js b/api/_lib/ops/index-lag.js
index 06bd43161..d01b1b920 100644
--- a/api/_lib/ops/index-lag.js
+++ b/api/_lib/ops/index-lag.js
@@ -79,6 +79,7 @@ function withTimeout(promise, ms) {
* evm: { lagMin: number|null, chains: number, configuredChains: number,
* uncrawledChains: number, staleChains: number, worstBlocksBehind: number,
* behindChains: number, worstChainId: number|null, worstChainName: string|null,
+ * stalestChainId: number|null, stalestChainName: string|null,
* historyGapChains: number, historyGapBlocks: number, events: number },
* lastEventAt: string|null,
* lastIndexedAt: string|null,
@@ -115,8 +116,12 @@ export async function readIndexLag() {
coalesce(sum(history_gap_blocks), 0)::bigint AS gap_blocks,
(
SELECT chain_id FROM erc8004_crawl_cursor
- ORDER BY blocks_behind DESC LIMIT 1
- )::int AS worst_chain_id
+ ORDER BY blocks_behind DESC, updated_at ASC LIMIT 1
+ )::int AS worst_chain_id,
+ (
+ SELECT chain_id FROM erc8004_crawl_cursor
+ ORDER BY updated_at ASC LIMIT 1
+ )::int AS stalest_chain_id
FROM erc8004_crawl_cursor
`,
QUERY_TIMEOUT_MS,
@@ -139,6 +144,8 @@ export async function readIndexLag() {
const t = totals[0] || {};
const worstChainId = e.worst_chain_id ?? null;
+ const stalestChainId = e.stalest_chain_id ?? null;
+ const chainName = (id) => CHAINS.find((c) => c.id === id)?.name ?? null;
return {
solana: {
@@ -163,7 +170,14 @@ export async function readIndexLag() {
behindChains: e.behind_chains ?? 0,
worstBlocksBehind: Number(e.worst_blocks_behind ?? 0),
worstChainId,
- worstChainName: CHAINS.find((c) => c.id === worstChainId)?.name ?? null,
+ worstChainName: chainName(worstChainId),
+ // The chain whose cursor is oldest, which is the one the worst cursor age
+ // belongs to. Distinct from the worst backlog on purpose: on 2026-10-08
+ // the detail paired a 639-hour cursor age with "worst backlog 0 blocks"
+ // and the name of a healthy chain that merely won a tie at zero, while
+ // the testnet actually stuck went unnamed.
+ stalestChainId,
+ stalestChainName: chainName(stalestChainId),
// Blocks the crawl skipped past a provider that no longer serves them.
// Reported, never scored: the gap is history that is already lost, so
// letting it drive the verdict would keep the subsystem red forever
@@ -265,9 +279,11 @@ export function indexLagVerdict(lag) {
const evmPart =
lag.evm.chains === 0
? 'EVM: no chain cursors'
- : `EVM: ${fmt(lag.evm.lagMin)} worst cursor age across ${lag.evm.chains}/${lag.evm.configuredChains} chains` +
+ : `EVM: ${fmt(lag.evm.lagMin)} worst cursor age` +
+ (lag.evm.staleChains && lag.evm.stalestChainName ? ` (${lag.evm.stalestChainName})` : '') +
+ ` across ${lag.evm.chains}/${lag.evm.configuredChains} chains` +
`, worst backlog ${lag.evm.worstBlocksBehind.toLocaleString('en-US')} blocks` +
- (lag.evm.worstChainName ? ` (${lag.evm.worstChainName})` : '') +
+ (lag.evm.worstBlocksBehind > 0 && lag.evm.worstChainName ? ` (${lag.evm.worstChainName})` : '') +
(lag.evm.behindChains ? `, ${lag.evm.behindChains} behind` : '') +
(lag.evm.staleChains ? `, ${lag.evm.staleChains} stale` : '') +
(lag.evm.uncrawledChains ? `, ${lag.evm.uncrawledChains} never crawled` : '') +
@@ -289,7 +305,7 @@ export function indexLagVerdict(lag) {
? 'Solana cursors are erroring, not just lagging, and the sweep stamps last_indexed_at on the failure path so they still look fresh. Group them: select error, count(*) from agent_event_cursor where error is not null group by 1 order by 2 desc. See docs/ops/agent-index.md.'
: lag.evm.worstBlocksBehind >= EVM_BLOCKS_BEHIND_DEGRADED
? 'An EVM chain is behind head, not just stale: the crawl grows its block window while behind, so a backlog that keeps rising means the RPC is rejecting ranges (erc8004_crawl_cursor.last_error) or the cron is being cut short by its budget.'
- : 'Check the crawl crons: /api/cron/solana-attestations-crawl and /api/cron/erc8004-crawl. A stale cursor means the job is failing or no longer scheduled.';
+ : 'Check the crawl crons: /api/cron/solana-attestations-crawl and /api/cron/erc8004-crawl. A stale cursor means the job is failing or no longer scheduled; erc8004_crawl_cursor.last_error names the lane that refused a stale EVM chain.';
return { status, detail, ...(hint ? { hint } : {}) };
}
diff --git a/api/_lib/solana-agent-events.js b/api/_lib/solana-agent-events.js
index 87b9d8e13..b2b00c096 100644
--- a/api/_lib/solana-agent-events.js
+++ b/api/_lib/solana-agent-events.js
@@ -26,7 +26,7 @@
import { PublicKey } from '@solana/web3.js';
import { sql } from './db.js';
-import { solanaConnection } from './solana/connection.js';
+import { solanaConnection, isTransientRpcError } from './solana/connection.js';
import { signaturesSinceCursor } from './solana/cursor-recovery.js';
import { RPC } from './solana-attestations.js';
import { recordEvents } from './onchain-events.js';
@@ -533,22 +533,47 @@ export async function nextAgentBatch({ limit = 40 } = {}) {
export const SOLANA_SWEEP_BUDGET_MS = 120_000;
/**
- * Crawl one tick's worth of the Solana agent directory.
- *
- * Drains the oldest-cursor-first batch through a small worker pool, stops on
- * the budget rather than on the batch, and stamps a failure onto every agent it
- * could not read so one unreadable account cannot hold the queue head forever.
+ * Consecutive RPC-fabric failures after which the sweep ends its tick early.
*
- * `truncated` means the budget ran out with agents still queued: the cycle time
- * the freshness sensor derives from SOLANA_SWEEP_BATCH assumes a batch that
- * drains, so a truncated tick is the signal that the batch has outgrown the
- * budget and the sensor's cycle number is now optimistic.
+ * When every Solana lane is cooling at once (paid plans over quota, free lanes
+ * answering 429), no agent in the batch can be read, and draining the rest of it
+ * anyway does two kinds of damage. It stamps an error onto every remaining
+ * cursor, so the agents look broken when the provider was, and it spends a
+ * request per agent against lanes that are already benched, which is how a
+ * cooldown gets extended instead of served. Measured on 2026-10-08: the 04:00
+ * tick wrote the same exhausted-chain error onto 126 cursors, 7.6% of the
+ * directory in one pass, and that alone moved the sensor's error rate past its
+ * degraded line.
*
- * @param {{ budgetMs?: number, limit?: number, concurrency?: number, now?: () => number }} [opts]
- * @returns {Promise<{ agents: number, scanned: number, inserted: number, rejected: number,
- * failed: number, truncated: boolean, batch: number, concurrency: number,
- * elapsedMs: number, error?: string }>}
+ * Stopping leaves the undispatched agents untouched, which is exactly right for
+ * an oldest-first queue: they stay at its head and are the first ones the next
+ * tick reads. Any success resets the count, so a single flaky account or a
+ * one-lane blip never trips it. Errors that are about the agent (a ref that is
+ * not an account key, a malformed transaction) never count toward it.
*/
+export const SOLANA_SWEEP_RPC_BREAKER = 5;
+
+/**
+ * Consecutive-failure breaker over RPC-fabric errors, reset by any success.
+ * @param {number} [threshold]
+ */
+export function rpcBreaker(threshold = SOLANA_SWEEP_RPC_BREAKER) {
+ let streak = 0;
+ let last = null;
+ return {
+ success() {
+ streak = 0;
+ },
+ failure(err) {
+ if (!isTransientRpcError(err)) return;
+ streak += 1;
+ last = err?.message || String(err);
+ },
+ tripped: () => streak >= threshold,
+ lastError: () => last,
+ };
+}
+
/**
* Run `handle` over `items` through a small worker pool, stopping on a
* wall-clock budget rather than on the list.
@@ -562,21 +587,34 @@ export const SOLANA_SWEEP_BUDGET_MS = 120_000;
* BEFORE the clock on purpose, so a run that consumed its last item on the
* final millisecond reports completion rather than phantom unfinished work.
*
+ * `shouldStop` is checked before every dispatch, the same way, and `stopped`
+ * reports that it cut the run short. Items never dispatched are left exactly as
+ * they were, which for the sweep means still at the head of the queue.
+ *
* @template T
* @param {T[]} items
* @param {(item: T, index: number) => Promise<void>} handle
- * @param {{ concurrency?: number, budgetMs?: number, now?: () => number }} [opts]
- * @returns {Promise<{ processed: number, truncated: boolean, workers: number, elapsedMs: number }>}
+ * @param {{ concurrency?: number, budgetMs?: number, now?: () => number, shouldStop?: () => boolean }} [opts]
+ * @returns {Promise<{ processed: number, truncated: boolean, stopped: boolean, workers: number, elapsedMs: number }>}
*/
-export async function drainWithBudget(items, handle, { concurrency = 1, budgetMs = Infinity, now = Date.now } = {}) {
+export async function drainWithBudget(
+ items,
+ handle,
+ { concurrency = 1, budgetMs = Infinity, now = Date.now, shouldStop = () => false } = {},
+) {
const startedAt = now();
const workers = Math.max(1, Math.min(Math.trunc(concurrency) || 1, items.length || 1));
let next = 0;
let truncated = false;
+ let stopped = false;
const drain = async () => {
for (;;) {
if (next >= items.length) return;
+ if (stopped || shouldStop()) {
+ stopped = true;
+ return;
+ }
if (now() - startedAt > budgetMs) {
truncated = true;
return;
@@ -587,7 +625,7 @@ export async function drainWithBudget(items, handle, { concurrency = 1, budgetMs
};
await Promise.all(Array.from({ length: workers }, drain));
- return { processed: next, truncated, workers, elapsedMs: now() - startedAt };
+ return { processed: next, truncated, stopped, workers, elapsedMs: now() - startedAt };
}
/**
@@ -601,10 +639,13 @@ export async function drainWithBudget(items, handle, { concurrency = 1, budgetMs
* cycle time the freshness sensor derives from SOLANA_SWEEP_BATCH assumes a
* batch that drains, so from that point on the sensor's cycle is optimistic.
*
+ * `stoppedOnRpc` means the RPC breaker ended the tick because every lane was
+ * failing (see SOLANA_SWEEP_RPC_BREAKER); `rpcError` carries the last error.
+ *
* @param {{ budgetMs?: number, limit?: number, concurrency?: number, now?: () => number }} [opts]
* @returns {Promise<{ agents: number, scanned: number, inserted: number, rejected: number,
- * failed: number, truncated: boolean, batch: number, concurrency: number,
- * elapsedMs: number, error?: string }>}
+ * failed: number, truncated: boolean, stoppedOnRpc: boolean, rpcError?: string|null,
+ * batch: number, concurrency: number, elapsedMs: number, error?: string }>}
*/
export async function sweepAgentEvents({
budgetMs = SOLANA_SWEEP_BUDGET_MS,
@@ -620,6 +661,7 @@ export async function sweepAgentEvents({
rejected: 0,
failed: 0,
truncated: false,
+ stoppedOnRpc: false,
batch: 0,
concurrency: 0,
elapsedMs: 0,
@@ -633,16 +675,19 @@ export async function sweepAgentEvents({
}
summary.batch = batch.length;
+ const breaker = rpcBreaker();
const run = await drainWithBudget(
batch,
async (row) => {
try {
const r = await crawlAgentEvents({ agentRef: row.agent_ref, network: row.network });
+ breaker.success();
summary.agents += 1;
summary.scanned += r.scanned;
summary.inserted += r.inserted;
summary.rejected += r.rejected;
} catch (err) {
+ breaker.failure(err);
summary.failed += 1;
await markAgentEventError({
agentRef: row.agent_ref,
@@ -651,10 +696,12 @@ export async function sweepAgentEvents({
}).catch(() => {});
}
},
- { concurrency, budgetMs, now },
+ { concurrency, budgetMs, now, shouldStop: breaker.tripped },
);
summary.truncated = run.truncated;
+ summary.stoppedOnRpc = run.stopped;
+ if (run.stopped) summary.rpcError = breaker.lastError();
summary.concurrency = run.workers;
summary.elapsedMs = run.elapsedMs;
return summary;
diff --git a/api/cron/[name].js b/api/cron/[name].js
index 7c26e8587..dc68e5e5c 100644
--- a/api/cron/[name].js
+++ b/api/cron/[name].js
@@ -453,7 +453,12 @@ const ERC8004_MIN_BLOCK_CHUNK = 100;
// smaller range fixes: matching it made the crawl read a plan limit as a range
// ceiling and shrink to the floor forever instead of surfacing the real fault.
// Every entry below names a range or a result volume, which shrinking does fix.
-const RANGE_REJECTED = /block range|range is too large|too wide|too many blocks|query returned more than|exceed maximum block range|limited to|response size|logs matched/i;
+//
+// `ranges? over N blocks` is dRPC's free tier, and its number is wrong: on
+// 2026-10-08 a testnet's dRPC lane answered "ranges over 10000 blocks are not
+// supported on free plan" to every window from 8,000 down to 200 and served 101.
+// It is still a range ceiling that shrinking reaches, which is all this asks.
+const RANGE_REJECTED = /block range|range is too large|too wide|too many blocks|ranges? over \d+ blocks|query returned more than|exceed maximum block range|limited to|response size|logs matched/i;
/**
* Is this RPC failure the provider refusing the width of the requested range?
@@ -609,8 +614,14 @@ async function erc8004CrawlChain(chain) {
}
}
// Any RPC failure that is not the provider refusing the range is a genuine
- // error and propagates to the per-chain handler above.
- if (!isRangeRejection(err?.message || err)) throw err;
+ // error and propagates to the per-chain handler above. The head is already
+ // known here, so bank the real backlog first: blocks_behind is otherwise
+ // written only on success, and a chain that errors every tick keeps the 0
+ // its last good crawl left behind and reads as caught up forever.
+ if (!isRangeRejection(err?.message || err)) {
+ await erc8004RecordBacklog(chain.id, latestBlock, fromBlock).catch(() => {});
+ throw err;
+ }
const reduced = backoffChunkSize(chunkSize);
if (reduced >= chunkSize) {
// Already at the floor: the provider will not serve even the smallest
@@ -844,6 +855,29 @@ async function erc8004CrawlChain(chain) {
};
}
+/**
+ * Record how far behind head a chain is on a tick that failed to advance it.
+ *
+ * Deliberately leaves updated_at and last_block alone: the cursor did not move,
+ * and the lag monitor reads updated_at as "last time this chain advanced". Only
+ * the backlog is refreshed, so a chain stuck on a dead lane shows the blocks it
+ * is missing instead of the 0 from its last successful crawl. Measured on
+ * 2026-10-08: one testnet had not advanced in 26 days (its first lane's
+ * hostname no longer resolves) and still reported 0 blocks behind against a
+ * head 2.3 million blocks past its cursor.
+ * @param {number} chainId
+ * @param {number} headBlock
+ * @param {number} fromBlock the first block the failed tick tried to read
+ */
+async function erc8004RecordBacklog(chainId, headBlock, fromBlock) {
+ await sql`
+ UPDATE erc8004_crawl_cursor
+ SET head_block = ${headBlock},
+ blocks_behind = ${Math.max(0, headBlock - fromBlock + 1)}
+ WHERE chain_id = ${chainId}
+ `;
+}
+
/**
* Stamp a caught-up chain's head so the lag monitor can tell "0 blocks behind"
* apart from "never measured". A chain with nothing to scan still reports.
diff --git a/docs/ops/agent-index.md b/docs/ops/agent-index.md
index 7316f2bb8..063b31864 100644
--- a/docs/ops/agent-index.md
+++ b/docs/ops/agent-index.md
@@ -98,10 +98,12 @@ gcloud logging read 'resource.type="cloud_run_revision" resource.labels.service_
| `solana rpc 429 @ <host>` | That lane is rate-limited. | Transient. The router cools the lane and retries; see [solana-rpc-lanes.md](solana-rpc-lanes.md) if it persists. |
| `solana rpc provider error -16401 @ <host>` | The lane gates this method behind a paid tier. | Per-method capability routing in `api/_lib/solana/connection.js`. Add the method to that lane's blocked set. |
| `fetch failed (…) @ <host>` | Transport fault on one lane. | Transient. Persistent means the lane is dead: drop it. |
+| `fetch failed (ERR_SSL_…) @ <host>` | The lane refused the TLS handshake. It was the last lane tried because every other lane was cooling. | The lane itself is dead (a disabled QuickNode endpoint does exactly this). Remove or replace it in `SOLANA_RPC_LAST_RESORT_URLS` / `SOLANA_RPC_FALLBACK_URLS`; the router now parks it for 30 minutes on its own. The error landing on many cursors in one tick means the paid lanes were over quota at the same moment. |
| `agent_ref is not a Solana account key` | A directory row whose ref is not an account. | Never crawlable. It is recorded once rather than retried every tick. |
| EVM `has been pruned` / `Archive requests require a personal token` | The provider will not serve the blocks the cursor points at, whether it dropped them or paywalled them. | Self-healing: the crawl resumes at the head, reports the skipped span as `prunedSkip`, and banks it in `history_gap_blocks`. That span is a permanent gap; only an archive node can backfill it. |
-| EVM `block range` / `response size` / `query returned more than` | The window was too wide. | Self-healing: `backoffChunkSize()` halves it in place and the width is persisted in `chunk_size`. |
+| EVM `block range` / `response size` / `query returned more than` / `ranges over N blocks` | The window was too wide. dRPC's free tier says `ranges over 10000 blocks` for any window above about 100 blocks, so its number is not the real ceiling. | Self-healing: `backoffChunkSize()` halves it in place and the width is persisted in `chunk_size`. |
| EVM `limit exceeded` | A plan or compute limit, **not** a range ceiling. | Shrinking does not help. Deliberately excluded from `isRangeRejection`. |
+| EVM `ENOTFOUND` / `HTTP 401 … tenant disabled` / `chain is not available on free plan` | The lane is gone, not busy. | Replace it in that chain's `rpcUrls` with a lane probed to serve `eth_getLogs` at the chain's window. A failing tick still banks `head_block` and `blocks_behind`, so a chain stuck on dead lanes shows its real backlog instead of the 0 its last good crawl left. |
| EVM `HTTP 403 from <host>` | A lane refused us with no readable JSON-RPC body. | The body is read first now, so a bare status here means the lane returned nothing to classify. The chain needs a lane that answers from a datacenter IP; see the `rpcUrls` note in `api/_lib/erc8004-chains.js`. |
## Recovery: drain a wedged backlog now
@@ -179,3 +181,21 @@ immediately in the sensor's error rate. The sweep reports `truncated: true` when
the budget runs out mid-batch, which is the signal that the batch has finally
outgrown the budget and the sensor's cycle number has become optimistic. Check
that flag before raising the batch again.
+
+The sweep also carries a breaker. After `SOLANA_SWEEP_RPC_BREAKER` consecutive
+RPC-fabric failures (exhausted chain, 429, transport, TLS; never an agent-level
+error), it stops dispatching for the rest of the tick and reports
+`stoppedOnRpc: true` with the last `rpcError`. The undispatched agents keep their
+old cursors, which leaves them at the head of the oldest-first queue for the next
+tick. Without it, one tick during a full-fabric brownout (2026-10-08 04:00, every
+paid lane over quota and every free lane 429-cooling) stamped the same error onto
+126 cursors and moved the error rate past its degraded line on its own, while
+spending a request per agent against lanes that were already benched.
+
+Raising the batch is an RPC-budget decision as much as a wall-clock one. Ticks
+finish in 35 to 55 seconds of the 120-second budget, so time is not the limit,
+but every agent is at least one `getSignaturesForAddress`, and a larger batch
+spends that against the same paid plans whose quota the rest of the platform is
+already exhausting. Check `rpc_lanes` on `/api/healthz` first: while
+`paidCooling` equals `paidTotal`, a bigger batch buys more 429s, not fresher
+cursors.
diff --git a/tests/agent-index.test.js b/tests/agent-index.test.js
index 0247d1776..75e063f6c 100644
--- a/tests/agent-index.test.js
+++ b/tests/agent-index.test.js
@@ -17,7 +17,9 @@ import {
SOLANA_SWEEP_BATCH,
SOLANA_SWEEP_PERIOD_MIN,
SOLANA_SWEEP_CONCURRENCY,
+ SOLANA_SWEEP_RPC_BREAKER,
drainWithBudget,
+ rpcBreaker,
} from '../api/_lib/solana-agent-events.js';
import {
normalizeEvent,
@@ -481,6 +483,17 @@ describe('isRangeRejection', () => {
expect(isRangeRejection('eth_getLogs is limited to a 10000 block range')).toBe(true);
});
+ it("reads dRPC's free-tier wording as a range ceiling even though its number is wrong", () => {
+ // Verbatim from erc8004_crawl_cursor.last_error on a stalled testnet, 2026-10-08.
+ // dRPC said this to every window from 8,000 down to 200 and served 101, so
+ // treating it as a genuine fault froze the cursor for 26 days instead of
+ // letting the shrink loop find the real ceiling.
+ expect(isRangeRejection('RPC 35: ranges over 10000 blocks are not supported on free plan')).toBe(true);
+ // Same provider, different refusal: no window size fixes a chain the plan
+ // does not carry, so it must stay a real fault.
+ expect(isRangeRejection('RPC 35: chain is not available on free plan, please upgrade to paid plan')).toBe(false);
+ });
+
it('does NOT treat a plan or rate limit as a range the crawl can shrink into', () => {
// bnbchain's data-seed nodes answer every eth_getLogs with this, at any
// width. Reading it as a range ceiling shrank BSC Testnet to the 100-block
@@ -605,6 +618,24 @@ describe('drainWithBudget', () => {
expect(run.truncated).toBe(false);
});
+ it('stops dispatching the moment shouldStop says so and leaves the rest untouched', async () => {
+ const seen = [];
+ const run = await drainWithBudget([1, 2, 3, 4, 5, 6], async (n) => void seen.push(n), {
+ concurrency: 1,
+ shouldStop: () => seen.length >= 2,
+ });
+ expect(seen).toEqual([1, 2]);
+ expect(run.stopped).toBe(true);
+ expect(run.truncated).toBe(false);
+ expect(run.processed).toBe(2);
+ });
+
+ it('does not report a stop for a run that drained before the predicate fired', async () => {
+ const run = await drainWithBudget([1, 2], async () => {}, { concurrency: 2, shouldStop: () => false });
+ expect(run.stopped).toBe(false);
+ expect(run.processed).toBe(2);
+ });
+
it('keeps the shipped concurrency low enough not to outrun the RPC lanes', () => {
// The lane router parks a cooling provider; a wide fan-out earns 429s
// faster than it earns signatures. This is a ceiling, not a target.
@@ -613,6 +644,58 @@ describe('drainWithBudget', () => {
});
});
+describe('rpcBreaker', () => {
+ // The 2026-10-08 04:00 tick: every lane cooling at once, and the sweep wrote
+ // the same exhausted-chain error onto 126 cursors in one pass.
+ const exhausted = new Error(
+ 'fetch failed (ERR_SSL_TLSV1_ALERT_INTERNAL_ERROR) @ https://example.solana-mainnet.quiknode.pro',
+ );
+
+ it('trips after the configured run of RPC-fabric failures', () => {
+ const b = rpcBreaker(3);
+ b.failure(exhausted);
+ b.failure(new Error('all solana rpc endpoints failed'));
+ expect(b.tripped()).toBe(false);
+ b.failure(new Error('solana rpc 429 @ https://lane'));
+ expect(b.tripped()).toBe(true);
+ expect(b.lastError()).toContain('429');
+ });
+
+ it('resets on any success, so a passing blip never ends the tick', () => {
+ const b = rpcBreaker(2);
+ b.failure(exhausted);
+ b.success();
+ b.failure(exhausted);
+ expect(b.tripped()).toBe(false);
+ });
+
+ it('ignores failures that are about the agent rather than the RPC', () => {
+ const b = rpcBreaker(2);
+ b.failure(new Error('agent_ref is not a Solana account key'));
+ b.failure(new Error('duplicate key value violates unique constraint'));
+ b.failure(new TypeError("Cannot read properties of undefined (reading 'meta')"));
+ expect(b.tripped()).toBe(false);
+ });
+
+ it('ends a sweep through drainWithBudget, leaving undispatched agents queued', async () => {
+ const b = rpcBreaker();
+ const agents = Array.from({ length: 240 }, (_, i) => i);
+ let attempted = 0;
+ const run = await drainWithBudget(
+ agents,
+ async () => {
+ attempted += 1;
+ b.failure(exhausted);
+ },
+ { concurrency: 4, shouldStop: b.tripped },
+ );
+ expect(run.stopped).toBe(true);
+ // At most the threshold plus the workers already in flight when it tripped.
+ expect(attempted).toBeLessThanOrEqual(SOLANA_SWEEP_RPC_BREAKER + 4);
+ expect(attempted).toBeGreaterThanOrEqual(SOLANA_SWEEP_RPC_BREAKER);
+ });
+});
+
// ─── Directory detail fallback ───────────────────────────────────────────────
// /discover lists external Solana agents from the crawled registry directory
// and links every one to /discover/a/sol/<asset>, which is also where the
@@ -809,6 +892,8 @@ function lagFixture({ solana = {}, evm = {} } = {}) {
worstBlocksBehind: 0,
worstChainId: null,
worstChainName: null,
+ stalestChainId: null,
+ stalestChainName: null,
historyGapChains: 0,
historyGapBlocks: 0,
events: 107296,
@@ -883,6 +968,34 @@ describe('indexLagVerdict', () => {
).toBe('ok');
});
+ it('names the stale chain beside the cursor age, not a chain that won a tie at zero backlog', () => {
+ // The production detail on 2026-10-08 named a healthy chain beside a
+ // 639-hour cursor age that belonged to a different, stalled one.
+ const verdict = indexLagVerdict(
+ lagFixture({
+ evm: {
+ lagMin: 38_386,
+ staleChains: 1,
+ worstBlocksBehind: 0,
+ worstChainId: 2,
+ worstChainName: 'Healthy Testnet',
+ stalestChainId: 1,
+ stalestChainName: 'Stalled Testnet',
+ },
+ }),
+ );
+ expect(verdict.detail).toContain('639h46m worst cursor age (Stalled Testnet)');
+ expect(verdict.detail).not.toContain('Healthy Testnet');
+ expect(verdict.hint).toContain('last_error');
+ });
+
+ it('still names the chain carrying a real backlog', () => {
+ const verdict = indexLagVerdict(
+ lagFixture({ evm: { worstBlocksBehind: 2_303_000, behindChains: 1, worstChainName: 'Stalled Testnet' } }),
+ );
+ expect(verdict.detail).toContain('worst backlog 2,303,000 blocks (Stalled Testnet)');
+ });
+
it('reports a never-crawled index as warming up rather than broken', () => {
const verdict = indexLagVerdict(lagFixture({ solana: { agents: 0 }, evm: { chains: 0 } }));
expect(verdict.status).toBe('unknown');