Memory leak: `taskIdentifiers` cache keeps every `run()`'s options for the life of the process

Aperta Adatta ai principianti
#658 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

Valutazione

Difficoltà
2/5
Tempo stimato
1-3 ore
Idoneità per principianti
88/100
Tipo di issue
Bug
Chiarezza
Specificata chiaramente
Stato di attività
Attiva
Stack tecnologico
node.js, postgresql, typescript

Direzione di ricerca

Leggi src/taskIdentifiers.ts e segui come viene consultato cacheByOptions quando le opzioni vengono compilate per ogni run(). L’issue indica come soluzione proposta la sostituzione di Map con WeakMap nella cache a livello di modulo; controlla i test esistenti per gli identificatori dei task e aggiungi o esegui una verifica di regressione che accerti che le esecuzioni ripetute non trattengano le proprie opzioni. Il lavoro è completato quando la cache non causa più una crescita dell’heap durante le esecuzioni ripetute.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

Version: graphile-worker 0.18.0 (the same code is on main), Node 24.22.3, PostgreSQL 16.14

What happens

A process that calls run() and runner.stop() repeatedly never frees what each run used. The heap grows by a fixed amount a run until the process runs out of memory.

We start a runner, let it drain the queue and stop it, on a timer, in a process that stays up. With a larger task list and a crontab we measured about 38 KB a run, and the process reached its heap limit (about 256 MB) after several thousand runs.

A process that calls run() once is not affected.

Cause

src/taskIdentifiers.ts keys a module-level Map on the compiled options and never deletes an entry:

const cacheByOptions = new Map<CompiledSharedOptions, Cache>();

Each run() compiles a new options object, so each adds an entry, which keeps the options and everything reachable from them.

Reproduction

// node --expose-gc repro.mjs   (needs DATABASE_URL)
import pg from 'pg';
import { Logger, run } from 'graphile-worker';

const pgPool = new pg.Pool({ connectionString: process.env.DATABASE_URL });
pgPool.on('error', () => {});
pgPool.on('connect', (c) => c.on('error', () => {}));
const logger = new Logger(() => () => {});
const heapKB = () => (gc(), gc(), process.memoryUsage().heapUsed / 1024);

async function once() {
  const runner = await run({
    pgPool, logger, noHandleSignals: true, taskList: { noop: async () => {} },
  });
  await new Promise((r) => setTimeout(r, 20)); // let it poll
  await runner.stop();
  await runner.promise;
}

for (let i = 0; i < 100; i++) await once();
let last = heapKB();
for (let block = 1; block <= 6; block++) {
  for (let i = 0; i < 200; i++) await once();
  const now = heapKB();
  console.log(`${block * 200} runs: ${(now / 1024).toFixed(1)} MB (${((now - last) / 200).toFixed(1)} KB a run)`);
  last = now;
}
await pgPool.end();

Heap after garbage collection, and growth a run over the last 200:

Runs 0.18.0 with WeakMap
200 12.4 MB (12.5 KB) 10.8 MB (4.5 KB)
400 14.6 MB (11.4 KB) 10.9 MB (0.4 KB)
600 17.0 MB (12.3 KB) 11.1 MB (1.2 KB)
800 19.2 MB (11.3 KB) 11.1 MB (0.0 KB)
1000 21.4 MB (11.3 KB) 11.1 MB (0.1 KB)
1200 23.6 MB (11.1 KB) 11.2 MB (0.1 KB)

Suggested fix

-const cacheByOptions = new Map<CompiledSharedOptions, Cache>();
+const cacheByOptions = new WeakMap<CompiledSharedOptions, Cache>();

The keys are always objects and the map is only read with get and written with set, so nothing else changes. We run 0.18.0 with this patch.

Related: #638 and #637 are about the same cache keeping a rejected lookup. This is a separate problem.

Lingua principale
TypeScript
Stelle
2.5k
Fork
134
Merge medio
16h 24m
PR unite (30g)
3

Preparare l'ambiente

  • Include un Dockerfile o un file Docker Compose
  • Nessun modello di pull request
  • Nessuna guida per i contributori

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di graphile/worker

Tutte le issue di graphile/worker

Issue simili

Altre issue su TypeScript

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.