mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-10-02 02:07:25 +08:00
## Thinking Path > - Paperclip manages AI agents and prepares their runtime inputs before each turn. > - Shared company skills are part of those inputs for native and legacy adapters. > - Runtime materialization refreshed the full inventory again for every declared file. > - Remote skill directories were also downloaded and rebuilt on every turn. > - Measured preparation took 42–73 seconds while runner execution took 7–9 seconds. > - This change reads the inventory once and reuses validated installed revisions. > - Agents retain their selected skills while repeated preparation avoids upstream work. ## Linked Issues or Issue Description **What happened?** One 114-skill preparation performed 407 inventory refreshes, 48 directory rebuilds, and 388 GitHub file fetches. Reusing existing local copies took 151 ms. **Expected behavior** Each listing refreshes inventory once. Unchanged installed remote revisions reuse complete, validated local copies. Local edits remain visible. Explicit updates select new revisions. **Steps to reproduce** 1. Import GitHub skills with supporting files. 2. Run an agent turn, then run another with the same installed revisions. 3. Observe repeated inventory scans, downloads, and runtime directory replacement before execution. Related prior attempts: #2330 and #9268 (still open; #9268 last updated July 9). Those use a marker compared with `updatedAt`. This patch follows the required content validation, immutable revision, company isolation, atomic publication, and read-only semantics, and removes refresh-per-file multiplication. ## What Changed - Split public file reading from reading an already loaded skill. Runtime listing refreshes inventory once. - Add a company-scoped revision cache with file manifests outside the delivered skill directory. Fingerprints omit cosmetic metadata. - Validate exact file inventory, sizes, and hashes before warm reuse. Reject traversal and symlinks. Stage complete builds and serialize atomic publication across processes. - Preserve local/catalog direct sources, stored Markdown fallback, explicit version snapshots, and legacy mutable-ref compatibility. Report missing supporting files and keep older valid revisions readable. - Clean both runtime layouts on rename/removal and record `skills.prepare` under preparation timing. - Add service/cache regressions and an isolated 114-skill benchmark, including a new-process warm run. ## Verification - Final targeted skill-service/cache/trace validation: 86 tests pass (61 embedded-PostgreSQL service tests, 19 cache tests, 6 trace tests). Database tests executed rather than skipped. Focused skill routes, adapter selection, and native runtime context also pass. - `pnpm -r typecheck` and `pnpm build` pass locally at `22caa1fe4`. - The full `pnpm test:run` matrix passes on supported Linux CI at the final head: [CI run](https://github.com/paperclipai/paperclip/actions/runs/34236097762). Local full-suite execution encountered PostgreSQL startup contention, a random allocated-port boundary, and a socket hang-up; every affected suite passed on an isolated rerun. The interrupted local serialized run is not claimed as a complete local pass. - Repeatable benchmark: `pnpm --filter @paperclipai/server exec tsx ../scripts/benchmark-skill-preparation.ts`. Mixed 114-skill inventory with 429 remote files on Linux: cold 286 ms, warm median 96 ms / maximum 153 ms including a new process. Every warm sample performs one refresh, zero upstream fetches/rebuilds, and reports no missing entries; content assertions pass. - Controlled deployment against the previously deployed revision completed with zero lost runs. Real inventory: 114 skills, 670 declared files; 402 cached files match the prior installed copies byte-for-byte. Ten post-deployment warm preparations: median 129 ms / maximum 208 ms; new-process warm 194 ms, zero downloads/rebuilds/missing entries. - Five sequential real browser questions persisted in 10.6–20.7 s (median 12.2 s), versus 50–83 s before. Skill preparation median 240 ms, with one 2.37 s outlier. Total preparation median 3.337 s / maximum 8.728 s **does not fully meet** the <3 s / <5 s target. The excluded historical-run redaction query takes about 1.36 s per scan at two preparation call sites; wider application latency coincided with the outlier, without a cache rebuild. These residuals are reported rather than discarded. - Disposable skill reimport verified through actual selected-skill runs: the next run read the changed code. Fixture removed and agent configuration verified unchanged. - Greptile 5/5, zero unresolved review threads, all final-head CI checks green. ## Risks - Cold preparation still requires upstream availability for supporting files. An unavailable revision is reported missing and never falls back to an older revision. - Valid older revisions and quarantined invalid entries consume additive disk space until skill cleanup. An abruptly killed publisher can leave a lock that requires operator cleanup after confirming its PID is dead. - Warm validation reads all cached file bytes. Very large inventories still have proportional local I/O cost. - No HTTP API, schema, agent configuration, or first-party Telemetry changes. OpenTelemetry retains its operator endpoint gate. ## Model Used OpenAI GPT-6 in Codex, with reasoning, repository inspection, code editing, and test execution. The exact serving snapshot 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 (targeted and isolated reruns; full Linux CI matrix passes, local full-run caveats above) - [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>
116 lines
6.8 KiB
TypeScript
116 lines
6.8 KiB
TypeScript
/** Isolated, repeatable preparation benchmark. Run with pnpm --filter @paperclipai/server exec tsx ../scripts/benchmark-skill-preparation.ts. */
|
|
import assert from "node:assert/strict";
|
|
import { randomUUID } from "node:crypto";
|
|
import { promises as fs } from "node:fs";
|
|
import os from "node:os";
|
|
import path from "node:path";
|
|
import { spawn } from "node:child_process";
|
|
import { fileURLToPath } from "node:url";
|
|
import { companies, companySkills, createDb, startEmbeddedPostgresTestDatabase } from "../packages/db/src/index.js";
|
|
import { removeRuntimeSkillCache } from "../server/src/services/runtime-skill-cache.js";
|
|
import { companySkillService } from "../server/src/services/company-skills.js";
|
|
|
|
const child = process.argv.includes("--warm-child");
|
|
const home = child ? process.env.PAPERCLIP_HOME! : await fs.mkdtemp(path.join(os.tmpdir(), "skill-preparation-benchmark-"));
|
|
process.env.PAPERCLIP_HOME = home;
|
|
process.env.PAPERCLIP_INSTANCE_ID = "default";
|
|
const database = child ? null : await startEmbeddedPostgresTestDatabase("skill-preparation-benchmark-");
|
|
const db = createDb(database?.connectionString ?? process.env.SKILL_BENCH_DATABASE_URL!);
|
|
const companyId = child ? process.env.SKILL_BENCH_COMPANY_ID! : randomUUID();
|
|
const svc = companySkillService(db);
|
|
let upstreamFetches = 0;
|
|
let inventoryRefreshes = 0;
|
|
let rebuilds = 0;
|
|
const originalFetch = globalThis.fetch;
|
|
globalThis.fetch = async (input) => { upstreamFetches++; return new Response(`# Fixture\n${String(input)}\n`); };
|
|
const originalSelect = db.select.bind(db);
|
|
db.select = ((fields?: Record<string, unknown>) => {
|
|
if (fields && Object.keys(fields).length === 1 && fields.id === companies.id) inventoryRefreshes++;
|
|
return originalSelect(fields as never);
|
|
}) as typeof db.select;
|
|
const originalMkdtemp = fs.mkdtemp;
|
|
fs.mkdtemp = ((prefix: string, ...args: unknown[]) => {
|
|
if (String(prefix).includes("__runtime_cache_v1__") && String(prefix).includes(".staging-")) rebuilds++;
|
|
return Reflect.apply(originalMkdtemp, fs, [prefix, ...args]);
|
|
}) as typeof fs.mkdtemp;
|
|
|
|
async function measure(label: string) {
|
|
upstreamFetches = inventoryRefreshes = rebuilds = 0;
|
|
const start = performance.now();
|
|
const entries = await svc.listRuntimeSkillEntries(companyId);
|
|
const durationMs = performance.now() - start;
|
|
const missingEntries = entries.filter((entry) => entry.sourceStatus === "missing").length;
|
|
assert.equal(entries.length, 114);
|
|
assert.equal(missingEntries, 0);
|
|
assert.equal(inventoryRefreshes, 1);
|
|
if (label !== "cold") { assert.equal(upstreamFetches, 0); assert.equal(rebuilds, 0); }
|
|
// Check every synthetic supporting file against its installed revision, outside the timed section.
|
|
const installed = await db.select().from(companySkills);
|
|
for (const skill of installed.filter((skill) => skill.sourceType === "github" || skill.sourceType === "skills_sh")) {
|
|
const entry = entries.find((entry) => entry.key === skill.key)!;
|
|
for (const file of skill.fileInventory) {
|
|
const expected = `# Fixture\nhttps://raw.githubusercontent.com/fixture/skills/${skill.sourceRef}/${skill.slug}/${file.path}\n`;
|
|
assert.equal(await fs.readFile(path.join(entry.source, file.path), "utf8"), expected);
|
|
}
|
|
}
|
|
return { label, durationMs: Math.round(durationMs * 100) / 100, inventoryRefreshes, upstreamFetches, rebuilds, missingEntries, entries: entries.length };
|
|
}
|
|
|
|
try {
|
|
if (child) {
|
|
console.log(JSON.stringify(await measure("warm-new-process")));
|
|
} else {
|
|
await db.insert(companies).values({ id: companyId, name: "Skill benchmark", issuePrefix: "BENCH" });
|
|
const bundled = await svc.listFull(companyId);
|
|
const additional = 114 - bundled.length;
|
|
assert.ok(additional >= 6, "Bundled inventory leaves insufficient room for mixed benchmark fixtures");
|
|
const remoteCount = 33;
|
|
const catalogCount = 21;
|
|
assert.ok(additional > remoteCount + catalogCount, "Bundled inventory leaves no room for local fixtures");
|
|
const filesPerRemote = Math.max(9, Math.ceil(400 / remoteCount));
|
|
for (let index = 0; index < additional; index++) {
|
|
const slug = `fixture-${index}`;
|
|
const sourceType = index < remoteCount ? (index < 28 ? "github" : "skills_sh")
|
|
: index === remoteCount ? "url" : index <= remoteCount + catalogCount ? "catalog" : "local_path";
|
|
const localDir = path.join(home, "instances", "default", "skills", companyId, slug);
|
|
if (sourceType === "local_path" || sourceType === "catalog") {
|
|
await fs.mkdir(localDir, { recursive: true });
|
|
await fs.writeFile(path.join(localDir, "SKILL.md"), `---\nname: ${slug}\ndescription: Benchmark\n---\n# Local\n`);
|
|
}
|
|
await db.insert(companySkills).values({
|
|
id: randomUUID(), companyId, key: `company/${companyId}/${slug}`, slug, name: slug,
|
|
markdown: `# ${slug}`, sourceType, sourceLocator: sourceType === "local_path" || sourceType === "catalog" ? localDir : `https://example.com/${slug}`,
|
|
sourceRef: index < remoteCount ? "a".repeat(40) : null,
|
|
trustLevel: "markdown_only", compatibility: "compatible",
|
|
metadata: { owner: "fixture", repo: "skills", repoSkillDir: slug },
|
|
fileInventory: [{ path: "SKILL.md", kind: "skill" }, ...Array.from({ length: index < remoteCount ? filesPerRemote - 1 : 0 }, (_, file) => ({ path: `references/${file}.md`, kind: "reference" as const }))],
|
|
});
|
|
}
|
|
const samples = [await measure("cold")];
|
|
for (let index = 0; index < 9; index++) samples.push(await measure(`warm-${index + 1}`));
|
|
const childOutput = await new Promise<string>((resolve, reject) => {
|
|
const proc = spawn(process.execPath, ["--import", fileURLToPath(new URL("../server/node_modules/tsx/dist/loader.mjs", import.meta.url)), fileURLToPath(import.meta.url), "--warm-child"], {
|
|
env: { ...process.env, SKILL_BENCH_DATABASE_URL: database!.connectionString, SKILL_BENCH_COMPANY_ID: companyId },
|
|
stdio: ["ignore", "pipe", "inherit"],
|
|
});
|
|
let output = "";
|
|
proc.stdout.on("data", (chunk) => { output += chunk; });
|
|
proc.on("error", reject);
|
|
proc.on("exit", (code) => code === 0 ? resolve(output) : reject(new Error(`Warm subprocess failed: ${code}`)));
|
|
});
|
|
samples.push(JSON.parse(childOutput.trim().split("\n").at(-1)!));
|
|
const warm = samples.slice(1).map((sample) => sample.durationMs).sort((a, b) => a - b);
|
|
console.log(JSON.stringify({ inventory: 114, materializedRemoteFiles: remoteCount * filesPerRemote,
|
|
warmMedianMs: (warm[4] + warm[5]) / 2, warmMaxMs: warm.at(-1), samples }, null, 2));
|
|
}
|
|
} finally {
|
|
globalThis.fetch = originalFetch;
|
|
fs.mkdtemp = originalMkdtemp;
|
|
if (!child) for (const skill of await db.select().from(companySkills)) {
|
|
await removeRuntimeSkillCache(path.join(home, "instances", "default", "skills", companyId), skill.id);
|
|
}
|
|
await db.$client.end();
|
|
await database?.cleanup();
|
|
if (!child) await fs.rm(home, { recursive: true, force: true });
|
|
}
|