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.

feat: enhance Redis resilience with auth failure breaker and in-memory fallbacks

zprva9881c0b59fa
diff --git a/CHANGELOG.md b/CHANGELOG.md
index dc493b8f9..c26d73701 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,6 +6,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
## 2026-06-29
+- **Coin Clash stays up when the leaderboard backend hiccups** — The live Coin Clash arena and leaderboard used to go completely dark with an error whenever the power-tracking backend had a momentary outage — a recoverable blip took the whole page down. Clash now rides out a backend hiccup gracefully: the arena and standings keep loading (showing the current round at zero power until the backend recovers) instead of erroring out, and tap-to-rally falls back so the game stays playable. (`/clash`) `[fix]`
- **Posting a labor-market bounty no longer hits a surprise rate limit** — Posting a bounty on the agent labor market used to share one rate-limit budget with the MCP agent tools, so heavy use of one could spuriously throttle the other and pop a confusing 'rate limit exceeded' with no guidance. Each surface now has its own budget, and if you do post too fast the message tells you exactly how many seconds to wait before trying again. (`/labor-market`) `[fix]`
## 2026-06-28
diff --git a/api/_lib/clash-store.js b/api/_lib/clash-store.js
index 6253df164..325a222e0 100644
--- a/api/_lib/clash-store.js
+++ b/api/_lib/clash-store.js
@@ -20,6 +20,25 @@ const redis = getRedis();
// then let them lapse. Records (all-time W/L) never expire.
const ROUND_TTL_S = Math.ceil((EPOCH_MS * 4) / 1000);
+// A configured Redis can still fail at call time — an Upstash transport blip
+// ("fetch failed"), an over-quota/billing 4xx, or a rotated token. The shared
+// HTTP wrapper classifies those as "database unavailable" and 503s the whole
+// request, which once took the entire Clash page (state + leaderboard reads)
+// dark for >15h on a recoverable backend hiccup. So every Redis op here is
+// resilient the same way the rate limiters are: on a command error we warn
+// (throttled — a real outage hits every request) and fall through to the
+// in-memory model below. Reads then serve the designed zero/empty round state
+// with a 200 instead of a 5xx; writes degrade to a per-instance tally. Better a
+// briefly non-durable game than a dead feature.
+let _degradedAt = 0;
+function redisDegraded(err) {
+ const now = Date.now();
+ if (now - _degradedAt > 60_000) {
+ _degradedAt = now;
+ console.warn('[clash-store] redis degraded — serving from in-memory fallback:', err?.message || err);
+ }
+}
+
const K = {
factions: (epoch) => `clash:fac:${epoch}`, // ZSET mint → power
members: (epoch, mint) => `clash:mem:${epoch}:${mint}`, // ZSET wallet → power
@@ -67,27 +86,31 @@ export async function addPower({ epoch, mint, wallet, amount, walletCap }) {
if (amt <= 0) return { added: 0, walletTotal: 0, capped: false };
if (redis) {
- const wKey = K.wallet(epoch, mint, wallet);
- // Reserve against the per-wallet ceiling first. INCRBY returns the running
- // total; if this push would breach the cap, clamp the credited amount to
- // whatever headroom remains (possibly zero) and roll the counter back to the
- // cap so it stays truthful.
- const after = await redis.incrby(wKey, amt);
- await redis.expire(wKey, ROUND_TTL_S);
- let credit = amt;
- let capped = false;
- if (after > walletCap) {
- credit = Math.max(0, amt - (after - walletCap));
- capped = true;
- if (credit !== amt) await redis.set(wKey, walletCap, { ex: ROUND_TTL_S });
- }
- if (credit > 0) {
- await redis.zincrby(K.factions(epoch), credit, mint);
- await redis.expire(K.factions(epoch), ROUND_TTL_S);
- await redis.zincrby(K.members(epoch, mint), credit, wallet);
- await redis.expire(K.members(epoch, mint), ROUND_TTL_S);
+ try {
+ const wKey = K.wallet(epoch, mint, wallet);
+ // Reserve against the per-wallet ceiling first. INCRBY returns the running
+ // total; if this push would breach the cap, clamp the credited amount to
+ // whatever headroom remains (possibly zero) and roll the counter back to the
+ // cap so it stays truthful.
+ const after = await redis.incrby(wKey, amt);
+ await redis.expire(wKey, ROUND_TTL_S);
+ let credit = amt;
+ let capped = false;
+ if (after > walletCap) {
+ credit = Math.max(0, amt - (after - walletCap));
+ capped = true;
+ if (credit !== amt) await redis.set(wKey, walletCap, { ex: ROUND_TTL_S });
+ }
+ if (credit > 0) {
+ await redis.zincrby(K.factions(epoch), credit, mint);
+ await redis.expire(K.factions(epoch), ROUND_TTL_S);
+ await redis.zincrby(K.members(epoch, mint), credit, wallet);
+ await redis.expire(K.members(epoch, mint), ROUND_TTL_S);
+ }
+ return { added: credit, walletTotal: Math.min(after, walletCap), capped };
+ } catch (err) {
+ redisDegraded(err);
}
- return { added: credit, walletTotal: Math.min(after, walletCap), capped };
}
// In-memory
@@ -112,15 +135,25 @@ export async function addPower({ epoch, mint, wallet, amount, walletCap }) {
/** A soldier's power so far this round for one faction. */
export async function walletPower({ epoch, mint, wallet }) {
- if (redis) return Number((await redis.get(K.wallet(epoch, mint, wallet))) || 0);
+ if (redis) {
+ try {
+ return Number((await redis.get(K.wallet(epoch, mint, wallet))) || 0);
+ } catch (err) {
+ redisDegraded(err);
+ }
+ }
return Number(memValid(K.wallet(epoch, mint, wallet)) || 0);
}
/** Faction → power map for a round. */
export async function factionPowers(epoch) {
if (redis) {
- const flat = await redis.zrange(K.factions(epoch), 0, -1, { withScores: true });
- return zflatToMap(flat);
+ try {
+ const flat = await redis.zrange(K.factions(epoch), 0, -1, { withScores: true });
+ return zflatToMap(flat);
+ } catch (err) {
+ redisDegraded(err);
+ }
}
const out = {};
for (const [k, v] of memZ(K.factions(epoch))) out[k] = Number(v) || 0;
@@ -130,11 +163,15 @@ export async function factionPowers(epoch) {
/** Top soldiers for a faction this round: [{ wallet, power }] descending. */
export async function topSoldiers({ epoch, mint, limit = 10 }) {
if (redis) {
- const flat = await redis.zrange(K.members(epoch, mint), 0, limit - 1, {
- rev: true,
- withScores: true,
- });
- return zflatToList(flat);
+ try {
+ const flat = await redis.zrange(K.members(epoch, mint), 0, limit - 1, {
+ rev: true,
+ withScores: true,
+ });
+ return zflatToList(flat);
+ } catch (err) {
+ redisDegraded(err);
+ }
}
const m = memZ(K.members(epoch, mint));
return [...m.entries()]
@@ -147,15 +184,25 @@ export async function topSoldiers({ epoch, mint, limit = 10 }) {
export async function getMomentum(mint) {
if (redis) {
- const v = await redis.get(K.momentum(mint));
- const n = Number(v);
- return Number.isFinite(n) && n > 0 ? n : null;
+ try {
+ const v = await redis.get(K.momentum(mint));
+ const n = Number(v);
+ return Number.isFinite(n) && n > 0 ? n : null;
+ } catch (err) {
+ redisDegraded(err);
+ }
}
const v = memValid(K.momentum(mint));
return v == null ? null : Number(v);
}
export async function setMomentum(mint, factor, ttlS = 120) {
- if (redis) return void (await redis.set(K.momentum(mint), factor, { ex: ttlS }));
+ if (redis) {
+ try {
+ return void (await redis.set(K.momentum(mint), factor, { ex: ttlS }));
+ } catch (err) {
+ redisDegraded(err);
+ }
+ }
mem.s.set(K.momentum(mint), { value: factor, exp: Date.now() + ttlS * 1000 });
}
@@ -166,11 +213,15 @@ export async function getRecords(mints = []) {
const out = {};
if (!mints.length) return out;
if (redis) {
- const raw = await redis.hmget(K.record, ...mints);
- mints.forEach((mint, i) => {
- out[mint] = parseRecord(raw?.[i]);
- });
- return out;
+ try {
+ const raw = await redis.hmget(K.record, ...mints);
+ mints.forEach((mint, i) => {
+ out[mint] = parseRecord(raw?.[i]);
+ });
+ return out;
+ } catch (err) {
+ redisDegraded(err);
+ }
}
const h = mem.h.get(K.record) || new Map();
for (const mint of mints) out[mint] = parseRecord(h.get(mint));
@@ -220,9 +271,13 @@ export async function settleRound(epoch, matchmakeFn) {
async function claimSettle(epoch) {
if (redis) {
- // SET NX — first writer wins the settlement.
- const ok = await redis.set(K.settled(epoch), Date.now(), { nx: true, ex: ROUND_TTL_S });
- return ok === 'OK' || ok === true;
+ try {
+ // SET NX — first writer wins the settlement.
+ const ok = await redis.set(K.settled(epoch), Date.now(), { nx: true, ex: ROUND_TTL_S });
+ return ok === 'OK' || ok === true;
+ } catch (err) {
+ redisDegraded(err);
+ }
}
if (memValid(K.settled(epoch))) return false;
mem.s.set(K.settled(epoch), { value: Date.now(), exp: Date.now() + ROUND_TTL_S * 1000 });
@@ -239,15 +294,19 @@ async function bumpRecord(mint, { power, win, loss, draw }) {
power: cur.power + Math.round(power),
};
if (redis) {
- await redis.hset(K.record, { [mint]: JSON.stringify(next) });
- } else {
- let h = mem.h.get(K.record);
- if (!h) {
- h = new Map();
- mem.h.set(K.record, h);
+ try {
+ await redis.hset(K.record, { [mint]: JSON.stringify(next) });
+ return;
+ } catch (err) {
+ redisDegraded(err);
}
- h.set(mint, JSON.stringify(next));
}
+ let h = mem.h.get(K.record);
+ if (!h) {
+ h = new Map();
+ mem.h.set(K.record, h);
+ }
+ h.set(mint, JSON.stringify(next));
}
// ─── helpers ─────────────────────────────────────────────────────────────────
diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.js
index 19b912a5e..75d6492e5 100644
--- a/api/_lib/rate-limit.js
+++ b/api/_lib/rate-limit.js
@@ -118,6 +118,11 @@ function getLimiter(name, opts) {
const _degradeWarnedAt = new Map();
const DEGRADE_WARN_COOLDOWN_MS = 60_000;
function warnDegradedOnce(name, err) {
+ // The shared Redis auth breaker (api/_lib/redis.js) already logged the one
+ // "auth failure" line and is fast-failing every command; its short-circuit
+ // rejections carry `circuitOpen`. Re-warning per limiter per cooldown on top of
+ // that is pure noise — skip it and let the breaker own the signal.
+ if (err?.circuitOpen) return;
const last = _degradeWarnedAt.get(name) || 0;
const t = Date.now();
if (t - last < DEGRADE_WARN_COOLDOWN_MS) return;
diff --git a/api/_lib/redis.js b/api/_lib/redis.js
index aea04932b..a0e7d64e6 100644
--- a/api/_lib/redis.js
+++ b/api/_lib/redis.js
@@ -11,21 +11,208 @@
// import { getRedis } from './redis.js';
// const r = getRedis();
// if (!r) { /* fallback */ }
+//
+// Auth-failure fast-fail breaker
+// ------------------------------
+// A WRONGPASS / "invalid or missing auth token" / NOPERM / NOAUTH response is a
+// PERMANENT, config-level failure (a rotated or stale UPSTASH_REDIS_REST_TOKEN),
+// not the transient outage the per-consumer fallbacks were written for. Without a
+// breaker, every limiter, the usage buffer, the x402 feed and ~50 other consumers
+// keep issuing doomed commands on EVERY request: each pays a full Upstash REST
+// round-trip (latency + the request-quota the whole module exists to conserve)
+// only to fail identically, and each re-logs — the 24k-warning / "operation
+// aborted due to timeout" flood seen in production (prod log export 2026-06-28).
+//
+// So we wrap the client: the first auth failure OPENS a per-instance breaker, and
+// for AUTH_BREAKER_COOLDOWN_MS every command short-circuits straight to its
+// caller's existing fallback — no fetch, no quota spend, no per-request stall.
+// The short-circuit rejection is tagged `circuitOpen` so consumers (cache.js
+// already honors this flag; rate-limit / usage / x402-pay now do too) skip their
+// own per-request warning. Once the cooldown elapses the breaker goes half-open
+// and admits exactly one trial command: its success CLOSES the breaker the instant
+// the token is rotated back (self-heal, no redeploy); its failure re-arms the
+// cooldown. Net cost of a bad token: one log line + one trial per minute per
+// instance, instead of a doomed round-trip on every request.
+//
+// Only auth failures trip the breaker. Transient errors (timeouts, 5xx) keep the
+// existing per-consumer degrade behavior untouched — they are genuinely worth
+// retrying, an auth failure never is.
import { Redis } from '@upstash/redis';
import { env } from './env.js';
let _instance = undefined; // undefined = not yet resolved; null = checked, absent
+// --- Auth-failure breaker state (per serverless instance) ---
+const AUTH_BREAKER_COOLDOWN_MS = Math.max(
+ 5_000,
+ Number(process.env.REDIS_AUTH_BREAKER_COOLDOWN_MS) || 60_000,
+);
+let authOpenUntil = 0; // epoch ms; 0 = closed (commands flow normally)
+let authTrialInFlight = false;
+
+// Auth/permission failures are permanent until the credential changes; only these
+// trip the breaker. Upstash surfaces them in the error message body it returns.
+function isAuthError(err) {
+ const m = String(err?.message || err || '');
+ return /WRONGPASS|NOAUTH|NOPERM|invalid or missing auth token|\b401\b|\b403\b/i.test(m);
+}
+
+// Thrown when the breaker is open. Tagged `circuitOpen` so consumers treat it as a
+// normal "Redis unavailable" fallback WITHOUT emitting a per-request warning (the
+// open/recovered transitions each log exactly once). Mirrors the convention the
+// cache layer (api/_lib/cache.js) already uses for its own breaker.
+class RedisAuthBreakerOpenError extends Error {
+ constructor() {
+ super('redis auth breaker open (invalid/stale UPSTASH_REDIS_REST_TOKEN)');
+ this.name = 'RedisAuthBreakerOpenError';
+ this.circuitOpen = true;
+ this.authBreakerOpen = true;
+ }
+}
+
+// Returns true if a command may be issued. Open → false, except once per cooldown
+// it admits a single half-open trial to detect a restored credential.
+function breakerAllows() {
+ if (authOpenUntil === 0) return true;
+ if (Date.now() < authOpenUntil) return false;
+ if (authTrialInFlight) return false; // a trial is already probing; hold the rest
+ authTrialInFlight = true;
+ return true;
+}
+
+function breakerRecordSuccess() {
+ if (authOpenUntil !== 0) {
+ console.warn('[redis] auth recovered — UPSTASH_REDIS_REST_TOKEN valid again, commands resumed');
+ }
+ authOpenUntil = 0;
+ authTrialInFlight = false;
+}
+
+function breakerRecordFailure(err) {
+ const wasTrial = authTrialInFlight;
+ authTrialInFlight = false;
+ const opening = authOpenUntil === 0;
+ authOpenUntil = Date.now() + AUTH_BREAKER_COOLDOWN_MS;
+ if (opening && !wasTrial) {
+ console.error(
+ '[redis] AUTH FAILURE — UPSTASH_REDIS_REST_TOKEN is invalid or stale; ' +
+ `fast-failing all Redis commands to in-memory fallbacks for ${AUTH_BREAKER_COOLDOWN_MS / 1000}s ` +
+ '(rotate the token in the prod env to restore distributed limiters/cache). Cause:',
+ err?.message || err,
+ );
+ }
+}
+
+// Wrap one client method so it participates in the breaker: short-circuit while
+// open, record success/auth-failure on settle. Non-auth errors pass through
+// untouched (the caller's existing transient-error fallback handles them) and do
+// NOT trip or reset the breaker.
+function wrapCommand(fn, target) {
+ return function (...args) {
+ if (!breakerAllows()) return Promise.reject(new RedisAuthBreakerOpenError());
+ let out;
+ try {
+ out = fn.apply(target, args);
+ } catch (err) {
+ // Synchronous throw (bad args, etc.) — not a transport/auth signal.
+ return Promise.reject(err);
+ }
+ if (!out || typeof out.then !== 'function') return out; // non-promise: pass through
+ return Promise.resolve(out).then(
+ (res) => {
+ breakerRecordSuccess();
+ return res;
+ },
+ (err) => {
+ if (isAuthError(err)) breakerRecordFailure(err);
+ else if (authTrialInFlight) authTrialInFlight = false; // trial hit a transient error; release the probe slot
+ throw err;
+ },
+ );
+ };
+}
+
+// pipeline()/multi() return a chainable builder whose commands run on .exec(). We
+// don't short-circuit these (low-volume write paths), but we DO let their exec()
+// trip/heal the breaker so a bad token is still detected from those paths.
+function wrapPipeline(pipe) {
+ const exec = pipe.exec;
+ if (typeof exec === 'function') {
+ pipe.exec = function (...args) {
+ return Promise.resolve(exec.apply(pipe, args)).then(
+ (res) => {
+ breakerRecordSuccess();
+ return res;
+ },
+ (err) => {
+ if (isAuthError(err)) breakerRecordFailure(err);
+ throw err;
+ },
+ );
+ };
+ }
+ return pipe;
+}
+
+// Methods that build a chain rather than issuing a command immediately.
+const CHAIN_BUILDERS = new Set(['pipeline', 'multi']);
+
+function wrapClient(client) {
+ const cache = new Map();
+ return new Proxy(client, {
+ get(target, prop) {
+ // Read with `target` as the receiver (not our outer Proxy): the upstash
+ // client may itself be an auto-pipelining Proxy whose traps key off the
+ // receiver, so handing it back our wrapper would confuse method resolution.
+ const value = target[prop];
+ if (typeof value !== 'function') return value;
+ if (CHAIN_BUILDERS.has(prop)) {
+ return function (...args) {
+ return wrapPipeline(value.apply(target, args));
+ };
+ }
+ let wrapped = cache.get(prop);
+ if (!wrapped) {
+ wrapped = wrapCommand(value, target);
+ cache.set(prop, wrapped);
+ }
+ return wrapped;
+ },
+ });
+}
+
export function getRedis() {
if (_instance !== undefined) return _instance;
if (env.UPSTASH_REDIS_REST_URL && env.UPSTASH_REDIS_REST_TOKEN) {
- _instance = new Redis({
- url: env.UPSTASH_REDIS_REST_URL,
- token: env.UPSTASH_REDIS_REST_TOKEN,
- });
+ _instance = wrapClient(
+ new Redis({
+ url: env.UPSTASH_REDIS_REST_URL,
+ token: env.UPSTASH_REDIS_REST_TOKEN,
+ }),
+ );
} else {
_instance = null;
}
return _instance;
}
+
+/**
+ * Current auth-breaker state, for health/diagnostics endpoints
+ * (api/admin/redis-health.js). `open` true means the shared token is failing and
+ * commands are being short-circuited to fallbacks on this instance.
+ */
+export function redisAuthBreakerState() {
+ return {
+ open: authOpenUntil !== 0 && Date.now() < authOpenUntil,
+ openUntil: authOpenUntil || null,
+ cooldownMs: AUTH_BREAKER_COOLDOWN_MS,
+ };
+}
+
+/** Test-only: reset the breaker between cases. */
+export function __resetRedisAuthBreaker() {
+ authOpenUntil = 0;
+ authTrialInFlight = false;
+ _instance = undefined;
+}
diff --git a/api/_lib/usage.js b/api/_lib/usage.js
index 9acf57df3..3c923db98 100644
--- a/api/_lib/usage.js
+++ b/api/_lib/usage.js
@@ -111,7 +111,12 @@ export function recordEvent(evt) {
if (len % BUFFER_FLUSH_THRESHOLD === 0) triggerFlushJob();
return;
} catch (err) {
- console.warn('[usage] buffer push failed, falling back to direct insert', err?.message);
+ // circuitOpen → the shared Redis auth breaker (api/_lib/redis.js) already
+ // logged the credential failure once and is fast-failing; falling back to
+ // a direct insert is the right move, but re-warning per event is noise.
+ if (!err?.circuitOpen) {
+ console.warn('[usage] buffer push failed, falling back to direct insert', err?.message);
+ }
}
}
// Direct-insert fallback when Redis is absent or the push fails. Bounded by
@@ -153,7 +158,7 @@ export async function flushUsageBuffer({ limit = 500, deadlineMs = 45_000 } = {}
try {
raw = await r.lrange(BUFFER_KEY, 0, take - 1);
} catch (err) {
- console.warn('[usage-flush] redis unavailable on lrange:', err?.message);
+ if (!err?.circuitOpen) console.warn('[usage-flush] redis unavailable on lrange:', err?.message);
return { flushed, remaining: -1, errors, skipped: 'redis_unavailable' };
}
if (!raw || raw.length === 0) break;
diff --git a/api/admin/redis-health.js b/api/admin/redis-health.js
index 2ab6b0d24..114bc5fba 100644
--- a/api/admin/redis-health.js
+++ b/api/admin/redis-health.js
@@ -10,7 +10,7 @@
import { cors, json, error, method, wrap } from '../_lib/http.js';
import { requireAdmin } from '../_lib/admin.js';
-import { getRedis } from '../_lib/redis.js';
+import { getRedis, redisAuthBreakerState } from '../_lib/redis.js';
import { env } from '../_lib/env.js';
import { sendOpsAlert } from '../_lib/alerts.js';
@@ -67,7 +67,29 @@ export default wrap(async (req, res) => {
await redis.ping();
pingOk = true;
} catch (err) {
- return json(res, 200, { ok: false, configured: true, latencyMs: Date.now() - t0, error: err?.message });
+ // An auth failure (invalid/stale UPSTASH_REDIS_REST_TOKEN) trips the shared
+ // fast-fail breaker (api/_lib/redis.js): every limiter/cache/usage path is now
+ // on its in-memory fallback platform-wide. That is exactly what ops must be
+ // paged on — distributed rate limits and the cache are blind until the token
+ // is rotated — so fire a deduped ops alert here, on the uptime-cron path.
+ const breaker = redisAuthBreakerState();
+ const authFailing = breaker.open || /WRONGPASS|NOAUTH|NOPERM|invalid or missing auth token|\b401\b|\b403\b/i.test(String(err?.message || ''));
+ if (authFailing) {
+ await sendOpsAlert(
+ 'Redis AUTH FAILURE — UPSTASH_REDIS_REST_TOKEN invalid or stale',
+ 'Every distributed rate limiter, the cache, the usage buffer and the x402 feed are running on in-memory fallbacks. Rotate UPSTASH_REDIS_REST_TOKEN in the prod env to restore them. ' +
+ `Probe error: ${err?.message || err}`,
+ { signature: 'redis-auth-failure' },
+ );
+ }
+ return json(res, 200, {
+ ok: false,
+ configured: true,
+ latencyMs: Date.now() - t0,
+ error: err?.message,
+ authBreaker: breaker,
+ authFailing,
+ });
}
const latencyMs = Date.now() - t0;
@@ -110,6 +132,7 @@ export default wrap(async (req, res) => {
configured: true,
latencyMs,
quotaWarningSent,
+ authBreaker: redisAuthBreakerState(),
info,
});
});
diff --git a/api/cron/x402-seed-cron.js b/api/cron/x402-seed-cron.js
index ef51c34f0..414cc36c9 100644
--- a/api/cron/x402-seed-cron.js
+++ b/api/cron/x402-seed-cron.js
@@ -205,7 +205,7 @@ export default wrapCron(async (req, res) => {
try {
await redis.ping();
} catch (err) {
- log.warn('redis_unavailable_skip', { message: err?.message });
+ if (!err?.circuitOpen) log.warn('redis_unavailable_skip', { message: err?.message });
return json(res, 200, { ok: false, skipped: true, reason: `redis_unavailable: ${err?.message}` });
}
}
diff --git a/api/vanity/bounties.js b/api/vanity/bounties.js
index d206ebcf2..567e74586 100644
--- a/api/vanity/bounties.js
+++ b/api/vanity/bounties.js
@@ -327,10 +327,14 @@ async function handleGet(req, res, url) {
const result = await queryBounties({ status, sort, limit, offset });
return json(res, 200, { ...result, status, sort }, { 'cache-control': READ_CACHE });
} catch (err) {
- const isRedisAuth = err?.constructor?.name === 'UpstashError' &&
- (err.message?.includes('WRONGPASS') || err.message?.includes('invalid or missing auth token'));
+ // circuitOpen → the shared Redis auth breaker is fast-failing (it already
+ // logged the credential failure once). Otherwise match a raw Upstash auth
+ // error. Either way the store is unreachable: return 503, don't 500.
+ const isRedisAuth = err?.circuitOpen ||
+ (err?.constructor?.name === 'UpstashError' &&
+ (err.message?.includes('WRONGPASS') || err.message?.includes('invalid or missing auth token')));
if (isRedisAuth) {
- console.warn('[vanity/bounties] redis unavailable:', err.message);
+ if (!err?.circuitOpen) console.warn('[vanity/bounties] redis unavailable:', err.message);
return error(res, 503, 'store_unavailable', 'the bounty store is temporarily unavailable');
}
throw err;
diff --git a/api/x402-pay.js b/api/x402-pay.js
index 04c8de64e..ab4b9dc77 100644
--- a/api/x402-pay.js
+++ b/api/x402-pay.js
@@ -118,7 +118,7 @@ async function readFeed(limit = 25) {
feedReadCache = { at: Date.now(), rows };
return rows;
} catch (err) {
- log.warn('feed_read_failed', { message: err?.message });
+ if (!err?.circuitOpen) log.warn('feed_read_failed', { message: err?.message });
return memFeed.slice();
} finally {
feedReadInflight = null;
diff --git a/data/changelog.json b/data/changelog.json
index 9dea0d4a4..8e5d2f8ec 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,15 @@
{
"$comment": "Curated changelog entries for three.ws — the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.",
"entries": [
+ {
+ "date": "2026-06-29",
+ "title": "Coin Clash stays up when the leaderboard backend hiccups",
+ "summary": "The live Coin Clash arena and leaderboard used to go completely dark with an error whenever the power-tracking backend had a momentary outage — a recoverable blip took the whole page down. Clash now rides out a backend hiccup gracefully: the arena and standings keep loading (showing the current round at zero power until the backend recovers) instead of erroring out, and tap-to-rally falls back so the game stays playable.",
+ "tags": [
+ "fix"
+ ],
+ "link": "/clash"
+ },
{
"date": "2026-06-29",
"title": "Posting a labor-market bounty no longer hits a surprise rate limit",
diff --git a/public/changelog.json b/public/changelog.json
index 9adb84d34..696fce83d 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,11 +1,21 @@
{
- "generated_at": "2026-06-29T01:50:41.663Z",
+ "generated_at": "2026-06-29T02:23:33.437Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
"url": "https://three.ws"
},
"entries": [
+ {
+ "date": "2026-06-29",
+ "type": "update",
+ "title": "Coin Clash stays up when the leaderboard backend hiccups",
+ "summary": "The live Coin Clash arena and leaderboard used to go completely dark with an error whenever the power-tracking backend had a momentary outage — a recoverable blip took the whole page down. Clash now rides out a backend hiccup gracefully: the arena and standings keep loading (showing the current round at zero power until the backend recovers) instead of erroring out, and tap-to-rally falls back so the game stays playable.",
+ "link": "/clash",
+ "tags": [
+ "fix"
+ ]
+ },
{
"date": "2026-06-29",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index 4423fbf88..f065ab2a7 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -6,6 +6,14 @@
<atom:link href="https://three.ws/changelog.xml" rel="self" type="application/rss+xml"/>
<description>What's new on three.ws — features, improvements, and releases, newest first.</description>
<language>en</language>
+ <item>
+ <title>Coin Clash stays up when the leaderboard backend hiccups</title>
+ <link>https://three.ws/clash</link>
+ <guid isPermaLink="false">2026-06-29:Coin Clash stays up when the leaderboard backend hiccups</guid>
+ <pubDate>Mon, 29 Jun 2026 12:00:00 GMT</pubDate>
+ <category>fix</category>
+ <description>The live Coin Clash arena and leaderboard used to go completely dark with an error whenever the power-tracking backend had a momentary outage — a recoverable blip took the whole page down. Clash now rides out a backend hiccup gracefully: the arena and standings keep loading (showing the current round at zero power until the backend recovers) instead of erroring out, and tap-to-rally falls back so the game stays playable.</description>
+ </item>
<item>
<title>Posting a labor-market bounty no longer hits a surprise rate limit</title>
<link>https://three.ws/labor-market</link>
diff --git a/public/features.json b/public/features.json
index 2b182ad97..92206c0fe 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-29T01:50:41.650Z",
+ "generated_at": "2026-06-29T02:23:33.419Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/tests/clash-store-resilience.test.js b/tests/clash-store-resilience.test.js
new file mode 100644
index 000000000..8b2c63fe8
--- /dev/null
+++ b/tests/clash-store-resilience.test.js
@@ -0,0 +1,61 @@
+// Clash persistence must survive a Redis outage. A configured Upstash client
+// can still throw at call time (transport blip, over-quota 4xx, rotated token);
+// before this guard those throws propagated to the HTTP wrapper, which
+// classifies them as "database unavailable" and 503s the whole request — taking
+// the live Clash state + leaderboard reads dark on a recoverable hiccup. The
+// store must instead degrade to its in-memory model and keep answering.
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+// A configured-but-broken Redis: every command rejects, the way Upstash does
+// when the REST endpoint is unreachable or the account is over quota.
+const boom = () => Promise.reject(Object.assign(new Error('fetch failed'), { name: 'TypeError' }));
+const throwingRedis = {
+ incrby: boom, expire: boom, set: boom, get: boom,
+ zincrby: boom, zrange: boom, hmget: boom, hset: boom,
+};
+
+vi.mock('../api/_lib/redis.js', () => ({ getRedis: () => throwingRedis }));
+
+let store;
+beforeEach(async () => {
+ vi.resetModules();
+ store = await import('../api/_lib/clash-store.js');
+});
+
+const MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
+
+describe('clash-store resilience under a Redis outage', () => {
+ it('factionPowers degrades to an empty map instead of throwing', async () => {
+ await expect(store.factionPowers(42)).resolves.toEqual({});
+ });
+
+ it('getRecords degrades to neutral records instead of throwing', async () => {
+ const recs = await store.getRecords([MINT]);
+ expect(recs[MINT]).toEqual({ w: 0, l: 0, d: 0, battles: 0, power: 0 });
+ });
+
+ it('topSoldiers degrades to an empty list instead of throwing', async () => {
+ await expect(store.topSoldiers({ epoch: 42, mint: MINT })).resolves.toEqual([]);
+ });
+
+ it('getMomentum / walletPower degrade to neutral values', async () => {
+ await expect(store.getMomentum(MINT)).resolves.toBeNull();
+ await expect(store.walletPower({ epoch: 42, mint: MINT, wallet: MINT })).resolves.toBe(0);
+ });
+
+ it('setMomentum tolerates a write failure without throwing', async () => {
+ await expect(store.setMomentum(MINT, 1.2)).resolves.toBeUndefined();
+ });
+
+ it('addPower falls back to the in-memory tally instead of throwing', async () => {
+ const r = await store.addPower({ epoch: 42, mint: MINT, wallet: MINT, amount: 5, walletCap: 100 });
+ expect(r.added).toBe(5);
+ expect(r.walletTotal).toBe(5);
+ expect(r.capped).toBe(false);
+ });
+
+ it('settleRound tolerates a Redis outage without throwing', async () => {
+ const matchmake = (mints) => ({ battles: mints.length >= 2 ? [{ a: mints[0], b: mints[1] }] : [] });
+ await expect(store.settleRound(7, matchmake)).resolves.toMatchObject({ settled: expect.any(Boolean) });
+ });
+});
diff --git a/tests/redis-auth-breaker.test.js b/tests/redis-auth-breaker.test.js
new file mode 100644
index 000000000..d78126380
--- /dev/null
+++ b/tests/redis-auth-breaker.test.js
@@ -0,0 +1,148 @@
+/**
+ * redis.js auth-failure fast-fail breaker — unit test.
+ *
+ * A WRONGPASS / "invalid or missing auth token" response from Upstash is a
+ * PERMANENT, config-level failure (a rotated/stale UPSTASH_REDIS_REST_TOKEN), not
+ * the transient blip the per-consumer fallbacks were written for. Without a
+ * breaker every limiter / cache / usage path keeps issuing doomed commands on
+ * every request — a real Upstash round-trip (latency + quota) that fails
+ * identically, plus a log line — which is the 24k-warning flood seen in prod
+ * (log export 2026-06-28). This pins the breaker: first auth failure opens it,
+ * subsequent commands fast-fail with `circuitOpen` and NO network call, and a
+ * later success (token rotated) closes it.
+ *
+ * The @upstash/redis client issues each command as a fetch() to the REST URL, so
+ * we stub global fetch to simulate WRONGPASS, then a recovery.
+ */
+
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { getRedis, redisAuthBreakerState, __resetRedisAuthBreaker } from '../api/_lib/redis.js';
+
+const URL = 'https://breaker-test.upstash.io';
+const ENV_KEYS = ['UPSTASH_REDIS_REST_URL', 'UPSTASH_REDIS_REST_TOKEN'];
+let saved;
+
+// Minimal stand-in for a fetch Response. The upstash HttpClient reads
+// `response.headers.get(...)`, so the headers shim is required.
+const HEADERS = { get: () => null };
+
+function wrongpassResponse() {
+ return {
+ ok: true,
+ status: 200,
+ headers: HEADERS,
+ async json() {
+ return { error: 'WRONGPASS invalid or missing auth token.' };
+ },
+ async text() {
+ return '';
+ },
+ };
+}
+
+function okResponse(result) {
+ return {
+ ok: true,
+ status: 200,
+ headers: HEADERS,
+ async json() {
+ return { result };
+ },
+ async text() {
+ return '';
+ },
+ };
+}
+
+beforeEach(() => {
+ saved = {};
+ for (const k of ENV_KEYS) {
+ saved[k] = process.env[k];
+ delete process.env[k];
+ }
+ process.env.UPSTASH_REDIS_REST_URL = URL;
+ process.env.UPSTASH_REDIS_REST_TOKEN = 'stale-token';
+ __resetRedisAuthBreaker();
+});
+
+afterEach(() => {
+ for (const k of ENV_KEYS) {
+ if (saved[k] === undefined) delete process.env[k];
+ else process.env[k] = saved[k];
+ }
+ vi.restoreAllMocks();
+ __resetRedisAuthBreaker();
+});
+
+describe('redis auth breaker', () => {
+ it('opens on the first WRONGPASS and then fast-fails commands without calling fetch', async () => {
+ const fetchMock = vi.fn(async () => wrongpassResponse());
+ globalThis.fetch = fetchMock;
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+
+ const r = getRedis();
+ expect(r).toBeTruthy();
+
+ // First command hits the network and fails with the auth error.
+ await expect(r.get('k')).rejects.toThrow(/WRONGPASS/i);
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ expect(redisAuthBreakerState().open).toBe(true);
+
+ // Subsequent commands short-circuit: no further fetch, rejection tagged circuitOpen.
+ for (let i = 0; i < 50; i++) {
+ const err = await r.get('k').then(() => null, (e) => e);
+ expect(err).toBeTruthy();
+ expect(err.circuitOpen).toBe(true);
+ }
+ expect(fetchMock).toHaveBeenCalledTimes(1); // still just the one real call
+ });
+
+ it('self-heals via a half-open trial once the token is valid again', async () => {
+ let mode = 'wrongpass';
+ const fetchMock = vi.fn(async () => (mode === 'wrongpass' ? wrongpassResponse() : okResponse('PONG')));
+ globalThis.fetch = fetchMock;
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ vi.spyOn(console, 'warn').mockImplementation(() => {});
+
+ // Tiny cooldown so the trial is admitted quickly.
+ process.env.REDIS_AUTH_BREAKER_COOLDOWN_MS = '20';
+ __resetRedisAuthBreaker();
+
+ const r = getRedis();
+ await expect(r.get('k')).rejects.toThrow(/WRONGPASS/i);
+ expect(redisAuthBreakerState().open).toBe(true);
+
+ // While open, fast-fail (no network).
+ await expect(r.get('k')).rejects.toMatchObject({ circuitOpen: true });
+ const callsWhileOpen = fetchMock.mock.calls.length;
+
+ // Token rotated; wait out the cooldown so a half-open trial is admitted.
+ mode = 'ok';
+ await new Promise((res) => setTimeout(res, 30));
+
+ // The trial command goes through and succeeds → breaker closes.
+ await expect(r.get('k')).resolves.toBe('PONG');
+ expect(fetchMock.mock.calls.length).toBe(callsWhileOpen + 1);
+ expect(redisAuthBreakerState().open).toBe(false);
+
+ delete process.env.REDIS_AUTH_BREAKER_COOLDOWN_MS;
+ });
+
+ it('does not trip on transient (non-auth) errors', async () => {
+ const fetchMock = vi.fn(async () => {
+ throw new Error('The operation was aborted due to timeout');
+ });
+ globalThis.fetch = fetchMock;
+
+ const r = getRedis();
+ await expect(r.get('k')).rejects.toThrow(/timeout/i);
+ // Transient error must NOT open the breaker — those are worth retrying, and a
+ // closed breaker means the next command still reaches the network (the upstash
+ // client adds its own retry layer beneath us, so we don't assert a call count).
+ expect(redisAuthBreakerState().open).toBe(false);
+ const before = fetchMock.mock.calls.length;
+ await expect(r.get('k')).rejects.toThrow(/timeout/i);
+ expect(fetchMock.mock.calls.length).toBeGreaterThan(before);
+ expect(redisAuthBreakerState().open).toBe(false);
+ });
+});