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(api): answer an unconfigured database with a retryable 503 across the cron and x402 paths

nirholas14fec9d0237f
diff --git a/api/_lib/db.js b/api/_lib/db.js
index 8dfcaef42..ab88a7c2a 100644
--- a/api/_lib/db.js
+++ b/api/_lib/db.js
@@ -186,9 +186,14 @@ export function isDbUnavailableError(err) {
// whose String() is "[object ErrorEvent]". Every message-based branch below
// therefore reads it as a code bug and 500s it. It is the opposite: a socket
// that never opened is the purest form of "the request never reached
- // Postgres". Matched structurally, since there is no text to match on.
- if (typeof ErrorEvent !== 'undefined' && err instanceof ErrorEvent) return true;
- if (err.type === 'error' && 'error' in err && !(err instanceof Error)) return true;
+ // Postgres".
+ //
+ // Matched structurally, on the two properties an ErrorEvent always carries,
+ // because there is no text to match on AND `instanceof ErrorEvent` cannot
+ // work here: ErrorEvent is not a Node global (checked on node 24), so the
+ // driver builds the event from its own bundled class. A plain Error is
+ // excluded so this door stays shut to genuine SQL faults.
+ if (!(err instanceof Error) && err.type === 'error' && 'error' in err) return true;
// esbuild minifies class names (e.g. NeonDbError → Pt in the bundle), so
// err.constructor.name is unreliable in production. Use err.name instead —
// NeonDbError explicitly sets `this.name = 'NeonDbError'` via a class field,
diff --git a/api/cron/[name].js b/api/cron/[name].js
index ef8287baa..862aeab35 100644
--- a/api/cron/[name].js
+++ b/api/cron/[name].js
@@ -350,6 +350,16 @@ const ERC8004_MIN_BLOCK_CHUNK = 100;
// 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;
+/**
+ * Is this RPC failure the provider refusing the width of the requested range?
+ * Only those are worth retrying smaller; everything else is a real fault.
+ * @param {unknown} message
+ * @returns {boolean}
+ */
+export function isRangeRejection(message) {
+ return RANGE_REJECTED.test(String(message ?? ''));
+}
+
/**
* The block window to request for a chain this tick.
*
@@ -445,7 +455,7 @@ async function erc8004CrawlChain(chain) {
} catch (err) {
// Any RPC failure that is not the provider refusing the range is a genuine
// error and propagates to the per-chain handler above.
- if (!RANGE_REJECTED.test(String(err?.message || err))) throw err;
+ if (!isRangeRejection(err?.message || err)) throw err;
const reduced = backoffChunkSize(chunkSize);
if (reduced >= chunkSize) {
// Already at the floor: the provider will not serve even the smallest
@@ -4035,7 +4045,10 @@ async function handleConfirmPendingPurchases(req, res) {
async function handleCleanupCsrfTokens(req, res) {
if (!method(req, res, ['GET'])) return;
if (!requireCron(req, res)) return;
- const result = await sql`DELETE FROM csrf_tokens WHERE expires_at < now() RETURNING token`;
+ // RETURNING 1, not RETURNING token: the row count is all this reports, and
+ // shipping every expired token value back over the wire puts live-until-a-
+ // moment-ago CSRF secrets in the response path for no gain.
+ const result = await sql`DELETE FROM csrf_tokens WHERE expires_at < now() RETURNING 1`;
return json(res, 200, { deleted: result.length });
}
diff --git a/api/x402/schema-check.js b/api/x402/schema-check.js
index c8f700705..42c2eebaa 100644
--- a/api/x402/schema-check.js
+++ b/api/x402/schema-check.js
@@ -33,6 +33,13 @@ const DESCRIPTION =
'Current target: changelog_json — the /changelog.json feed holders and RSS consumers ' +
'depend on. Returns { valid, version, entry_count, schema_errors }.';
+// Dispatch table. The advertised enum, the 400 message and the runtime branch
+// all read from these keys, so adding a target is one entry, not three places to
+// keep in step. checkChangelogJson is a hoisted function declaration further
+// down, so referencing it here is safe.
+const CHECKERS = { changelog_json: checkChangelogJson };
+const SUPPORTED_APIS = Object.keys(CHECKERS);
+
const INPUT_SCHEMA = {
$schema: 'https://json-schema.org/draft/2020-12/schema',
type: 'object',
@@ -40,7 +47,7 @@ const INPUT_SCHEMA = {
properties: {
api: {
type: 'string',
- enum: ['changelog_json'],
+ enum: SUPPORTED_APIS,
description: 'Which public JSON API to fetch and validate.',
},
},
@@ -203,11 +210,6 @@ async function checkChangelogJson(origin, fetched_at) {
return { ok: true, api: 'changelog_json', valid, version, entry_count, schema_errors, fetched_at };
}
-// Dispatch table: the enum in INPUT_SCHEMA, the 400 message and the runtime
-// branch all read from these keys, so adding a target is one entry, not four.
-const CHECKERS = { changelog_json: checkChangelogJson };
-const SUPPORTED_APIS = Object.keys(CHECKERS);
-
export default paidEndpoint({
route: ROUTE,
method: 'POST',
diff --git a/scripts/cron-local-proof.mjs b/scripts/cron-local-proof.mjs
index c4e254304..a2f0cfc6e 100644
--- a/scripts/cron-local-proof.mjs
+++ b/scripts/cron-local-proof.mjs
@@ -126,6 +126,57 @@ function coerce(value, oid) {
return value;
}
+// Run one parameterized query and shape the reply exactly as Neon's endpoint
+// does. `client` is either the pool (single query) or a checked-out client
+// pinned inside a transaction.
+async function runOne(client, { query, params }) {
+ const r = await client.query({
+ text: query,
+ values: params || [],
+ rowMode: 'array',
+ types: { getTypeParser: () => (v) => v },
+ });
+ return {
+ fields: r.fields.map((f) => ({ name: f.name, dataTypeID: f.dataTypeID })),
+ rows: r.rows.map((row) => row.map((v, i) => coerce(v, r.fields[i].dataTypeID))),
+ rowCount: r.rowCount,
+ command: r.command,
+ };
+}
+
+// sql.transaction() posts { queries: [...] } instead of a single { query },
+// answers with { results: [...] }, and carries its isolation level, read-only
+// and deferrable settings in Neon-Batch-* headers. A shim that understood only
+// the single-query shape handed `text: undefined` to pg, which threw "A query
+// must have either text or a name" - surfacing as a 500 from any handler that
+// writes atomically (custody-attest was the one that caught it) and reading
+// like a bug in the handler rather than in this bridge.
+async function runBatch(pool, queries, headers) {
+ const client = await pool.connect();
+ try {
+ const isolation = headers['neon-batch-isolation-level'];
+ const readOnly = headers['neon-batch-read-only'] === 'true';
+ const deferrable = headers['neon-batch-deferrable'] === 'true';
+ let begin = 'BEGIN';
+ if (isolation) begin += ` ISOLATION LEVEL ${isolation.replace(/[^A-Za-z ]/g, '')}`;
+ begin += readOnly ? ' READ ONLY' : ' READ WRITE';
+ // DEFERRABLE is only legal on a serializable read-only transaction.
+ if (deferrable && readOnly) begin += ' DEFERRABLE';
+ await client.query(begin);
+ try {
+ const results = [];
+ for (const q of queries) results.push(await runOne(client, q));
+ await client.query('COMMIT');
+ return results;
+ } catch (e) {
+ await client.query('ROLLBACK').catch(() => {});
+ throw e;
+ }
+ } finally {
+ client.release();
+ }
+}
+
async function startShim(pool) {
const port = await freePort(54800);
const server = http.createServer(async (req, res) => {
@@ -133,21 +184,12 @@ async function startShim(pool) {
let body = '';
for await (const c of req) body += c;
try {
- const { query, params } = JSON.parse(body || '{}');
- const r = await pool.query({
- text: query,
- values: params || [],
- rowMode: 'array',
- types: { getTypeParser: () => (v) => v },
- });
- const rows = r.rows.map((row) => row.map((v, i) => coerce(v, r.fields[i].dataTypeID)));
+ const parsed = JSON.parse(body || '{}');
+ const payload = Array.isArray(parsed.queries)
+ ? { results: await runBatch(pool, parsed.queries, req.headers) }
+ : await runOne(pool, parsed);
res.writeHead(200, { 'content-type': 'application/json' });
- res.end(JSON.stringify({
- fields: r.fields.map((f) => ({ name: f.name, dataTypeID: f.dataTypeID })),
- rows,
- rowCount: r.rowCount,
- command: r.command,
- }));
+ res.end(JSON.stringify(payload));
} catch (e) {
res.writeHead(500, { 'content-type': 'application/json' });
res.end(JSON.stringify({ message: String(e?.message || e), code: e?.code, constraint: e?.constraint }));
diff --git a/tests/agent-index.test.js b/tests/agent-index.test.js
index 4c5fca451..a640b804d 100644
--- a/tests/agent-index.test.js
+++ b/tests/agent-index.test.js
@@ -19,7 +19,7 @@ import {
} from '../api/_lib/solana-agent-events.js';
import { normalizeEvent, toDate, agentRef, EVENT_CLASSES } from '../api/_lib/onchain-events.js';
import { sweepCycleMin } from '../api/_lib/ops/index-lag.js';
-import { nextChunkSize, backoffChunkSize } from '../api/cron/[name].js';
+import { nextChunkSize, backoffChunkSize, isRangeRejection } from '../api/cron/[name].js';
import { splitCapabilities } from '../api/explore-item.js';
import { decodeReputationLog } from '../api/_lib/erc8004-reputation-events.js';
@@ -341,6 +341,42 @@ describe('backoffChunkSize', () => {
expect(backoffChunkSize(100)).toBe(100);
expect(backoffChunkSize(1)).toBe(100);
});
+
+ it('reaches a fixed point at the floor so the in-tick retry terminates', () => {
+ // erc8004CrawlChain retries the same blocks at backoffChunkSize until the
+ // value stops shrinking. If halving never converged, that loop would spin.
+ let size = 8000;
+ for (let i = 0; i < 20; i++) {
+ const next = backoffChunkSize(size);
+ if (next >= size) break;
+ size = next;
+ }
+ expect(size).toBe(100);
+ expect(backoffChunkSize(size)).toBe(size);
+ });
+});
+
+describe('isRangeRejection', () => {
+ it('recognises how each provider words a range it will not serve', () => {
+ // Verbatim messages observed from the configured lanes on 2026-08-14.
+ expect(isRangeRejection('block range is too wide (maximum 1024)')).toBe(true);
+ expect(isRangeRejection('Log response size exceeded')).toBe(true);
+ expect(isRangeRejection('query returned more than 10000 results')).toBe(true);
+ expect(isRangeRejection('eth_getLogs is limited to a 10000 block range')).toBe(true);
+ });
+
+ 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
+ // floor and froze its cursor while the backlog grew every tick.
+ expect(isRangeRejection('limit exceeded')).toBe(false);
+ expect(isRangeRejection('cu limit exceeded; Method "eth_getLogs" is not available')).toBe(false);
+ });
+
+ it('treats a missing or empty message as a real fault, not a range problem', () => {
+ expect(isRangeRejection(null)).toBe(false);
+ expect(isRangeRejection('')).toBe(false);
+ });
});
// ─── Sweep capacity ──────────────────────────────────────────────────────────
diff --git a/tests/db-unconfigured.test.js b/tests/db-unconfigured.test.js
index 30a7db74f..3ea708c69 100644
--- a/tests/db-unconfigured.test.js
+++ b/tests/db-unconfigured.test.js
@@ -125,4 +125,33 @@ describe('db.js with an unconfigured DATABASE_URL', () => {
it('classifies a bare `fetch failed` TypeError (pre-wrap transport error)', () => {
expect(isDbUnavailableError(new TypeError('fetch failed'))).toBe(true);
});
+
+ it('classifies the WebSocket Pool’s ErrorEvent, which carries no message at all', () => {
+ // The ws-based Pool (scripts that share code with crons, e.g.
+ // scripts/sniper-evolve.mjs) rejects with a DOM ErrorEvent, not an Error,
+ // when its socket never opens. Its name and message are both empty and
+ // String() is "[object ErrorEvent]", so every message-based branch reads it
+ // as a code bug. Proven against a real Postgres: api/cron/sniper-evolve
+ // answered `{"ok":false,"error":""}` with a GREEN heartbeat, the exact
+ // dead-loop-behind-a-green-check shape the fleet watchdog exists to catch.
+ // ErrorEvent is not a Node global, so the driver builds the event from its
+ // own bundled class. Reconstruct the observed shape rather than reaching
+ // for a global that does not exist in the runtime this ships on.
+ class WsErrorEvent {
+ constructor(cause) {
+ this.error = cause;
+ this.type = 'error';
+ this.stack = 'Error\n at ws/index.js';
+ }
+ get message() { return ''; }
+ }
+ const event = new WsErrorEvent(new TypeError());
+ expect(event.message).toBe('');
+ expect(event.name).toBeUndefined();
+ expect(isDbUnavailableError(event)).toBe(true);
+
+ // A plain Error still has to go through the message branches, so a genuine
+ // SQL fault cannot slip into the transient bucket via this door.
+ expect(isDbUnavailableError(new Error('column "nope" does not exist'))).toBe(false);
+ });
});