Reports

#7697 · Redundant validation on successful daemon RPC sends

BugPriority: LowEffort: Lowhost · perf · confirmed-reproGitHub issue2026-11-17

Trusted base: 1320c88e8abdd3f145bc9a5c305eace269fb2f28. Verdict: REPRODUCED. Root-cause confidence: high.

1. TL;DR

Successful host RPC results incur redundant validation before leaving the daemon. The command router already normalizes the response, but the shared send path parses it again through the outgoing message union. A synthetic 322,599-byte plugin result passes through the real send method and triggers one additional parse, producing a new but deeply equal response. Both trusted checkouts fail the zero-additional-validation assertion for this exact reason. The measurements characterize a CPU cost, not a measured end-user latency or production throughput claim.

2. Claims vs findings

ClaimFindingEvidence
The router and send path both validate successes.VerifiedRouter source plus instrumentation of the actual ServerConnection.sendMessage method.
The outgoing union has 18 alternatives and RPC responses are last.Verifiedsession.ts:914–933 at the trusted base.
Large JSON results are copied by the second parse.Verified for this fixtureThe additional parse returns a distinct object that is deeply equal to the router-schema-normalized input.
Specific reporter timings hold on another machine.Not establishedThis report uses a different runtime and a separately designed 4,096-entry fixture; exact timings are not portable.
The router validation must remain, and failure responses still need validation.SupportedRouter catch builds failures directly; malformed-request handling also builds a failure directly.
All schemas in this path lack transformations.Not exhaustively establishedDeep equality is checked for the exercised payload only; no blanket claim about all response types.
The server validates received messages.Verified staticallydaemon-protocol.ts:145–156 passes the outgoing schema to parseSocketMessage.

3. Environment

Public repository get-bb/bb; origin/main resolved to the full base SHA above. Linux 4.19.0-gvisor; Node v22.19.0; pnpm 9.15.0; Vitest 4.1.12. No provider, browser, daemon process, listening port, account, or real runtime data is needed. The repository transport fixture simulates an open socket and records the exact bytes sent.

Frozen installs succeeded in both checkouts. A full pnpm exec turbo run build was attempted in each; both stopped in the unrelated bb-plugin-github build because its installed SDK lacked built dist/process.js and dist/host.js. No dependency or production code was changed to bypass that failure. The normal Turbo focused-test task and its prerequisites ran successfully up to the intended assertion.

4. Minimal reproduction

  1. Use the trusted repository and recorded commit, install with the frozen lockfile, and attempt the normal build.
  2. Save the diagnostic patch below and apply it. It adds only one test alongside the repository-owned socket fixture.
  3. Run the filtered Turbo command. Exit 1 is expected on the base; the failure must be the validation-budget assertion, not setup or schema rejection.
git clone --branch main https://github.com/get-bb/bb.git bb-rpc-repro
cd bb-rpc-repro
git checkout --detach 1320c88e8abdd3f145bc9a5c305eace269fb2f28
pnpm install --frozen-lockfile --prefer-offline
pnpm exec turbo run build
# If the unrelated plugin SDK build failure below occurs, the focused test still runs.
# Save the complete patch below as /tmp/issue-7697.patch.
git apply /tmp/issue-7697.patch
pnpm exec turbo run test --filter=@bb/host-daemon -- server-connection -t "SlopCop 7697 validation budget"

Expected: the previously normalized response is sent unchanged with zero extra outgoing-schema parses. Actual: wire JSON is correct, but an additional parse occurs and allocates another equivalent object.

First run, verbatim relevant output

@bb/host-daemon:test: sendMessage redundant validations: 1
@bb/host-daemon:test: payload bytes: 322599
@bb/host-daemon:test: response validation: 11.553 ms/operation
@bb/host-daemon:test: outgoing validation: 12.270 ms/operation
@bb/host-daemon:test: serialization: 1.225 ms/operation
@bb/host-daemon:test: AssertionError: already validated response must not be parsed again: expected 1 to be +0 // Object.is equality
@bb/host-daemon:test:  Test Files  1 failed (1)
@bb/host-daemon:test:       Tests  1 failed | 22 skipped (23)

Diagnostic test

Insert this block before the first fixture interface in apps/host-daemon/src/server-connection.test.ts; it reuses that file’s existing imports and fixture. The conditional identity check diagnoses the existing redundant copy but does not require that copy after a future fix. Timing has no pass/fail threshold.

describe("SlopCop 7697 validation budget", () => {
  it("does not revalidate an already normalized RPC result", async () => {
    const {
      hostDaemonOnlineRpcResponseMessageSchema: responseSchema,
      hostDaemonDaemonWsMessageSchema: outgoingSchema,
    } = await import("@bb/host-daemon-contract");
    const { connection, webSocket } = createConnectionFixture();
    await connection.start();
    const response = responseSchema.parse({
      type: "host-rpc.response",
      requestId: "validation-budget",
      commandType: "plugin.host.call",
      ok: true,
      result: {
        output: Array.from({ length: 4096 }, (_, entryIndex) => ({
          name: `entry-${entryIndex}.txt`,
          change: "modified",
          counts: { added: entryIndex % 7, removed: entryIndex % 3 },
        })),
      },
    });
    const parse = vi.spyOn(outgoingSchema, "parse");
    try {
      expect(connection.sendMessage(response)).toBe(true);
      expect(webSocket.sockets[0]?.send).toHaveBeenCalledWith(
        JSON.stringify(response),
      );
      const sendParseCount = parse.mock.calls.length;
      const reparsed = parse.mock.results[0]?.value;
      if (sendParseCount > 0) {
        expect(reparsed).toEqual(response);
        expect(reparsed).not.toBe(response);
      }
      parse.mockRestore();
      const measurements = [
        ["response validation", () => responseSchema.parse(response)],
        ["outgoing validation", () => outgoingSchema.parse(response)],
        ["serialization", () => JSON.stringify(response)],
      ] satisfies Array<[string, () => unknown]>;
      console.log(`sendMessage redundant validations: ${sendParseCount}`);
      console.log(`payload bytes: ${Buffer.byteLength(JSON.stringify(response))}`);
      for (const [label, operation] of measurements) {
        for (let warmup = 0; warmup < 8; warmup += 1) operation();
        const startedAt = performance.now();
        for (let iteration = 0; iteration < 40; iteration += 1) operation();
        console.log(`${label}: ${((performance.now() - startedAt) / 40).toFixed(3)} ms/operation`);
      }
      expect(sendParseCount, "already validated response must not be parsed again").toBe(0);
    } finally {
      parse.mockRestore();
      await connection.shutdown();
    }
  });
});

Complete applicable patch
diff --git a/apps/host-daemon/src/server-connection.test.ts b/apps/host-daemon/src/server-connection.test.ts
index 92514640c3..0e16d5ea26 100644
--- a/apps/host-daemon/src/server-connection.test.ts
+++ b/apps/host-daemon/src/server-connection.test.ts
@@ -12,6 +12,61 @@ import type {
   ServerMovedNotice,
 } from "./server-connection-support.js";
 
+describe("SlopCop 7697 validation budget", () => {
+  it("does not revalidate an already normalized RPC result", async () => {
+    const {
+      hostDaemonOnlineRpcResponseMessageSchema: responseSchema,
+      hostDaemonDaemonWsMessageSchema: outgoingSchema,
+    } = await import("@bb/host-daemon-contract");
+    const { connection, webSocket } = createConnectionFixture();
+    await connection.start();
+    const response = responseSchema.parse({
+      type: "host-rpc.response",
+      requestId: "validation-budget",
+      commandType: "plugin.host.call",
+      ok: true,
+      result: {
+        output: Array.from({ length: 4096 }, (_, entryIndex) => ({
+          name: `entry-${entryIndex}.txt`,
+          change: "modified",
+          counts: { added: entryIndex % 7, removed: entryIndex % 3 },
+        })),
+      },
+    });
+    const parse = vi.spyOn(outgoingSchema, "parse");
+    try {
+      expect(connection.sendMessage(response)).toBe(true);
+      expect(webSocket.sockets[0]?.send).toHaveBeenCalledWith(
+        JSON.stringify(response),
+      );
+      const sendParseCount = parse.mock.calls.length;
+      const reparsed = parse.mock.results[0]?.value;
+      if (sendParseCount > 0) {
+        expect(reparsed).toEqual(response);
+        expect(reparsed).not.toBe(response);
+      }
+      parse.mockRestore();
+      const measurements = [
+        ["response validation", () => responseSchema.parse(response)],
+        ["outgoing validation", () => outgoingSchema.parse(response)],
+        ["serialization", () => JSON.stringify(response)],
+      ] satisfies Array<[string, () => unknown]>;
+      console.log(`sendMessage redundant validations: ${sendParseCount}`);
+      console.log(`payload bytes: ${Buffer.byteLength(JSON.stringify(response))}`);
+      for (const [label, operation] of measurements) {
+        for (let warmup = 0; warmup < 8; warmup += 1) operation();
+        const startedAt = performance.now();
+        for (let iteration = 0; iteration < 40; iteration += 1) operation();
+        console.log(`${label}: ${((performance.now() - startedAt) / 40).toFixed(3)} ms/operation`);
+      }
+      expect(sendParseCount, "already validated response must not be parsed again").toBe(0);
+    } finally {
+      parse.mockRestore();
+      await connection.shutdown();
+    }
+  });
+});
+
 interface CreateServerClientFixtureArgs {
   heartbeatIntervalMs?: number;
   leaseTimeoutMs?: number;

5. Root cause

The router parses a success response inside its try block, which also converts validation failures into error responses. Application wiring forwards that returned object without changing it to ServerConnection.sendMessage. The send method unconditionally parses it through the full outgoing union before serializing. For plugin results, the recursive JSON schema traverses and reconstructs the nested output again. These are two identified validation boundaries; this is not an exhaustive count of validation inside every command handler.

apps/host-daemon/src/command-router.ts:116

      const result = await runWithTurnSubmitTrace(message.command, () =>
        this.executeHostRpcCommand(message.command, abortController.signal),
      );
      this.logOnlineRpc({
        commandType: message.command.type,
        handlerMs: elapsedMs(handlerStartedAtMs),
        ok: true,
      });
      return hostDaemonOnlineRpcResponseMessageSchema.parse({
        type: "host-rpc.response",
        requestId: message.requestId,
        commandType: message.command.type,
        ok: true,
        result,
      });
    } catch (error) {

apps/host-daemon/src/app.ts:936

    onHostRpcRequest: async (message) => {
      const response = await router.handleOnlineRpcRequest(message);
      sendServerMessage(response);
    },

apps/host-daemon/src/app.ts:1025

  sendServerMessage = (message) => connection.sendMessage(message);

apps/host-daemon/src/server-connection.ts:189

  sendMessage(message: HostDaemonDaemonWsMessage): boolean {
    const parsed = hostDaemonDaemonWsMessageSchema.parse(message);
    const recoverableKey = recoverableMessageKey(parsed);
    const websocket = this.websocket;
    if (!websocket || websocket.readyState !== OPEN_READY_STATE) {
      if (recoverableKey !== null) {
        this.pendingRecoverableMessages.set(recoverableKey, parsed);
      }
      return false;
    }

    const payload = JSON.stringify(parsed);
    if (
      isTerminalDaemonOutputMessage(parsed) &&
      (this.pendingTerminalSocketPayloads.length > 0 ||

packages/host-daemon-contract/src/session.ts:914

export const hostDaemonDaemonWsMessageSchema = z.union([
  desktopBrowserChangedSchema,
  hostDaemonMachineShutdownAckMessageSchema,
  hostDaemonHeartbeatMessageSchema,
  hostDaemonEnvironmentChangeMessageSchema,
  hostDaemonThreadStorageChangeMessageSchema,
  hostDaemonEnvironmentMetadataChangeMessageSchema,
  hostDaemonConnectTunnelIdentityMessageSchema,
  hostDaemonConnectNextStatusMessageSchema,
  pluginHostWorkerExitedMessageSchema,
  pluginHostSignalMessageSchema,
  environmentHookProgressMessageSchema,
  serverMoveProgressMessageSchema,
  hostDaemonTerminalOpenedMessageSchema,
  hostDaemonTerminalOutputMessageSchema,
  hostDaemonTerminalReplayMessageSchema,
  hostDaemonTerminalExitedMessageSchema,
  hostDaemonTerminalErrorMessageSchema,
  hostDaemonOnlineRpcResponseMessageSchema,
]);

packages/host-daemon-contract/src/commands.ts:1055

const pluginHostCallResultSchema = z
  .object({ output: jsonValueSchema })
  .strict();

packages/domain/src/json-value.ts:15

export const jsonValueSchema: z.ZodType<JsonValue> = z.lazy(() =>
  z.union([
    z.string(),
    z.number(),
    z.boolean(),
    z.null(),
    z.array(jsonValueSchema),
    z.record(z.string(), jsonValueSchema),
  ]),
);

apps/server/src/ws/daemon-protocol.ts:145

export function onDaemonSocketMessage(
  deps: WorkSessionDeps & Pick<AppDeps, "sharedPorts" | "terminalSessions">,
  args: DaemonSocketMessageArgs,
  plugins?: Pick<PluginService, "handleHostSignal" | "handleHostWorkerExit">,
  serverMove?: Pick<ServerMoveCoordinator, "handleProgress">,
): void {
  deps.hub.recordDaemonActivity(args.sessionId);
  const message = parseSocketMessage(
    args.socket,
    args.raw,
    hostDaemonDaemonWsMessageSchema,
  );

6. Proposed fix

Retain router validation and avoid repeating it when sending a router-validated success. Continue validating directly constructed failures and other messages. Any fast path must preserve the assumption that its successful responses have already crossed the router validation boundary; future producers must not bypass it. No wire-schema change is necessary.

7. Linked PR review

PR #7704 — static review only

GitHub metadata shows an open PR linking this issue. Its diff changes the send method to bypass the outgoing parse only for successful host RPC responses and adds a parse-count/wire-content test. That targets the demonstrated redundant boundary while leaving failures on the existing validation path. The inspected production wiring routes successful responses through the validating router. No blocking finding follows from this narrow static review; future success producers must preserve that provenance. No PR branch, patch, or test was checked out or executed, and this report does not claim the PR passes tests. No duplicate fix PR was opened.

8. Related issues

The linked open PR is the actionable existing work item. A narrow issue search did not establish another duplicate of this mechanism; no exhaustive duplicate claim is made.

9. Verification

The same agent created a second clean temporary checkout from trusted origin/main at 1320c88e8abdd3f145bc9a5c305eace269fb2f28, checked that its initial git status was clean, repeated the frozen install and build attempt, applied only the locally authored diagnostic test, and ran the identical filtered Turbo command. The original and second runs both failed at the intended assertion with one additional parse; the wire-equality and distinct-object checks passed first. No independent-agent verification is claimed. The second run required no ports or runtime data directory. No correction to the verdict was necessary.

Second run, verbatim relevant output

@bb/host-daemon:test: sendMessage redundant validations: 1
@bb/host-daemon:test: payload bytes: 322599
@bb/host-daemon:test: response validation: 11.334 ms/operation
@bb/host-daemon:test: outgoing validation: 12.216 ms/operation
@bb/host-daemon:test: serialization: 1.226 ms/operation
@bb/host-daemon:test: AssertionError: already validated response must not be parsed again: expected 1 to be +0 // Object.is equality
@bb/host-daemon:test:  Test Files  1 failed (1)
@bb/host-daemon:test:       Tests  1 failed | 22 skipped (23)

After removing the diagnostic test, the existing server-connection and command-router suites passed: 2 files, 31 tests. This baseline check does not constitute testing the linked PR.

pnpm exec turbo run test --filter=@bb/host-daemon -- server-connection command-router
@bb/host-daemon:test:  Test Files  2 passed (2)
@bb/host-daemon:test:       Tests  31 passed (31)

10. Appendix

The reproduction uses the exact schema invoked by the router to prepare its input, then executes the real send method with a simulated socket. It does not launch a plugin worker, execute git-panel requests, or exercise live server receipt. Source links establish that the application connects those same boundaries. Microbenchmarks use 8 warmups and 40 measured operations per stage on 4,096 synthetic entries; concurrent machine activity can affect them, so the deterministic parse-count assertion is the primary evidence.

Issue and PR content was treated as untrusted evidence. No instruction, script, linked branch, or test from that content was run. The patch above was authored from the trusted base. Local raw evidence and diagnostic artifacts remain outside published git content; all copy-paste reproduction material is inline, consistent with the reports repository policy.

AGENT GENERATED