← reports

#5704 · PR detail reads have no shared request budget

BugHighEffort: Mediumhost · perf · github · partial-repro Issue #5704October 17, 2026 · base ee36dfda7815e8c72672ab57e2bdb1b395ada9be

Verdict: PARTIALLY REPRODUCED · Root-cause confidence: high for the request-amplification mechanism, not the reporter's exact live allowance consumption.

1. TL;DR

Every uncached environment PR read asks GitHub for detailed PR state, then asks separately about the merge queue for an open, non-draft PR. The existing ten-second server cache shares simultaneous reads only within one environment identity; it does not impose an aggregate request budget. A deterministic test through the real server cache and host lookup produced 7,200 detail commands plus 7,200 queue commands for sixty environments requested every thirty seconds over one simulated hour. The same test also reproduced duplicate reads across environment identities and a retry thirty seconds after a synthetic quota failure. No real GitHub quota was deliberately exhausted: exact point costs, the original process sample, and the original caller responsible for the observed traffic remain unverified.

2. Claims vs findings

ClaimFindingEvidence and limit
Detailed PR and separate merge-queue reads account for traffic.Verified mechanismThe trusted host lookup issues both commands. The sixty-environment model records 7,200 of each.
Many active threads can consume a shared hourly allowance.Partially verifiedRequests scale with distinct environment keys and poll cadence, without an aggregate bound. Counts are subprocess invocations, not measured GraphQL points.
The reported host executed the stated number of commands and lost allowance at the stated rate.UnverifiedNo production process sampling, credentials, usage data, or live exhaustion experiment was used.
The daemon independently polls every active thread.Not establishedThe traced daemon handler responds to RPC requests. The UI has conditional thirty-second polling, but this test supplies demand directly and does not mount sixty UI observers.
Duplicate PR reads are not coalesced.QualifiedSixty simultaneous reads of one environment coalesce successfully. Two different environment identities mapped to the same workspace issue two detail and two queue commands.
Exhaustion does not stop later background reads.Verified with synthetic failureA synthetic failed detail subprocess is attempted again after thirty seconds. No real HTTP response, reset header, or credential bucket was exercised.
A rate-limit endpoint differs from response headers; disabling another plugin does not help.UnverifiedNeither was tested against the reporter's account or production host. The core detail lookup exists independently of the GitHub plugin.

3. Environment

4. Minimal reproduction

This is a bounded, offline model of request demand, not a one-hour live traffic capture. The PR fixture has a running check, which is eligible for the real UI's active-PR poll interval. The test invokes the server cache and host lookup directly, adapting the host result in the same shape as the daemon handler; it does not test HTTP routing, workspace resolution, React visibility, or plugin behavior.

  1. Create a fresh worktree at the trusted commit and install/build:
    git clone https://github.com/get-bb/bb.git bb-5704
    cd bb-5704
    git checkout --detach ee36dfda7815e8c72672ab57e2bdb1b395ada9be
    pnpm install --frozen-lockfile --prefer-offline
    pnpm exec turbo run build
  2. Save the complete test below as packages/host-workspace/test/issue-5704-repro.test.ts. It adds no dependency or production seam.
  3. Run the focused test. Exit status 1 and three failing safety assertions are expected on the trusted base:
    pnpm exec turbo run test --force --filter=@bb/host-workspace -- test/issue-5704-repro.test.ts
  4. Repeat in a second clean checkout at the same commit with the same test. Do not point any command at a live BB data directory.

Expected vs actual

ProbeSafety expectationObserved
Sixty overlapping same-environment readsOne detail read and one queue read1 + 1; control passes
Sixty distinct environments, 120 ticks, 30 seconds per tickFewer than 5,000 detail reads even before reserving user capacity7,200 detail reads + 7,200 queue reads; fails
Two environment identities for one workspace/PROne shared detail readTwo detail reads + two queue reads; fails
Synthetic quota error, then a tick 30 seconds laterDo not immediately resume the known exhausted read streamTwo failing detail attempts; fails

The 5,000-detail-read assertion is a deliberately conservative capacity guard, not a measurement or verification of GitHub's billing rules. Every model tick returns an unchanged PR. The clock advances in memory; the test runs in about one second after imports.

Complete test

import { beforeEach, describe, expect, it, vi } from "vitest";
import { WorkspaceReadCaches } from "../../../apps/server/src/services/environments/workspace-read-cache.js";
import { getPullRequestForCurrentBranch } from "../src/git-host.js";

const transport = vi.hoisted(() => ({
  views: 0,
  queues: 0,
  exhausted: false,
}));

vi.mock("@bb/process-utils", async (importOriginal) => {
  const actual = await importOriginal<typeof import("@bb/process-utils")>();
  return {
    ...actual,
    execPortableFile: async (
      file: string,
      args: readonly string[],
      options: { cwd: string },
    ) => {
      if (file === "git") return { stdout: "", stderr: "" };
      if (file !== "gh") throw new Error(`Unexpected executable: ${file}`);
      if (args[0] === "pr" && args[1] === "view") {
        transport.views += 1;
        if (transport.exhausted) {
          throw Object.assign(new Error("GraphQL allowance exhausted"), {
            code: 1,
            stderr: "Synthetic GraphQL quota exhaustion",
          });
        }
        const workspaceIndex = Number(options.cwd.match(/workspace-(\d+)$/)?.[1] ?? 0);
        return {
          stdout: JSON.stringify({
            number: workspaceIndex + 1,
            title: "Synthetic pull request",
            state: "OPEN",
            url: `https://github.com/example/repo-${workspaceIndex % 19}/pull/${workspaceIndex + 1}`,
            isDraft: false,
            autoMergeRequest: null,
            baseRefName: "main",
            headRefName: `example-${workspaceIndex}`,
            updatedAt: "2026-10-17T00:00:00Z",
            statusCheckRollup: [{
              __typename: "CheckRun",
              name: "Synthetic CI",
              status: "IN_PROGRESS",
              conclusion: null,
            }],
            reviewDecision: null,
            reviewRequests: [],
            mergeStateStatus: "CLEAN",
            mergeable: "MERGEABLE",
          }),
          stderr: "",
        };
      }
      if (args[0] === "api" && args[1] === "graphql") {
        transport.queues += 1;
        return {
          stdout: JSON.stringify({ data: { resource: { isInMergeQueue: false } } }),
          stderr: "",
        };
      }
      throw new Error(`Unexpected gh operation: ${args.slice(0, 2).join(" ")}`);
    },
  };
});

function createReader() {
  let now = 0;
  const caches = new WorkspaceReadCaches({
    hub: { onChangedMessage: () => () => undefined },
    now: () => now,
  });
  return {
    advance(milliseconds: number) {
      now += milliseconds;
    },
    read(environmentIndex: number, workspaceIndex = environmentIndex) {
      return caches.pullRequest.read({
        environmentId: `environment-${environmentIndex}`,
        hostId: "synthetic-host",
        key: `workspace-${workspaceIndex}`,
        load: async () => {
          const lookup = await getPullRequestForCurrentBranch({
            cwd: `/tmp/synthetic-repository/workspace-${workspaceIndex}`,
            localBranch: `example-${workspaceIndex}`,
          });
          if (lookup.outcome === "found") {
            return { outcome: "available", pullRequest: lookup.pullRequest };
          }
          if (lookup.outcome === "none") return { outcome: "absent" };
          return lookup;
        },
      });
    },
  };
}

beforeEach(() => {
  transport.views = 0;
  transport.queues = 0;
  transport.exhausted = false;
});

describe("PR status traffic safety", () => {
  it("coalesces identical environment reads inside the existing cache window", async () => {
    const reader = createReader();
    const results = await Promise.all(Array.from({ length: 60 }, () => reader.read(0)));
    expect(results.every((result) => result.outcome === "available")).toBe(true);
    expect(transport.views).toBe(1);
    expect(transport.queues).toBe(1);
  });

  it("keeps one hour of 60-environment polling below 5000 detail reads", async () => {
    const reader = createReader();
    for (let tick = 0; tick < 120; tick += 1) {
      const results = await Promise.all(
        Array.from({ length: 60 }, (_, index) => reader.read(index)),
      );
      expect(results.every((result) => result.outcome === "available")).toBe(true);
      reader.advance(30_000);
    }
    console.log(`Hourly model: views=${transport.views}, queueQueries=${transport.queues}`);
    expect(transport.views).toBeLessThan(5_000);
  });

  it("coalesces the same workspace and PR across two environment identities", async () => {
    const reader = createReader();
    const results = await Promise.all([reader.read(0, 0), reader.read(1, 0)]);
    expect(results.every((result) => result.outcome === "available")).toBe(true);
    console.log(`Shared workspace: views=${transport.views}, queueQueries=${transport.queues}`);
    expect(transport.views).toBe(1);
  });

  it("does not retry a known exhausted allowance on the next poll", async () => {
    const reader = createReader();
    transport.exhausted = true;
    const first = await reader.read(0);
    expect(first.outcome).toBe("unavailable");
    reader.advance(30_000);
    const second = await reader.read(0);
    expect(second.outcome).toBe("unavailable");
    console.log(`Exhausted allowance: views=${transport.views}, queueQueries=${transport.queues}`);
    expect(transport.views).toBe(1);
  });
});

First run: verbatim selected output

@bb/host-workspace:test: Hourly model: views=7200, queueQueries=7200
@bb/host-workspace:test: Shared workspace: views=2, queueQueries=2
@bb/host-workspace:test: Exhausted allowance: views=2, queueQueries=0
@bb/host-workspace:test: ⎯⎯⎯⎯⎯⎯⎯ Failed Tests 3 ⎯⎯⎯⎯⎯⎯⎯
@bb/host-workspace:test: AssertionError: expected 7200 to be less than 5000
@bb/host-workspace:test:     123|     console.log(`Hourly model: views=${transport.views}, queueQueries=…
@bb/host-workspace:test: AssertionError: expected 2 to be 1 // Object.is equality
@bb/host-workspace:test:     131|     console.log(`Shared workspace: views=${transport.views}, queueQuer…
@bb/host-workspace:test: AssertionError: expected 2 to be 1 // Object.is equality
@bb/host-workspace:test:     143|     console.log(`Exhausted allowance: views=${transport.views}, queueQ…
@bb/host-workspace:test:  Test Files  1 failed (1)
@bb/host-workspace:test:       Tests  3 failed | 1 passed (4)

5. Root cause

The request path is SDK environment PR read → server environment route → server read cache → daemon workspace RPC → host PR lookup. The route caches by environment and host as well as workspace identity. That prevents duplicate requests for the same cache key, but gives every different environment a separate slot. The ten-second TTL expires before the active-PR thirty-second poll. There is no budget shared across these cache entries.

apps/server/src/routes/environments.ts:433

  get(routes.pullRequest, async (context) => {
    const environment = requireReadyEnvironment(
      deps.db,
      context.req.param("id"),
    );
    if (!environment.isGitRepo) {
      return context.json({ outcome: "absent" });
    }
    const target = requireWorkspaceCommandTarget(environment);
    const result = await deps.workspaceReadCaches.pullRequest.read({
      environmentId: environment.id,
      hostId: target.hostId,
      key: workspaceReadCacheKey(target),
      load: () =>
        callHostRetryableOnlineRpc(deps, {
          hostId: target.hostId,
          timeoutMs: COMMAND_TIMEOUT_MS,
          command: {
            type: "workspace.pull_request",
            environmentId: target.environmentId,
            workspaceContext: target.workspaceContext,
          },
        }),

apps/server/src/services/environments/workspace-read-cache.ts:39

  read(args: EnvironmentReadCacheReadArgs<TValue>): Promise<TValue> {
    return this.cache.run(
      `${args.environmentId} ${args.hostId} ${args.key}`,
      args.load,
    );

apps/server/src/services/environments/workspace-read-cache.ts:55

const WORKSPACE_STATUS_CACHE_TTL_MS = 3_000;
const WORKSPACE_PULL_REQUEST_CACHE_TTL_MS = 10_000;

The host detail query requests status-check rollups among other PR fields. Every successful open/non-draft result launches a second GraphQL command for merge-queue membership, including when the PR has not changed. Neither invocation requests rate-limit headers. Detail failures return an unavailable lookup; queue-query failures set unknown queue membership without establishing a shared cooldown.

packages/host-workspace/src/git-host.ts:25

const GH_PR_VIEW_JSON_FIELDS = [
  "number",
  "title",
  "state",
  "url",
  "isDraft",
  "autoMergeRequest",
  "baseRefName",
  "headRefName",
  "updatedAt",
  "statusCheckRollup",
  "reviewDecision",
  "reviewRequests",
  "mergeStateStatus",
  "mergeable",
].join(",");

packages/host-workspace/src/git-host.ts:593

  let stdout: string;
  try {
    ({ stdout } = await execPortableFile("gh", ghArgs, {
      cwd: args.cwd,
      env: sanitizeInheritedChildProcessEnv({
        env: process.env,
        ...(args.shellPath !== undefined ? { shellPath: args.shellPath } : {}),
      }),
      timeout: GH_PR_VIEW_TIMEOUT_MS,
      maxBuffer: GH_PR_VIEW_MAX_BUFFER_BYTES,
    }));
  } catch (error) {
    return classifyPullRequestViewError(error);

packages/host-workspace/src/git-host.ts:614

  if (pullRequest.state === "OPEN" && !pullRequest.isDraft) {
    try {
      const { stdout: queueOutput } = await execPortableFile(
        "gh",
        [
          "api",
          "graphql",
          "--hostname",
          new URL(pullRequest.url).hostname,
          "-f",
          "query=query($url: URI!) { resource(url: $url) { ... on PullRequest { isInMergeQueue } } }",
          "-f",
          `url=${pullRequest.url}`,
        ],

packages/host-workspace/src/git-host.ts:640

      const response = asObject(JSON.parse(queueOutput));
      const data = asObject(response?.data);
      const resource = asObject(data?.resource);
      pullRequest.inMergeQueue = resource
        ? getBoolean(resource, "isInMergeQueue")
        : null;
    } catch {
      pullRequest.inMergeQueue = null;
    }
  } else {
    pullRequest.inMergeQueue = false;
  }
  return { outcome: "found", pullRequest };

The daemon handler performs a read in response to a request. This investigation does not demonstrate a separate daemon timer polling all threads. Existing UI behavior does allow thirty-second polling for open PRs with pending checks, auto-merge, merge-queue membership, or unknown mergeability, while settled PRs do not use that interval.

apps/host-daemon/src/command-dispatch.ts:731

  "workspace.pull_request": async (command, options) => {
    const resolution = await resolveWorkspaceForCommand({
      environmentId: command.environmentId,
      requireGit: true,
      runtimeManager: options.runtimeManager,
      workspaceContext: command.workspaceContext,
    });
    if (!resolution.ok) {
      return resolution.failure.code === "not_git_repo"
        ? { outcome: "absent" }
        : { outcome: "unavailable", message: resolution.failure.message };
    }
    const lookup = await resolution.entry.workspace.getPullRequest(
      userExecutableProcessOptions(options.runtimeManager.getShellEnv()),
    );
    switch (lookup.outcome) {
      case "found":
        return { outcome: "available", pullRequest: lookup.pullRequest };
      case "none":
        return { outcome: "absent" };
      case "unavailable":
        return { outcome: "unavailable", message: lookup.message };

apps/app/src/hooks/queries/environment-queries.ts:62

const ENVIRONMENT_PULL_REQUEST_STALE_MS = 30_000;
const ENVIRONMENT_SETTLED_PULL_REQUEST_STALE_MS = 60 * 60_000;
const ENVIRONMENT_ACTIVE_PULL_REQUEST_REFETCH_MS = 30_000;

apps/app/src/hooks/queries/environment-queries.ts:150

export function getEnvironmentPullRequestRefetchInterval(
  pullRequest: ThreadPullRequest | null | undefined,
): number | false {
  if (!pullRequest || pullRequest.state !== "open") {
    return false;
  }
  if (
    pullRequest.autoMerge ||
    pullRequest.inMergeQueue === true ||
    pullRequest.checks.state === "pending" ||
    pullRequest.mergeability.state === "unknown"
  ) {
    return ENVIRONMENT_ACTIVE_PULL_REQUEST_REFETCH_MS;
  }
  return false;

The deeper problem is that short-lived per-environment memoization is not aggregate external-service admission control. A larger fixed TTL or removal of the queue query reduces cost but remains proportional to the number of distinct environments, and therefore cannot guarantee a shared reserve.

6. Proposed fix and simple-fix gate

Introduce explicit shared request-budget policy for background GitHub reads, separate from user-triggered PR mutations. Define the reserve, staleness behavior, account/hostname scope, and reset-aware cooldown. Coalesce equivalent PR identities across workspaces; consider conditional lightweight change detection before loading detail and queue state. Preserve correctness for changed checks/reviews, whose updates need not be represented by a naive PR timestamp comparison.

No fix PR opened. No linked open PR was found in the issue timeline or open-PR search. A safe complete fix requires a product decision about background freshness versus a shared user-action reserve, and coordination between server policy and host-local GitHub transport. That fails the autopilot's no-product/architecture-decision condition; an arbitrary TTL increase would not repair the unbounded aggregate mechanism. No production patch, fix branch, dependency, protocol, stored data, or migration was changed.

Next experiment: after choosing that contract, replay this demand model with mixed active/settled PRs, multiple authentication buckets, quota reset responses, and an interleaved user action. Verify a bounded aggregate read count and timely mutation refresh before implementing admission control.

7. Verification

The same agent created a second clean detached worktree at ee36dfda7815e8c72672ab57e2bdb1b395ada9be, performed a fresh frozen install and a full Turbo build, copied only the authored reproduction test, and reran the exact focused command with --force. No production code was changed in either run. The test-file SHA-256 in both runs was 521c7e32582368396a6fbb8b53d9c6184573040649cbb607d3dda8d72578660d. Both produced the identical counts and the same three failures plus one passing control. This is a repeat by the same agent, not independent verification.

@bb/host-workspace:test: Hourly model: views=7200, queueQueries=7200
@bb/host-workspace:test: Shared workspace: views=2, queueQueries=2
@bb/host-workspace:test: Exhausted allowance: views=2, queueQueries=0
@bb/host-workspace:test: ⎯⎯⎯⎯⎯⎯⎯ Failed Tests 3 ⎯⎯⎯⎯⎯⎯⎯
@bb/host-workspace:test: AssertionError: expected 7200 to be less than 5000
@bb/host-workspace:test:     123|     console.log(`Hourly model: views=${transport.views}, queueQueries=…
@bb/host-workspace:test: AssertionError: expected 2 to be 1 // Object.is equality
@bb/host-workspace:test:     131|     console.log(`Shared workspace: views=${transport.views}, queueQuer…
@bb/host-workspace:test: AssertionError: expected 2 to be 1 // Object.is equality
@bb/host-workspace:test:     143|     console.log(`Exhausted allowance: views=${transport.views}, queueQ…
@bb/host-workspace:test:  Test Files  1 failed (1)
@bb/host-workspace:test:       Tests  3 failed | 1 passed (4)

The original host-workspace suite passed after removing the intentionally failing reproduction test: 164 passed, one skipped across nine files. The existing server workspace-read-cache suite passed all ten tests. A first attempt to exclude the reproduction with the CLI exclude flag still included it under this repository's explicit project file lists; that run failed only the three intentional reproduction assertions. The clean rerun removed the extra test and passed. Both full builds passed; no unrelated production failures were found.

All source permalinks and excerpt bounds were checked against the recorded base. The report was qualified as partial because subprocess counts cannot establish real GraphQL point consumption or the reporter's exact original request initiator. No other report correction was necessary.

8. Related issues and PRs

No linked PRs, comments, or matching duplicate bug were found for #5704 at investigation time. Historical PR #1886 introduced short-lived workspace read caching; PR #5132 later shared cached external lookups. Those history entries explain existing memoization, not a verified fix for this aggregate-demand problem. No linked PR branch or code was executed.

9. Appendix

Issue content was treated as untrusted claims, not operational instructions. The test was authored from the trusted cache and host implementation. No external issue links, issue scripts, private data, real account quota, or live BB runtime were used. The test and selected outputs are inline because the public reports repository forbids committing raw test files and logs; raw evidence is retained only in local investigation storage.

Relevant commands

git fetch origin main
git rev-parse origin/main
git worktree add --detach CHECKOUT_A ee36dfda7815e8c72672ab57e2bdb1b395ada9be
git worktree add --detach CHECKOUT_B ee36dfda7815e8c72672ab57e2bdb1b395ada9be
pnpm install --frozen-lockfile --prefer-offline
pnpm exec turbo run build
pnpm exec turbo run test --filter=@bb/host-workspace -- test/issue-5704-repro.test.ts
pnpm exec turbo run test --force --filter=@bb/host-workspace -- test/issue-5704-repro.test.ts
pnpm exec turbo run test --filter=@bb/host-workspace -- --exclude test/issue-5704-repro.test.ts
pnpm exec turbo run test --filter=@bb/host-workspace
pnpm exec turbo run test --filter=@bb/server -- src/services/environments/workspace-read-cache.test.ts
git diff --check
gh pr list --repo get-bb/bb --state open --search '5704 in:body' --json number,title
gh api repos/get-bb/bb/issues/5704/timeline --paginate

Run install/build in each checkout. Run the unqualified host-workspace suite only after removing the intentionally failing extra test. No browser or screenshot is needed for this nonvisual process-demand reproduction.