From b46062cd37cbfe97657b46dc486c0ea35441a4e9 Mon Sep 17 00:00:00 2001 From: Cato <41178744+catomean@users.noreply.github.com> Date: Sat, 28 Nov 2026 21:31:52 +0100 Subject: [PATCH] fix(market-data): keep EDGAR snapshots in memory only when the database write fails (#415) writeSnapshot put every fundamentals and holders snapshot into a module-level Map before writing it to research_market_snapshots, and never dropped it. Every company the nightly /api/cron/prices facts run refreshed stayed in the app heap until the next restart: about 0.1 MB a company, measured against live SEC data, across 506 tracked SEC filers. The app unit is throttled at MemoryHigh=768M (killed at 1G), and the substrata crons have failed starting with the 22:07 UTC prices run on 2026-11-20 and 2026-11-21. The module's own comment says the in-process copy stands in where there is no database. It now does only that: set when the row cannot be written, dropped when it is. Co-authored-by: Claude --- lib/market-data/snapshots.ts | 19 +++++++++-- test/snapshots-memory.test.ts | 59 +++++++++++++++++++++++++++++++++++ 2 files changed, 75 insertions(+), 3 deletions(-) create mode 100644 test/snapshots-memory.test.ts diff --git a/lib/market-data/snapshots.ts b/lib/market-data/snapshots.ts index c010e7d..b43527c 100644 --- a/lib/market-data/snapshots.ts +++ b/lib/market-data/snapshots.ts @@ -2,8 +2,8 @@ * Computed EDGAR reads (fundamentals, holders) kept per CIK, so a question does * not re-read four megabytes of company facts. The database row * (research_market_snapshots) is the shared copy the cron refreshes; an - * in-process copy stands in where there is no database (a fresh deployment, - * a test). Every figure inside a snapshot carries its own filing and date. + * in-process copy stands in only where the row cannot be written (no + * database, a fresh deployment, a test). Every figure inside a snapshot carries its own filing and date. */ import { database } from '@/lib/db'; @@ -29,20 +29,33 @@ async function readRow(kind: SnapshotKind, key: string): Promise } } +/** + * The database row is the copy; the in-process one is kept only when the row + * could not be written. Keeping both held every snapshot the nightly run + * refreshed (about 0.1 MB a company, 506 SEC filers) in the app's heap for + * good, inside a unit throttled at 768 MB. + */ export async function writeSnapshot(kind: SnapshotKind, key: string, data: T): Promise { - memory.set(`${kind}:${key}`, { data, fetchedAt: new Date().toISOString() }); + const id = `${kind}:${key}`; try { await database().query( `INSERT INTO research_market_snapshots (kind, key, data) VALUES ($1, $2, $3) ON CONFLICT (kind, key) DO UPDATE SET data = EXCLUDED.data, fetched_at = now()`, [kind, key, JSON.stringify(data)], ); + memory.delete(id); return true; } catch { + memory.set(id, { data, fetchedAt: new Date().toISOString() }); return false; } } +/** How many snapshots this process holds itself (tests). */ +export function snapshotsInMemory(): number { + return memory.size; +} + /** * The snapshot if younger than `maxAgeMs`, else `compute()` stored and * returned. A failed compute falls back to an older snapshot, if any. diff --git a/test/snapshots-memory.test.ts b/test/snapshots-memory.test.ts new file mode 100644 index 0000000..c915fcb --- /dev/null +++ b/test/snapshots-memory.test.ts @@ -0,0 +1,59 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { + cachedSnapshot, + resetSnapshots, + snapshotsInMemory, + writeSnapshot, +} from '../lib/market-data/snapshots'; + +test('without a database the process keeps the snapshot itself, so a read still works', async () => { + const saved = process.env.DATABASE_URL; + delete process.env.DATABASE_URL; + resetSnapshots(); + try { + assert.equal(await writeSnapshot('fundamentals', '1', { n: 1 }), false); + assert.equal(snapshotsInMemory(), 1); + let computed = 0; + const snap = await cachedSnapshot('fundamentals', '1', 60_000, async () => { + computed += 1; + return { n: 2 }; + }); + assert.deepEqual(snap?.data, { n: 1 }); + assert.equal(computed, 0, 'a fresh in-process copy is used, not recomputed'); + } finally { + resetSnapshots(); + if (saved !== undefined) process.env.DATABASE_URL = saved; + } +}); + +test('a snapshot written to the database is not also held in the app heap', async () => { + const saved = process.env.DATABASE_URL; + const g = globalThis as typeof globalThis & { substrataPool?: unknown }; + const before = g.substrataPool; + const queries: string[] = []; + process.env.DATABASE_URL = 'postgres://stub'; + g.substrataPool = { + query: async (sql: string) => { + queries.push(sql); + return { rows: [] }; + }, + }; + resetSnapshots(); + try { + // An earlier failed write left a copy behind; a successful one drops it. + delete process.env.DATABASE_URL; + await writeSnapshot('holders', '2', { a: 1 }); + process.env.DATABASE_URL = 'postgres://stub'; + assert.equal(snapshotsInMemory(), 1); + assert.equal(await writeSnapshot('holders', '2', { a: 2 }), true); + assert.equal(await writeSnapshot('fundamentals', '3', { b: 1 }), true); + assert.equal(snapshotsInMemory(), 0); + assert.equal(queries.filter((q) => /INSERT INTO research_market_snapshots/.test(q)).length, 2); + } finally { + resetSnapshots(); + g.substrataPool = before; + if (saved === undefined) delete process.env.DATABASE_URL; + else process.env.DATABASE_URL = saved; + } +});