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(oracle): answer 503 during a database outage instead of a confident empty record

nirholasa78bb9abced6
diff --git a/api/oracle/action-stream.js b/api/oracle/action-stream.js
index bb345ca46..7e35e031d 100644
--- a/api/oracle/action-stream.js
+++ b/api/oracle/action-stream.js
@@ -1,5 +1,5 @@
/**
- * Oracle — live agent action stream (SSE).
+ * Oracle: live agent action stream (SSE).
*
* GET /api/oracle/action-stream?network=mainnet&mode=live|simulate
*
@@ -8,11 +8,11 @@
* /activity trading-floor page with sub-5-second latency instead of 30s polling.
*
* Events:
- * hello — sent on connect with network + ts
- * action — a new oracle_watch_actions row (entry or outcome update)
- * settle — an existing action whose outcome just changed (win/loss/flat)
- * ping — keepalive every 15s
- * bye — server rotating the connection after MAX_DURATION_MS
+ * hello : sent on connect with network + ts
+ * action : a new oracle_watch_actions row (entry or outcome update)
+ * settle : an existing action whose outcome just changed (win/loss/flat)
+ * ping : keepalive every 15s
+ * bye : server rotating the connection after MAX_DURATION_MS
*
* The client reconnects automatically via EventSource's built-in retry.
* It passes `?since=<iso>` on reconnect so no events are missed.
@@ -157,7 +157,7 @@ export default async function handleActionStream(req, res) {
send('settle', shapeAction(r));
}
if (settles.length) settleCursor = settles[settles.length - 1].settled_at;
- } catch { /* transient — next tick */ }
+ } catch { /* transient, retried on the next tick */ }
};
const pollTimer = setInterval(poll, POLL_MS);
diff --git a/api/oracle/activity.js b/api/oracle/activity.js
index a6440b2c6..92d6ed396 100644
--- a/api/oracle/activity.js
+++ b/api/oracle/activity.js
@@ -1,5 +1,5 @@
/**
- * Oracle — global action activity feed.
+ * Oracle: global action activity feed.
*
* GET /api/oracle/activity
* ?network=mainnet default: mainnet
@@ -12,7 +12,7 @@
*
* Public, IP rate-limited, 15-second CDN cache. Returns actions from
* oracle_watch_actions joined to agent_identities so the feed shows real
- * agent names and avatars — the "trading floor" view of all autonomous
+ * agent names and avatars: the "trading floor" view of all autonomous
* agents acting on conviction in real time.
*/
@@ -109,7 +109,7 @@ export default wrap(async (req, res) => {
const items = rows.map(shapeRow);
// Summary counts for the header KPIs. `.then(r => r[0])` already unwraps the
- // single aggregate row, so assign it directly — array-destructuring a plain
+ // single aggregate row, so assign it directly. Array-destructuring a plain
// row object (or the null/undefined the catch/empty-result yields) throws
// "(intermediate value) is not iterable" and 500s the endpoint.
const summary = await sql`
diff --git a/api/oracle/agent-stats.js b/api/oracle/agent-stats.js
index 2b35e7e3f..0ea62629c 100644
--- a/api/oracle/agent-stats.js
+++ b/api/oracle/agent-stats.js
@@ -1,30 +1,30 @@
/**
- * Oracle — public agent track record.
+ * Oracle: public agent track record.
*
* GET /api/oracle/agent-stats?agent_id=<uuid>&network=mainnet&limit=20
*
* Returns an agent's oracle trading summary (win rate, realized PnL, ROI) plus
* the N most recent actions so any visitor can verify the track record.
- * This endpoint is public — no auth required. It's the evidence behind copy-
+ * This endpoint is public, no auth required. It's the evidence behind copy-
* trading: followers can see exactly which conviction calls were made and how
* they resolved before choosing to mirror a leader.
*
* An agent with no oracle activity returns 200 with an empty summary
- * (summary.total === 0), not a 404 — "no track record yet" is a valid state the
+ * (summary.total === 0), not a 404: "no track record yet" is a valid state the
* widget hides, and most agents never trade through the oracle. Only a malformed
* agent_id is a 400.
*
* Cache: 60s public CDN (the data changes only when the settle-loop runs).
*/
-import { cors, json, method, rateLimited } from '../_lib/http.js';
+import { cors, json, method, wrap, rateLimited } from '../_lib/http.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
-import { sql } from '../_lib/db.js';
+import { sql, isDbUnavailableError } from '../_lib/db.js';
import { recentActions, actionsSummary } from '../_lib/oracle/store.js';
import { isUuid } from '../_lib/validate.js';
const NETWORKS = new Set(['mainnet', 'devnet']);
-export default async function handleAgentStats(req, res) {
+export default wrap(async function handleAgentStats(req, res) {
if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
if (!method(req, res, ['GET'])) return;
@@ -50,14 +50,26 @@ export default async function handleAgentStats(req, res) {
// The track record lives in oracle_watch_actions, keyed by agent_id alone.
// The agent_identities row only enriches the response with a name/avatar so
// callers don't need a separate /api/agents fetch. Most agents never trade
- // through the oracle, so a missing identity row is the common case — not an
+ // through the oracle, so a missing identity row is the common case, not an
// error: return an empty record (summary.total === 0) and let the caller hide
// the widget rather than 404'ing every agent page. All three reads are
// independent, so run them concurrently.
+ //
+ // The identity read doubles as the outage canary. actionsSummary() and
+ // recentActions() swallow their own failures into an empty record, so during a
+ // database outage this endpoint used to answer 200 with `summary.total: 0`:
+ // "this agent has never traded" stated as fact, when the truth is "we cannot
+ // tell right now". That is the public evidence copy-traders judge a leader on,
+ // and it is CDN-cached for 60s, so the wrong answer outlives the blip.
+ // Rethrowing a connectivity failure lets wrap() answer the shared 503 +
+ // Retry-After instead; a merely missing identity row still resolves to null.
const [agentRow, summary, actions] = await Promise.all([
sql`select name, description, image_url from agent_identities where id = ${agentId}`
.then((rows) => rows[0] || null)
- .catch(() => null),
+ .catch((err) => {
+ if (isDbUnavailableError(err)) throw err;
+ return null;
+ }),
actionsSummary(agentId, network),
recentActions(agentId, network, limit),
]);
@@ -103,4 +115,4 @@ export default async function handleAgentStats(req, res) {
oracle_url: `https://three.ws/oracle?mint=${a.mint}`,
})),
}, { 'cache-control': 'public, max-age=60, s-maxage=60' });
-}
+});
diff --git a/api/oracle/backtest.js b/api/oracle/backtest.js
index df11a2ecf..641efd408 100644
--- a/api/oracle/backtest.js
+++ b/api/oracle/backtest.js
@@ -1,5 +1,5 @@
/**
- * Oracle — conviction accuracy backtest.
+ * Oracle: conviction accuracy backtest.
*
* GET /api/oracle/backtest?period=7d&tier=prime&network=mainnet
*
@@ -7,15 +7,15 @@
* (ground truth: graduated, rugged, ATH multiple) and returns hit-rate stats
* per tier. This is the honest answer to "does the oracle engine actually work?"
*
- * Only coins with a resolved outcome are counted — open positions are excluded
+ * Only coins with a resolved outcome are counted: open positions are excluded
* from the win-rate calculation so the denominator is accurate.
*
* Params:
- * period — 1d | 7d | 30d | 90d | all (default: 30d)
- * tier — prime | strong | lean | watch | avoid | all (default: all)
- * network — mainnet | devnet (default: mainnet)
+ * period : 1d | 7d | 30d | 90d | all (default: 30d)
+ * tier : prime | strong | lean | watch | avoid | all (default: all)
+ * network : mainnet | devnet (default: mainnet)
*
- * Cached for 5 minutes — the DB table is large and this query is expensive.
+ * Cached for 5 minutes: the DB table is large and this query is expensive.
*/
import { cors, json, method, rateLimited } from '../_lib/http.js';
@@ -34,10 +34,10 @@ const _cache = new Map(); // key → { data, at }
function cacheKey(period, tier, network) { return `${period}:${tier}:${network}`; }
/**
- * Wilson score interval — the honest 95% confidence band for a win rate. Unlike
+ * Wilson score interval: the honest 95% confidence band for a win rate. Unlike
* the naive ±√(p(1-p)/n), it stays inside [0,1] and is well-behaved at small n,
* which is exactly the regime a young backtest lives in. Returned as integer
- * percentages so the UI can render "68% (54–80)" without further math.
+ * percentages so the UI can render "68% (54-80)" without further math.
*
* @param {number} wins
* @param {number} n resolved sample (wins + losses)
@@ -64,13 +64,13 @@ async function query(days, tier, network) {
// ── per-tier breakdown ────────────────────────────────────────────────────
const tierFilter = tier !== 'all' ? sql`and c.tier = ${tier}` : sql``;
const periodFilter = days != null ? sql`and c.scored_at >= now() - (${days} || ' days')::interval` : sql``;
- // Quote/stablecoin/LST mints are not coins — exclude them from every accuracy
+ // Quote/stablecoin/LST mints are not coins, so exclude them from every accuracy
// calc so a stray cached USDC row can't poison the win-rate or top performers.
const quoteFilter = sql`and c.mint <> all(${QUOTE_MINT_LIST}::text[])`;
// Win = graduated OR (ath ≥ 2 AND not rugged). The "not rugged" clause is
// load-bearing: a bundle that spikes 2× and collapses is an exit-liquidity
- // event, not a win — counting it would let pump-and-dumps inflate the very
+ // event, not a win: counting it would let pump-and-dumps inflate the very
// number that's supposed to expose them. Keep in sync with stats.js/wins.js.
const rows = await sql`
select
@@ -119,7 +119,7 @@ async function query(days, tier, network) {
// REALIZED win rate per band. A trustworthy engine produces a monotonic ladder
// (higher band → higher realized rate) that tracks the band's own prediction.
// Brier = mean squared error of score/100 (treated as a probability) vs the
- // 0/1 outcome — one number for "how well-calibrated overall" (lower is better).
+ // 0/1 outcome: one number for "how well-calibrated overall" (lower is better).
// This pass is unconditional on tier so the baseline is the true market rate.
const calRows = await sql`
select
@@ -144,7 +144,7 @@ async function query(days, tier, network) {
const hi = r.bucket * 10;
const realized = r.n ? Math.round((r.wins / r.n) * 100) : null;
return {
- band: `${lo}–${hi}`,
+ band: `${lo}-${hi}`,
lo, hi,
n: r.n,
wins: r.wins,
diff --git a/api/oracle/batch.js b/api/oracle/batch.js
index 0363405c8..e3369a313 100644
--- a/api/oracle/batch.js
+++ b/api/oracle/batch.js
@@ -1,12 +1,12 @@
/**
- * Oracle — batch conviction scores for multiple mints.
+ * Oracle: batch conviction scores for multiple mints.
*
* GET /api/oracle/batch?mints=<m1>,<m2>,...&network=mainnet
*
* Accepts up to 20 base58 mints (comma-separated). Returns a map of
* { mint → { score, tier, pillars: { pedigree, structure, narrative, momentum } } }
* for every mint that exists in the oracle_conviction cache. Mints with no
- * cached score are omitted (not an error — means unscored).
+ * cached score are omitted (not an error: it means unscored).
*
* Used by the watchlist page and any surface that needs conviction badges for
* a known set of coins without issuing N individual /api/oracle/coin requests.
diff --git a/api/oracle/categories.js b/api/oracle/categories.js
index 41d4b3183..4d788790d 100644
--- a/api/oracle/categories.js
+++ b/api/oracle/categories.js
@@ -1,20 +1,20 @@
/**
- * Oracle — category intelligence summary.
+ * Oracle: category intelligence summary.
*
* GET /api/oracle/categories?network=mainnet&hours=24
*
* Aggregates oracle_conviction rows from the last `hours` window by category,
* returning per-category stats sorted by average conviction score:
*
- * category — the narrative label
- * total — total coins scored in this category in the window
- * avg_score — mean conviction score
- * prime_count — coins at prime tier (score ≥ 86)
- * strong_count — coins at strong tier (72–85)
- * best_score — highest single score in this category
- * best_mint — mint address of the best coin
- * best_symbol — symbol of the best coin
- * best_image_uri — image of the best coin
+ * category : the narrative label
+ * total : total coins scored in this category in the window
+ * avg_score : mean conviction score
+ * prime_count : coins at prime tier (score >= 86)
+ * strong_count : coins at strong tier (72 to 85)
+ * best_score : highest single score in this category
+ * best_mint : mint address of the best coin
+ * best_symbol : symbol of the best coin
+ * best_image_uri : image of the best coin
*
* Use this endpoint to render a "hot sectors" panel that tells users which
* narrative categories are generating the highest conviction right now.
@@ -24,7 +24,7 @@
import { cors, json, method, wrap, rateLimited } from '../_lib/http.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
-import { sql } from '../_lib/db.js';
+import { sql, isDbUnavailableError } from '../_lib/db.js';
import { QUOTE_MINT_LIST } from '../_lib/quote-mints.js';
const NETWORKS = new Set(['mainnet', 'devnet']);
@@ -76,7 +76,15 @@ export default wrap(async (req, res) => {
join best_coin bc on bc.category = a.category
order by a.avg_score desc, a.prime_count desc, a.total desc
limit 12
- `.catch(() => []);
+ `.catch((err) => {
+ // A connectivity failure is not "no hot sectors right now". Returning [] for
+ // it served a confident empty panel with a 5-minute CDN cache, so a blip
+ // lasting seconds showed users a dead market for the next five minutes.
+ // Rethrow so wrap() answers 503 + Retry-After and nothing caches the lie;
+ // a statement-level fault still degrades to the empty panel.
+ if (isDbUnavailableError(err)) throw err;
+ return [];
+ });
const items = rows.map((r) => ({
category: r.category,
diff --git a/api/oracle/coin.js b/api/oracle/coin.js
index dd333d9fe..615e310a0 100644
--- a/api/oracle/coin.js
+++ b/api/oracle/coin.js
@@ -1,11 +1,11 @@
/**
- * Oracle — full intel for one coin.
+ * Oracle: full intel for one coin.
*
* GET /api/oracle/coin?mint=<mint>&network=mainnet
*
* Returns the fused conviction verdict (lazy-scored with a fresh narrative read
* on a cache miss), the transparent pillar reasons, the narrative classification,
- * the ground-truth outcome if known, and the live "who's in" trader breakdown —
+ * the ground-truth outcome if known, and the live "who's in" trader breakdown:
* every early wallet labeled by its data-brain archetype + track record. This is
* the trader-classification surface the product is built around.
*/
@@ -38,18 +38,18 @@ export default wrap(async (req, res) => {
try {
scored = await scoreCoin(mint, { network, classify: true, persist: true });
} catch {
- // Scoring threw — the intel store / DB is degraded, NOT "coin unknown".
+ // Scoring threw: the intel store / DB is degraded, NOT "coin unknown".
// A 404 here would let clients and the CDN cache a transient outage as an
// authoritative "this mint doesn't exist". Surface 503 so callers retry.
- return error(res, 503, 'scoring_unavailable', 'coin scoring is temporarily unavailable — retry shortly');
+ return error(res, 503, 'scoring_unavailable', 'coin scoring is temporarily unavailable, retry shortly');
}
if (!scored) {
- // Clean empty result — the coin is genuinely unknown to the data brain.
+ // Clean empty result: the coin is genuinely unknown to the data brain.
// This is a stable, idempotent fact (coins are ingested by the always-on
// observer, never inline here), so cache the negative answer briefly at the
// CDN. The always-on polling surfaces (coin page, oracle UI) would otherwise
// re-spin this function and re-run assembleIntel on every poll for a mint the
- // brain has never seen — one such mint produced hundreds of redundant
+ // brain has never seen. One such mint produced hundreds of redundant
// invocations. The window is short enough that a coin becoming known surfaces
// within seconds.
return json(res, 404, { error: 'not_found', error_description: 'this mint has not been observed yet', mint, network }, {
@@ -57,9 +57,9 @@ export default wrap(async (req, res) => {
});
}
coin = await safeReadCoin(mint, network);
- // Scoring succeeded but the warm re-read came back empty (read-path blip) —
+ // Scoring succeeded but the warm re-read came back empty (read-path blip), so
// don't return a hollow 200; treat it as transient.
- if (!coin) return error(res, 503, 'scoring_unavailable', 'coin scoring is temporarily unavailable — retry shortly');
+ if (!coin) return error(res, 503, 'scoring_unavailable', 'coin scoring is temporarily unavailable, retry shortly');
}
return json(res, 200, { network, mint, ...coin }, {
diff --git a/api/oracle/feed.js b/api/oracle/feed.js
index ca704409b..9625635f2 100644
--- a/api/oracle/feed.js
+++ b/api/oracle/feed.js
@@ -1,17 +1,18 @@
/**
- * Oracle — live conviction feed.
+ * Oracle: live conviction feed.
*
* GET /api/oracle/feed?network=mainnet&limit=50&min_score=0&tier=strong&category=ai
*
* Serves the materialized oracle_conviction cache (one fast indexed read). On a
* cold cache it opportunistically scores a handful of recent coins straight from
- * the data brain (no LLM — DB-only, fast) so the feed is never empty before the
+ * the data brain (no LLM, DB-only, fast) so the feed is never empty before the
* ingestion augmentor has swept. Also returns the conviction-tier backtest so
* the UI can prove the edge.
*/
import { cors, json, method, wrap, rateLimited } from '../_lib/http.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
+import { isDbUnavailableError } from '../_lib/db.js';
import { readFeed, convictionBacktest, scoreCoin } from '../_lib/oracle/store.js';
import { recentMints } from '../_lib/oracle/sources.js';
@@ -55,6 +56,18 @@ export default wrap(async (req, res) => {
}, { 'Cache-Control': 'public, max-age=3, stale-while-revalidate=15' });
});
+// A read fault degrades to an empty feed, which the cold-start path above then
+// tries to warm. A connectivity failure must NOT take that route: it is not "no
+// coins scored yet", and treating it as one made the outage far more expensive
+// than the outage itself. Every request answered 200 with an empty feed (so the
+// page rendered a dead market as fact), and on the way there it fired eight
+// scoreCoin() calls that could not possibly persist. Rethrowing hands it to
+// wrap() for the shared 503 + Retry-After and skips the pointless warm attempt.
async function safeFeed(opts) {
- try { return await readFeed(opts); } catch { return []; }
+ try {
+ return await readFeed(opts);
+ } catch (err) {
+ if (isDbUnavailableError(err)) throw err;
+ return [];
+ }
}
diff --git a/api/oracle/follow.js b/api/oracle/follow.js
index d95badfce..867f924c0 100644
--- a/api/oracle/follow.js
+++ b/api/oracle/follow.js
@@ -1,5 +1,5 @@
/**
- * Oracle — agent follower subscriptions (the Watch tier of social copy-trading).
+ * Oracle: agent follower subscriptions (the Watch tier of social copy-trading).
*
* GET /api/oracle/follow?agent_id=<uuid>&chat_id=<telegram>&network=mainnet
* → { following: bool, min_score: int|null }
@@ -22,10 +22,27 @@
import { cors, json, readJson, wrap, error, rateLimited } from '../_lib/http.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
-import { sql } from '../_lib/db.js';
+import { sql, isDbUnavailableError } from '../_lib/db.js';
import { isUuid } from '../_lib/validate.js';
const NETWORKS = new Set(['mainnet', 'devnet']);
+
+// Every read here is a subscription FACT the caller acts on: "am I following?",
+// "does this agent exist?", "did my unsubscribe land?". A blanket `.catch()`
+// turned a database outage into a confident wrong answer for all three: the GET
+// reported `following: false` to a subscriber who was in fact subscribed, the
+// POST reported `agent not found` for an agent that plainly exists, and the
+// DELETE reported `{ ok: true }` while the row survived, so the caller believed
+// they had unsubscribed and kept receiving Telegram alerts with no way to stop
+// them. Rethrowing a connectivity failure hands it to wrap(), which answers the
+// shared 503 + Retry-After that tells the caller to try again. A genuine
+// statement-level fault still degrades to the empty result the callers expect.
+function orRethrowIfDbDown(fallback) {
+ return (err) => {
+ if (isDbUnavailableError(err)) throw err;
+ return fallback;
+ };
+}
const CHAT_ID_RE = /^-?\d{1,20}$|^@[a-zA-Z0-9_]{5,32}$/;
function validateChatId(v) {
return typeof v === 'string' && CHAT_ID_RE.test(v.trim());
@@ -44,7 +61,7 @@ export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,POST,DELETE,OPTIONS', origins: '*' })) return;
const ip = clientIp(req);
- // ── GET — check follow status ─────────────────────────────────────────────
+ // ── GET: check follow status ────────────────────────────────────────────
// Branch on req.method directly: the shared method() helper writes a 405 and
// ends the response on the first mismatch, so calling it per-branch (GET first)
// would 405 every POST/DELETE before its branch was reached. A single trailing
@@ -65,7 +82,7 @@ export default wrap(async (req, res) => {
select min_score from oracle_followers
where agent_id = ${agentId} and chat_id = ${chatId} and network = ${network}
limit 1
- `.catch(() => []);
+ `.catch(orRethrowIfDbDown([]));
return json(res, 200, {
following: rows.length > 0,
@@ -73,7 +90,7 @@ export default wrap(async (req, res) => {
});
}
- // ── POST — subscribe or update ────────────────────────────────────────────
+ // ── POST: subscribe or update ───────────────────────────────────────────
if (req.method === 'POST') {
const rl = await limits.oracleFollowIp(ip);
if (!rl.success) return rateLimited(res, rl);
@@ -92,14 +109,14 @@ export default wrap(async (req, res) => {
// Ensure the agent exists (guard against phantom subscriptions)
const agentRows = await sql`
select id from agent_identities where id = ${agentId} and deleted_at is null limit 1
- `.catch(() => []);
+ `.catch(orRethrowIfDbDown([]));
if (!agentRows.length) return error(res, 404, 'not_found', 'agent not found');
const existing = await sql`
select id from oracle_followers
where agent_id = ${agentId} and chat_id = ${chatId} and network = ${network}
limit 1
- `.catch(() => []);
+ `.catch(orRethrowIfDbDown([]));
if (existing.length) {
await sql`
@@ -118,7 +135,7 @@ export default wrap(async (req, res) => {
return json(res, 201, { ok: true, action: 'subscribed', min_score: minScore });
}
- // ── DELETE — unsubscribe ──────────────────────────────────────────────────
+ // ── DELETE: unsubscribe ─────────────────────────────────────────────────
if (req.method === 'DELETE') {
const rl = await limits.publicIp(ip);
if (!rl.success) return rateLimited(res, rl);
@@ -133,10 +150,14 @@ export default wrap(async (req, res) => {
if (!isUuid(agentId)) return error(res, 400, 'validation_error', 'agent_id must be a UUID');
if (!validateChatId(chatId)) return error(res, 400, 'validation_error', 'chat_id must be a numeric Telegram ID or @handle');
+ // No `.catch()` swallow: this statement IS the response. Reporting
+ // `{ ok: true }` on a delete that never ran leaves the follower subscribed
+ // and still receiving alerts while believing they opted out. Let wrap()
+ // answer 503 (outage) or 500 (real fault) so the caller can retry.
await sql`
delete from oracle_followers
where agent_id = ${agentId} and chat_id = ${chatId} and network = ${network}
- `.catch(() => {});
+ `;
return json(res, 200, { ok: true });
}