Skip to content

Graph progress callbacks retain completed HTTP responses; failed initial calculators retain watcher listeners #2103

Open

Description

@sensei-woo

Bug report. Two lifecycle leaks that keep memory alive in a long-running dev server. Metro config: Expo's default (@expo/metro-config), pnpm, Node 24.19.0, macOS ARM64.

Versions and upstream status

Measured with Node 24.19.0 on macOS ARM64, Expo 57.0.26, @expo/cli 57.0.27, @expo/metro 56.0.2, Metro 0.84.5. Both lifecycle patterns are still present in Metro main at 5cfcfe2 and the 0.84.6 release (118de9f). The repository now redirects from facebook/metro to react/metro.

A search of issue/PR titles and bodies did not find these exact two paths. PR #1963 fixes a different Bundler-initialization cleanup path. Please split this report if separate issues are preferred.

Observed

A long-lived Expo Metro reached roughly 5 GB and imposed substantial swap pressure. Heap inspection found:

  1. Fifteen registered graphs held their original HTTP progress callbacks. Ten aborted compressed responses retained 336,315,002 bytes of native Brotli state plus 144,978,282 bytes of input buffers. The graph-to-response edge remains relevant even after upgrading compression to its released abort fix.
  2. Sixteen live Graph/DeltaCalculator objects versus fifteen registered graphs. The extra empty calculator remained subscribed to the FileMap and queued 177,085 paths after its initial iOS transform failed. The logged transform error was Cannot find module './configs/hermes-v0' in babel-preset-expo. Its added-path Set table alone used 5 MiB.

The 15-minute idle measurement was flat; these findings establish retained state and lifecycle defects, not a measured continuous idle growth rate.

Retaining paths:

DeltaBundler._deltaCalculators
  -> DeltaCalculator._options.onProgress
  -> callback context.res
  -> ServerResponse.flush
  -> compression stream

FileMap._events.change
  -> DeltaCalculator._handleMultipleFileChanges
  -> calculator._graph / _addedFiles / _modifiedFiles / _deletedFiles

Minimal reproduction

In a temporary Node project, install metro@0.84.5, save the following as repro.cjs, and run node --expose-gc repro.cjs baseline. It creates no Metro server. It uses actual Metro graph traversal with a throwing transform, and retains the actual request processor's progress callback while dropping test references. The response is a minimal EventEmitter-backed HTTP-output fixture; the multipart cases use Metro's real MultipartResponse.

After applying equivalent fixes, run node --expose-gc repro.cjs fixed.

const assert = require("node:assert/strict")
const { EventEmitter } = require("node:events")
const Server = require("metro/private/Server").default
const DeltaBundler = require("metro/private/DeltaBundler").default

async function dependencies() {
  for (const method of ["getDependencies", "buildGraph"]) {
    const watcher = new EventEmitter()
    const bundler = new DeltaBundler(watcher)
    const error = new Error("real transform failed")
    await assert.rejects(bundler[method](["/entry.js"], { transform: async () => {
      throw error
    }, resolve: () => {}, transformOptions: {} }), e => e === error)
    console.log(method + " failure watcher listeners=" + watcher.listenerCount("change"))
    assert.equal(watcher.listenerCount("change"), process.argv[2] !== "baseline" ? 0 : 1)
    bundler.end()
  }
  const watcher = new EventEmitter()
  const bundler = new DeltaBundler(watcher)
  const options = { transform: async () => ({ dependencies: [], output: [], getSource: () => Buffer.alloc(0) }), resolve: () => {}, transformOptions: {} }
  const graph = await bundler.buildGraph(["/entry.js"], options)
  assert.equal(graph.dependencies.size, 1)
  assert.equal(watcher.listenerCount("change"), 1)
  assert.equal((await bundler.getDelta(graph, { reset: false, shallow: false })).modified.size, 0)
  bundler.endGraph(graph)
  assert.equal(watcher.listenerCount("change"), 0)
  assert.equal((await bundler.getDependencies(["/entry.js"], options)).size, 1)
  assert.equal(watcher.listenerCount("change"), 0)
  console.log("successful graph/getDelta/endGraph and one-shot cleanup passed")
}
async function response(event, multipart = false) {
  let retained
  let uncorks = 0
  let reports = 0
  const server = {
    _resolveRelativePath: async () => "/entry.js",
    _config: { transformer: {}, reporter: {} },
    _reporter: {
      update: e => {
        if (e.type === "bundle_transform_progressed") reports++
      },
    },
    _fetchTimings: [],
    _activeFetchCount: 0,
  }
  const processor = Server.prototype._createRequestProcessor.call(server, {
    bundleType: "bundle",
    createStartEntry: () => ({ action_name: "test" }),
    createEndEntry: () => ({}),
    build: async context => {
      retained = context.onProgress
      retained(1, 2)
      if (event !== "settled" && event !== "failed") {
        (context.mres.res || context.mres).emit(event)
      }
      const count = uncorks
      retained(2, 2)
      if (process.argv[2] !== "baseline" && event !== "settled" && event !== "failed") {
        assert.equal(uncorks, count)
      }
      if (event === "failed") throw new Error("real build failed")
      return {}
    },
    finish: () => {},
  })
  let req = { method: "GET", headers: multipart ? { accept: "multipart/mixed" } : {} }
  let res = new EventEmitter()
  res.socket = {
    uncork: () => {
      uncorks++
    },
  }
  res.write = () => {}
  res.writeHead = () => {}
  res.end = () => {}
  const reqRef = new WeakRef(req)
  const resRef = new WeakRef(res)
  await processor.call(server, req, res, { entryFile: "entry.js", customResolverOptions: {}, customTransformOptions: {} }, { buildNumber: 1, bundlePerfLogger: { annotate: () => {}, end: () => {} } })
  assert.ok(reports >= 1)
  req = null
  res = null
  const count = uncorks
  retained(3, 3)
  if (process.argv[2] !== "baseline") assert.equal(uncorks, count)
  let iterations = 20
  while (iterations-- > 0) {
    await new Promise(resolve => setImmediate(resolve))
    global.gc()
  }
  const alive = { req: !!reqRef.deref(), res: !!resRef.deref() }
  console.log(event + (multipart ? " multipart" : " plain") + " retained callback GC=" + JSON.stringify(alive) + " reports=" + reports)
  assert.deepEqual(alive, { req: false, res: process.argv[2] === "baseline" })
  assert.equal(typeof retained, "function")
}
async function main() {
  await dependencies()
  for (const multipart of [false, true]) {
    for (const event of ["finish", "close", "settled", "failed"]) {
      await response(event, multipart)
    }
  }
}
main().catch(error => {
  console.error(error)
  process.exitCode = 1
})

Expected versus actual

  • Expected: rejected initial getDependencies and buildGraph traversals return watcher listener counts to zero. Actual: one change listener remains subscribed for each failed attempt.
  • Expected: cached progress callbacks do not keep completed request/response objects alive. Actual: the response remains reachable after finish, close, success, and failure, for plain and multipart cases.
  • Successful graphs must still support updates and remain subscribed until endGraph.

Our dependency patch changes all eight response cases to collected request/response objects and both failure cases to zero watcher listeners; successful graph/update/endGraph behavior remains intact.

Suggested fixes

  • Server.js: put the graph-retained callback in a separate lexical context holding only a nullable request delegate. Clear the delegate on response finish/close and when the build settles. A wrapper created in the original request scope can still retain shared request context. Subsequent graph work must not emit request progress to an old response.
  • DeltaBundler.js: guarantee calculator disposal in one-shot getDependencies via try/finally; dispose on buildGraph initial traversal rejection before rethrowing. Preserve successful graph registration and normal endGraph ownership.

No dominator retained sizes were calculated; byte counts above are sums of distinct native self-size nodes along verified strong root paths.

Activity

  1. aliassar commented on Nov 2, 2026

    @aliassar

    Can I work on this?

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

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions