mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-09 16:02:36 +01:00
## Thinking Path > - Paperclip manages agent work through shared server and database services. > - High query volume can spend main-thread time on SQL construction and result decoding. > - The existing bounded response capture counts rows and bytes, but it cannot name the operation that executed a query. > - Bundled callers can be missing, and measuring every parsed JSON value adds work to the diagnostic. > - This pull request carries a semantic execution owner into each measured query and bounds response sizing. > - Operators can rank query volume by owner before choosing a performance fix. ## Linked Issues or Issue Description Refs #17504, #17522, #17537, #17564. **What existing behavior does this improve?** The opt-in `PAPERCLIP_DB_RESPONSE_CAPTURE_WINDOW` diagnostic. **Subsystem affected** Database diagnostics and existing server execution boundaries. **Current behavior** The capture groups by table, operation, and builder caller. It cannot distinguish execution owners that reuse a prepared query. Bundled deployments need source maps for caller locations. The capture visits every returned value and serializes parsed JSON again to estimate its size. **Proposed behavior** Version 2 captures use fixed semantic owners for HTTP requests, delivery queues, execution phases, and budget work. They count completed calls, returned rows, errors, and completion wall time. They sample successful results 1, 17, 33, and so on, with fixed cell and string/byte limits. Complex values remain explicitly unmeasured. Semantic ownership works without source maps. **Reason and benefit** A short census can identify which operations issue the most queries or return the most rows. It preserves each query's execution owner through pooled connections, concurrent operations, and prepared-query reuse. It reduces diagnostic work without claiming per-query CPU attribution. **Breaking changes** Opt-in capture output moves from `entry.v1`/`summary.v1` to `entry.v2`/`summary.v2`. Sampled primitive byte lower bounds replace all-result byte estimates. Consumers must use the new fields and must not extrapolate them into a total. There is no database migration or application API change. ## What Changed - Added `withDatabaseOperation(owner, action)` to the DB package. The server owns semantic labels. Queries retain execution ownership in their completion closure. - Added fixed owners at existing HTTP, delivery, budget, and execution timing boundaries. Delivery work replaces the context of the producer that woke it. - Added complete call/row/error counters and completion wall durations within the existing bounded window. Durations include waits and are not CPU measurements. - Sampled and bounded primitive-value sizing. Complex and oversized values remain unmeasured. Known owners skip repeated stack extraction. - Preserved the deadline, group limit, paced output, query outcomes, and existing coverage exclusions. Updated the operator documentation. - Added real PostgreSQL owner-isolation and prepared-query tests, server scope tests, and plain bundled-runtime proof. - Moved projection-test and benchmark full-response sizing into an explicit test helper. Existing payload-size thresholds remain unchanged; these synthetic checks do not use the production sampler. ## Verification - Final-commit DB capture suites: 43 tests passed in 13.86 seconds against the actual PostgreSQL driver, including concurrent owners, prepared reuse, transaction failure, a dedicated client, sampling, and a query crossing the deadline. DB typecheck passed. - Server attribution and existing delivery/execution/budget suites: 53 tests passed. Final concurrent HTTP GET/JSON POST scope refinement: 5 tests passed. - Runtime bundle suite: 8 existing tests passed. The new no-source-map owner test passed after its fixture was corrected to use a driver thenable. An ordinary native Promise can bypass an overridden `.then`; the real PostgreSQL tests separately cover driver integration. - Observer-only experiment: three alternating pairs per case on Node 24.22.2, macOS arm64, 3,000 calls per run after warm-up. For an already-materialized synthetic JSON result, median capture CPU fell from 82.37 to 1.87 microseconds/call. For a 100-row primitive result, it fell from 8.10 to 4.40 microseconds/call. Every result retained identity and all calls were counted. The new diagnostic intentionally measures less byte data; these are observer costs, not database latency or a hosted application speedup. Disabled-case timings were below one microsecond/call and too small for a performance conclusion. - Final lifecycle regression: 28 unit tests and DB typecheck passed. Closing the last capture disables and replaces owner storage; overlapping captures retain it. - Final-commit full recursive typecheck passed in 38.38 seconds and full build passed in 40.81 seconds. The build stamp matches `83ed4ba9cebd68d48929c46f15ab32d5c0b9687b`. Focused server attribution tests also passed 5/5 before the test-helper-only migration. Full test acceptance will use the repository's parallel CI gates; the unsharded local command takes hours. - Verification failures retained: initial sandbox runs could not open local IPC/PostgreSQL listeners; permitted reruns exercised the real services. One old test expected JSON serialization and was updated to assert explicit unmeasured complex values. The first bundle fixture used the wrong promise boundary, as described above. A retained-callback regression also demonstrated that disabling and reusing the same AsyncLocalStorage instance could resurrect an old owner; replacing the instance after the last capture closes fixes that case. - The first CI run found older projection tests consuming the previous full-response fields. Those consumers now use the full-response test helper, preserving their byte thresholds. The two complete affected route suites plus helper tests passed 115/115 in 73.08 seconds. A temporary full-row query negative control then failed the unchanged 2,048-byte limit at 5,000,812 bytes and was restored; five other service suites passed 34/34 and the affected chat cases passed 3/3. All three previously failing CI shards passed on the corrected head. A local skill-list benchmark smoke check completed 255 captured queries with no in-flight queries or overflow; this was integration verification under concurrent test load, not a timing benchmark. - Two final-head runner jobs lost communication with GitHub before reporting a test result. One targeted retry of those jobs and their dependent aggregate passed. All 53 final-head checks passed, with 3 intentional skips; previously passing suites were preserved. - Hosted capture remains pending until the reviewed revision is deployed and a bounded window is explicitly configured. Reproduce the focused checks with Node 24 and the repository pnpm version: ```sh pnpm exec vitest run packages/db/src/response-capture.test.ts packages/db/src/response-capture-postgres.test.ts pnpm --dir server exec vitest run --config vitest.config.ts src/__tests__/database-operation-attribution.test.ts scripts/bundle-runtime.test.mjs pnpm -r typecheck pnpm build ``` ## Risks - Owner context is active while a valid future capture window is armed, up to 30 minutes before accounting starts. No-window and expired calls take the direct path. Diagnostics still add bounded work while enabled. - A nearest nested owner is reported. Broad `http.request` and unattributed groups remain visible; this does not identify every service callsite or SQL shape. - The existing census excludes tagged/raw explicit-execute/streaming paths and internal protocol commands. Its counts are not PostgreSQL transaction totals. - Completion wall time includes queue/database/network/scheduling waits. Concurrent durations overlap. Sampled bytes exclude complex values, large strings, and values beyond the sizing limits. - Activation is startup-only. Operators must choose the window after artifact preparation, allow rollout/warm-up time, and remove the expired setting afterward. ## Model Used OpenAI Codex, GPT-6 family, with code execution, repository inspection, and parallel agents. The exact deployment model ID and context-window size are not exposed in this session. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
174 lines
10 KiB
TypeScript
174 lines
10 KiB
TypeScript
import { randomBytes, randomUUID } from "node:crypto";
|
|
import { eq, sql, type SQL } from "drizzle-orm";
|
|
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest";
|
|
import { createDb, plugins, type Db } from "@paperclipai/db";
|
|
import { createFullDatabaseResponseCapture, installDatabaseResponseCapture } from "./helpers/full-database-response-capture.js";
|
|
import type { PaperclipPluginManifestV1, PluginEnvironmentDriverDeclaration } from "@paperclipai/shared";
|
|
import { resolvePluginSandboxProviderConfigSchema, resolvePluginSandboxProviderDriverByKey } from "../services/plugin-environment-driver.js";
|
|
import { resolveEnvironmentDriverConfigForRuntime, resolveSandboxProviderSecretRefPaths } from "../services/environment-config.js";
|
|
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
|
|
|
|
const support = await getEmbeddedPostgresTestSupport();
|
|
|
|
describe.skipIf(!support.supported)("sandbox provider schema reads", () => {
|
|
let temporary: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
|
|
let db: Db;
|
|
const clients: Db[] = [];
|
|
const key = "fixture-schema-provider";
|
|
const driver = (driverKey = key, configSchema: unknown = { type: "object" }) => ({
|
|
driverKey, kind: "sandbox_provider", displayName: "Schema fixture", configSchema,
|
|
}) as PluginEnvironmentDriverDeclaration;
|
|
const manifest = (id: string, declarations: PluginEnvironmentDriverDeclaration[]): PaperclipPluginManifestV1 => ({
|
|
id: `test.schema.${id}`, apiVersion: 1, version: "1.0.0", displayName: "Schema fixture",
|
|
description: "Fixture", author: "Test", categories: ["automation"],
|
|
capabilities: ["environment.drivers.register"], entrypoints: { worker: "worker.js" }, environmentDrivers: declarations,
|
|
});
|
|
async function seed(declarations = [driver()], installOrder = 0) {
|
|
const id = randomUUID();
|
|
await db.insert(plugins).values({
|
|
id, pluginKey: `test.schema.${id}`, packageName: "@test/schema", version: "1.0.0",
|
|
installOrder, status: "disabled", manifestJson: manifest(id, declarations),
|
|
});
|
|
return id;
|
|
}
|
|
function observer() {
|
|
const observed = createDb(temporary.connectionString);
|
|
clients.push(observed);
|
|
return observed;
|
|
}
|
|
const lookup = (client: Db, driverKey = key) => resolvePluginSandboxProviderConfigSchema({ db: client, driverKey });
|
|
async function measure<T>(client: Db, operation: () => Promise<T>) {
|
|
const events: Array<Record<string, unknown>> = [], now = Date.now();
|
|
const capture = createFullDatabaseResponseCapture({ start: now - 100, end: now + 59_000 }, event => events.push(event), () => now);
|
|
installDatabaseResponseCapture(client, { plugins }, capture);
|
|
try {
|
|
const value = await operation();
|
|
capture.flush();
|
|
const entries = events.filter(event => event.event === "paperclip.test_db_response_capture.entry.v1");
|
|
return { value, bytes: entries.reduce((sum, entry) => sum + Number(entry.responseValueBytes), 0),
|
|
calls: entries.reduce((sum, entry) => sum + Number(entry.calls), 0) };
|
|
} finally { capture.flush(); }
|
|
}
|
|
|
|
beforeAll(async () => {
|
|
temporary = await startEmbeddedPostgresTestDatabase("sandbox-schema-reads-");
|
|
db = createDb(temporary.connectionString);
|
|
}, 120_000);
|
|
beforeEach(async () => { await db.delete(plugins); });
|
|
afterEach(async () => { await Promise.all(clients.splice(0).map(client => client.$client.end())); });
|
|
afterAll(async () => { await temporary?.cleanup(); });
|
|
|
|
it("keeps runtime secret paths current without retransferring an unchanged schema", async () => {
|
|
const schema = { type: "object", description: randomBytes(16 * 1024).toString("hex"), properties: {
|
|
credentials: { type: "object", properties: { token: { type: "string", format: "secret-ref" } } },
|
|
} };
|
|
const id = await seed([driver(key, schema)]), observed = observer();
|
|
const before = await db.select().from(plugins).where(eq(plugins.id, id));
|
|
const cold = await measure(observed, () => resolveSandboxProviderSecretRefPaths(observed, key));
|
|
const warm = await measure(observed, () => resolveSandboxProviderSecretRefPaths(observed, key));
|
|
expect(cold.value).toEqual(new Set(["credentials.token"]));
|
|
expect(warm.value).toEqual(cold.value);
|
|
expect(cold.calls).toBe(1);
|
|
expect(warm.calls).toBe(1);
|
|
expect(cold.bytes).toBeGreaterThan(32 * 1024);
|
|
expect(warm.bytes).toBeLessThan(256);
|
|
const changed = { type: "object", allOf: [{ properties: { apiKey: { type: "string", format: "secret-ref" } } }] };
|
|
await db.update(plugins).set({ manifestJson: manifest(id, [driver(key, changed)]) }).where(eq(plugins.id, id));
|
|
expect(await resolveSandboxProviderSecretRefPaths(observed, key)).toEqual(new Set(["apiKey"]));
|
|
const environment = { id: randomUUID(), driver: "sandbox" as const, config: { provider: key, apiKey: randomUUID() } };
|
|
await expect(resolveEnvironmentDriverConfigForRuntime(observed, null, environment)).rejects.toThrow("companyId");
|
|
await db.update(plugins).set({ manifestJson: before[0].manifestJson }).where(eq(plugins.id, id));
|
|
expect(await db.select().from(plugins).where(eq(plugins.id, id))).toEqual(before);
|
|
});
|
|
|
|
it("preserves install order, first matching declarations, and default readiness checks", async () => {
|
|
const a = await seed([driver(key, { title: "first" }), driver(key, { title: "second" })], 1);
|
|
const b = await seed([driver(key, { title: "other plugin" })], 2), observed = observer();
|
|
expect((await lookup(observed))).toEqual({ title: "first" });
|
|
const full = await resolvePluginSandboxProviderDriverByKey({ db: observed, driverKey: key });
|
|
expect(full?.plugin.id).toBe(a);
|
|
expect(full?.plugin.status).toBe("disabled");
|
|
expect(await resolvePluginSandboxProviderDriverByKey({ db: observed, driverKey: key, requireRunning: true })).toBeNull();
|
|
await db.update(plugins).set({ installOrder: 0 }).where(eq(plugins.id, b));
|
|
expect((await lookup(observed))).toEqual({ title: "other plugin" });
|
|
await db.delete(plugins).where(eq(plugins.id, b));
|
|
expect((await lookup(observed))).toEqual({ title: "first" });
|
|
await db.update(plugins).set({ manifestJson: manifest(a, [driver("replacement")]) }).where(eq(plugins.id, a));
|
|
expect(await lookup(observed)).toBeNull();
|
|
});
|
|
|
|
it.each([null, true, "invalid", [], undefined])("preserves non-object schema behavior: %s", async value => {
|
|
const first = driver(key, value);
|
|
if (value === undefined) delete (first as Partial<PluginEnvironmentDriverDeclaration>).configSchema;
|
|
await seed([first, driver(key, { properties: { secret: { format: "secret-ref" } } })]);
|
|
const observed = observer();
|
|
expect(await resolveSandboxProviderSecretRefPaths(observed, key)).toEqual(new Set());
|
|
expect(await resolveSandboxProviderSecretRefPaths(observed, key)).toEqual(new Set());
|
|
});
|
|
|
|
it("returns independent schema objects and keeps separate database clients cold", async () => {
|
|
await seed([driver(key, { description: "x".repeat(4096), properties: { token: { format: "secret-ref" } } })]);
|
|
const a = observer(), b = observer();
|
|
const first = await lookup(a);
|
|
first!.properties = {};
|
|
expect(await resolveSandboxProviderSecretRefPaths(a, key)).toEqual(new Set(["token"]));
|
|
const warm = await measure(a, () => lookup(a)), independent = await measure(b, () => lookup(b));
|
|
expect(warm.bytes).toBeLessThan(256);
|
|
expect(independent.bytes).toBeGreaterThan(4096);
|
|
warm.value!.properties = {};
|
|
expect(await resolveSandboxProviderSecretRefPaths(a, key)).toEqual(new Set(["token"]));
|
|
});
|
|
|
|
it("bounds retained schemas and does not retain oversized definitions", async () => {
|
|
const declarations = Array.from({ length: 33 }, (_, index) => driver(`provider-${index}`, { description: "x".repeat(2048) }));
|
|
declarations.push(driver("oversized", { description: "x".repeat(128 * 1024) }));
|
|
await seed(declarations);
|
|
const observed = observer();
|
|
for (let index = 0; index < 33; index++) await lookup(observed, `provider-${index}`);
|
|
expect((await measure(observed, () => lookup(observed, "provider-32"))).bytes).toBeLessThan(256);
|
|
expect((await measure(observed, () => lookup(observed, "provider-0"))).bytes).toBeGreaterThan(2048);
|
|
await lookup(observed, "oversized");
|
|
expect((await measure(observed, () => lookup(observed, "oversized"))).bytes).toBeGreaterThan(128 * 1024);
|
|
});
|
|
|
|
it("binds unusual keys and never serves retained schemas after a lookup error", async () => {
|
|
const unusual = "provider-\"quoted' OR true --";
|
|
await seed([driver(unusual, { title: "exact provider" })]);
|
|
const observed = observer();
|
|
let fail = false;
|
|
const guarded = { execute: async (query: SQL) => {
|
|
if (fail) throw new Error("fixture database unavailable");
|
|
return observed.execute(query);
|
|
} } as unknown as Db;
|
|
expect((await lookup(guarded, unusual))).toEqual({ title: "exact provider" });
|
|
fail = true;
|
|
await expect(lookup(guarded, unusual)).rejects.toThrow("fixture database unavailable");
|
|
fail = false;
|
|
expect((await lookup(guarded, unusual))).toEqual({ title: "exact provider" });
|
|
expect(await lookup(guarded, "unknown-provider")).toBeNull();
|
|
});
|
|
|
|
it("keeps each concurrent lookup tied to the database revision it observed", async () => {
|
|
const id = await seed([driver(key, { title: "old" })]), observed = observer();
|
|
let pause = false, release!: () => void, reached!: () => void;
|
|
const gate = new Promise<void>(resolve => { release = resolve; });
|
|
const paused = new Promise<void>(resolve => { reached = resolve; });
|
|
const raced = { execute: async (query: SQL) => {
|
|
const rows = await observed.execute(query);
|
|
if (pause) { pause = false; reached(); await gate; }
|
|
return rows;
|
|
} } as unknown as Db;
|
|
expect((await lookup(raced))).toEqual({ title: "old" });
|
|
pause = true;
|
|
const oldRead = lookup(raced);
|
|
await paused;
|
|
try {
|
|
await db.update(plugins).set({ manifestJson: manifest(id, [driver(key, { title: "new" })]) }).where(eq(plugins.id, id));
|
|
expect((await lookup(raced))).toEqual({ title: "new" });
|
|
} finally { release(); }
|
|
expect((await oldRead)).toEqual({ title: "old" });
|
|
expect((await lookup(raced))).toEqual({ title: "new" });
|
|
expect((await db.execute<{ title: string }>(sql`select ${plugins.manifestJson}->'environmentDrivers'->0->'configSchema'->>'title' as title from ${plugins} where ${plugins.id}=${id}`))[0].title).toBe("new");
|
|
});
|
|
});
|