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 <noreply@anthropic.com>
This commit is contained in:
CatoandClaude authored and GitHub committed 2026-11-28 21:31:52 +01:00
1 parent 8338520d89
commit b46062cd37
2 files changed
+75 -3

No files matched your search

+16 -3
View File
@@ -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<T>(kind: SnapshotKind, key: string): Promise<Snapshot<T>
}
}
/**
* 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<T>(kind: SnapshotKind, key: string, data: T): Promise<boolean> {
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.
+59
View File
@@ -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;
}
});