Skip to content

The open-source app everyone uses to manage agents at work

fix(db): complete bounded response attribution (#17537)

Devin Foleya12329b8a962
diff --git a/doc/DATABASE.md b/doc/DATABASE.md
index 717ec1ca0e..17fbb47f40 100644
--- a/doc/DATABASE.md
+++ b/doc/DATABASE.md
@@ -341,7 +341,7 @@ The diagnostic measures awaited Postgres.js `unsafe` responses before Drizzle
column decoding. It retains the Drizzle builder caller for normal, prepared,
transaction, and dedicated-pool execution. It issues no queries.
It logs the public server caller locations, static schema table, operation,
-query/row counts, and response value sizes. It emits at most 512 aggregate
+query/row counts, and response value sizes. It emits at most 2,048 aggregate
groups and a summary at the deadline. It never logs SQL, parameters, result
values, connection strings, or query errors. In-flight queries continue normally.
@@ -355,6 +355,25 @@ Look for `paperclip.db_response_capture.entry.v1` and
can store `event` as a structured field instead of message text. Filter by that
field or read the bounded window from the exact deployment. Check the summary
and group totals, including the unattributed overflow group.
+
+Fetch a complete capture as follows:
+
+1. Read the summary events from the exact deployment and window. Keep each
+ distinct `captureId` separately.
+2. Each entry has a unique `groupIndex` within that capture and a `groupPage`.
+ The summary gives `groupPageSize` (128) and `groupPages`. Fetch every page
+ from zero through `groupPages - 1`, filtering on the entry event, `captureId`,
+ and `groupPage`. Request at least `groupPageSize` matching records per page.
+ A structured query can use
+ `@event:paperclip.db_response_capture.entry.v1 AND @captureId:<id> AND @groupPage:0`.
+3. If the provider's record limit is smaller than a page, fetch each
+ `groupIndex` separately with the same capture ID. Each index matches one
+ entry. Do not split by timestamp: entries can share a timestamp.
+4. Deduplicate by `(captureId, groupIndex)`. Require every index from zero
+ through `groups - 1`, with no gaps. Entry count must equal `groups`, summed
+ `calls` must equal `completedQueries`, and summed `responseValueBytes` must
+ equal the summary total. A missing page is an incomplete measurement.
+
Tagged raw-driver calls, streams, unawaited raw-driver
dispatch, and protocol overhead are not measured. Relational queries use a driver-level caller fallback.
Queries still in flight at the deadline are reported separately. Sizes describe
diff --git a/packages/db/src/response-capture.test.ts b/packages/db/src/response-capture.test.ts
index 4b87c7924a..9fc1c80f5b 100644
--- a/packages/db/src/response-capture.test.ts
+++ b/packages/db/src/response-capture.test.ts
@@ -107,12 +107,31 @@ describe("bounded database response capture", () => {
});
it("bounds cardinality without dropping response-byte totals", () => {
const f = fixture();
- for (let i = 0; i < 600; i += 1) f.capture.execute(() => [i], { ...metadata, callers: [`services/f${i}.ts:1:1`] });
+ for (let i = 0; i < 2200; i += 1) f.capture.execute(() => [i], { ...metadata, callers: [`services/f${i}.ts:1:1`] });
f.capture.flush();
const summary = f.events.at(-1)!;
- expect(summary).toMatchObject({ startedQueries: 600, completedQueries: 600, groups: 512, overflowCalls: 89 });
- expect(f.events).toHaveLength(513);
- expect(summary.responseValueBytes).toBe(Array.from({ length: 600 }, (_, i) => Buffer.byteLength(JSON.stringify([i]))).reduce((a, b) => a + b, 0));
+ expect(summary).toMatchObject({ startedQueries: 2200, completedQueries: 2200, groups: 2048, overflowCalls: 153,
+ groupPageSize: 128, groupPages: 16 });
+ expect(f.events).toHaveLength(2049);
+ const entries = f.events.slice(0, -1);
+ expect(entries.map(entry => entry.groupIndex)).toEqual(Array.from({ length: 2048 }, (_, index) => index));
+ for (let page = 0; page < 16; page += 1) {
+ expect(entries.filter(entry => entry.groupPage === page)).toHaveLength(128);
+ }
+ expect(entries.reduce((sum, entry) => sum + Number(entry.calls), 0)).toBe(2200);
+ expect(summary.responseValueBytes).toBe(Array.from({ length: 2200 }, (_, i) => Buffer.byteLength(JSON.stringify([i]))).reduce((a, b) => a + b, 0));
+ });
+ it.each([0, 129])("numbers every page including an empty or partial final page (%s)", count => {
+ const f = fixture();
+ for (let index = 0; index < count; index += 1) {
+ f.capture.execute(() => [index], { ...metadata, callers: [`services/page${index}.ts:1:1`] });
+ }
+ f.capture.flush();
+ const entries = f.events.slice(0, -1), summary = f.events.at(-1)!;
+ expect(summary).toMatchObject({ groups: count, groupPageSize: 128, groupPages: Math.ceil(count / 128) });
+ expect(entries.map(entry => entry.groupIndex)).toEqual(Array.from({ length: count }, (_, index) => index));
+ expect(entries.filter(entry => entry.groupPage === 0)).toHaveLength(Math.min(count, 128));
+ expect(entries.filter(entry => entry.groupPage === 1)).toHaveLength(Math.max(0, count - 128));
});
it("does not execute builders or prepared statements until requested", async () => {
const f = fixture(), rows = [{ id: 1 }], execute = vi.fn(async () => rows);
diff --git a/packages/db/src/response-capture.ts b/packages/db/src/response-capture.ts
index f8e6da8e87..675d57eeb8 100644
--- a/packages/db/src/response-capture.ts
+++ b/packages/db/src/response-capture.ts
@@ -7,6 +7,7 @@ type Entry = Metadata & { calls: number; rows: number; bytes: number; maxBytes:
type Event = Record<string, unknown>;
type Method = (this: unknown, ...args: unknown[]) => unknown;
export type ResponseCaptureWindow = { start: number; end: number };
+const GROUP_PAGE_SIZE = 128;
export function responseCaptureWindow(value: string | undefined, now = Date.now()): ResponseCaptureWindow | undefined {
if (!value) return;
@@ -76,7 +77,8 @@ export function createDatabaseResponseCapture(
clearTimeout(timer);
scope.disable();
const ordered = [...entries.values()].sort((a, b) => b.bytes - a.bytes);
- for (const entry of ordered) send({ event: "paperclip.db_response_capture.entry.v1", captureId: id,
+ for (const [groupIndex, entry] of ordered.entries()) send({ event: "paperclip.db_response_capture.entry.v1", captureId: id,
+ groupIndex, groupPage: Math.floor(groupIndex / GROUP_PAGE_SIZE),
operation: entry.operation, table: entry.table, callers: entry.callers, calls: entry.calls, rows: entry.rows,
responseValueBytes: entry.bytes, maxResponseValueBytes: entry.maxBytes, estimatedValues: entry.estimatedValues,
queryErrors: entry.queryErrors, serializationErrors: entry.serializationErrors });
@@ -84,6 +86,7 @@ export function createDatabaseResponseCapture(
windowStart: new Date(window.start).toISOString(), windowEnd: new Date(window.end).toISOString(),
closedAt: new Date(now()).toISOString(),
startedQueries: started, completedQueries: completed, inFlightAtEnd: inFlight, groups: entries.size,
+ groupPageSize: GROUP_PAGE_SIZE, groupPages: Math.ceil(ordered.length / GROUP_PAGE_SIZE),
overflowCalls, responseValueBytes: ordered.reduce((sum, entry) => sum + entry.bytes, 0),
rowValuesLogged: false, sqlOrParametersLogged: false, wireBytesMeasured: false,
measurementBoundary: "postgres-js results before Drizzle column decoding",
@@ -99,7 +102,7 @@ export function createDatabaseResponseCapture(
completed += 1;
try {
let key = JSON.stringify(metadata);
- if (!entries.has(key) && entries.size >= 511) {
+ if (!entries.has(key) && entries.size >= 2047) {
overflowCalls += 1;
metadata = { operation: "other", table: "other", callers: [] };
key = "overflow";