Skip to content

Fix memory leak in the task identifier cache - #660

Open
Devpaul-01 wants to merge 5 commits into
graphile:mainfrom
Devpaul-01:fix/task-identifier-cache-leak
Open

Devpaul-01 wants to merge 5 commits into
graphile:mainfrom
Devpaul-01:fix/task-identifier-cache-leak

Conversation

@Devpaul-01

Copy link
Copy Markdown

Fixes #658.

Problem

getTaskDetails caches its result per options object in a module-level Map keyed by CompiledSharedOptions. A Map holds its keys strongly, so every run() leaves its options object (and everything that references) reachable for the life of the process, even after the runner has stopped. Processes that start and stop runners repeatedly grow without bound.

Fix

Use a WeakMap so the cache entry is released together with its options. Behaviour for live options is unchanged. The diagnosis and the suggested change come from the issue report.

Verification

  • Reproduced with the script from the issue (start a runner, stop it, repeat, force a GC between samples). On unmodified main the heap grew by about 12 KB per run() across 800 runs. With this change the first block of runs still warms up (about 8.5 KB per run), then growth drops below 1 KB per run and the heap plateaus at about 10.8 MB. These numbers are from my machine (Node 22, Postgres 16) and are only indicative.
  • Added __tests__/taskIdentifiers.test.ts, which needs no database:
    • the cache still avoids repeat queries for the same options object;
    • options that are no longer referenced get garbage collected (uses a FinalizationRegistry and forces a GC). This test fails on main and passes with the fix; I ran it 5 times with the fix and it passed each time.
  • Full suite on Postgres 16: 24 suites, 109 tests pass. prettier, eslint, tsc and depcheck are clean.
  • Added a patch changeset.

I have only run this against Postgres 16 locally, not other versions.

@benjie benjie left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks!

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

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

2 participants