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.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
fix(pump-bounties): serve last-known-good data instead of a 502 when pump.fun GO is unreachable
nirholasaa4343e6ba36
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c04cc259d..8dce9b520 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-10-25+- **GET /api/pump-bounties and its stats/detail routes serve last-known-good data instead of a 502**: pump.fun's Cloudflare anti-bot challenge has been rejecting livestream-api.pump.fun's bounty API for hours at a time, which left the bounty list, the aggregate stats, and individual bounty detail pages 502ing for every visitor even though the board itself had not changed. All three routes now go through the same last-known-good cache tier already proven on /api/portal and /api/crypto/bonding: a fresh answer is mirrored into a 24-hour backup, and that backup answers (flagged with an x-pump-stale header) instead of a 502 once the live fetch fails. A true miss, with nothing cached at all, still returns the original pump.fun error unchanged. (`/bounties`) `[fix]`- **Image-to-3D Forge instances recycle before a VRAM leak crashes a job**: The trellis lane's GPU worker already restarted itself between jobs once host memory ratcheted up, but had no equivalent check for GPU memory: a rasterizer dependency allocates outside torch's own memory pool, so an instance's usable VRAM only ever shrank, and the instance's own health check kept passing right up until a job crashed or Cloud Run killed it mid-generation. The worker now also tracks GPU memory after every job and restarts cleanly between jobs once it has ratcheted far enough, the same way the existing memory guard already does, so Forge image-to-3D jobs on this lane fail or stall less often. (`/image-to-3d`) `[fix]`## 2026-10-24diff --git a/api/pump-bounties.js b/api/pump-bounties.jsindex af37cf30f..821d6d003 100644--- a/api/pump-bounties.js+++ b/api/pump-bounties.js@@ -10,18 +10,18 @@// surfaced to us as a PumpGoError) with no server-side way to pass it. Before// 2026-10-24 that left this route 502ing for every visitor for hours at a time// (every 24h sample failed) even though the board had not actually changed.-// A long-lived last-known-good copy, written on every real success and served-// (marked stale) when the live fetch fails, rides out the block the same way-// api/_lib/pump-feed-fetch.js already does for the other pump.fun feeds.+// cacheWrapLastGood (api/_lib/cache.js) rides out the block the same way it+// already does for api/portal.js and the other pump.fun feeds: a fresh value+// is served for 30s, mirrored into a 24h last-known-good copy, and that copy+// answers (flagged with an x-pump-stale header) instead of a 502 when the+// live fetch throws.import { cors, json, error, wrap, method, rateLimited } from './_lib/http.js';import { limits, clientIp } from './_lib/rate-limit.js';-import { cacheGet, cacheSet } from './_lib/cache.js';+import { cacheWrapLastGood } from './_lib/cache.js';import { listBounties, PumpGoError } from './_lib/pump-go.js';import { clampInt } from './_lib/http-params.js';-const LKG_TTL_S = 1800;-export default wrap(async (req, res) => {if (cors(req, res, { methods: 'GET,OPTIONS' })) return;if (!method(req, res, ['GET'])) return;@@ -39,28 +39,16 @@ export default wrap(async (req, res) => {const status = url.searchParams.get('status') || null;const cacheKey = `pumpgo:list:${limit}:${cursor || '_'}:${status || '_'}`;- const lkgKey = `${cacheKey}:lkg`;- const cached = await cacheGet(cacheKey).catch(() => null);- if (cached) {- res.setHeader('cache-control', 'public, s-maxage=30, stale-while-revalidate=120');- return json(res, 200, cached);- }- let data;+ let value, stale;try {- data = await listBounties({ limit, cursor, status });+ ({ value, stale } = await cacheWrapLastGood(cacheKey, 30, () => listBounties({ limit, cursor, status }), { withMeta: true }));} catch (e) {if (!(e instanceof PumpGoError)) throw e;- const stale = await cacheGet(lkgKey).catch(() => null);- if (stale) {- res.setHeader('cache-control', 'public, s-maxage=30, stale-while-revalidate=120');- return json(res, 200, { ...stale, stale: true });- }return error(res, e.status, e.code, e.message);}- await cacheSet(cacheKey, data, 30).catch(() => {});- await cacheSet(lkgKey, data, LKG_TTL_S).catch(() => {});+ if (stale) res.setHeader('x-pump-stale', '1');res.setHeader('cache-control', 'public, s-maxage=30, stale-while-revalidate=120');- return json(res, 200, data);+ return json(res, 200, value);});diff --git a/api/pump-bounties/[id].js b/api/pump-bounties/[id].jsindex e1af76dd5..0373e0e07 100644--- a/api/pump-bounties/[id].js+++ b/api/pump-bounties/[id].js@@ -4,9 +4,14 @@// its submissions in parallel from the public livestream-api, normalizes, and// caches briefly. A submissions failure degrades to an empty list rather than// failing the whole page — the bounty itself is the primary content.+//+// The bounty detail itself goes through cacheWrapLastGood (see+// api/pump-bounties.js): a 24h last-known-good copy answers (flagged with an+// x-pump-stale header) instead of a 502 when pump.fun's Cloudflare challenge+// blocks the live fetch. A stale bounty still tries for fresh submissions.import { cors, json, error, wrap, method } from '../_lib/http.js';-import { cacheGet, cacheSet } from '../_lib/cache.js';+import { cacheWrapLastGood } from '../_lib/cache.js';import { isUuid } from '../_lib/validate.js';import { getBounty, getSubmissions, PumpGoError } from '../_lib/pump-go.js';@@ -17,36 +22,32 @@ export default wrap(async (req, res) => {const id = req.query?.id || req.url?.split('/').pop()?.split('?')[0];if (!id || !isUuid(id)) return error(res, 400, 'bad_request', 'valid bounty taskId required');- const cacheKey = `pumpgo:task:${id}`;- const cached = await cacheGet(cacheKey).catch(() => null);- if (cached) {- res.setHeader('cache-control', 'public, s-maxage=30, stale-while-revalidate=120');- return json(res, 200, cached);- }+ // Fired alongside the bounty fetch, not after it, so a cache miss on the+ // bounty does not add its own latency onto the submissions fetch too.+ const submissionsPromise = getSubmissions(id, { limit: 50 }).catch((e) => {+ // Degrading to an empty list is deliberate, but a silent degrade hides a+ // real pump.fun outage behind a page that just looks unpopular. Log it.+ console.warn(`[pump-bounties] submissions for ${id} unavailable: ${e.message}`);+ return { items: [], nextCursor: null };+ });- let bounty, submissions;+ let bounty, stale;try {- [bounty, submissions] = await Promise.all([- getBounty(id),- getSubmissions(id, { limit: 50 }).catch((e) => {- // Degrading to an empty list is deliberate, but a silent degrade hides a- // real pump.fun outage behind a page that just looks unpopular. Log it.- console.warn(`[pump-bounties] submissions for ${id} unavailable: ${e.message}`);- return { items: [], nextCursor: null };- }),- ]);+ ({ value: bounty, stale } = await cacheWrapLastGood(`pumpgo:task:${id}`, 30, () => getBounty(id), { withMeta: true }));} catch (e) {if (e instanceof PumpGoError) return error(res, e.status, e.code, e.message);throw e;}if (!bounty) return error(res, 404, 'not_found', 'bounty not found');+ const submissions = await submissionsPromise;+const payload = {bounty,submissions: submissions.items,submissionsCursor: submissions.nextCursor,};- await cacheSet(cacheKey, payload, 30).catch(() => {});+ if (stale) res.setHeader('x-pump-stale', '1');res.setHeader('cache-control', 'public, s-maxage=30, stale-while-revalidate=120');return json(res, 200, payload);});diff --git a/api/pump-bounties/stats.js b/api/pump-bounties/stats.jsindex ee9c287ce..aea422985 100644--- a/api/pump-bounties/stats.js+++ b/api/pump-bounties/stats.js@@ -6,75 +6,72 @@// walk runs at most once per window no matter how many visitors load the page.//// pump.fun's Cloudflare anti-bot challenge can reject the underlying list call-// for hours at a time (see api/pump-bounties.js); a long-lived last-known-good-// copy, written on every real success, is served (marked stale) instead of a-// 502 when that happens.+// for hours at a time (see api/pump-bounties.js); cacheWrapLastGood mirrors+// every real walk into a 24h last-known-good copy and serves that (flagged+// with an x-pump-stale header) instead of a 502 when that happens. The whole+// paginated walk is one cache unit, same as before: a mid-walk failure is+// never partially cached or served.import { cors, json, error, wrap, method } from './../_lib/http.js';-import { cacheGet, cacheSet } from './../_lib/cache.js';+import { cacheWrapLastGood } from './../_lib/cache.js';import { listBounties, PumpGoError } from './../_lib/pump-go.js';const PAGE = 50;const MAX_PAGES = 20; // hard ceiling: ≤1000 bounties scanned per refreshconst CACHE_TTL_S = 120;const CACHE_KEY = 'pumpgo:stats:v1';-const LKG_KEY = 'pumpgo:stats:v1:lkg';-const LKG_TTL_S = 1800;export default wrap(async (req, res) => {if (cors(req, res, { methods: 'GET,OPTIONS' })) return;if (!method(req, res, ['GET'])) return;- const cached = await cacheGet(CACHE_KEY).catch(() => null);- if (cached) {- res.setHeader('cache-control', 'public, s-maxage=120, stale-while-revalidate=300');- return json(res, 200, cached);- }+ let value, stale;+ try {+ ({ value, stale } = await cacheWrapLastGood(+ CACHE_KEY,+ CACHE_TTL_S,+ async () => {+ let count = 0;+ let totalRewardUsd = 0;+ let totalSubmissions = 0;+ let totalLikes = 0;+ let cursor = null;+ let pages = 0;+ let truncated = false;- let count = 0;- let totalRewardUsd = 0;- let totalSubmissions = 0;- let totalLikes = 0;- let cursor = null;- let pages = 0;- let truncated = false;+ do {+ const { items, nextCursor } = await listBounties({ limit: PAGE, cursor });+ for (const b of items) {+ count += 1;+ totalRewardUsd += Number(b.reward.totalUsd) || 0;+ totalSubmissions += b.counts.submissions || 0;+ totalLikes += b.likeCount || 0;+ }+ cursor = nextCursor;+ pages += 1;+ if (pages >= MAX_PAGES && cursor) {+ truncated = true;+ break;+ }+ } while (cursor);- try {- do {- const { items, nextCursor } = await listBounties({ limit: PAGE, cursor });- for (const b of items) {- count += 1;- totalRewardUsd += Number(b.reward.totalUsd) || 0;- totalSubmissions += b.counts.submissions || 0;- totalLikes += b.likeCount || 0;- }- cursor = nextCursor;- pages += 1;- if (pages >= MAX_PAGES && cursor) {- truncated = true;- break;- }- } while (cursor);+ return {+ count,+ totalRewardUsd: Math.round(totalRewardUsd * 100) / 100,+ totalSubmissions,+ totalLikes,+ truncated, // true → the board is larger than what we scanned+ updatedAt: new Date().toISOString(),+ };+ },+ { withMeta: true },+ ));} catch (e) {if (!(e instanceof PumpGoError)) throw e;- const stale = await cacheGet(LKG_KEY).catch(() => null);- if (stale) {- res.setHeader('cache-control', 'public, s-maxage=120, stale-while-revalidate=300');- return json(res, 200, { ...stale, stale: true });- }return error(res, e.status, e.code, e.message);}- const payload = {- count,- totalRewardUsd: Math.round(totalRewardUsd * 100) / 100,- totalSubmissions,- totalLikes,- truncated, // true → the board is larger than what we scanned- updatedAt: new Date().toISOString(),- };- await cacheSet(CACHE_KEY, payload, CACHE_TTL_S).catch(() => {});- await cacheSet(LKG_KEY, payload, LKG_TTL_S).catch(() => {});+ if (stale) res.setHeader('x-pump-stale', '1');res.setHeader('cache-control', 'public, s-maxage=120, stale-while-revalidate=300');- return json(res, 200, payload);+ return json(res, 200, value);});diff --git a/data/changelog.json b/data/changelog.jsonindex 12a2f0510..40d7a1eb8 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, desktop (desktop entries become the desktop app's release notes). `link` is optional and must be a live three.ws path.","entries": [+ {+ "date": "2026-10-25",+ "title": "GET /api/pump-bounties and its stats/detail routes serve last-known-good data instead of a 502",+ "summary": "pump.fun's Cloudflare anti-bot challenge has been rejecting livestream-api.pump.fun's bounty API for hours at a time, which left the bounty list, the aggregate stats, and individual bounty detail pages 502ing for every visitor even though the board itself had not changed. All three routes now go through the same last-known-good cache tier already proven on /api/portal and /api/crypto/bonding: a fresh answer is mirrored into a 24-hour backup, and that backup answers (flagged with an x-pump-stale header) instead of a 502 once the live fetch fails. A true miss, with nothing cached at all, still returns the original pump.fun error unchanged.",+ "tags": [+ "fix"+ ],+ "link": "/bounties"+ },{"date": "2026-10-25","title": "Image-to-3D Forge instances recycle before a VRAM leak crashes a job",diff --git a/public/changelog-recent.json b/public/changelog-recent.jsonindex 8ea4d169d..a63dad2e5 100644--- a/public/changelog-recent.json+++ b/public/changelog-recent.json@@ -1,14 +1,24 @@{- "generated_at": "2026-10-25T01:03:00.076Z",+ "generated_at": "2026-10-25T01:58:36.704Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws","url": "https://three.ws"},- "total": 4193,+ "total": 4194,"complete": false,"full_feed": "/changelog.json","entries": [+ {+ "date": "2026-10-25",+ "type": "update",+ "title": "GET /api/pump-bounties and its stats/detail routes serve last-known-good data instead of a 502",+ "summary": "pump.fun's Cloudflare anti-bot challenge has been rejecting livestream-api.pump.fun's bounty API for hours at a time, which left the bounty list, the aggregate stats, and individual bounty detail pages 502ing for every visitor even though the board itself had not changed. All three routes now go through the same last-known-good cache tier already proven on /api/portal and /api/crypto/bonding: a fresh answer is mirrored into a 24-hour backup, and that backup answers (flagged with an x-pump-stale header) instead of a 502 once the live fetch fails. A true miss, with nothing cached at all, still returns the original pump.fun error unchanged.",+ "link": "/bounties",+ "tags": [+ "fix"+ ]+ },{"date": "2026-10-25","type": "update",@@ -1551,17 +1561,6 @@"feature","docs"]- },- {- "date": "2026-10-12",- "type": "update",- "title": "Animation Studio: trim, loop-blend, and save any generated clip to your library",- "summary": "The Animation Studio's prompt-to-clip flow (type a prompt, generate motion on the self-hosted GPU worker, preview it retargeted onto the loaded avatar) now has an editing and persistence half. The transport grows trim start/end inputs, a loop-blend duration field, and a loop toggle, all recomputed through a non-destructive edit path so the live preview, the GLB export, and the saved clip always agree on the current edit. A Save to library button collects a name and visibility and posts the canonical, pre-retarget clip to the shared clip library, so it plays back correctly on any future rig, not just the avatar it was previewed on. A separate bug that crashed every generated clip's playback the moment it reached the browser (AnimationClip.parse() expected userData as a JSON string, the server was sending an object) is also fixed.",- "link": "/pose",- "tags": [- "feature",- "fix"- ]}]}diff --git a/public/changelog.json b/public/changelog.jsonindex dcf6c97d6..53426ee81 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,11 +1,21 @@{- "generated_at": "2026-10-25T01:03:00.051Z",+ "generated_at": "2026-10-25T01:58:36.680Z","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-10-25",+ "type": "update",+ "title": "GET /api/pump-bounties and its stats/detail routes serve last-known-good data instead of a 502",+ "summary": "pump.fun's Cloudflare anti-bot challenge has been rejecting livestream-api.pump.fun's bounty API for hours at a time, which left the bounty list, the aggregate stats, and individual bounty detail pages 502ing for every visitor even though the board itself had not changed. All three routes now go through the same last-known-good cache tier already proven on /api/portal and /api/crypto/bonding: a fresh answer is mirrored into a 24-hour backup, and that backup answers (flagged with an x-pump-stale header) instead of a 502 once the live fetch fails. A true miss, with nothing cached at all, still returns the original pump.fun error unchanged.",+ "link": "/bounties",+ "tags": [+ "fix"+ ]+ },{"date": "2026-10-25","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex 8953825fd..65872a765 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>GET /api/pump-bounties and its stats/detail routes serve last-known-good data instead of a 502</title>+ <link>https://three.ws/bounties</link>+ <guid isPermaLink="false">2026-10-25:GET /api/pump-bounties and its stats/detail routes serve last-known-good data instead of a 502</guid>+ <pubDate>Sun, 25 Oct 2026 12:00:00 GMT</pubDate>+ <category>fix</category>+ <description>pump.fun's Cloudflare anti-bot challenge has been rejecting livestream-api.pump.fun's bounty API for hours at a time, which left the bounty list, the aggregate stats, and individual bounty detail pages 502ing for every visitor even though the board itself had not changed. All three routes now go through the same last-known-good cache tier already proven on /api/portal and /api/crypto/bonding: a fresh answer is mirrored into a 24-hour backup, and that backup answers (flagged with an x-pump-stale header) instead of a 502 once the live fetch fails. A true miss, with nothing cached at all, still returns the original pump.fun error unchanged.</description>+ </item><item><title>Image-to-3D Forge instances recycle before a VRAM leak crashes a job</title><link>https://three.ws/image-to-3d</link>diff --git a/public/features.json b/public/features.jsonindex 87b2bc58a..41b18ad60 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-10-25T01:03:00.034Z",+ "generated_at": "2026-10-25T01:58:36.663Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/tests/pump-bounties-endpoint.test.js b/tests/pump-bounties-endpoint.test.jsnew file mode 100644index 000000000..016aa3814--- /dev/null+++ b/tests/pump-bounties-endpoint.test.js@@ -0,0 +1,234 @@+// Route-level tests for the three api/pump-bounties* handlers after they moved+// onto cacheWrapLastGood (api/_lib/cache.js). Production 2026-10-24: pump.fun's+// Cloudflare anti-bot challenge rejected livestream-api.pump.fun for hours at a+// time; every one of these routes had no (or, for the list/stats pair, only a+// hand-rolled) last-known-good tier, so a sustained block turned into a 502 for+// every visitor even though the board itself had not changed.+//+// cache.js is mocked with a Map-backed fake that implements cacheWrapLastGood's+// real semantics (api/_lib/cache.js:608-627): serve a fresh hit, otherwise run+// the loader, mirror a success into both the live key and its `:lkg` sibling,+// and if the loader rejects fall back to the `:lkg` mirror if one exists, else+// rethrow. The handlers call cacheWrapLastGood directly, so the fake has to be+// the real thing's behavior, not a plain cacheGet/cacheSet stand-in.++import { describe, it, expect, vi, beforeEach } from 'vitest';++vi.mock('../api/_lib/rate-limit.js', () => ({+ limits: { publicIp: vi.fn(async () => ({ success: true, reset: Date.now() + 1000 })) },+ clientIp: () => '203.0.113.1',+}));++const store = new Map();++async function fakeCacheWrapLastGood(key, _ttlSeconds, fn, opts = {}) {+ const { withMeta = false } = opts;+ const lkgKey = `${key}:lkg`;+ if (store.has(key)) {+ const value = store.get(key);+ return withMeta ? { value, stale: false } : value;+ }+ try {+ const value = await fn();+ store.set(key, value);+ store.set(lkgKey, value);+ return withMeta ? { value, stale: false } : value;+ } catch (err) {+ if (store.has(lkgKey)) {+ const value = store.get(lkgKey);+ return withMeta ? { value, stale: true } : value;+ }+ throw err;+ }+}++vi.mock('../api/_lib/cache.js', () => ({+ cacheWrapLastGood: vi.fn((key, ttlSeconds, fn, opts) => fakeCacheWrapLastGood(key, ttlSeconds, fn, opts)),+}));++const listBounties = vi.fn();+const getBounty = vi.fn();+const getSubmissions = vi.fn();+vi.mock('../api/_lib/pump-go.js', async () => {+ const actual = await vi.importActual('../api/_lib/pump-go.js');+ return { ...actual, listBounties, getBounty, getSubmissions };+});++const { PumpGoError } = await import('../api/_lib/pump-go.js');++function makeReqRes(url) {+ const req = { method: 'GET', url, headers: {} };+ const res = {+ statusCode: 200,+ headers: {},+ body: '',+ setHeader(k, v) {+ this.headers[k.toLowerCase()] = v;+ },+ getHeader(k) {+ return this.headers[k.toLowerCase()];+ },+ end(b) {+ this.body = b ?? '';+ },+ };+ return { req, res };+}++const upstream403 = () => new PumpGoError('pump.fun GO upstream 403', 502, 'pump_go_upstream');++beforeEach(() => {+ store.clear();+ listBounties.mockReset();+ getBounty.mockReset();+ getSubmissions.mockReset();+});++describe('GET /api/pump-bounties', () => {+ it('serves fresh data and populates both the live and last-known-good cache entries', async () => {+ const { default: handler } = await import('../api/pump-bounties.js');+ listBounties.mockResolvedValueOnce({ items: [{ taskId: 't1' }], nextCursor: null });++ const { req, res } = makeReqRes('/api/pump-bounties?limit=30');+ await handler(req, res);++ expect(res.statusCode).toBe(200);+ expect(JSON.parse(res.body).items).toEqual([{ taskId: 't1' }]);+ expect(res.getHeader('x-pump-stale')).toBeUndefined();+ expect(store.has('pumpgo:list:30:_:_')).toBe(true);+ expect(store.has('pumpgo:list:30:_:_:lkg')).toBe(true);+ });++ it('serves the last-known-good list with x-pump-stale instead of a 502', async () => {+ const { default: handler } = await import('../api/pump-bounties.js');+ store.set('pumpgo:list:30:_:_:lkg', { items: [{ taskId: 'old' }], nextCursor: null });+ listBounties.mockRejectedValueOnce(upstream403());++ const { req, res } = makeReqRes('/api/pump-bounties?limit=30');+ await handler(req, res);++ expect(res.statusCode).toBe(200);+ expect(res.getHeader('x-pump-stale')).toBe('1');+ expect(JSON.parse(res.body).items).toEqual([{ taskId: 'old' }]);+ });++ it('propagates the upstream error unchanged on a true miss (no live data, no last-known-good)', async () => {+ const { default: handler } = await import('../api/pump-bounties.js');+ listBounties.mockRejectedValueOnce(upstream403());++ const { req, res } = makeReqRes('/api/pump-bounties?limit=30');+ await handler(req, res);++ expect(res.statusCode).toBe(502);+ expect(res.getHeader('x-pump-stale')).toBeUndefined();+ const body = JSON.parse(res.body);+ expect(body.error).toBe('pump_go_upstream');+ expect(body.error_description).toBe('pump.fun GO upstream 403');+ });+});++describe('GET /api/pump-bounties/stats', () => {+ it('serves fresh totals and populates both cache entries', async () => {+ const { default: handler } = await import('../api/pump-bounties/stats.js');+ listBounties.mockResolvedValueOnce({+ items: [{ reward: { totalUsd: 10 }, counts: { submissions: 2 }, likeCount: 1 }],+ nextCursor: null,+ });++ const { req, res } = makeReqRes('/api/pump-bounties/stats');+ await handler(req, res);++ expect(res.statusCode).toBe(200);+ expect(JSON.parse(res.body).count).toBe(1);+ expect(store.has('pumpgo:stats:v1')).toBe(true);+ expect(store.has('pumpgo:stats:v1:lkg')).toBe(true);+ });++ it('serves the last-known-good totals with x-pump-stale instead of a 502', async () => {+ const { default: handler } = await import('../api/pump-bounties/stats.js');+ store.set('pumpgo:stats:v1:lkg', { count: 3, totalRewardUsd: 30, totalSubmissions: 5, totalLikes: 2, truncated: false, updatedAt: '2026-10-24T00:00:00.000Z' });+ listBounties.mockRejectedValueOnce(upstream403());++ const { req, res } = makeReqRes('/api/pump-bounties/stats');+ await handler(req, res);++ expect(res.statusCode).toBe(200);+ expect(res.getHeader('x-pump-stale')).toBe('1');+ expect(JSON.parse(res.body).count).toBe(3);+ });++ it('propagates the upstream error unchanged on a true miss, even if it fails mid-walk', async () => {+ const { default: handler } = await import('../api/pump-bounties/stats.js');+ listBounties+ .mockResolvedValueOnce({ items: [{ reward: { totalUsd: 1 }, counts: { submissions: 0 }, likeCount: 0 }], nextCursor: 'c2' })+ .mockRejectedValueOnce(upstream403());++ const { req, res } = makeReqRes('/api/pump-bounties/stats');+ await handler(req, res);++ expect(res.statusCode).toBe(502);+ expect(store.has('pumpgo:stats:v1')).toBe(false);+ });+});++describe('GET /api/pump-bounties/:id', () => {+ const id = 'b4a26396-75a7-4bce-a3b5-e3c99aaa73c1';++ it('serves the fresh bounty with its submissions', async () => {+ const { default: handler } = await import('../api/pump-bounties/[id].js');+ getBounty.mockResolvedValueOnce({ taskId: id, title: 'Fresh' });+ getSubmissions.mockResolvedValueOnce({ items: [{ id: 's1' }], nextCursor: null });++ const { req, res } = makeReqRes(`/api/pump-bounties/${id}`);+ await handler(req, res);++ expect(res.statusCode).toBe(200);+ const body = JSON.parse(res.body);+ expect(body.bounty.title).toBe('Fresh');+ expect(body.submissions).toEqual([{ id: 's1' }]);+ expect(res.getHeader('x-pump-stale')).toBeUndefined();+ });++ it('serves the last-known-good bounty with x-pump-stale, and still tries for fresh submissions', async () => {+ const { default: handler } = await import('../api/pump-bounties/[id].js');+ store.set(`pumpgo:task:${id}:lkg`, { taskId: id, title: 'Stale' });+ getBounty.mockRejectedValueOnce(upstream403());+ getSubmissions.mockResolvedValueOnce({ items: [{ id: 's1' }], nextCursor: null });++ const { req, res } = makeReqRes(`/api/pump-bounties/${id}`);+ await handler(req, res);++ expect(res.statusCode).toBe(200);+ expect(res.getHeader('x-pump-stale')).toBe('1');+ const body = JSON.parse(res.body);+ expect(body.bounty.title).toBe('Stale');+ expect(body.submissions).toEqual([{ id: 's1' }]);+ expect(getSubmissions).toHaveBeenCalledWith(id, { limit: 50 });+ });++ it('propagates the upstream error unchanged when nothing is cached', async () => {+ const { default: handler } = await import('../api/pump-bounties/[id].js');+ getBounty.mockRejectedValueOnce(upstream403());+ getSubmissions.mockResolvedValueOnce({ items: [], nextCursor: null });++ const { req, res } = makeReqRes(`/api/pump-bounties/${id}`);+ await handler(req, res);++ expect(res.statusCode).toBe(502);+ expect(res.getHeader('x-pump-stale')).toBeUndefined();+ });++ it('degrades submissions to an empty list on their own failure without touching the bounty', async () => {+ const { default: handler } = await import('../api/pump-bounties/[id].js');+ getBounty.mockResolvedValueOnce({ taskId: id, title: 'Fresh' });+ getSubmissions.mockRejectedValueOnce(new Error('submissions down'));++ const { req, res } = makeReqRes(`/api/pump-bounties/${id}`);+ await handler(req, res);++ expect(res.statusCode).toBe(200);+ const body = JSON.parse(res.body);+ expect(body.bounty.title).toBe('Fresh');+ expect(body.submissions).toEqual([]);+ });+});diff --git a/tests/pump-bounties-handlers.test.js b/tests/pump-bounties-handlers.test.jsdeleted file mode 100644index 92dee5af8..000000000--- a/tests/pump-bounties-handlers.test.js+++ /dev/null@@ -1,115 +0,0 @@-// Handler-shape tests for api/pump-bounties.js and api/pump-bounties/stats.js.-//-// Production 2026-10-24: pump.fun's Cloudflare anti-bot challenge rejected-// livestream-api.pump.fun/bounties/tasks (a "Just a moment..." 403, surfaced-// here as a PumpGoError) for hours at a time. Neither route had a last-known--// good fallback, so every single sample in the 24h log window 502'd even-// though the bounty board itself had not changed. These pin the fix: a-// long-lived cache entry written on every real success, served (marked-// `stale: true`) instead of a 502 when the live fetch fails and the short-// cache has already expired.--import { describe, it, expect, vi, beforeEach } from 'vitest';--vi.mock('../api/_lib/rate-limit.js', () => ({- limits: { publicIp: vi.fn(async () => ({ success: true, reset: Date.now() + 1000 })) },- clientIp: () => '203.0.113.1',-}));--const store = new Map();-vi.mock('../api/_lib/cache.js', () => ({- cacheGet: vi.fn(async (k) => (store.has(k) ? store.get(k) : null)),- cacheSet: vi.fn(async (k, v) => { store.set(k, v); }),-}));--const listBounties = vi.fn();-vi.mock('../api/_lib/pump-go.js', async () => {- const actual = await vi.importActual('../api/_lib/pump-go.js');- return { ...actual, listBounties };-});--function makeReqRes(url) {- const req = { method: 'GET', url, headers: {} };- const res = {- statusCode: 200,- headers: {},- body: '',- setHeader(k, v) { this.headers[k.toLowerCase()] = v; },- getHeader(k) { return this.headers[k.toLowerCase()]; },- end(b) { this.body = b ?? ''; },- };- return { req, res };-}--beforeEach(() => {- store.clear();- listBounties.mockReset();-});--describe('GET /api/pump-bounties: last-known-good fallback', () => {- it('propagates the upstream failure when no last-known-good copy exists', async () => {- const { default: handler } = await import('../api/pump-bounties.js');- const { PumpGoError } = await import('../api/_lib/pump-go.js');- listBounties.mockRejectedValue(new PumpGoError('pump.fun GO upstream 403', 502, 'pump_go_upstream'));-- const { req, res } = makeReqRes('/api/pump-bounties?limit=30');- await handler(req, res);- expect(res.statusCode).toBe(502);- });-- it('serves the last-known-good list, marked stale, instead of a 502', async () => {- const { default: handler } = await import('../api/pump-bounties.js');- const { PumpGoError } = await import('../api/_lib/pump-go.js');-- listBounties.mockResolvedValueOnce({ items: [{ taskId: 't1' }], nextCursor: null });- const warm = makeReqRes('/api/pump-bounties?limit=30');- await handler(warm.req, warm.res);- expect(warm.res.statusCode).toBe(200);- // Expire the short-TTL live cache (the real one lapses after 30s) while- // leaving the long-TTL last-known-good copy in place.- store.delete('pumpgo:list:30:_:_');-- listBounties.mockRejectedValueOnce(new PumpGoError('pump.fun GO upstream 403', 502, 'pump_go_upstream'));- const { req, res } = makeReqRes('/api/pump-bounties?limit=30');- await handler(req, res);- expect(res.statusCode).toBe(200);- const body = JSON.parse(res.body);- expect(body.stale).toBe(true);- expect(body.items).toEqual([{ taskId: 't1' }]);- });-});--describe('GET /api/pump-bounties/stats: last-known-good fallback', () => {- it('propagates the upstream failure when no last-known-good copy exists', async () => {- const { default: handler } = await import('../api/pump-bounties/stats.js');- const { PumpGoError } = await import('../api/_lib/pump-go.js');- listBounties.mockRejectedValue(new PumpGoError('pump.fun GO upstream 403', 502, 'pump_go_upstream'));-- const { req, res } = makeReqRes('/api/pump-bounties/stats');- await handler(req, res);- expect(res.statusCode).toBe(502);- });-- it('serves the last-known-good totals, marked stale, instead of a 502', async () => {- const { default: handler } = await import('../api/pump-bounties/stats.js');- const { PumpGoError } = await import('../api/_lib/pump-go.js');-- listBounties.mockResolvedValueOnce({- items: [{ reward: { totalUsd: 10 }, counts: { submissions: 2 }, likeCount: 1 }],- nextCursor: null,- });- const warm = makeReqRes('/api/pump-bounties/stats');- await handler(warm.req, warm.res);- expect(warm.res.statusCode).toBe(200);- expect(JSON.parse(warm.res.body).count).toBe(1);- store.delete('pumpgo:stats:v1');-- listBounties.mockRejectedValueOnce(new PumpGoError('pump.fun GO upstream 403', 502, 'pump_go_upstream'));- const { req, res } = makeReqRes('/api/pump-bounties/stats');- await handler(req, res);- expect(res.statusCode).toBe(200);- const body = JSON.parse(res.body);- expect(body.stale).toBe(true);- expect(body.count).toBe(1);- });-});