mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-03 17:51:58 +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>
205 lines
13 KiB
JavaScript
205 lines
13 KiB
JavaScript
import { execFile } from "node:child_process";
|
|
import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
|
|
import { tmpdir } from "node:os";
|
|
import path from "node:path";
|
|
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
import { promisify } from "node:util";
|
|
|
|
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
|
|
|
import { bundleRuntime, preserveModuleLocation } from "./bundle-runtime.mjs";
|
|
|
|
const execFileAsync = promisify(execFile);
|
|
|
|
function write(file, content) {
|
|
mkdirSync(path.dirname(file), { recursive: true });
|
|
writeFileSync(file, content);
|
|
}
|
|
|
|
describe("bundleRuntime", () => {
|
|
let root;
|
|
|
|
beforeEach(() => {
|
|
root = realpathSync(mkdtempSync(path.join(tmpdir(), "paperclip-bundle-runtime-")));
|
|
const pkg = path.join(root, "packages", "fixture");
|
|
write(path.join(pkg, "package.json"), JSON.stringify({ name: "@paperclipai/fixture", type: "module", exports: { ".": "./src/index.ts" } }));
|
|
write(path.join(pkg, "src", "asset.txt"), "asset beside its source\n");
|
|
write(path.join(pkg, "src", "helper.ts"), "export const double = (value: number): number => value * 2;\n");
|
|
write(path.join(pkg, "src", "index.ts"), [
|
|
"import { readFileSync } from \"node:fs\";",
|
|
"import { double } from \"./helper.js\";",
|
|
"import { onlyForPackage } from \"package-private-dep\";",
|
|
"import { nodeBuild } from \"dual-build-dep\";",
|
|
"export const asset = readFileSync(new URL(\"./asset.txt\", import.meta.url), \"utf8\").trim();",
|
|
"export const location = import.meta.dirname;",
|
|
"export const values = { doubled: double(21), onlyForPackage, nodeBuild };",
|
|
"",
|
|
].join("\n"));
|
|
write(path.join(pkg, "node_modules", "package-private-dep", "package.json"), JSON.stringify({ name: "package-private-dep", type: "module", main: "index.js" }));
|
|
write(path.join(pkg, "node_modules", "package-private-dep", "index.js"), "export const onlyForPackage = \"resolved from the package\";\n");
|
|
write(path.join(pkg, "node_modules", "dual-build-dep", "package.json"), JSON.stringify({
|
|
name: "dual-build-dep", exports: { ".": { module: "./bundler/index.js", default: "./node.cjs" } },
|
|
}));
|
|
write(path.join(pkg, "node_modules", "dual-build-dep", "node.cjs"), "exports.nodeBuild = \"node build\";\n");
|
|
write(path.join(pkg, "node_modules", "dual-build-dep", "bundler", "index.js"), "export * from \"./extensionless\";\n");
|
|
|
|
const server = path.join(root, "server");
|
|
mkdirSync(path.join(server, "node_modules", "@paperclipai"), { recursive: true });
|
|
symlinkSync(pkg, path.join(server, "node_modules", "@paperclipai", "fixture"), "dir");
|
|
write(path.join(server, "package.json"), JSON.stringify({ name: "server", type: "module" }));
|
|
for (const [version, flavor] of [["1", "installed at build"], ["2", "replaced after build"]]) {
|
|
const store = path.join(root, "node_modules", ".pnpm", `server-dep@${version}`);
|
|
write(path.join(store, "package.json"), JSON.stringify({ name: "server-dep", type: "module", main: "index.js" }));
|
|
write(path.join(store, "index.js"), `export const flavor = ${JSON.stringify(flavor)};\n`);
|
|
}
|
|
symlinkSync(path.join(root, "node_modules", ".pnpm", "server-dep@1"), path.join(server, "node_modules", "server-dep"), "dir");
|
|
write(path.join(server, "dist", "late.js"), "import { values } from \"@paperclipai/fixture\";\nexport const late = () => values.doubled + 1;\n");
|
|
write(path.join(server, "dist", "index.js"), [
|
|
"import { asset, location, values } from \"@paperclipai/fixture\";",
|
|
"import { flavor } from \"server-dep\";",
|
|
"import { pathToFileURL } from \"node:url\";",
|
|
"const { late } = await import(\"./late.js\");",
|
|
"// The server only starts when it is the main module.",
|
|
"if (pathToFileURL(process.argv[1]).href === import.meta.url) {",
|
|
" console.log(JSON.stringify({ asset, location, values, flavor, late: late(), entryDir: import.meta.dirname }));",
|
|
"}",
|
|
"",
|
|
].join("\n"));
|
|
});
|
|
|
|
afterEach(() => {
|
|
rmSync(root, { recursive: true, force: true });
|
|
});
|
|
|
|
it("packages a maintenance entry without starting the application or needing a TypeScript loader", async () => {
|
|
const maintenanceEntry = path.join(root, "server", "dist", "maintenance.js");
|
|
write(maintenanceEntry, 'import { asset } from "@paperclipai/fixture"; console.log(JSON.stringify({ asset, phase: process.argv.at(-1) }));');
|
|
const outdir = path.join(root, "server", "dist-runtime");
|
|
await bundleRuntime({ entry: path.join(root, "server", "dist", "index.js"), outdir, maintenanceEntry });
|
|
const { stdout } = await execFileAsync(process.execPath, [path.join(outdir, "agent-files.mjs"), "--phase=eligibility"], { timeout: 30_000 });
|
|
expect(JSON.parse(stdout)).toEqual({ asset: "asset beside its source", phase: "--phase=eligibility" });
|
|
});
|
|
|
|
it("packages standalone enrollment without starting the app", async () => {
|
|
const ephemeralMigrationEntry = path.join(root, "server", "dist", "migration.js");
|
|
write(ephemeralMigrationEntry, 'import { values } from "@paperclipai/fixture"; console.log(JSON.stringify({ migrated: values.doubled }));');
|
|
const outdir = path.join(root, "server", "dist-runtime");
|
|
await bundleRuntime({ entry: path.join(root, "server", "dist", "index.js"), outdir, ephemeralMigrationEntry });
|
|
const { stdout } = await execFileAsync(process.execPath, [path.join(outdir, "ephemeral-migration.mjs")], { timeout: 30_000 });
|
|
expect(JSON.parse(stdout)).toEqual({ migrated: 42 });
|
|
});
|
|
|
|
it("bundles workspace TypeScript and runs with plain node", async () => {
|
|
const outdir = path.join(root, "server", "dist-runtime");
|
|
const summary = await bundleRuntime({ entry: path.join(root, "server", "dist", "index.js"), outdir });
|
|
expect(summary.outfile).toBe(path.join(outdir, "index.mjs"));
|
|
|
|
const { stdout } = await execFileAsync(process.execPath, [summary.outfile], { cwd: path.join(root, "server"), timeout: 30_000 });
|
|
const output = JSON.parse(stdout);
|
|
expect(output.values).toEqual({ doubled: 42, onlyForPackage: "resolved from the package", nodeBuild: "node build" });
|
|
expect(output.late).toBe(43);
|
|
expect(output.asset).toBe("asset beside its source");
|
|
expect(output.location).toBe(path.join(root, "packages", "fixture", "src"));
|
|
expect(output.entryDir).toBe(path.join(root, "server", "dist"));
|
|
});
|
|
|
|
it("keeps database caller locations public in a source-mapped runtime bundle", async () => {
|
|
const captureModule = fileURLToPath(new URL("../../packages/db/src/response-capture.ts", import.meta.url));
|
|
write(path.join(root, "server", "dist", "services", "response-caller.js"), [
|
|
`import { publicDatabaseCallers } from ${JSON.stringify(captureModule)};`,
|
|
'export function callers() { return publicDatabaseCallers(new Error("private-capture-message").stack); }',
|
|
].join("\n"));
|
|
write(path.join(root, "server", "dist", "index.js"), [
|
|
'import { callers } from "./services/response-caller.js";',
|
|
'console.log(JSON.stringify({ callers: callers() }));',
|
|
].join("\n"));
|
|
const summary = await bundleRuntime({ entry: path.join(root, "server", "dist", "index.js"), outdir: path.join(root, "server", "dist-runtime") });
|
|
const env = { ...process.env };
|
|
delete env.NODE_OPTIONS;
|
|
delete env.PAPERCLIP_DB_RESPONSE_CAPTURE_WINDOW;
|
|
const options = { cwd: path.join(root, "server"), env, timeout: 30_000 };
|
|
const plain = JSON.parse((await execFileAsync(process.execPath, [summary.outfile], options)).stdout);
|
|
const mapped = JSON.parse((await execFileAsync(process.execPath, ["--enable-source-maps", summary.outfile], options)).stdout);
|
|
expect(plain.callers).toEqual([]);
|
|
expect(mapped.callers).toEqual([expect.stringMatching(/^services\/response-caller\.js:\d+:\d+$/)]);
|
|
for (const result of [plain, mapped]) {
|
|
const output = JSON.stringify(result);
|
|
expect(output).not.toContain(root);
|
|
expect(output).not.toContain(captureModule);
|
|
expect(output).not.toContain("private-capture-message");
|
|
}
|
|
});
|
|
|
|
it("attributes asynchronous database operations in a plain runtime bundle", async () => {
|
|
const captureModule = fileURLToPath(new URL("../../packages/db/src/response-capture.ts", import.meta.url));
|
|
write(path.join(root, "server", "dist", "services", "database-owner.js"), [
|
|
`import { withDatabaseOperation } from ${JSON.stringify(captureModule)};`,
|
|
'export const run = (owner, db) => withDatabaseOperation(owner, async () => {',
|
|
' await Promise.resolve();',
|
|
' return await db.$client.unsafe("select $1", ["private-parameter"]);',
|
|
'});',
|
|
].join("\n"));
|
|
write(path.join(root, "server", "dist", "index.js"), [
|
|
`import { createDatabaseResponseCapture, installDatabaseResponseCapture } from ${JSON.stringify(captureModule)};`,
|
|
'import { run } from "./services/database-owner.js";',
|
|
'const events = [];',
|
|
'const now = Date.now();',
|
|
'const capture = createDatabaseResponseCapture({ start: now, end: now + 60000 }, event => events.push(event));',
|
|
'const db = { $client: { unsafe: () => ({ then(resolve, reject) { return Promise.resolve(Object.assign([["private-result"]], { columns: [{ name: "value" }] })).then(resolve, reject); } }) } };',
|
|
'installDatabaseResponseCapture(db, {}, capture);',
|
|
'await Promise.all([run("fixture.first", db), run("fixture.second", db)]);',
|
|
'capture.flush();',
|
|
'console.log(JSON.stringify(events));',
|
|
].join("\n"));
|
|
const summary = await bundleRuntime({ entry: path.join(root, "server", "dist", "index.js"), outdir: path.join(root, "server", "dist-runtime") });
|
|
const env = { ...process.env };
|
|
delete env.NODE_OPTIONS;
|
|
delete env.PAPERCLIP_DB_RESPONSE_CAPTURE_WINDOW;
|
|
const { stdout } = await execFileAsync(process.execPath, [summary.outfile], { cwd: path.join(root, "server"), env, timeout: 30_000 });
|
|
const events = JSON.parse(stdout);
|
|
const entries = events.filter(event => event.event === "paperclip.db_response_capture.entry.v2");
|
|
expect(entries.map(entry => entry.owner).sort()).toEqual(["fixture.first", "fixture.second"]);
|
|
for (const entry of entries) expect(entry).toMatchObject({ calls: 1, rows: 1, callers: [] });
|
|
expect(events.at(-1)).toMatchObject({ event: "paperclip.db_response_capture.summary.v2", completedQueries: 2 });
|
|
expect(stdout).not.toContain("private-parameter");
|
|
expect(stdout).not.toContain("private-result");
|
|
expect(stdout).not.toContain(root);
|
|
});
|
|
|
|
it("emits a server module that loads without starting the server", async () => {
|
|
const outdir = path.join(root, "server", "dist-runtime");
|
|
const summary = await bundleRuntime({ entry: path.join(root, "server", "dist", "index.js"), outdir });
|
|
expect(summary.serverModule).toBe(path.join(outdir, "server.mjs"));
|
|
const probe = path.join(root, "server", "probe.mjs");
|
|
write(probe, `await import(${JSON.stringify(pathToFileURL(summary.serverModule).href)});\nconsole.log("loaded");\n`);
|
|
const loaded = await execFileAsync(process.execPath, [probe], { cwd: path.join(root, "server"), timeout: 30_000 });
|
|
expect(loaded.stdout.trim()).toBe("loaded");
|
|
const started = await execFileAsync(process.execPath, [summary.outfile], { cwd: path.join(root, "server"), timeout: 30_000 });
|
|
expect(JSON.parse(started.stdout).late).toBe(43);
|
|
});
|
|
|
|
it("leaves the server's own dependencies to runtime resolution", async () => {
|
|
const outdir = path.join(root, "server", "dist-runtime");
|
|
const summary = await bundleRuntime({ entry: path.join(root, "server", "dist", "index.js"), outdir });
|
|
rmSync(path.join(root, "server", "node_modules", "server-dep"));
|
|
symlinkSync(path.join(root, "node_modules", ".pnpm", "server-dep@2"), path.join(root, "server", "node_modules", "server-dep"), "dir");
|
|
const { stdout } = await execFileAsync(process.execPath, [summary.outfile], { cwd: path.join(root, "server"), timeout: 30_000 });
|
|
expect(JSON.parse(stdout).flavor).toBe("replaced after build");
|
|
});
|
|
|
|
it("keeps third-party packages external", async () => {
|
|
const outdir = path.join(root, "server", "dist-runtime");
|
|
await bundleRuntime({ entry: path.join(root, "server", "dist", "index.js"), outdir });
|
|
const { stdout } = await execFileAsync("grep", ["-rl", "resolved from the package", outdir], { encoding: "utf8" }).catch(() => ({ stdout: "" }));
|
|
expect(stdout.trim()).toBe("");
|
|
});
|
|
});
|
|
|
|
describe("preserveModuleLocation", () => {
|
|
it("replaces import.meta location properties with the original path", () => {
|
|
const file = "/srv/app/packages/x/src/mod.ts";
|
|
const out = preserveModuleLocation("a(import.meta.url); b(import.meta.dirname); c(import.meta.filename); d(import.meta.resolve);", file);
|
|
expect(out).toBe(`a("file:///srv/app/packages/x/src/mod.ts"); b("/srv/app/packages/x/src"); c("/srv/app/packages/x/src/mod.ts"); d(import.meta.resolve);`);
|
|
});
|
|
});
|