Skip to content

timers: unenroll() on a queued Immediate corrupts immediateInfo bookkeeping — crash in processImmediate skip path, stranded immediate_idle_handle, orphaned immediate queue #67981

Not planned

Description

@john-stalvern

Version

v22.23.5 (analysis against v22.23.5 sources: lib/timers.js, lib/internal/timers.js, src/env.cc, src/env.h)

Platform

Linux x64 (6.3.5-2-cachyos), reproduced on 8-core host; also reproduced in jest worker processes (see "In the wild").

What steps will reproduce the bug?

Repro 1 — crash: a documented API call makes processImmediate throw from node internals.

// node repro1.js   (no flags)
const timers = require('timers');

const h = setImmediate(() => console.log('h'));
timers.unenroll(h); // documented (deprecated) API — called on a QUEUED Immediate

setImmediate(() => console.log('second'));

setTimeout(() => console.log('done'), 100);

Actual:

node:internal/timers:460
        outstandingQueue.head = immediate = prevImmediate._idleNext;
                                                          ^
TypeError: Cannot read properties of undefined (reading '_idleNext')
    at process.processImmediate (node:internal/timers:460:59)

Expected: h is skipped (it was unenrolled) and second/done run; process exits 0.

Repro 2 — state corruption: stranded immediate_idle_handle, orphaned queue, unrecoverable spin.

When the unenrolled node is not the first node of the next drain (e.g. one more setImmediate is queued first), no crash occurs and the process instead corrupts immediateInfo bookkeeping and hangs: the process never exits (the immediate_idle_handle stays uv_idle_started, the loop polls at 0 timeout forever), later setImmediate callbacks never run, and even calling the live processImmediate closure by hand cannot reach them. Instrumented version (needs --expose-internals only to READ state; the trigger itself is plain API):

// node --expose-internals repro2.js
const req = require('module').createRequire(__filename);
const it = req('internal/timers');

process.on('uncaughtException', () => {}); // survive the Repro-1 crash path

const refedAliveInChain = () => {
  let n = it.immediateQueue.head, c = 0;
  while (n && c < 1000) { if (!n._destroyed && n.hasRef()) c++; n = n._idleNext; }
  return c;
};
const immRes = () => process.getActiveResourcesInfo().filter((r) => r === 'Immediate').length;

const h = setImmediate(() => {});
require('timers').unenroll(h);
let laterRan = false;
setImmediate(() => { laterRan = true; });

setTimeout(() => {
  console.log('immRes =', immRes(), '(refed immediates counted)');
  console.log('refedAliveInChain =', refedAliveInChain(), '(refed nodes actually queued)');
  console.log('laterRan =', laterRan);
  const cb = it.getTimerCallbacks(() => {});
  cb.processImmediate(); // manual drain bypassing CheckImmediate's gate
  console.log('after manual drain: immRes =', immRes(), 'laterRan =', laterRan);
}, 100);

Actual (verbatim):

immRes = 2 (refed immediates counted)
refedAliveInChain = 0 (refed nodes actually queued)
laterRan = false
after manual drain: immRes = 2 laterRan = false

Expected: immRes === refedAliveInChain at all times, laterRan = true, process exits.

How often does it reproduce?

Deterministic (every run of both repros).

What is the bug?

Accounting against v22.23.5 sources — unenroll() (lib/timers.js:75-108) is timer-specific but is not guarded against Immediate objects, and its effects on an Immediate are wrong in three independent ways:

  1. Lost kRefCount decrement: unenroll never touches immediateInfo[kRefCount] (only clearImmediate and the drain do). The destroyed node's ref is leaked, so immediate_idle_handle (src/env.cc:1596-1603) stays uv_idle_started forever — the loop spins at 0-timeout polling even though the immediate queue can no longer produce work.
  2. Spurious timer-side decRefCount(): unenroll decrements timeoutInfo[0] for the Immediate (lib/timers.js:93-104, item[kRefed] is the same symbol on both classes), corrupting the ref-count that Environment::RunTimers' return-value contract (src/env.cc:1553-1561, return timeoutInfo[0] > 0 ? nextExpiry : -nextExpiry) uses to arm/unref the timer handle — pending timers can then never fire.
  3. ImmediateList head/tail corruption: unenroll splices via linkedlist.remove (lib/timers.js:86), which does not update immediateQueue.head/.tail (lib/internal/timers.js:289-305 is the only path that does). The stale head/tail re-anchors the next setImmediate append to a dead node, orphaning whatever is queued (Repro 2's laterRan = false).

And the crash path of Repro 1: the drain's skip branch (lib/internal/timers.js:459-462) assumes prevImmediate exists (prevImmediate._idleNext), which is false for a destroyed first node — the invariant "a destroyed node cannot be in the queue" is only maintained by clearImmediate, which unenroll bypasses.

A secondary observation from the same class: Environment::CheckImmediate (src/env.cc:1571-1593) gates the drain on immediate_info()->count() == 0. Since count is an AliasedUint32Array field (src/env.h:451) written from JS, any lost increment / double decrement (e.g. from the paths above) closes the gate while refed Immediates are queued — the loop stays alive on the stranded idle handle and no immediate ever drains again.

What do you expect to happen instead?

unenroll(x) on an Immediate should either be a no-op (as clearTimeout(x) already is, via the timer?._onTimeout guard) or behave exactly as clearImmediate(x). Internally, unenroll could guard with if (!('_onTimeout' in item)) return; (or route Immediate instances to clearImmediate).

In the wild

This state is what wedges long-lived jest workers (jest 29 / node v22.23.5, heavy teardown-time immediate churn): the wedged worker's captured state is a queued refed Immediate that the check phase never drains (or an orphaned queue with getActiveResourcesInfo() still reporting the leaked Immediate ref), an un-armed expired timer handle, and an empty JS stack spinning at 80-99% CPU. internal/timers.js's processImmediate/processTimers drain loops also mutate immediateQueue/timerListMap bookkeeping from microtasks that run inside the walk (runNextTicks() at lib/internal/timers.js:452/518), which is where our in-tree tracing loses the counter balance (exact interleaving not yet minimized). Our evidence corpus (pre-reap inspector captures of wedged workers, --report-on-signal libuv reports, async_hooks lifecycle traces) is committed on the branch wt/t_bdb1842e of a private repo; the two repros above are the extractable, self-contained part.

Activity

  1. Renegade334 commented on Dec 3, 2026

    @Renegade334
    Member

    This is not part of the public documented API, and v22.x is soon to be EOL. We can let this lie.

  2. added
    wontfix
    timers
    v22.x
    on Dec 3, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    timersv22.xwontfix

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions