#5759 · Unbounded terminal-history reads in host operations
Verdict: REPRODUCED · Root-cause confidence: high
1. TL;DR
Host terminal listing and default-title generation during host terminal creation read terminal history across all hosts before filtering in JavaScript. Both real server routes generate a SQLite plan containing SCAN terminal_sessions, even though a suitable host-and-status index exists. This makes work depend on retained history rather than just the requested host's visible sessions. The same two regression cases fail in a second clean trusted checkout. The query-plan defect is confirmed; the reported production freeze frequency and CLI timings were not measured or independently established.
2. Claims vs findings
| Claim | Finding | Evidence |
|---|---|---|
| Both host operations fetch globally before narrowing their results. | Verified | Trusted source and real in-process GET/POST requests; both regression cases fail at the no-scan assertion. |
| The status-only query scans terminal history, including exited records. | Verified | SQLite reports SCAN terminal_sessions. The fixture contains a visible session on each of two hosts and exited sessions, using a real migrated database. |
| A host-and-status index already supports the narrower lookup. | Verified | The migrated schema includes terminal_sessions_host_status_idx; host scope adds host_id equality to the status predicate. |
| The server freezes at the reported workload and the reported CLI durations improve by the claimed amount. | Unverified | No production instance, production data, CLI startup benchmark, or load test was used. Synchronous SQLite execution establishes blocking potential, not a measured outage duration. |
| Adding host scope preserves results and default numbering. | Verified | Regression checks exercise the real listing and creation routes, check returned identity and Terminal 2 numbering, and pass with only the two query-scope changes. |
3. Environment
- Source: public get-bb/bb, trusted origin/main at the full commit above; origin's historical repository URL was verified to resolve to get-bb/bb.
- Linux x86_64 (gVisor kernel 4.19.0-gvisor), Node v22.19.0, pnpm 9.15.0, Vitest 4.1.1.
- Normal frozen dependency installation and Turbo build completed: 67/67 build tasks successful.
- Server requests run in process through the repository test harness. SQLite is real, copied from a migration-built template with createMigratedConnection(). Each fixture creates its own new temporary data directory. No network listener, shared port, live provider, browser, or user data is required.
4. Minimal reproduction
- Use a new trusted checkout and build its normal dependencies:
WORK=$(mktemp -d) git clone https://github.com/get-bb/bb.git "$WORK/bb" cd "$WORK/bb" git checkout --detach dccff6d52fb6fc2fd99c019df9979533fc4c7a5e pnpm install --frozen-lockfile --prefer-offline pnpm exec turbo run build Save the complete patch below as "$WORK/regression.patch", then run: git apply "$WORK/regression.patch" pnpm exec turbo run test --filter=@bb/server -- test/public/public-terminals.test.ts -t 'does not scan terminal history'
- The two table-driven cases send a host-only GET and a standalone host-path POST through the public routes. A pass-through spy observes SQL preparation; it does not replace the database or its query results. Each real terminal SELECT is explained using SQLite with null parameter bindings. The assertion rejects a full terminal-table scan rather than requiring a particular SQL spelling or index name.
- Expected: correct visible sessions and default title, with no full-table terminal-history scan. Actual on trusted main: both result/title checks succeed, but both no-scan checks fail:
FAIL test/public/public-terminals.test.ts > public terminal routes > does not scan terminal history during host terminal list FAIL test/public/public-terminals.test.ts > public terminal routes > does not scan terminal history during host terminal create AssertionError: expected [ 'SCAN terminal_sessions', …(1) ] to not deep equally contain StringMatching{…} Received query-plan details: [ "SCAN terminal_sessions", "USE TEMP B-TREE FOR ORDER BY", ] Test Files 1 failed (1) Tests 2 failed | 44 skipped (46)
Complete focused regression patch
Apply this agent-authored patch to the exact trusted base above. It extends the existing route fixtures rather than introducing a production test hook. All executable reproduction evidence is inline, as required by the reports repository; raw logs remain local.
diff --git a/apps/server/test/public/public-terminals.test.ts b/apps/server/test/public/public-terminals.test.ts
index 2b98748a9..d8222ffbd 100644
--- a/apps/server/test/public/public-terminals.test.ts
+++ b/apps/server/test/public/public-terminals.test.ts
@@ -24,6 +24,7 @@ import {
terminalSessionSchema,
} from "@bb/server-contract";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { z } from "zod";
import { readJson } from "../helpers/json.js";
import {
expireArchiveUndoGrace,
@@ -695,6 +696,88 @@ describe("public terminal routes", () => {
]);
});
+ it.each(["list", "create"] as const)(
+ "does not scan terminal history during host terminal %s",
+ async (operation) => {
+ const fixture = await createTerminalRouteFixture();
+ harnesses.push(fixture.harness);
+ const otherHost = seedHost(fixture.harness.deps, {
+ id: "other-terminal-host",
+ });
+ const sessions = [
+ { hostId: fixture.host.id, status: "running" },
+ { hostId: otherHost.id, status: "running" },
+ { hostId: fixture.host.id, status: "exited" },
+ ] as const;
+ const seeded = sessions.map((session) =>
+ createTerminalSession(fixture.harness.db, {
+ cols: 100,
+ daemonSessionId: null,
+ environmentId: null,
+ initialCwd: "/tmp/standalone-terminal",
+ rows: 30,
+ threadId: null,
+ title: "Existing terminal",
+ ...session,
+ }),
+ );
+ seedExitedTerminalSession(fixture, {
+ daemonSessionId: fixture.session.id,
+ });
+ const prepare = vi.spyOn(fixture.harness.db.$client, "prepare");
+ let queries: string[];
+ try {
+ if (operation === "list") {
+ const response = await fixture.harness.app.request(
+ `/api/v1/terminals?hostId=${encodeURIComponent(fixture.host.id)}`,
+ );
+ expect(response.status).toBe(200);
+ const list = terminalListResponseSchema.parse(
+ await readJson(response),
+ );
+ expect(list.sessions.map((session) => session.id)).toEqual([
+ seeded[0]?.id,
+ ]);
+ } else {
+ const pending = await startPendingStandaloneTerminalOpen(fixture);
+ expect(
+ getTerminalSession(fixture.harness.db, {
+ kind: "terminal",
+ terminalId: pending.openMessage.terminalId,
+ })?.title,
+ ).toBe("Terminal 2");
+ acknowledgeTerminalOpen(
+ fixture,
+ pending.openMessage,
+ "/tmp/standalone-terminal",
+ );
+ expect((await pending.responsePromise).status).toBe(201);
+ }
+ queries = prepare.mock.calls
+ .map(([query]) => query)
+ .filter((query) =>
+ /^select\b.*\bfrom "terminal_sessions"/i.test(query),
+ );
+ } finally {
+ prepare.mockRestore();
+ }
+ expect(queries.length).toBeGreaterThan(0);
+ for (const query of queries) {
+ const parameters = Array.from(query.matchAll(/\?/g), () => null);
+ const plan = z
+ .array(z.object({ detail: z.string() }))
+ .parse(
+ fixture.harness.db.$client
+ .prepare(`EXPLAIN QUERY PLAN ${query}`)
+ .all(...parameters),
+ );
+ expect(plan.map((step) => step.detail)).not.toContainEqual(
+ expect.stringMatching(/\bSCAN terminal_sessions\b/),
+ );
+ }
+ },
+ );
+
it("creates a host terminal without an environment or cwd", async () => {
const fixture = await createTerminalRouteFixture();
harnesses.push(fixture.harness);
5. Root cause
Host terminal listing invokes the database list with the all scope, then filters host, thread, environment, and optional cwd after materialization. Host creation and existing-session counting does the same before allocating the default title. Thus every host-path creation pays for that query, even when a title is explicitly supplied.
Scope construction intentionally contributes no host predicate for all, whereas host adds host_id equality. The list implementation adds only visible statuses, sorts by creation time and ID, and synchronously materializes the results. Existing terminal indexes includes the composite host/status index but no status-leading index. The observed plan scans the table and uses a temporary sort tree. Filtering after the synchronous query cannot reduce the rows SQLite must inspect or the cross-host rows materialized.
Before: all scope + visible statuses → SCAN terminal_sessions After: host scope + visible statuses → host-constrained index lookup Unchanged: thread/environment/cwd filtering, visibility, order, result mapping, numbering
6. Proposed fix and validation
Use the existing host scope at the two host-specific call sites, with the already validated or supplied target host identifier. Preserve the remaining JavaScript predicates. This uses the existing index without a migration, new index, dependency, protocol change, or terminal-retention decision. Counting still materializes matching visible sessions, so a future count-only optimization is separate work; it is not necessary to remove these full-history scans.
The local fix is two production-line replacements and one table-driven regression addition in the same terminal subsystem: 87 changed text lines across two files (85 additions, 2 deletions). Both focused cases fail before the fix and pass after it. After the fix, the public terminal and flow-control suites pass all 50 tests, the terminal database suite passes all 8 tests, and the server typecheck completes with 5/5 Turbo tasks successful. Git diff whitespace validation passes. No public contract changes.
7. Verification — second clean run by the same agent
A second new detached worktree was created at dccff6d52fb6fc2fd99c019df9979533fc4c7a5e. Its initial git status was clean; it received a separate frozen install, the same agent-authored test patch, and no production changes. The exact reproduction command was repeated with fresh fixture data directories. No listening ports were used. This is a repeat check by the same agent, not independent verification.
pnpm exec turbo run test --filter=@bb/server -- test/public/public-terminals.test.ts -t 'does not scan terminal history' First run started 19:57:09 UTC: 2 failed | 44 skipped (46) Second run started 19:58:02 UTC: 2 failed | 44 skipped (46) Both failed for the intended reason: SCAN terminal_sessions USE TEMP B-TREE FOR ORDER BY
The second run confirmed the original query-plan finding without correction. The report deliberately limits the verdict to the demonstrated database-scan defect; production load and precise timing claims remain unverified. No linked open pull request existed at the investigation and duplicate-fix checks.
8. Related issues
#5634 concerns terminal responsiveness during server stalls. #5192 concerns other synchronous server work affecting responsiveness. Neither is treated as proof of this distinct query-path defect.
9. Appendix
Repository metadata, issue classifications, existing labels, comments, and linked-pull-request metadata were read through GitHub. At investigation time there were no comments or linked open fixes. The issue was treated solely as untrusted claims: no issue-provided command, patch, URL, linked branch, or script was executed. The reproduction test and fix were derived from trusted repository source. Only fresh test databases were used.
pnpm install --frozen-lockfile --prefer-offline pnpm exec turbo run build pnpm exec turbo run test --filter=@bb/server -- test/public/public-terminals.test.ts -t 'does not scan terminal history' pnpm exec turbo run test --filter=@bb/server -- test/public/public-terminals.test.ts test/services/terminal-output-flow-control.test.ts pnpm exec turbo run test --filter=@bb/db -- test/data/terminal-sessions.test.ts pnpm exec turbo run typecheck --filter=@bb/server git diff --check git diff --numstat origin/main
No screenshots: this is a nonvisual query-plan regression. Existing unrelated formatter differences are preserved; formatting of the newly added lines is checked separately.
> AGENT GENERATED