fix(sandbox): release one-shot timeout ids after they run (#96161)
### What? Fire-and-forget `setTimeout` calls in the Edge runtime sandbox (e.g. from middleware) are tracked forever by Next.js's sandbox `TimeoutsManager`, even after the timeout has run. In a long-lived standalone/self-hosted server this makes tracked timeout resources grow monotonically, producing step-like heap growth and eventual OOM. ### Why? `TimeoutsManager.add()` pushes each timeout id into a `resources` array. When a one-shot timeout fires naturally, `webSetTimeoutPolyfill`'s `finally` clears the underlying Node timer (the workaround for nodejs/node#53335) but never removes the id from the manager. The id is dropped only if user code calls `clearTimeout(id)` or the whole module context is torn down (`clearModuleContext`, introduced in #57235). The natural-completion path — module context stays alive, timeout finishes on its own — was missing, so ids accumulate for the lifetime of the process. ### How? - `TimeoutsManager.create()` now wraps the callback so the timeout untracks its own id once it has run. The Node-timer workaround and the `this`/args binding in `webSetTimeoutPolyfill` are preserved. - Refactored the base `ResourceManager.remove()` into `untrack()` (stop tracking) + `destroy()`, so natural completion can release tracking without a redundant `clearTimeout`. - Intervals are intentionally unchanged: they fire repeatedly and must remain tracked until `clearInterval`/`removeAll`. - Added a unit test covering natural release, no monotonic growth across repeated rounds, the `clearTimeout`/`remove` path, callback `this`/args binding, and that intervals stay tracked. Verified: `pnpm --filter=next types` clean, prettier/eslint clean, and the new unit test fails on the current behavior (reverting only the release logic) and passes with the fix. Fixes #95094 --- **Update:** this branch now lands @berry95's commit from #94794 first (`Set`-based resource tracking, which also makes `untrack`/`remove` O(1)), with the fix rebased on top. --------- Co-authored-by:Berry Kim <wlsdud40@gmail.com> Co-authored-by:
Dan Abramov <dan.abramov@gmail.com>
Showing
Please
register
or
sign in
to comment