Reports

#6797 · Realtime list refreshes bypass the existing throttle

BugPriority: MediumEffort: Mediumui, perf GitHub issue · 2026-11-01

Trusted main commit: 916d684ac23d0b0de82c09cfc7553a50287d2188

Verdict: REPRODUCED · Root-cause confidence: high

1. TL;DR

The app maintains a shared sidebar query plus thread-list queries, including related-thread lists. Eleven kinds of realtime thread changes bypass the existing one-second active-refetch throttle. A deterministic test delivers four events spaced 200 ms apart: the sidebar query executes four times instead of once within that burst. Both clean checkouts produce the same failure; the test also observes real TanStack Query list observers rather than mocking the cache. This reproduces the request-amplification mechanism, not the reporter's production request rates, server timings, or CPU share.

2. Claims vs findings

ClaimFindingEvidence
Realtime changes repeatedly refetch sidebar and related listsVerified mechanismFour events produce four sidebar query executions in 800 ms in both runs; source shows identical unthrottled invalidation for project/fork lists.
Only some paths use throttlingVerifiedThe metadata-less status fallback uses the throttled helper; background activity, title, queue, read state and structural list changes use other handlers.
Production rates, response sizes, latency and CPU contributionUnverifiedNo production profile or runtime data was accessed. These depend on load and network timing.
Timeline responses lack compressionUnverified; separate claimNot exercised by this cache-level reproduction or proposed fix.

3. Environment

4. Minimal reproduction

  1. Clone the public repository into a scratch directory and check out the recorded base commit.
  2. Install frozen dependencies and build the app's prerequisites.
  3. Copy the complete inline reproduction test into the path shown below; it is authored from trusted repository APIs, not copied from issue data.
  4. Run the focused test. It must fail on the unchanged base.
git clone https://github.com/get-bb/bb.git scratch
cd scratch
git checkout --detach 916d684ac23d0b0de82c09cfc7553a50287d2188
pnpm install --frozen-lockfile --prefer-offline
pnpm exec turbo run build:types --filter=@get-bb/plugin-sdk
pnpm exec turbo run build --filter=@bb/app
# Place the attached test at apps/app/src/hooks/realtime-thread-list-throttle.test.ts
pnpm exec turbo run test --filter=@bb/app -- src/hooks/realtime-thread-list-throttle.test.ts

Expected: at most one refresh of each observed list during the first 800 ms, followed by one trailing refresh that reads the newest revision. Actual:

AssertionError: expected "vi.fn()" to be called 1 times, but got 4 times
Test Files  1 failed (1)
     Tests  11 failed (11)

The test fails on the first observer (sidebar), before its post-burst list and cleanup assertions; those assertions become the fix's regression contract, not additional claimed baseline observations.

Complete reproduction test
import { QueryClient, QueryObserver } from "@tanstack/react-query";
import { afterEach, expect, it, vi } from "vitest";
import { createRealtimeCacheEffects } from "./realtime-cache-effects";
import {
  sidebarNavigationQueryKey,
  threadListQueryKey,
} from "./queries/query-keys";

afterEach(() => {
  vi.useRealTimers();
});

it.each([
  "thread-created",
  "thread-deleted",
  "history-rewritten",
  "title-changed",
  "queue-changed",
  "archived-changed",
  "pin-state-changed",
  "parent-changed",
  "environment-changed",
  "read-state-changed",
  "events-appended",
] as const)("coalesces %s list reads with a trailing refresh", async (change) => {
  vi.useFakeTimers();
  const queryClient = new QueryClient({
    defaultOptions: { queries: { gcTime: Infinity, retry: false } },
  });
  const effects = createRealtimeCacheEffects({ queryClient });
  let revision = 0;
  const keys = [
    sidebarNavigationQueryKey(),
    threadListQueryKey({ archived: false }),
    threadListQueryKey({ archived: false, projectId: "project-1" }),
    threadListQueryKey({
      archived: false,
      projectId: "project-1",
      sourceThreadId: "thr_parent",
      originKind: "fork",
    }),
  ];
  const reads = keys.map(() => vi.fn(async () => revision));
  const observers = keys.map(
    (queryKey, index) =>
      new QueryObserver(queryClient, {
        queryKey,
        queryFn: reads[index],
        staleTime: Infinity,
      }),
  );
  const stops = observers.map((observer) => observer.subscribe(() => {}));
  const inactiveKey = threadListQueryKey({
    archived: false,
    projectId: "project-1",
    sourceThreadId: "thr_inactive",
  });
  queryClient.setQueryData(inactiveKey, 0);
  try {
    await vi.advanceTimersByTimeAsync(0);
    for (const read of reads) {
      read.mockClear();
    }
    for (revision = 1; revision <= 4; revision += 1) {
      effects.handleChanged({
        type: "changed",
        entity: "thread",
        id: "thr_child",
        changes: [change],
        metadata: { projectId: "project-1", backgroundActivityChanged: true },
      });
      await vi.advanceTimersByTimeAsync(200);
    }
    for (const read of reads) {
      expect(read).toHaveBeenCalledTimes(1);
    }
    expect(queryClient.getQueryState(inactiveKey)?.isInvalidated).toBe(true);
    await vi.advanceTimersByTimeAsync(300);
    for (const read of reads) {
      expect(read).toHaveBeenCalledTimes(2);
    }
    for (const observer of observers) {
      expect(observer.getCurrentResult().data).toBe(revision);
    }
    revision += 1;
    effects.handleChanged({
      type: "changed",
      entity: "thread",
      id: "thr_child",
      changes: [change],
      metadata: { projectId: "project-1", backgroundActivityChanged: true },
    });
    await vi.advanceTimersByTimeAsync(200);
    effects.dispose();
    await vi.advanceTimersByTimeAsync(2_000);
    for (const read of reads) {
      expect(read).toHaveBeenCalledTimes(2);
    }
  } finally {
    for (const stop of stops) {
      stop();
    }
    effects.dispose();
    queryClient.clear();
  }
});

5. Root cause

Thread changes are dispatched through a registry. The short scheduler debounce coalesces changes within a small window, but not a stream spaced 200 ms apart. Structural changes call dirtyThreadListQueries; title, queue, read state, environment and background activity call dirtyActiveThreadListQueries. Both directly refetch active queries. Only the metadata-less status fallback uses dirtyActiveThreadListQueriesWithThrottledRefetch.

apps/app/src/hooks/cache-owners/realtime-cache-registry.ts:747

function dirtyThreadListQueries({
  projectId,
  queryClient,
}: ThreadRealtimeDirtyContext): QueryKey[] {
  if (projectId) {
    for (const queryKey of getCachedGlobalThreadListInvalidationQueryKeys({
      queryClient,
    })) {
      invalidateQueryKeyWithoutCancelingActiveFetch({
        exact: true,
        queryClient,
        queryKey,
      });
    }
  }
  return getThreadListInvalidationQueryKeys({ projectId, queryClient });
}

function dirtyActiveThreadListQueries({
  projectId,
  queryClient,
}: ThreadRealtimeDirtyContext): QueryKey[] {
  const listQueryKeys = projectId
    ? [
        ...getCachedProjectThreadListInvalidationQueryKeys({
          projectId,
          queryClient,
        }),
        ...getCachedGlobalThreadListInvalidationQueryKeys({ queryClient }),
      ]
    : getCachedThreadListQueryKeys(queryClient);
  for (const queryKey of listQueryKeys) {
    if (isArchivedThreadListQueryKey(queryKey)) {
      queryClient.invalidateQueries({
        exact: true,
        queryKey,
        refetchType: "none",
      });
      continue;
    }
    invalidateQueryKeyWithoutCancelingActiveFetch({
      exact: true,
      queryClient,
      queryKey,
    });
  }
  return [sidebarNavigationQueryKey(), threadSearchQueryKeyPrefix()];
}

function dirtyActiveThreadListQueriesWithThrottledRefetch({
  projectId,
  queryClient,
}: ThreadRealtimeDirtyContext): void {
  const listQueryKeys = projectId
    ? [
        ...getCachedProjectThreadListInvalidationQueryKeys({
          projectId,
          queryClient,
        }),
        ...getCachedGlobalThreadListInvalidationQueryKeys({ queryClient }),
      ]
    : getCachedThreadListQueryKeys(queryClient);
  for (const queryKey of listQueryKeys) {
    if (isArchivedThreadListQueryKey(queryKey)) {
      queryClient.invalidateQueries({
        exact: true,
        queryKey,
        refetchType: "none",
      });
      continue;
    }
    invalidateQueryKeyWithThrottledActiveRefetch({
      exact: true,
      minIntervalMs: THREAD_LIST_STATUS_FALLBACK_REFETCH_MIN_INTERVAL_MS,
      queryClient,
      queryKey,
    });
  }
  for (const queryKey of [
    sidebarNavigationQueryKey(),
    threadSearchQueryKeyPrefix(),
  ]) {
    invalidateQueryKeyWithThrottledActiveRefetch({
      exact: false,
      minIntervalMs: THREAD_LIST_STATUS_FALLBACK_REFETCH_MIN_INTERVAL_MS,
      queryClient,
      queryKey,
    });
  }
}

The shared key group includes sidebarNavigationQueryKey; its query function calls the bootstrap endpoint. Related-thread lists use the same cached thread-list key family, so the active-list loop also invalidates them. Refetches now avoid cancelling an active fetch (a prior livelock fix), but that protection does not rate-limit quick completed reads.

apps/app/src/hooks/cache-owners/cache-invalidation-groups.ts:81

export function getThreadListInvalidationQueryKeys({
  projectId,
  queryClient,
}: ThreadListInvalidationArgs): QueryKey[] {
  const threadListQueryKeys = projectId
    ? getCachedProjectThreadListInvalidationQueryKeys({
        projectId,
        queryClient,
      })
    : [threadsQueryKey()];
  return [
    ...threadListQueryKeys,
    sidebarNavigationQueryKey(),
    threadSearchQueryKeyPrefix(),
  ];
}

apps/app/src/hooks/queries/sidebar-navigation-query.ts:22

function fetchSidebarNavigation(
  signal?: AbortSignal,
): Promise<SidebarBootstrapResponse> {
  return request<SidebarBootstrapResponse>(
    apiClient["sidebar-bootstrap"].$get(undefined, requestOptions(signal)),
  );
}

6. Proposed fix

Route both structural and active-only thread-list invalidations through the existing per-QueryClient, per-key one-second leading/trailing refetch scheduler. Preserve archived-list invalidation rules, immediate stale marking, non-cancelling in-flight behavior and disposal cleanup. Share the same buckets with the status fallback so mixed event types cannot bypass the bound. Do not alter HTTP protocols, server policy, compression or dependencies.

7. Related issues and pull requests

No linked open PR appeared in the issue timeline or an open-PR search for its number at investigation time. Trusted history includes commit 41c6abe6daf274dc727c323ab0729bc4824e564e (PR #6458), which prevented active-read cancellation livelock; it did not extend status-fallback throttling to the other list handlers. No external issue links or linked PR code was executed.

8. Verification

The same agent repeated the reproduction in a second clean detached worktree at the identical trusted commit. A new frozen install and owning-app Turbo build completed before adding only the reproduction test. The command was the same focused Turbo test invocation shown above. All eleven cases again failed with four calls rather than one. No live service was needed, so there were no ports or data directories to reuse. This is a second clean run, not an independent-agent verification. No report correction was needed.

First run: 11 cases failed, duration 12.60s. Second run: 11 cases failed, duration 11.85s. Both printed the exact assertion above. Raw logs stay outside the public repository under its publication rules.

9. Appendix

The test uses genuine TanStack QueryClient and QueryObserver instances and the production createRealtimeCacheEffects entry point. It counts query-function executions, not HTTP traffic; functions return a revision counter to avoid requiring an API or database. No visual claim is made and no synthetic screenshot is supplied. The optional production fix must additionally prove trailing freshness, inactive-query stale marking and timer cancellation, then run existing realtime suites.

Commands executed: git fetch origin main; git worktree add --detach for each checkout; frozen pnpm installs; initial full Turbo build; SDK type build; owning-app builds; focused Turbo tests. Metadata was read with GitHub CLI and classification written through the supplied SlopCop wrapper. Issue content was treated only as untrusted claims; its suggested actions were not followed as instructions.

> AGENT GENERATED