← reports

#7340 · Retention batch validation repeatedly scans the thread catalog

BugMedium priorityLow effortplugins · perf · confirmed-reproGitHub issue

2026-11-10 · trusted base 7c1353d80729983b86ea1555d18b42407f320406

Verdict: REPRODUCED · Root-cause confidence: high

1. TL;DR

The hourly retention job finds groups of old threads to archive or delete. Before processing each group it reads the complete thread catalog again, including unrelated threads. With 7,600 synthetic threads and 50 eligible roots for each action, one sweep issued 1,616 unfiltered thread-list requests and received 766,375 rows. A second clean checkout produced the same counts. The minimal snapshot-and-targeted-reread optimization reduced the load but failed the archive safety test by dispatching an archive request after a newly attached hidden lifecycle dependent should have blocked it; that local prototype was reverted, not pushed.

2. Claims vs findings

ClaimStatusEvidence
Eligibility checks repeat full pagination before each selected group.Verified101 complete catalog scans: one initial scan plus 100 revalidation scans.
A sweep can consider 50 archive and 50 delete groups.VerifiedThe test observes archivedCount=50, deletedCount=50, failedCount=0.
The request count can reach roughly 1,500 with several thousand threads.Verified1,616 unfiltered SDK requests for the 7,600-thread fixture, each full scan requiring 16 pages.
Candidate selection traverses the catalog again for each group.Verified by sourceThe reread helper calls selectCandidates on the entire returned array.
Refreshing only known group IDs is a safe replacement.Refuted for the evaluated prototypeThe archive fresh-membership safety test passes on main but fails with known-ID snapshot overlays.

3. Environment

4. Minimal reproduction

  1. Fetch trusted origin/main and create a clean worktree at the recorded base:
    git fetch origin main
    VERIFY=$(mktemp -d)
    git worktree add --detach "$VERIFY" 7c1353d80729983b86ea1555d18b42407f320406
    cd "$VERIFY"
    pnpm install --frozen-lockfile --prefer-offline
    pnpm exec turbo run build --filter=bb-plugin-bb--storage-retention
  2. Save the complete test below as plugins/storage-retention/src/retention-sweep-budget.test.ts. It uses 7,500 pinned background threads, 50 old unarchived roots, and 50 old archived roots. Archive and delete mutate the fake transport's rows so the next read sees their effects. Both policies are 30 days.
  3. Run:
    pnpm exec turbo run test --filter=bb-plugin-bb--storage-retention -- src/retention-sweep-budget.test.ts
  4. Expected: the sweep processes both 50-root batches without re-paging unrelated catalog rows for every group; the test allows one 16-page full scan. Also, a new hidden, pinned lifecycle dependent must block its live root's archive action.

    Actual output excerpts, identical counts in both trusted-base runs:

    {"fullListCalls":1616,"returnedRows":766375}
    × bounds full-list reads while processing both retention batches
    ✓ rechecks a newly attached lifecycle dependent before archive
    AssertionError: expected 1616 to be less than or equal to 16
    Test Files  1 failed (1)
    Tests  1 failed | 1 passed (2)

    The failure is intentional and demonstrates the performance regression. The successful state assertion confirms both 50-root batches really ran. These are SDK request/row counts, not a SQL query profiler or an end-to-end latency measurement.

Complete repeatable test, including the archive fresh-membership safety check
import { expect, it } from "vitest";
import {
  createFakePluginHost,
  makeThreadResponse,
} from "@get-bb/plugin-sdk/testing";
import plugin from "./server.js";

it("bounds full-list reads while processing both retention batches", async () => {
  const rows = new Map(
    Array.from({ length: 7600 }, (_, index) => {
      const thread = makeThreadResponse({
        id: `thr_budget_${String(index).padStart(5, "0")}`,
        updatedAt: 1,
        archivedAt: index >= 50 && index < 100 ? 1 : null,
        pinnedAt: index >= 100 ? 1 : null,
      });
      return [thread.id, thread];
    }),
  );
  let fullListCalls = 0;
  let returnedRows = 0;
  const host = createFakePluginHost({
    pluginId: "storage-retention",
    sdk: {
      threads: {
        list: async (input) => {
          const all = [...rows.values()];
          const requested = input?.threadIds;
          const selected = requested
            ? all.filter((thread) => requested.includes(thread.id))
            : all;
          if (input?.threadIds === undefined) fullListCalls++;
          const offset = input?.offset ?? 0;
          const page = selected.slice(offset, offset + (input?.limit ?? 500));
          returnedRows += page.length;
          return page;
        },
        archive: async ({ threadId }) => {
          rows.get(threadId)!.archivedAt = Date.now();
          return { archivedThreadIds: [threadId] };
        },
        delete: async ({ threadId }) => {
          rows.delete(threadId);
          return { ok: true };
        },
      },
    },
  });
  try {
    plugin(host.bb);
    await host.harness.callRpc("configure", {
      archiveAfterDays: 30,
      deleteAfterDays: 30,
    });
    await host.harness.runSchedule("retention");
    expect(await host.harness.callRpc("state", null)).toMatchObject({
      lastRun: { archivedCount: 50, deletedCount: 50, failedCount: 0 },
    });
    console.log(JSON.stringify({ fullListCalls, returnedRows }));
    expect(fullListCalls).toBeLessThanOrEqual(16);
  } finally {
    await host.harness.dispose();
  }
});

it("rechecks a newly attached lifecycle dependent before archive", async () => {
  const root = makeThreadResponse({
    id: "thr_root",
    updatedAt: 1,
    archivedAt: null,
  });
  const rows = new Map([[root.id, root]]);
  let initialRead = true;
  const host = createFakePluginHost({
    pluginId: "storage-retention",
    sdk: {
      threads: {
        list: async (input) => {
          const requested = input?.threadIds;
          const result = [...rows.values()].filter(
            (thread) =>
              requested === undefined || requested.includes(thread.id),
          );
          if (initialRead) {
            initialRead = false;
            const dependent = makeThreadResponse({
              id: "thr_new_dependent",
              lifecycleOwnerThreadId: root.id,
              parentThreadId: null,
              sourceThreadId: null,
              visibility: "hidden",
              updatedAt: Date.now(),
              pinnedAt: Date.now(),
            });
            rows.set(dependent.id, dependent);
          }
          return result;
        },
        archive: async ({ threadId }) => ({ archivedThreadIds: [threadId] }),
        delete: async () => ({ ok: true }),
      },
    },
  });
  try {
    plugin(host.bb);
    await host.harness.callRpc("configure", {
      archiveAfterDays: 30,
      deleteAfterDays: null,
    });
    await host.harness.runSchedule("retention");
    expect(host.harness.sdk.callsTo("threads.archive")).toHaveLength(0);
  } finally {
    await host.harness.dispose();
  }
});

5. Root cause

service.ts:39–42 defines candidates() as a full read followed by selection:

const threads = await readThreads(bb);
return selectCandidates(threads, policy, Date.now());

service.ts:66–86 calls this once before the loops and again for each root, even though the second result is only used to find that one root. The two action loops each cap candidates at 50. sdk-data.ts:1–16 requests pages of 500 until a short page, without a filter restricting the catalog.

Consequently the 100-root fixture invokes the complete selection 101 times. All full reads still contain at least 7,550 rows, so every read needs 16 pages: 101 × 16 = 1,616. Deletions reduce the later row counts, explaining the measured total of 766,375 returned rows rather than 101 identical 7,600-row responses. policy.ts:32–79 also rebuilds relationship indexes and traverses roots on every call.

Why targeted rereads alone are insufficient

The eligibility graph includes lifecycle ownership, parentage, and hidden source references, not just a fixed set of IDs. policy.ts:46–51 links lifecycle dependents into both archive and delete groups. For a live archive root, a dependent that appears after the initial snapshot is absent from the known-ID set; refreshing the root, its old members, and its parent/source cannot discover it. The safety test inserts exactly that new hidden dependent between selection and revalidation; main correctly skips the root.

Existing APIs do not directly provide the complete replacement graph: thread-list filters have parent/source/ID filters but no lifecycle-owner filter; descendants traversal follows parentage only; and cascade API contract deliberately omits hidden threads. archive cascade implementation does include lifecycle, child, and hidden source relationships, so missing those eligibility exemptions is unsafe.

6. Proposed fix and simple-fix decision

Separate the initial selection from fresh, bounded revalidation, but retain discovery of newly attached lifecycle dependents and hidden source threads. A scoped relationship query or a proven membership-aware invalidation design could support this. The repair must preserve policy changes, pin/unarchive exemptions, disposal handling, and the existing batch limits; continue to use the plugin's existing SDK and CLI surfaces.

The evaluated local prototype read a snapshot once, refreshed known group members plus the root's parent/source by ID, removed missing rows, and reran selection over the overlay. It passed the load budget but failed the archive safety check:

{"fullListCalls":16,"returnedRows":7700}
✓ bounds full-list reads while processing both retention batches
× rechecks a newly attached lifecycle dependent before archive
AssertionError: expected [ [ { threadId: 'thr_root' } ] ] to have a length of +0 but got 1
Tests  1 failed | 1 passed (2)

That failure records unsafe archive SDK dispatch, not mutation of real data. A time-to-live would not discover a dependent attached before that interval expires. The prototype was stopped and fully reverted because preserving behavior is a mandatory simple-fix gate. No branch was pushed and no pull request was opened. A different fresh-membership strategy needs further design/verification rather than silently weakening retention safety.

7. Verification

The same agent repeated the reproduction in a second, clean temporary worktree pinned to the full trusted base commit, with its own frozen install and owning-package dependency build. The only source addition there was the authored test above. Running the exact Turbo reproduction command again exited 1 with 1,616 full-list requests, 766,375 returned rows, one intentional budget failure, and the archive safety check passing. This is a second clean run, not an independent review. Verification correction: an earlier version also injected a new lifecycle dependent under an already archived root. That delete fixture was removed because thread creation requires a live lifecycle owner (see liveThread and owner validation). Both trusted-base reproductions were rerun with the corrected two-test file, and the prototype was rerun and rejected on the reachable archive case alone. The performance verdict and counts are unchanged.

After rejecting and reverting the prototype, the existing plugin suites passed:

pnpm exec turbo run test --filter=bb-plugin-bb--storage-retention -- src/retention.test.ts src/storage.test.ts src/disk-usage.test.ts app.test.tsx
Test Files  4 passed (4)
Tests  88 passed (88)

git diff --check passed; there were no binary changes. The rejected prototype changed 24 production text lines (21 added, 3 removed) in one subsystem; the authored test has 115 added lines, for 139 total across two files. Size was not the stopping condition; the failed archive safety test was. All production source was restored byte-for-byte.

8. Related issues and pull requests

No open pull request linking #7340 was found in issue timeline metadata or a repository-scoped open-PR search for the numeric issue reference before the fix assessment. Existing eligibility-refresh coverage already checks changes to known pinned/unarchived threads; the new checks cover previously unknown dependents instead. #5730 concerns general storage growth, not this per-group request amplification; no duplicate conclusion is asserted.

9. Appendix and limits

The issue and comments were treated only as untrusted claims. Suggested implementation instructions were not executed; the tests and rejected prototype were authored from trusted repository code. There were no issue comments or linked open pull requests at the time of review. No external issue links, attachment scripts, or PR branches were used.

Setup in both checkouts used the frozen install and scoped Turbo build commands shown above. The full existing plugin test command is recorded in Verification. The temporary prototype ran only the two corrected focused tests. Raw logs and the test remain in local investigation storage; per this public reports repository's rules the reproduction is published inline, not as separate test/log files. This is not a measurement of wall-clock production impact, and the pinned background fixtures intentionally isolate list amplification from unrelated retention eligibility behavior.