Skip to content

Long-lived stdio logs have no runtime size cap/rotation, and handlerStats / inFlightWorkAtObservation conflate passive async waits with CPU work #8326

Description

@vburojevic

1. Summary

Two small observability/operations rough edges observed during a live performance audit of long-running bb server/daemon processes:

  1. spawnLoggedProcess rotates server-stdio.log / host-daemon-stdio.log only once at spawn time (MAX_STDIO_LOG_BYTES_AT_SPAWN = 10 MiB) via a raw file descriptor, with no runtime size cap while long-lived processes run and no cleanup/cap on oversized .1.log files (leaving 887 MB of stale .1.log files on disk for weeks).
  2. invokeWrapped records total async wall-clock duration (performance.now() - startedAt, including passive 25s long-polls and proxied streams) into handlerStats.totalMs/maxMs and wraps the entire async lifetime in runEventLoopWork, so "Event loop stalled" inFlightWorkAtObservation lists passive awaited I/O handlers (like bb-account 25s long-poll or account-pool proxy hub) alongside genuine synchronous CPU blockers.

2. Versions and environment

  • bb version: 0.50.1 (Desktop app on macOS), code verified on main at commit b0ddaad731565d7e4de68d824120d802fc78f7d5
  • OS: macOS 27.2.0 (arm64, Apple Silicon)

3. Steps to reproduce

  1. Stdio log growth: Run bb server / host daemon across long uptimes with verbose plugin or process stderr/stdout output; inspect ~/.bb/logs/*-stdio*.log. Because the child writes directly to an open fd and rotation only happens in spawnLoggedProcess, a single process run can grow *-stdio.log unboundedly and leave hundreds of MB in *-stdio.1.log until the next spawn overwrites it.
  2. Async wait attribution: Trigger any synchronous event-loop stall while a plugin holds a long-lived async handler or service (e.g., bb-account 25s waitForStatusChange long-poll or account-pool service hub), and inspect "Event loop stalled" in ~/.bb/logs/server.*.log or plugin handlerStats.

4. Expected vs actual

Actual:

  • Disk: ~/.bb/logs/server-stdio.1.log + host-daemon-stdio.1.log accumulated 887 MB (from Oct 24, still sitting on disk on Nov 28).
  • Server log (server.14.log, 631 stall entries): every stall prints inFlightWorkAtObservation dominated by passive long-lived services/waits, masking which synchronous handler actually stalled the loop:
{"level":30,"component":"server","intervalMs":5000,"maxDelayMs":1104,"thresholdMs":500,"inFlightWorkAtObservation":"plugin:account-pool service hub | plugin:admiral service scheduler | ..."}
  • Plugin handlerStats reports bb-account at 10.76s avg / 25.2s max despite 0ms CPU usage, purely from its 25s long-poll wait.

Expected:

  • Cap/rotate *-stdio.log during long process lifetimes (or truncate/expire oversized *-stdio.1.log files) so stale stdio logs cannot hold ~1 GB indefinitely.
  • Distinguish synchronous event-loop execution time (or active sync frames) from total async wall-clock lifetime in handlerStats and inFlightWorkAtObservation, making real stall attribution immediate.

5. Evidence

  • MAX_STDIO_LOG_BYTES_AT_SPAWN = 10 * 1024 * 1024 and spawn-only rotation in packages/bb-app/src/logged-process.ts:
    const MAX_STDIO_LOG_BYTES_AT_SPAWN = 10 * 1024 * 1024;

    export function spawnLoggedProcess(args: SpawnLoggedProcessArgs): ChildProcess {
    mkdirSync(args.logDir, { recursive: true });
    const logPath = join(args.logDir, `${args.logName}-stdio.log`);
    if (
    (statSync(logPath, { throwIfNoEntry: false })?.size ?? 0) >
    MAX_STDIO_LOG_BYTES_AT_SPAWN
    ) {
    renameSync(logPath, join(args.logDir, `${args.logName}-stdio.1.log`));
    }
    const launch = resolveLoggedProcessLaunch(args);
    const fd = openSync(logPath, "a", 0o600);
    try {
    return spawn(launch.command, launch.args, {
    cwd: process.cwd(),
    env: launch.env,
    stdio: args.ipc === true ? ["ignore", fd, fd, "ipc"] : ["ignore", fd, fd],
    });
    } finally {
    closeSync(fd);
    }
    }
  • invokeWrapped records full async wall-clock time into handlerStats and wraps the full async promise in runEventLoopWork:
    function statsFor(id: string): PluginHandlerStats {
    let stats = handlerStats.get(id);
    if (!stats) {
    stats = { count: 0, totalMs: 0, maxMs: 0, errorCount: 0 };
    handlerStats.set(id, stats);
    }
    return stats;
    }

    async function invokeWrapped<T>(
    instance: LoadedPlugin,
    label: string,
    run: (signal: AbortSignal) => T | Promise<T>,
    callerSignal?: AbortSignal,
    ): Promise<PluginInvocationOutcome<T>> {
    const id = instance.pluginId;
    const released = instance.released.signal;
    if (released.aborted) {
    return {
    ok: false,
    error: `${label} not started: plugin "${id}" was reloaded or disabled`,
    cause: undefined,
    };
    }
    const lifetime = instance.stopping.signal.aborted
    ? released
    : instance.stopping.signal;
    const call =
    callerSignal === undefined
    ? { signal: lifetime, unlink: () => {} }
    : linkCallSignal(callerSignal, lifetime);
    const signal = call.signal;
    const stats = statsFor(id);
    const startedAt = performance.now();
    const execution = pluginCodeContext.run(id, () =>
    runEventLoopWork(`plugin:${id} ${label}`, () => run(signal)),
    );
    const settled = execution.then(
    () => undefined,
    () => undefined,
    );
    instance.invocations.add(settled);
    void settled.then(() => {
    call.unlink();
    instance.invocations.delete(settled);
    const elapsedMs = performance.now() - startedAt;
    stats.count += 1;
    stats.totalMs += elapsedMs;
    if (elapsedMs > stats.maxMs) stats.maxMs = elapsedMs;
    });
  • inFlightWorkAtObservation reports all activeFrames on every event-loop stall:
    function formatActiveWork(): string | null {
    if (activeFrames.size === 0) {
    return null;
    }
    const roots = [...activeFrames.values()]
    .filter(
    (frame) => frame.parent === null || !activeFrames.has(frame.parent.id),
    )
    .sort((left, right) => left.id - right.id);
    return roots.map((root) => formatLineage(root)).join(" | ");
    }
    function roundNullableDurationMs(durationMs: number | null): number | null {
    return durationMs === null ? null : roundDurationMs(durationMs);
    }
    function getEventLoopWorkSnapshot(): EventLoopWorkSnapshot {
    const longest = longestInWindow;
    return {
    inFlightWorkAtObservation: formatActiveWork(),
    lastCompletedWork:
    lastCompleted === null ? null : describeLabel(lastCompleted.label),
    lastCompletedWorkWallMs:
    lastCompleted === null ? null : roundDurationMs(lastCompleted.durationMs),
    longestSynchronousWork: longest === null ? null : formatWorkChain(longest),
    longestSynchronousWorkCaller: longest?.callerDescription ?? null,
    longestSynchronousWorkCpuMs: roundNullableDurationMs(
    longest?.cpuMs ?? null,
    ),
    longestSynchronousWorkWallMs: roundNullableDurationMs(
    longest?.durationMs ?? null,
    ),
    longestSynchronousWorkVoluntaryContextSwitches:
    longest?.contextSwitches?.voluntary ?? null,
    longestSynchronousWorkInvoluntaryContextSwitches:
    longest?.contextSwitches?.involuntary ?? null,
    };
    }

    export async function runEventLoopWork<T>(
    label: string,
    work: () => Promise<T> | T,
    ): Promise<T> {
    const frame = createFrame(label, currentAsyncParentFrame(), false);
    const startedAt = performance.now();
    activeFrames.set(frame.id, frame);
    const segmentCaller = currentSyncFrame ?? frame.parent;
    return currentAsyncFrame.run(frame, async () => {
    try {
    return await runSynchronousWorkFrame(
    `${label} (until first await)`,
    segmentCaller,
    true,
    work,
    );
    } finally {
    activeFrames.delete(frame.id);
    completeFrame(frame, performance.now() - startedAt);
    }
    });
    }

    prepareSample: () => {
    const work = takeEventLoopWorkWindowSnapshot();
    return ({ stall, suspension }) => {
    if (suspension !== null)
    options.logger.info(suspension, "System suspension observed");
    if (stall !== null) {
    const hasCandidate =
    work.longestSynchronousWorkWallMs !== null &&
    work.longestSynchronousWorkWallMs + stall.resolutionMs >=
    stall.maxDelayMs;
    options.logger.info(
    {
    ...stall,
    ...work,
    stallAttribution: hasCandidate ? "candidate" : "unattributed",
    stallCauseCandidate: hasCandidate
    ? work.longestSynchronousWork
    : null,
    },
    "Event loop stalled",
    );
    }
    };

6. What you ruled out

7. Suggested priority and effort

Low priority, small-to-medium effort: improves disk hygiene for long-running servers and makes event-loop stall diagnostics far more actionable when debugging plugins or core stalls.

AGENT GENERATED

Activity

  1. added theissue type on Nov 28, 2026
  2. added
    host
    plugins
    partial-repro
    on Nov 28, 2026
  3. bb-slop-cop commented on Nov 28, 2026

    @bb-slop-cop
    Contributor

    🚨 SLOP COP 🚨 · new-issue-autopilot

    • Classification: Bug · Priority: Low · Effort: Medium · Areas: host, plugins, perf.
    • Reproduction report: PARTIALLY REPRODUCED · root-cause confidence: high · label: partial-repro.
    • Evidence: Two clean checkouts of trusted main reproduced 12 MiB live stdio files and unchanged 13 MiB history files. A promise-gated plugin route also contributed waiting time to handler statistics and remained in flight. Complete tests and outputs are embedded in the report.
    • Root cause: Stdio uses inherited append-only descriptors with only a spawn-time size check. Async statistics measure promise lifetime; importantly, separate synchronous CPU/wall-time and stall-candidate fields already exist and correctly identified the controlled blocker. Historical disk totals and macOS stalls were not independently verified.
    • No PR: The combined repair spans launcher logging and server diagnostics and requires rotation/measurement policy decisions, outside the one-subsystem simple-fix gate.
  4. added a commit that references this issue on Dec 1, 2026
    e611693
  5. added a commit that references this issue on Dec 1, 2026
    90ef6dc
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

    hostpartial-reproperfplugins

    Type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions