Reports

#5553 · Watcher shutdown and plain-root scope

BugHighEffort: Mediumhost · perf · partial-reproGitHub issue

October 15, 2026 · Trusted main commit 05771e3c82404328854468f0fff7f0f8203e2076

Verdict: PARTIALLY REPRODUCED · Root-cause confidence: medium overall; high for the two bounded findings below.

1. TL;DR

A real native watcher remains alive after its IPC connection is closed if completion of its unsubscribe operation is deliberately withheld. The child waits for cleanup before exiting and has no shutdown deadline. A separate native-filesystem experiment confirms that a plain project root reports changes inside output ignored by a nested repository, whereas an explicit ignore at an outer Git root excludes that output. Neither experiment recreates the reported daemon heap exhaustion or establishes that recycling leaks parent memory; recycling already sends SIGKILL on this trusted base. These are partial findings, not a reproduction of the full incident.

2. Claims vs Findings

Claim being assessedFindingEvidence and limits
Plain workspace roots cover nested ignored build output.VerifiedThe real public workspace watcher reports a write under a nested Git repository's ignored output directory. The same write is excluded after adding an ignore at an outer Git root.
Child shutdown can remain blocked after the IPC parent is lost.Verified under controlled faultThe real child entry and handler run in a forked process with an active native watcher. With native unsubscribe completion withheld, the child remains alive after 2 seconds; the healthy control exits with code 0. This is an explicit IPC disconnect, not a daemon crash or PPID-1 observation.
A slow initial subscribe necessarily causes unsubscribe timeout and recycling.Not established; simple explanation contradicted by codeIf an ID has no ready subscription, the child records its cancellation and immediately acknowledges unsubscribe. A slow initial crawl alone does not prove the reported timeout. Event-loop or established-native-cleanup stalls remain possible.
Timed-out recycling fails to kill the old child.Refuted as a missing implementation on this baseThe timeout calls killAndRespawn, which calls channel.kill; the fork channel sends SIGKILL. Whether a particular kernel delays process death was not measured.
Recycling causes daemon heap OOM; prior child retains gigabytes.UnverifiedNo million-entry corpus, daemon heap exhaustion, heap snapshots, RSS trend, native hang, or 35-minute churn run was collected. The experiments cannot assign the parent's retained heap to any code path.

3. Environment

4. Minimal Reproduction

Use a disposable Linux checkout with existing pnpm prerequisites. Save the two complete script blocks below as disconnect.mjs and scope.mjs in a directory named bb-5553-evidence beside the clone directory. The scripts are newly authored from trusted repository code; no issue-provided command, script, patch, or branch is executed. Public report policy requires inline evidence rather than downloadable script or log files; raw artifacts remain in local scratch storage.

git clone https://github.com/get-bb/bb.git bb-5553-a
cd bb-5553-a
git checkout --detach 05771e3c82404328854468f0fff7f0f8203e2076
pnpm install --frozen-lockfile --prefer-offline
pnpm exec turbo run build
node ../bb-5553-evidence/disconnect.mjs .
pnpm exec tsx ../bb-5553-evidence/scope.mjs .
pnpm exec turbo run test --filter=@bb/host-watcher
  1. Install and build the recorded trusted commit. Both full builds succeeded (66 tasks).
  2. Run disconnect.mjs. It bundles the trusted child entry with existing esbuild, forks it, waits for ready and subscribed, then disconnects IPC. The healthy control uses the unchanged real backend. The stalled variant opens a real native subscription, but deliberately replaces unsubscribe completion with an unresolved promise. Expected safety invariant: the child eventually terminates despite stalled cleanup. Actual: it is still alive at the 2-second observation deadline. The harness SIGKILLs it and awaits exit in finally, so no orphan is left behind. Exit 1 is the intended failing safety assertion, not a build failure.
  3. Run scope.mjs through the installed tsx loader. It writes to a nested repository's ignored output, first under a plain root and then under an outer Git root that explicitly ignores the nested tree. Exit 0 confirms both observed behaviors. The one-second event observation window is a bounded experiment, not a stress or performance measurement.

disconnect.mjs

import assert from "node:assert/strict";
import { fork } from "node:child_process";
import { once } from "node:events";
import fs from "node:fs/promises";
import { createRequire } from "node:module";
import os from "node:os";
import path from "node:path";

const checkout = path.resolve(process.argv[2] ?? ".");
const requireFromCheckout = createRequire(path.join(checkout, "package.json"));
const { build } = requireFromCheckout("esbuild");
const packageDir = path.join(checkout, "packages/host-watcher");
const bundleDir = await fs.mkdtemp(path.join(packageDir, "test/issue-5553-"));
const watchDir = await fs.mkdtemp(path.join(os.tmpdir(), "watch-disconnect-"));
const deadlineMs = 2000;

function receive(child, kind) {
  return new Promise((resolve, reject) => {
    const deadline = setTimeout(() => {
      child.off("message", onMessage);
      reject(new Error(`Timed out waiting for ${kind}`));
    }, 10000);
    function onMessage(message) {
      if (message.kind === kind) {
        clearTimeout(deadline);
        child.off("message", onMessage);
        resolve(message);
      }
    }
    child.on("message", onMessage);
  });
}

async function run(stalled) {
  const output = path.join(bundleDir, stalled ? "stalled.mjs" : "healthy.mjs");
  await build({
    entryPoints: [path.join(packageDir, "src/parcel-subprocess/parcel-child-entry.ts")],
    outfile: output,
    bundle: true,
    platform: "node",
    format: "esm",
    packages: "external",
    plugins: stalled ? [{
      name: "stall-native-unsubscribe",
      setup(builder) {
        builder.onResolve({ filter: /real-parcel-watcher\.js$/ }, () => ({
          path: "fault-backend",
          namespace: "fault",
        }));
        builder.onLoad({ filter: /.*/, namespace: "fault" }, () => ({
          resolveDir: path.join(packageDir, "src"),
          contents: `
            import native from "@parcel/watcher";
            export const realParcelWatcher = {
              async subscribe(...args) {
                await native.subscribe(...args);
                return {
                  unsubscribe() {
                    process.stderr.write("native cleanup entered; completion withheld\\n");
                    return new Promise(() => {});
                  }
                };
              }
            };
          `,
        }));
      },
    }] : [],
  });
  const child = fork(output, [], { execArgv: [], stdio: ["ignore", "ignore", "pipe", "ipc"] });
  let stderr = "";
  child.stderr.on("data", (data) => { stderr += data; });
  const exit = once(child, "exit");
  let deadline;
  try {
    await receive(child, "ready");
    const subscribed = receive(child, "subscribed");
    child.send({ kind: "subscribe", id: "probe", dir: watchDir });
    await subscribed;
    child.disconnect();
    const outcome = await Promise.race([
      exit.then(([code, signal]) => ({ exited: true, code, signal })),
      new Promise((resolve) => { deadline = setTimeout(() => resolve({ exited: false }), deadlineMs); }),
    ]);
    console.log(`${stalled ? "stalled" : "healthy"}: ${JSON.stringify(outcome)}`);
    if (stderr.trim()) console.log(stderr.trim());
    return outcome;
  } finally {
    clearTimeout(deadline);
    if (child.exitCode === null && child.signalCode === null) {
      child.kill("SIGKILL");
    }
    await exit;
  }
}

try {
  const healthy = await run(false);
  assert.equal(healthy.exited, true, "healthy native watcher must exit after IPC disconnect");
  const stalled = await run(true);
  assert.equal(stalled.exited, true, "watcher must exit after IPC disconnect even when unsubscribe stalls");
} finally {
  await fs.rm(bundleDir, { recursive: true, force: true });
  await fs.rm(watchDir, { recursive: true, force: true });
}

scope.mjs

import assert from "node:assert/strict";
import { execFileSync } from "node:child_process";
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { pathToFileURL } from "node:url";

const checkout = path.resolve(process.argv[2] ?? ".");
const { watchWorkspaceStatus } = await import(pathToFileURL(path.join(checkout, "packages/host-watcher/src/watch-status.ts")));
const root = await fs.mkdtemp(path.join(os.tmpdir(), "watch-scope-"));
const nested = path.join(root, "nested");
const output = path.join(nested, "build-output");

async function measure() {
  const changedPaths = new Set();
  let ready;
  let reject;
  const started = new Promise((resolve, fail) => { ready = resolve; reject = fail; });
  const stop = watchWorkspaceStatus(root, {
    onChange(event) { for (const changedPath of event.changedPaths) changedPaths.add(changedPath); },
    onReady: ready,
    onWatchError: reject,
  });
  let timeout;
  try {
    await Promise.race([started, new Promise((_, fail) => {
      timeout = setTimeout(() => fail(new Error("watch setup timed out")), 10000);
    })]);
    await fs.writeFile(path.join(output, "part-0/artifact.txt"), `${Date.now()}\n`);
    await new Promise((resolve) => setTimeout(resolve, 1000));
    return changedPaths.has(path.join(output, "part-0/artifact.txt"));
  } finally {
    clearTimeout(timeout);
    await stop();
  }
}

try {
  await fs.mkdir(output, { recursive: true });
  execFileSync("git", ["init", "-q", nested]);
  await fs.writeFile(path.join(nested, ".gitignore"), "/build-output/\n");
  for (let index = 0; index < 200; index += 1) {
    const directory = path.join(output, `part-${index}`);
    await fs.mkdir(directory);
    await fs.writeFile(path.join(directory, "artifact.txt"), "sample\n");
  }
  const plainRootReportsNestedIgnoredOutput = await measure();
  execFileSync("git", ["init", "-q", root]);
  await fs.writeFile(path.join(root, ".gitignore"), "/nested/\n");
  const gitRootReportsOuterIgnoredOutput = await measure();
  console.log(JSON.stringify({ directoriesInNestedIgnoredOutput: 200, plainRootReportsNestedIgnoredOutput, gitRootReportsOuterIgnoredOutput }));
  assert.equal(plainRootReportsNestedIgnoredOutput, true, "plain root reports output ignored by the nested repository");
  assert.equal(gitRootReportsOuterIgnoredOutput, false, "outer git ignore prunes the nested tree");
} finally {
  await fs.rm(root, { recursive: true, force: true });
}

Observed Output

healthy: {"exited":true,"code":0,"signal":null}
stalled: {"exited":false}
native cleanup entered; completion withheld
AssertionError [ERR_ASSERTION]: watcher must exit after IPC disconnect even when unsubscribe stalls

{"directoriesInNestedIgnoredOutput":200,"plainRootReportsNestedIgnoredOutput":true,"gitRootReportsOuterIgnoredOutput":false}

5. Root Cause

Shutdown: the disconnect listener calls handler.dispose().finally(() => process.exit(0)). dispose awaits Promise.all of active subscription unsubscribes. With a native subscription still holding an event-loop handle, a never-settling unsubscribe prevents the explicit exit. There is no independent deadline in that path. The controlled fault proves this lifecycle vulnerability, not the natural occurrence of the native fault.

process.on("disconnect", () => {
  void handler.dispose().finally(() => process.exit(0));
});

Scope: the built-in ignored globs do not include arbitrary nested output. plain and Git ignore assembly adds Git-discovered ignores only for a Git root. workspace startup selects the plain path when the workspace itself lacks .git. It does not recursively discover each nested repository's ignore policy. The scope experiment observes the consequence with the native backend.

Important counterevidence: unsubscribe before subscription readiness acknowledges cancelled pending IDs immediately. the unsubscribe timeout calls killAndRespawn, and the real channel kill already sends SIGKILL. It would be incorrect to claim that adding a missing SIGKILL explains or fixes this incident on main.

Unresolved deeper cause: allocation retention in the daemon, natural native unsubscribe stalls, and the claimed relation between recycling and heap exhaustion require a representative workload and heap/process telemetry. IPC event batches are a candidate to measure, not an established leak.

6. Proposed Fix and PR Decision

Bound child shutdown after IPC disconnect independently of async cleanup, while retaining fast graceful cleanup. Validate a separate targeted patch against both healthy and deliberately stalled unsubscribe, including the case where unsubscribe was already in flight. That is a narrower lifecycle hardening change, not a demonstrated daemon-OOM fix.

Before changing plain-root traversal, specify which nested files the product must observe. Automatically pruning nested repositories or adding ignore configuration changes coverage and requires a product decision. Collect a parent heap profile and a native-hang reproduction before choosing memory/back-pressure changes.

No fix branch or PR was created: the reported OOM/recycling failure was not reproduced on trusted main. Only scope behavior and a fault-injected shutdown gap were established, so a verified root-cause OOM fix cannot satisfy the simple-fix gate. No open PR linked to this issue was found in the issue timeline or repository search during this run.

7. Verification

The same agent repeated both final artifacts in a second fresh detached checkout at exactly 05771e3c82404328854468f0fff7f0f8203e2076. This is a second clean run, not an independent-agent verification. It received its own frozen install and full Turbo build, and both scripts allocated new temporary directories and child processes; neither used network ports.

checkout: verify (clean at recorded base)
pnpm install --frozen-lockfile --prefer-offline : exit 0
pnpm exec turbo run build : exit 0, 66 successful tasks
node EVIDENCE/disconnect.mjs . : exit 1, expected failing safety assertion
pnpm exec tsx EVIDENCE/scope.mjs . : exit 0, plain=true, outer-git=false
git status --short : empty

Both final outputs matched the first run. The first checkout's existing watcher suite also passed through Turbo: 7 test files passed, 1 skipped; 59 tests passed, 1 skipped. No production or repository test files were changed.

Report correction: an initial attempt to use /proc/self/fdinfo inotify counts returned zero in this gVisor environment and was unsuitable evidence. The final experiment observes real delivered file events instead; no watch-count or RSS claim is made. The final event-based artifact passed in both clean checkouts.

8. Related Issues

Repository searches surfaced #3362 (native binary packaging) and #3579 (process lifecycle). This run did not investigate or reproduce them. Neither a native packaging failure nor accumulating SIGKILL-resistant children was observed.

9. Appendix

Full artifact output follows; temporary paths are normalized to $WORK. The commands above are the reproduction and validation commands. Additional read-only checks covered current classification, public visibility, labels, issue comments, linked-PR timeline, and source history. All issue content was treated as untrusted evidence; suggestions were not executed. No external issue links were fetched.

disconnect-first

healthy: {"exited":true,"code":0,"signal":null}
stalled: {"exited":false}
native cleanup entered; completion withheld
node:internal/modules/run_main:123
    triggerUncaughtException(
    ^

AssertionError [ERR_ASSERTION]: watcher must exit after IPC disconnect even when unsubscribe stalls

false !== true

    at file://$WORK/reports/issues/5553/repro/disconnect.mjs:101:10
    at process.processTicksAndRejections (node:internal/process/task_queues:105:5) {
  generatedMessage: false,
  code: 'ERR_ASSERTION',
  actual: false,
  expected: true,
  operator: 'strictEqual',
  diff: 'simple'
}

Node.js v22.19.0

scope-first

{"directoriesInNestedIgnoredOutput":200,"plainRootReportsNestedIgnoredOutput":true,"gitRootReportsOuterIgnoredOutput":false}

disconnect-second

healthy: {"exited":true,"code":0,"signal":null}
stalled: {"exited":false}
native cleanup entered; completion withheld
node:internal/modules/run_main:123
    triggerUncaughtException(
    ^

AssertionError [ERR_ASSERTION]: watcher must exit after IPC disconnect even when unsubscribe stalls

false !== true

    at file://$WORK/reports/issues/5553/repro/disconnect.mjs:101:10
    at process.processTicksAndRejections (node:internal/process/task_queues:105:5) {
  generatedMessage: false,
  code: 'ERR_ASSERTION',
  actual: false,
  expected: true,
  operator: 'strictEqual',
  diff: 'simple'
}

Node.js v22.19.0

scope-second

{"directoriesInNestedIgnoredOutput":200,"plainRootReportsNestedIgnoredOutput":true,"gitRootReportsOuterIgnoredOutput":false}