From e7f31705dad6dfdfd0f0f3f9e017ed2e0afc584b Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Sun, 15 Nov 2026 06:40:21 -0600 Subject: [PATCH 1/4] perf(release): stage the verified host release daemon instead of compiling it in publish_canary (#21555) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Every master push runs a canary, and only one canary runs at a time, so its duration sets how often merged work ships > - `publish_canary` takes about 30 min. 8 min of it is `pnpm build`, and 4 min 40 s of that is an uncached `cargo build --release` of `paperclip-runnerd` > - The release then replaces that binary with the exact-source daemons that `release_runner_binaries` already built and verified for all four targets > - This pull request stages the verified daemon for the publisher's own target during a release, instead of compiling it > - The benefit is about 4.5 min less per canary, with the same verified bytes published ## Linked Issues or Issue Description **What happened?** In canary run 43487884481 (2026-11-13), the `Publish canary` step took 28.6 min. Its `pnpm build` ran 19:42-19:50. The `packages/paperclip-runner build` took 5.3 min, and its `cargo build` reported `Finished release profile ... in 4m 40s`. Every other package waited for it. `release.sh` then runs `assemble-daemons`, which overwrites `dist/bin` with the four exact-source release daemons. **Expected behavior** A release does not compile a binary that it discards. The Runner build stamp stays valid, so the server build still reuses the Runner build. Refs #21554 (the other canary speed-up) ## What Changed - `packages/paperclip-runner/scripts/build-runner-binary.mjs` (new): when `PAPERCLIP_RELEASE_RUNNER_ARTIFACTS_DIR` is set, it checks the release daemons with the existing `releaseDaemonManifest` (source revision equal to `HEAD`, digest, architecture, build metadata) and stages the host target's daemon at `dist/bin` with the existing `stageRunnerBinary`. Otherwise it runs `pnpm run build:binary` as before. - The Runner `build` chain calls this script in place of `pnpm run build:binary`. `build:binary` itself and the image build are unchanged. - `stage-release-runner-binaries.mjs` exports `metadataContract`. - Tests: `stage-runner-binary.test.mjs` (staging per target, wrong source, bad digest, missing target, non-release fallback); `runner-image-identity.test.ts` step list. - `doc/RELEASING.md` describes the behavior. ## Verification - `node --test packages/paperclip-runner/scripts/stage-runner-binary.test.mjs`: 9 of 9 pass. - `server`: `vitest run src/__tests__/runner-image-identity.test.ts`: 42 of 42 pass. - With the real daemon artifacts of canary run 43487884481 (receipts pointed at this commit): `PAPERCLIP_RELEASE_RUNNER_ARTIFACTS_DIR=... pnpm run build` in `packages/paperclip-runner` finished in 15 s with no `cargo` line. The build stamp was recorded, and `server/scripts/prepare-runner-vendor.mjs` then reported `action:reuse,reason:inputs_unchanged`. The staged daemon runs. - After merge: the next canary's `packages/paperclip-runner build` log shows "Staged the verified exact-source linux-x64 release daemon" and no `Compiling` lines. ## Risks - Low. A release still fails closed: a daemon with the wrong source, digest, architecture or metadata stops the build, and `assemble-daemons` checks all four again afterwards. - Local, Docker and CI builds without the variable are unchanged. - On macOS, staging re-signs the binary, as it does for a compiled one. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, in Claude Code with tool use and code execution. ## 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 - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [ ] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- doc/RELEASING.md | 7 +++ packages/paperclip-runner/package.json | 2 +- .../scripts/build-runner-binary.mjs | 52 +++++++++++++++++ .../scripts/stage-release-runner-binaries.mjs | 2 +- .../scripts/stage-runner-binary.test.mjs | 58 +++++++++++++++++++ .../__tests__/runner-image-identity.test.ts | 2 +- 6 files changed, 120 insertions(+), 3 deletions(-) create mode 100644 packages/paperclip-runner/scripts/build-runner-binary.mjs diff --git a/doc/RELEASING.md b/doc/RELEASING.md index 68230fcb677..d88794e7232 100644 --- a/doc/RELEASING.md +++ b/doc/RELEASING.md @@ -137,6 +137,13 @@ discarded. The native daemon build cache holds dependency crates only. Its key covers the Cargo manifest, Cargo configuration, host and target, but not the Runner's own source, so a Runner change does not discard the dependencies. +During a release (`PAPERCLIP_RELEASE_RUNNER_ARTIFACTS_DIR` set), the Runner +package build does not compile `paperclip-runnerd`. It verifies the +exact-source release daemon for the publisher's own target (source, digest, +architecture and build metadata) and stages it at `dist/bin`, so the build +stamp and the server's vendored Runner stay current. Every other build still +runs `build:binary`. + After publication, the onboarding smoke checks out the same source SHA and installs its test dependencies from the publisher's resolved lockfile with `--frozen-lockfile`. The same-run artifact is captured before tracked files are diff --git a/packages/paperclip-runner/package.json b/packages/paperclip-runner/package.json index c89d6b11040..b57658f5b54 100644 --- a/packages/paperclip-runner/package.json +++ b/packages/paperclip-runner/package.json @@ -67,7 +67,7 @@ }, "sideEffects": false, "scripts": { - "build": "node scripts/record-build-inputs.mjs --begin && pnpm run check:protocol-manifest && pnpm run build:typescript && pnpm run check:capability-contract && pnpm run check:capability-inventory && pnpm run check:protocol-coverage && node scripts/generate-semantic-contracts.mjs --check && node scripts/check-runner-workflow-traceability.mjs && pnpm run build:binary && node scripts/generate-replay-goldens.mjs --check && node scripts/generate-semantic-action-catalog.mjs --check && node scripts/record-build-inputs.mjs --finish", + "build": "node scripts/record-build-inputs.mjs --begin && pnpm run check:protocol-manifest && pnpm run build:typescript && pnpm run check:capability-contract && pnpm run check:capability-inventory && pnpm run check:protocol-coverage && node scripts/generate-semantic-contracts.mjs --check && node scripts/check-runner-workflow-traceability.mjs && node scripts/build-runner-binary.mjs && node scripts/generate-replay-goldens.mjs --check && node scripts/generate-semantic-action-catalog.mjs --check && node scripts/record-build-inputs.mjs --finish", "build:typescript": "pnpm run check:acpx-profiles && pnpm run ensure:eval-build-deps && pnpm run check:protocol-types && node ./node_modules/typescript/bin/tsc --version && node ./node_modules/typescript/bin/tsc -p tsconfig.json && node ./node_modules/typescript/bin/tsc -p tsconfig.surfaces.json && node scripts/build-verified-provider-entrypoints.mjs && node scripts/install-copilot-assets.mjs", "build:rust": "cargo build --manifest-path runner/Cargo.toml --locked --workspace --bins", "build:binary": "cargo build --release --manifest-path runner/Cargo.toml --locked -p paperclip-runner-core --bin paperclip-runnerd && node scripts/stage-runner-binary.mjs", diff --git a/packages/paperclip-runner/scripts/build-runner-binary.mjs b/packages/paperclip-runner/scripts/build-runner-binary.mjs new file mode 100644 index 00000000000..dd9b25be093 --- /dev/null +++ b/packages/paperclip-runner/scripts/build-runner-binary.mjs @@ -0,0 +1,52 @@ +import { execFileSync, spawnSync } from "node:child_process"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { stageRunnerBinary } from "./stage-runner-binary.mjs"; + +export const RELEASE_ARTIFACTS_VARIABLE = "PAPERCLIP_RELEASE_RUNNER_ARTIFACTS_DIR"; + +export function hostRunnerTarget(platform = process.platform, arch = process.arch) { + return `${platform}-${arch}`; +} + +export async function stageReleaseHostBinary({ artifactDirectory, sourceRevision, packageRoot, verifyMetadata, target = hostRunnerTarget(), stage = stageRunnerBinary }) { + const { releaseDaemonManifest } = await import("./stage-release-runner-binaries.mjs"); + const manifest = releaseDaemonManifest(artifactDirectory, sourceRevision, verifyMetadata); + const artifact = manifest.platforms[target]; + if (!artifact) throw new Error(`No exact-source release daemon for ${target}`); + const executable = target.startsWith("win32-") ? "paperclip-runnerd.exe" : "paperclip-runnerd"; + await stage(artifact.path, path.join(packageRoot, "dist", "bin", executable)); + return { target, sha256: artifact.sha256 }; +} + +function pnpmInvocation(env) { + const npmExecPath = env.npm_execpath?.trim(); + if (npmExecPath && npmExecPath.toLowerCase().includes("pnpm")) { + return /\.(c|m)?js$/i.test(npmExecPath) ? { command: process.execPath, args: [npmExecPath] } : { command: npmExecPath, args: [] }; + } + return { command: "pnpm", args: [] }; +} + +export async function main({ env = process.env, packageRoot, log = console.log } = {}) { + const root = packageRoot ?? path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); + const artifactDirectory = env[RELEASE_ARTIFACTS_VARIABLE]?.trim(); + if (artifactDirectory) { + const { metadataContract } = await import("./stage-release-runner-binaries.mjs"); + const sourceRevision = execFileSync("git", ["rev-parse", "HEAD"], { cwd: root, encoding: "utf8" }).trim(); + const staged = await stageReleaseHostBinary({ artifactDirectory, sourceRevision, packageRoot: root, verifyMetadata: await metadataContract() }); + log(`Staged the verified exact-source ${staged.target} release daemon (${staged.sha256}) instead of compiling it.`); + return { reused: true, ...staged }; + } + const { command, args } = pnpmInvocation(env); + const result = spawnSync(command, [...args, "run", "build:binary"], { cwd: root, env, stdio: "inherit", shell: process.platform === "win32" && command === "pnpm" }); + if (result.error) throw result.error; + if (result.status !== 0) throw new Error(`build:binary exited with ${result.status ?? result.signal}`); + return { reused: false }; +} + +if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { + main().catch((error) => { + console.error(error.message); + process.exitCode = 1; + }); +} diff --git a/packages/paperclip-runner/scripts/stage-release-runner-binaries.mjs b/packages/paperclip-runner/scripts/stage-release-runner-binaries.mjs index ab6153b7ce7..0b5b1224572 100644 --- a/packages/paperclip-runner/scripts/stage-release-runner-binaries.mjs +++ b/packages/paperclip-runner/scripts/stage-release-runner-binaries.mjs @@ -31,7 +31,7 @@ function regularFile(path, maximumSize) { return readFileSync(path); } -async function metadataContract() { +export async function metadataContract() { const { PAPERCLIP_RUNNER_BUILD_METADATA } = await import("../dist/evals/build-metadata.js"); const { parsePaperclipRunnerdBuildMetadata } = await import("../dist/evals/runnerd-artifact.js"); return metadata => verifyReleaseRunnerMetadata(parsePaperclipRunnerdBuildMetadata(metadata), PAPERCLIP_RUNNER_BUILD_METADATA); diff --git a/packages/paperclip-runner/scripts/stage-runner-binary.test.mjs b/packages/paperclip-runner/scripts/stage-runner-binary.test.mjs index ddffc53e4c8..e262d64a213 100644 --- a/packages/paperclip-runner/scripts/stage-runner-binary.test.mjs +++ b/packages/paperclip-runner/scripts/stage-runner-binary.test.mjs @@ -7,6 +7,7 @@ import { tmpdir } from "node:os"; import path from "node:path"; import { test } from "node:test"; import { stageBuiltRunnerBinary, stageRunnerBinary } from "./stage-runner-binary.mjs"; +import { main as buildRunnerBinary, RELEASE_ARTIFACTS_VARIABLE, stageReleaseHostBinary } from "./build-runner-binary.mjs"; import { RELEASE_RUNNER_TARGETS, releaseRunnerTargets, releaseDaemonManifest, verifyReleaseRunnerMetadata } from "./stage-release-runner-binaries.mjs"; import { paperclipRunnerBinaryNeedsBuild, resolveNativeRunnerDevBinary } from "../../../scripts/dev-runner-native-binary.mjs"; import { resolvePackagedRunnerBinary } from "../src/live/runner-binary.ts"; @@ -231,3 +232,60 @@ test("failed preparation preserves the published bytes and mode", async () => { await rm(root, { recursive: true, force: true }); } }); + +async function writeReleaseDaemons(root, source) { + for (const target of RELEASE_RUNNER_TARGETS) { + await mkdir(path.join(root, target), { recursive: true }); + const bytes = Buffer.alloc(64); + if (target.startsWith("linux-")) { + bytes.set([0x7f, 0x45, 0x4c, 0x46, 2, 1]); bytes.writeUInt16LE(target === "linux-x64" ? 62 : 183, 18); + } else { bytes.writeUInt32LE(0xfeedfacf); bytes.writeUInt32LE(target === "darwin-x64" ? 0x01000007 : 0x0100000c, 4); } + await writeFile(path.join(root, target, "paperclip-runnerd"), bytes); + await writeFile(path.join(root, target, "receipt.json"), JSON.stringify({ schema: "paperclip.runner.release-artifact.v1", sourceRevision: source, + target, sha256: "sha256:" + createHash("sha256").update(bytes).digest("hex"), buildMetadata: metadata })); + } +} + +test("a release build stages the verified exact-source host daemon instead of compiling it", async () => { + const root = await realpath(await mkdtemp(path.join(tmpdir(), "runner-release-host-"))), source = "a".repeat(40); + const artifacts = path.join(root, "artifacts"), packageRoot = path.join(root, "package"); + const verifyMetadata = value => verifyReleaseRunnerMetadata(value, contract); + const staged = []; + const stage = async (from, to) => { staged.push([from, to]); await mkdir(path.dirname(to), { recursive: true }); await copyFile(from, to); }; + try { + await writeReleaseDaemons(artifacts, source); + for (const target of RELEASE_RUNNER_TARGETS) { + const result = await stageReleaseHostBinary({ artifactDirectory: artifacts, sourceRevision: source, packageRoot, verifyMetadata, target, stage }); + assert.equal(result.target, target); + const bytes = await readFile(path.join(packageRoot, "dist", "bin", "paperclip-runnerd")); + assert.deepEqual(bytes, await readFile(path.join(artifacts, target, "paperclip-runnerd"))); + assert.deepEqual(staged.at(-1), [path.join(artifacts, target, "paperclip-runnerd"), path.join(packageRoot, "dist", "bin", "paperclip-runnerd")]); + } + await assert.rejects(stageReleaseHostBinary({ artifactDirectory: artifacts, sourceRevision: "b".repeat(40), packageRoot, verifyMetadata, target: "linux-x64", stage }), + /source, digest or architecture/); + await assert.rejects(stageReleaseHostBinary({ artifactDirectory: artifacts, sourceRevision: source, packageRoot, verifyMetadata, target: "win32-x64", stage }), + /No exact-source release daemon for win32-x64/); + await writeFile(path.join(artifacts, "linux-x64", "paperclip-runnerd"), Buffer.alloc(64, 1)); + await assert.rejects(stageReleaseHostBinary({ artifactDirectory: artifacts, sourceRevision: source, packageRoot, verifyMetadata, target: "linux-x64", stage }), + /digest or architecture/); + assert.equal(staged.length, RELEASE_RUNNER_TARGETS.length, "rejected artifacts are never staged"); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test("a build without release daemons still compiles the Runner binary", async () => { + const root = await realpath(await mkdtemp(path.join(tmpdir(), "runner-local-build-"))); + try { + const marker = path.join(root, "ran"); + await writeFile(path.join(root, "build.cjs"), `require("node:fs").writeFileSync(${JSON.stringify(marker)}, "yes");\n`); + await writeFile(path.join(root, "package.json"), JSON.stringify({ name: "fixture", private: true, scripts: { "build:binary": "node build.cjs" } })); + const env = { ...process.env }; + delete env[RELEASE_ARTIFACTS_VARIABLE]; + const result = await buildRunnerBinary({ env, packageRoot: root, log: () => {} }); + assert.deepEqual(result, { reused: false }); + assert.equal(await readFile(marker, "utf8"), "yes"); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); diff --git a/server/src/__tests__/runner-image-identity.test.ts b/server/src/__tests__/runner-image-identity.test.ts index 43f497eac14..18e73885d62 100644 --- a/server/src/__tests__/runner-image-identity.test.ts +++ b/server/src/__tests__/runner-image-identity.test.ts @@ -348,7 +348,7 @@ describe("Runner image stages", () => { "pnpm run check:protocol-coverage", "node scripts/generate-semantic-contracts.mjs --check", "node scripts/check-runner-workflow-traceability.mjs", - "pnpm run build:binary", + "node scripts/build-runner-binary.mjs", "node scripts/generate-replay-goldens.mjs --check", "node scripts/generate-semantic-action-catalog.mjs --check", "node scripts/record-build-inputs.mjs --finish", From 3244780bd03294c860e8cedea3bf8ea29e03cd1f Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Sun, 15 Nov 2026 07:05:34 -0600 Subject: [PATCH 2/4] fix(queue): keep a message a starting run's first turn took out of the queue (#21747) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - A message posted while a run is starting goes into that run's first turn, and the task page shows it as sent > - The page shows it as sent only while the live queue lists it as a first-turn message > - When that queue closes, for example after a later Steer, the page has no lasting record of the delivery > - It then infers that the message is queued and shows it again with a Steer button > - This pull request reports each run's own first-turn receipt in the run list, and the page places those messages in that run > - The benefit is that a sent message stays sent ## Linked Issues or Issue Description Follow-up to #21661, found while I verified that change on staging. **What happened?** With a Codex runner, two messages were posted while the run was starting. The first turn took them and the agent acted on both. Then a third message was steered into the running turn. After the Steer, the first two messages came back into the queue with Steer buttons. The server queue was empty. **Expected behavior** Messages that a run's first turn took stay in the conversation as delivered. **Steps to reproduce** 1. Start a task with a Paperclip runner agent. 2. While the runner is starting, post one or two messages. 3. After the turn starts, post another message and click Steer. ## What Changed - `activityService.runsForIssue` returns `firstTurnCommentIds` from the run's `firstTurnQueuedInput` receipt. The field is set only when the receipt names this run, because a retry copies its predecessor's context. - `IssueDetail` adds those ids to the run's start inputs, so the messages are placed in that run and are not inferred as queued. - `RunForIssue` type gets the new optional field. ## Verification Red/green tests. Each failed before the fix and passes after it: - `server/src/__tests__/activity-service.test.ts`: "reports the queued messages a run's own first turn took, not a predecessor's". 33/33 pass. - `ui/src/pages/IssueDetail.test.tsx`: "keeps a message the running turn already took out of the queue after the live queue closes". The IssueDetail, queue helper, and task-chat suites pass (69 files, 1298 tests). UI typecheck passes. Staging, after #21661 deployed, Codex runner: two messages posted while the run started were taken into the first turn and acted on. No Interrupt, error banner, or composer wait was shown. A mid-turn Steer was accepted in seconds. This PR fixes the one defect that the check found. ## Risks - Low. One new read-only field on the run list. A run that took messages and then failed before its provider accepted the turn now shows those messages in that run. The next run still delivers them, and the queue still lists them while they wait. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use and code execution. ## 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 - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- server/src/__tests__/activity-service.test.ts | 41 +++++++++++++++++++ server/src/services/activity.ts | 3 ++ .../src/services/queued-comment-delivery.ts | 28 +++++++++++++ ui/src/api/activity.ts | 2 + ui/src/pages/IssueDetail.test.tsx | 36 ++++++++++++++++ ui/src/pages/IssueDetail.tsx | 12 +++++- 6 files changed, 120 insertions(+), 2 deletions(-) diff --git a/server/src/__tests__/activity-service.test.ts b/server/src/__tests__/activity-service.test.ts index 2ac88be6d82..ddebc3f5339 100644 --- a/server/src/__tests__/activity-service.test.ts +++ b/server/src/__tests__/activity-service.test.ts @@ -10,6 +10,7 @@ import { createDb, documentRevisions, documents, + heartbeatRunEvents, heartbeatRuns, issueComments, issueDocuments, @@ -69,6 +70,7 @@ describeEmbeddedPostgres("activity service", () => { await db.delete(documentRevisions); await db.delete(documents); await db.delete(issues); + await db.delete(heartbeatRunEvents); await db.delete(heartbeatRuns); await db.delete(agentWakeupRequests); await db.delete(agents); @@ -275,6 +277,45 @@ describeEmbeddedPostgres("activity service", () => { expect(rows.map((row) => row.action)).not.toContain("private.changed"); }); + it("reports the queued messages a run's own accepted first turn took", async () => { + const companyId = randomUUID(), agentId = randomUUID(), issueId = randomUUID(); + const acceptedRunId = randomUUID(), unacceptedRunId = randomUUID(), retryRunId = randomUUID(); + const taken = [randomUUID(), randomUUID()], editedAfterSeal = randomUUID(); + await db.insert(companies).values({ id: companyId, name: "Paperclip", + issuePrefix: `F${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`, requireBoardApprovalForNewAgents: false }); + await db.insert(agents).values({ id: agentId, companyId, name: "Runner", role: "engineer", status: "running", + adapterType: "paperclip_runner", adapterConfig: {}, runtimeConfig: {}, permissions: {} }); + await db.insert(issues).values({ id: issueId, companyId, title: "First turn", status: "in_progress", + priority: "medium", assigneeAgentId: agentId }); + await db.insert(issueComments).values([...taken, editedAfterSeal].map((id, index) => ({ + id, companyId, issueId, authorType: "user" as const, authorUserId: "board-user", body: `Message ${index}`, + createdAt: new Date("2026-11-14T23:59:00.000Z"), + // Edited after the run sealed its input: still waiting to be delivered. + updatedAt: new Date(id === editedAfterSeal ? "2026-11-15T00:00:05.000Z" : "2026-11-14T23:59:00.000Z"), + }))); + const receipt = (runId: string) => ({ schema: "paperclip.first-turn-queued-input.v1", runId, + wakeupRequestIds: [], commentIds: [...taken, editedAfterSeal], claimedAt: "2026-11-15T00:00:00.000Z" }); + await db.insert(heartbeatRuns).values([ + { id: acceptedRunId, receiptRunId: acceptedRunId, status: "running" }, + // Sealed its input, then failed to start: the receipt proves nothing. + { id: unacceptedRunId, receiptRunId: unacceptedRunId, status: "failed" }, + // A retry copies its predecessor's context; that receipt is not its own. + { id: retryRunId, receiptRunId: acceptedRunId, status: "running" }, + ].map((run, index) => ({ + id: run.id, companyId, agentId, scopeKind: "issue" as const, issueId, invocationSource: "assignment", + status: run.status, createdAt: new Date(Date.now() - (3 - index) * 1000), + contextSnapshot: { issueId, firstTurnQueuedInput: receipt(run.receiptRunId) }, + }))); + await db.insert(heartbeatRunEvents).values([acceptedRunId, retryRunId].map(runId => ({ + companyId, runId, agentId, seq: 1, eventType: "turn.accepted", stream: "system", level: "info", + message: "turn accepted" }))); + const runs = await activityService(db).runsForIssue(companyId, issueId); + const ids = (runId: string) => runs.find(run => run.runId === runId)?.firstTurnCommentIds ?? null; + expect(ids(acceptedRunId)).toEqual(taken); + expect(ids(unacceptedRunId)).toBeNull(); + expect(ids(retryRunId)).toBeNull(); + }); + it.each([null, "native_provider_model_rejected", "adapter_failed"])("returns compact issue runs with bounded model rejection details: %s", async (errorCode) => { const companyId = randomUUID(); const agentId = randomUUID(); diff --git a/server/src/services/activity.ts b/server/src/services/activity.ts index c44b130dd26..4fa79b84104 100644 --- a/server/src/services/activity.ts +++ b/server/src/services/activity.ts @@ -1,6 +1,7 @@ import { DELIVERY_QUEUES, notifyDeliveryWork } from "./delivery-work-notifications.js"; import { skillAccessService } from "./skill-access.js"; import { credentialAccessConnectionNameSql } from "./credential-access-visibility.js"; +import { acceptedFirstTurnCommentIdsSql } from "./queued-comment-delivery.js"; import { executionProjectionsForRuns } from "./execution-projection.js"; import { and, asc, desc, eq, inArray, isNull, or, sql, type SQL } from "drizzle-orm"; import type { Db } from "@paperclipai/db"; @@ -549,6 +550,8 @@ export function activityService(db: Db) { lastUsefulActionAt: heartbeatRuns.lastUsefulActionAt, nextAction: heartbeatRuns.nextAction, wakeCommentIds: sql`${heartbeatRuns.contextSnapshot} -> 'wakeCommentIds'`, + // Queued messages this run's own accepted first turn took. + firstTurnCommentIds: acceptedFirstTurnCommentIdsSql(heartbeatRuns), queuedCommentSourceWakeIds: sql`${heartbeatRuns.contextSnapshot} -> 'queuedCommentSourceWakeIds'`, wakeCommentId: sql`${heartbeatRuns.contextSnapshot} ->> 'wakeCommentId'`, contextCommentId: sql`${heartbeatRuns.contextSnapshot} ->> 'commentId'`, diff --git a/server/src/services/queued-comment-delivery.ts b/server/src/services/queued-comment-delivery.ts index 343671a16ec..d2846bf6c4b 100644 --- a/server/src/services/queued-comment-delivery.ts +++ b/server/src/services/queued-comment-delivery.ts @@ -166,6 +166,34 @@ function firstTurnDeliveredSql(companyId: string, issueId: string, agentId: stri and accepted.event_type in ('turn.accepted', 'turn.started')))`; } +/** + * The comment ids a run's own first-turn receipt sealed, once that run's + * provider accepted the turn. A receipt alone proves nothing: the run may + * have failed before acceptance, and a retry copies its predecessor's + * receipt. A message edited after the seal is still undelivered. Same + * evidence as `firstTurnDeliveredSql`. + */ +export function acceptedFirstTurnCommentIdsSql(run: { id: typeof heartbeatRuns.id; companyId: typeof heartbeatRuns.companyId; + contextSnapshot: typeof heartbeatRuns.contextSnapshot }) { + return sql`case + when ${run.contextSnapshot} #>> '{firstTurnQueuedInput,schema}' = 'paperclip.first-turn-queued-input.v1' + and ${run.contextSnapshot} #>> '{firstTurnQueuedInput,runId}' = ${run.id}::text + and ${run.contextSnapshot} #>> '{firstTurnQueuedInput,claimedAt}' is not null + and jsonb_typeof(${run.contextSnapshot} #> '{firstTurnQueuedInput,commentIds}') = 'array' + and exists (select 1 from ${heartbeatRunEvents} accepted + where accepted.company_id = ${run.companyId} and accepted.run_id = ${run.id} + and accepted.event_type in ('turn.accepted', 'turn.started')) + then (select jsonb_agg(sealed_comment.id::text order by sealed.position) + from (select case when raw.id ~* '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' + then raw.id::uuid end as id, raw.position + from jsonb_array_elements_text(${run.contextSnapshot} #> '{firstTurnQueuedInput,commentIds}') + with ordinality as raw(id, position)) sealed + join ${issueComments} sealed_comment on sealed_comment.id = sealed.id + and sealed_comment.company_id = ${run.companyId} + where (${run.contextSnapshot} #>> '{firstTurnQueuedInput,claimedAt}')::timestamptz + >= date_trunc('milliseconds', sealed_comment.updated_at)) end`; +} + /** Ids that an accepted first provider turn already received (see `deliveredQueuedCommentIds`). */ export async function firstTurnDeliveredCommentIds(tx: Pick, input: { companyId: string; issueId: string; agentId: string; commentIds: string[]; diff --git a/ui/src/api/activity.ts b/ui/src/api/activity.ts index f2011f7eabd..75ca32163d2 100644 --- a/ui/src/api/activity.ts +++ b/ui/src/api/activity.ts @@ -38,6 +38,8 @@ export interface RunForIssue { lastUsefulActionAt?: string | null; nextAction?: string | null; wakeCommentIds?: string[] | null; + /** Queued messages this run's first provider turn took while it was starting. */ + firstTurnCommentIds?: string[] | null; wakeCommentId?: string | null; contextCommentId?: string | null; contextIssueId?: string | null; diff --git a/ui/src/pages/IssueDetail.test.tsx b/ui/src/pages/IssueDetail.test.tsx index 8015df04df7..c2547cdda51 100644 --- a/ui/src/pages/IssueDetail.test.tsx +++ b/ui/src/pages/IssueDetail.test.tsx @@ -5616,6 +5616,42 @@ describe("IssueDetail", () => { expect(props().queuedCommentQueue?.entries.map(entry => entry.comment.id)).toEqual([waiting.id]); }); + it("keeps a message the running turn already took out of the queue after the live queue closes", async () => { + // Posted while the run was still starting; its first turn took it. + const taken = createIssueComment({ id: "first-turn-message", body: "Include the word PINEAPPLE" }); + const run = { + id: "run-native", runtimeMode: "native" as const, status: "running", + invocationSource: "issue", triggerDetail: null, + contextCommentId: null, contextWakeCommentId: null, + startedAt: "2026-04-21T00:00:01.000Z", finishedAt: null, + createdAt: "2026-04-21T00:00:01.000Z", agentId: "agent-1", + agentName: "Runner", adapterType: "paperclip_runner", issueId: "issue-1", + }; + mockIssuesApi.get.mockResolvedValue(createIssue({ status: "in_progress", assigneeAgentId: "agent-1", executionRunId: run.id })); + mockAgentsApi.list.mockResolvedValue([createAgent({ adapterType: "paperclip_runner" })]); + mockHeartbeatsApi.activeRunForIssue.mockResolvedValue(run); + mockHeartbeatsApi.liveRunsForIssue.mockResolvedValue([run]); + mockIssuesApi.listComments.mockResolvedValue([taken]); + // The deferred wake has retired, so the live queue no longer lists it. + mockIssuesApi.getQueuedComments.mockResolvedValue(createQueuedCommentQueue({ + queueId: null, state: null, targetRunId: null, entries: [], + })); + mockActivityApi.runsForIssue.mockResolvedValue([{ + runId: run.id, agentId: "agent-1", adapterType: "paperclip_runner", + status: "running", startedAt: run.startedAt, finishedAt: null, + createdAt: run.createdAt, wakeCommentIds: null, firstTurnCommentIds: [taken.id], + wakeupRequestId: "wake-start", contextIssueId: "issue-1", + }]); + await act(async () => renderIssueView()); + await waitForAssertion(() => { + const props = mockIssueChatThreadRender.mock.calls.at(-1)![0]; + expect(props.queuedCommentQueue?.entries ?? []).toEqual([]); + const comment = props.comments.find((comment: IssueComment) => comment.id === taken.id); + expect(comment).toMatchObject({ consumedByRunId: run.id }); + expect(comment?.queueState).toBeUndefined(); + }); + }); + it("keeps an admitted message pending until its queued run starts", async () => { const queued = createIssueComment({ id: "not-started" }); mockIssuesApi.get.mockResolvedValue(createIssue({ status: "in_progress", assigneeAgentId: "agent-1", executionRunId: "run-queued" })); diff --git a/ui/src/pages/IssueDetail.tsx b/ui/src/pages/IssueDetail.tsx index d1d77565620..a852c5ede64 100644 --- a/ui/src/pages/IssueDetail.tsx +++ b/ui/src/pages/IssueDetail.tsx @@ -1793,8 +1793,16 @@ const IssueDetailChatTab = memo(function IssueDetailChatTab({ run.contextCommentId.length > 0 ? run.contextCommentId : null; - const inputIds = - batchedIds.length > 0 ? batchedIds : fallbackId ? [fallbackId] : []; + // Messages posted while the run was starting, which its first turn took. + const firstTurnIds = Array.isArray(run.firstTurnCommentIds) + ? run.firstTurnCommentIds.filter( + (value): value is string => typeof value === "string" && value.length > 0, + ) + : []; + const inputIds = [...new Set([ + ...(batchedIds.length > 0 ? batchedIds : fallbackId ? [fallbackId] : []), + ...firstTurnIds, + ])]; const anchorAt = run.startedAt ?? run.createdAt; const anchorMs = new Date(anchorAt).getTime(); inputIds.forEach((commentId, sequence) => { From 15afc32137cf0678087a204cc3652769c3b9af2a Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Sun, 15 Nov 2026 08:07:03 -0600 Subject: [PATCH 3/4] test(scaling): wait for agent setup and gate the ramp on a first started run (#21757) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The scaling effort uses a real-agent ramp harness (`scripts/scale-agents-ramp.ts`, added in #21695) to load a hosted test instance through the product API > - Its first real run held a 20-minute step with 10 tasks, 10 queued runs and 0 started runs, and reported only "concurrency_reached failed (observed 0)" > - The cause was in the harness: it bound the agents to a plugin Runner-task environment, which runs only agents with a managed AI connection. Each agent stayed in setup (status `paused`, setup state `verifying`) with that reason, so each run stayed queued. The product did what it is designed to do > - The harness did not wait for agent setup, did not read the setup error, and held the full step with nothing running. Its fake API created agents ready at once, so its tests could not catch this > - This pull request makes the harness wait for agent setup, gate the ramp on one started run, and stop within minutes with Paperclip's own reason > - The benefit is that a wrong environment or any other start blocker costs about one minute and prints the cause, not a 20-minute step with no explanation ## Linked Issues or Issue Description Refs #21695 **What happened?** A ramp of 10 then 50 agents on a hosted test stack created 10 agents, 10 tasks and 10 runs. In 20 minutes no run started. The result said only "concurrency_reached failed (observed 0)". Cleanup found every agent already paused and cancelled 10 queued runs. The tasks never left `todo` (status version 1, no checkout run). The agents were bound to the "Paperclip Sandbox (Daytona)" plugin environment, whose `daytona-tasks` driver declares `supportsTasks: true`. For such an environment, lifecycle verification refuses a `paperclip_runner` agent that has no `runtimeConfig.aiConnection` (`ai_connection_required`, see `server/src/services/agent-harness-verification.ts` and its test "refuses a plugin Runner-task agent without a managed AI connection before allocating a target"). The failure pauses automatic verification, so the agents never become ready. **Expected behavior** The harness must not create a full step of work before agents can run. When agents cannot finish setup, or when no run starts, it must stop soon, print the task, run and agent state with Paperclip's reason, and clean up. **Steps to reproduce** 1. Run `node --test scripts/scale-ramp/scale-ramp.test.ts` with the new fake (agents start in setup; `agentSetupError` keeps them there) and the old `ramp.ts`, `setup.ts` and `config.ts`. 2. The new test "stops within minutes with Paperclip's reason when the agents never finish setup" fails with `concurrency_reached`, the same result as the real run. 3. With this change, it stops with `agents_ready` and the setup reason in under 5 virtual minutes. **Paperclip version or commit** Instance on `2026.1106.0+2555.git.819f61f1f` (master at 11:34Z on 2026-11-15); harness from #21695. ## What Changed - `setup.ts`: add `waitForAgentsReady`, `agentReady` and `describeAgent`. The harness reads the company agent list until each agent has setup state `ready` and is not paused. It stops when an agent reports a setup error for 60 s, or after `--agent-ready-minutes` (default 10), and prints the agent's status, setup state, holds and Paperclip's reason. - `ramp.ts`: before the first step, a preflight creates one agent and one task and creates the rest only after that task's run starts. A new check stops the ramp when no run has started within `--start-timeout-minutes` (default 5) of the first task. The stop reason names the task status, any execution blocker, the run status, error code, error and liveness, and the agent's setup state. New stop criteria: `agents_ready` and `run_started`. Run records keep `error`, `errorCode` and `livenessReason`. - `config.ts`: add `--start-timeout-minutes` and `--agent-ready-minutes`. - `fake-paperclip.ts`: agents start as the real product creates them (status `paused`, setup state `preparing`) and become `ready` after `agentReadyDelayMs`, or stay in `verifying` with `agentSetupError`. Issue creation queues a run even for an agent in setup, as the real product does. Runs start only for a ready agent. - `scale-ramp.test.ts`: three tests. Agents that never finish setup stop the run with `agents_ready` and the reason, with one agent and no task created. A first task that never starts stops the run at the preflight with `run_started`, the task, run and agent state, and one cancelled run. The rest of a step is created only after the preflight task starts. - `doc/plans/2026-11-13-thousand-concurrent-agents.md`: the Phase 3 runbook describes the start checks, the first run's cause, and which environments the harness can use. ## Verification - `node --test scripts/scale-ramp/scale-ramp.test.ts`: 43 of 43 pass. - Red check: with the new fake and tests but the `origin/master` `ramp.ts`, `setup.ts` and `config.ts`, 3 tests fail. The setup test fails with `concurrency_reached` (the real run's result) where `agents_ready` is expected. - `tsc -p scripts/scale-ramp/tsconfig.json` (same options): no errors. - Read-only inspection of the hosted instance (GET only): task rows (`todo`, status version 1, no checkout run), activity (agent created, no pause, 10 `heartbeat.cancelled` at cleanup), the plugin manifest (`daytona-tasks` `supportsTasks: true`), and the company AI connections (no OpenRouter connection). The run and agent rows were deleted with the agents at cleanup, so their setup error was inferred from the code path and the cleanup counts, not read. - Not run: a new real ramp (needs the owner's go-ahead). ## Risks - Low risk. The change touches only the scale-ramp harness, its fake and its tests, and one runbook section. No product code changes. - A real ramp now spends up to one preflight start (seconds to minutes) before the first step. The preflight task is part of step 1 and the preflight running samples are dropped, so step metrics keep their meaning. - An agent whose setup error clears within 60 s does not stop the run. ## Model Used Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use (shell, file edits, read-only HTTP GETs to the test instance). ## 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 - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- .../2026-11-13-thousand-concurrent-agents.md | 25 ++- scripts/scale-ramp/config.ts | 6 + scripts/scale-ramp/fake-paperclip.ts | 29 ++- scripts/scale-ramp/ramp.ts | 117 +++++++++++- scripts/scale-ramp/scale-ramp.test.ts | 170 ++++++++++++++++++ scripts/scale-ramp/setup.ts | 91 +++++++++- 6 files changed, 423 insertions(+), 15 deletions(-) diff --git a/doc/plans/2026-11-13-thousand-concurrent-agents.md b/doc/plans/2026-11-13-thousand-concurrent-agents.md index 825f67dcdfa..24e850f2a4b 100644 --- a/doc/plans/2026-11-13-thousand-concurrent-agents.md +++ b/doc/plans/2026-11-13-thousand-concurrent-agents.md @@ -362,9 +362,12 @@ of other servers keep their records. `scripts/scale-agents-ramp.ts` runs real agents on a hosted instance through the product API only. It ramps concurrency in steps, holds each step, stops at -the first failed criterion, and always cleans up. It has run only against the -in-process fake API of its tests (`scripts/scale-ramp/scale-ramp.test.ts`). -A run on a real instance needs the owner's go-ahead. +the first failed criterion, and always cleans up. A run on a real instance +needs the owner's go-ahead. Its first real run, on 2026-11-15, held a +20-minute step with nothing running: it bound the agents to a plugin +Runner-task environment (Paperclip Sandbox (Daytona)), which needs a managed +AI connection, so every agent stayed in setup with that reason and every run +stayed queued. The harness now checks this before it creates the rest. **What one run does.** It creates a company named `Scale ramp `, or uses `--company ` (a Cloud-managed instance refuses company creation, so @@ -377,6 +380,22 @@ concurrency. Each task is the same small job: stream a sentence, run `pwd` and `ls`, write `scale-.txt` in the workspace, read it back, post a `CHECKPOINT` comment, post a `DONE` comment and mark the task done. +**Start checks.** A new agent cannot run until it finishes setup +(`lifecycleState` `ready`). Before each step the harness waits for its agents +to finish setup, at most `--agent-ready-minutes` (default 10). It stops when +an agent reports a setup error for 60 s, and prints the agent's state and +Paperclip's reason. Before the first step it creates one agent and one task, +and creates the rest only after that task's run starts. If no run starts +within `--start-timeout-minutes` (default 5) of the first task, it stops and +prints the task status, the run status and error, and the agent's state. +Every stop cleans up. + +**Environment.** Use a `sandbox`-driver environment (Paperclip Sandbox), +which takes the provider key the harness stores. A plugin environment that +runs Runner tasks (Paperclip Sandbox (Daytona), Paperclip Computer, +Paperclip Sandbox (Unikraft)) runs only agents with a managed AI connection. +The harness does not set one up, so its agents never finish setup there. + **Run it.** ```sh diff --git a/scripts/scale-ramp/config.ts b/scripts/scale-ramp/config.ts index 2165cbbe75d..65db8760d38 100644 --- a/scripts/scale-ramp/config.ts +++ b/scripts/scale-ramp/config.ts @@ -49,6 +49,8 @@ export interface Options { pollMs: number; boardProbeMs: number; taskMinutes: number; + startTimeoutMs: number; + agentReadyTimeoutMs: number; maxTasks: number | null; companyId: string | null; environmentId: string | null; @@ -141,6 +143,8 @@ export function parseOptions(argv: readonly string[], env: NodeJS.ProcessEnv, no "poll-seconds": { type: "string" }, "board-probe-seconds": { type: "string" }, "task-minutes": { type: "string" }, + "start-timeout-minutes": { type: "string" }, + "agent-ready-minutes": { type: "string" }, "max-tasks": { type: "string" }, company: { type: "string" }, environment: { type: "string" }, @@ -180,6 +184,8 @@ export function parseOptions(argv: readonly string[], env: NodeJS.ProcessEnv, no pollMs: number(values["poll-seconds"], "--poll-seconds", 15, 1, 300) * 1_000, boardProbeMs: number(values["board-probe-seconds"], "--board-probe-seconds", 10, 1, 300) * 1_000, taskMinutes: number(values["task-minutes"], "--task-minutes", 3, 0.5, 120), + startTimeoutMs: number(values["start-timeout-minutes"], "--start-timeout-minutes", 5, 1, 60) * 60_000, + agentReadyTimeoutMs: number(values["agent-ready-minutes"], "--agent-ready-minutes", 10, 1, 60) * 60_000, maxTasks: values["max-tasks"] === undefined ? null : number(values["max-tasks"], "--max-tasks", 0, 1, 1_000_000), companyId: values.company ?? env.PAPERCLIP_SCALE_COMPANY_ID ?? null, environmentId: values.environment ?? env.PAPERCLIP_SCALE_ENVIRONMENT_ID ?? null, diff --git a/scripts/scale-ramp/fake-paperclip.ts b/scripts/scale-ramp/fake-paperclip.ts index efd17e9d02a..0dcddcac131 100644 --- a/scripts/scale-ramp/fake-paperclip.ts +++ b/scripts/scale-ramp/fake-paperclip.ts @@ -19,6 +19,8 @@ export interface FakeConfig { token: string; origin: string; cloudManaged: boolean; + agentReadyDelayMs: number | ((index: number) => number); + agentSetupError: string | null; startDelayMs: number; runDurationMs: number; capacity: number; @@ -63,6 +65,7 @@ export class FakePaperclip { readonly memberCompanyIds: string[] = []; readonly environmentId = "00000000-0000-4000-8000-0000000000e1"; private seq = 0; + private agentsCreated = 0; private counts = new Map(); readonly clock: VirtualClock; @@ -73,6 +76,8 @@ export class FakePaperclip { token: "board-token-value", origin: "https://scale1.test.paperclip.app", cloudManaged: false, + agentReadyDelayMs: 3_000, + agentSetupError: null, startDelayMs: 2_000, runDurationMs: 60_000, capacity: Number.POSITIVE_INFINITY, @@ -115,8 +120,24 @@ export class FakePaperclip { return [...this.runs.values()].filter(run => ["queued", "running"].includes(run.status)); } + private invokable(agentId: string): boolean { + const agent = this.agents.get(agentId); + return Boolean(agent && agent.lifecycleState === "ready" && agent.status === "idle"); + } + advance(): void { const now = this.clock.now(); + for (const agent of this.agents.values()) { + const delay = typeof this.config.agentReadyDelayMs === "function" ? this.config.agentReadyDelayMs(agent.index) : this.config.agentReadyDelayMs; + if (!["preparing", "verifying"].includes(agent.lifecycleState) || now < agent.createdAt + delay) continue; + if (this.config.agentSetupError) { + agent.lifecycleState = "verifying"; + agent.lifecycleError = this.config.agentSetupError; + } else { + agent.lifecycleState = "ready"; + agent.status = "idle"; + } + } for (const run of [...this.runs.values()].sort((a, b) => a.createdAt - b.createdAt)) { if (run.status === "running" && run.startedAt !== null && now >= run.startedAt + this.config.runDurationMs) { run.finishedAt = run.startedAt + this.config.runDurationMs; @@ -131,7 +152,7 @@ export class FakePaperclip { } } for (const run of [...this.runs.values()].sort((a, b) => a.createdAt - b.createdAt)) { - if (run.status !== "queued" || now < run.createdAt + this.config.startDelayMs) continue; + if (run.status !== "queued" || now < run.createdAt + this.config.startDelayMs || !this.invokable(run.agentId)) continue; if (this.running() >= this.config.capacity) break; run.status = "running"; run.startedAt = Math.max(run.createdAt + this.config.startDelayMs, now - 1_000); @@ -145,6 +166,7 @@ export class FakePaperclip { return { id: run.id, agentId: run.agentId, issueId: run.issueId, status: run.status, createdAt: iso(run.createdAt), startedAt: iso(run.startedAt), finishedAt: iso(run.finishedAt), costUsd: run.status === "succeeded" || run.status === "failed" ? this.config.costPerRunUsd : null, + error: null, errorCode: null, }; } @@ -208,7 +230,8 @@ export class FakePaperclip { if (c === "agents") { if (method === "GET") return json(200, [...this.agents.values()].filter(agent => agent.companyId === companyId)); const id = this.id(); - this.agents.set(id, { id, companyId, name: body.name, status: "idle", lifecycleState: null, payload: body }); + this.agents.set(id, { id, companyId, name: body.name, status: "paused", lifecycleState: "preparing", lifecycleHolds: [], lifecycleError: null, + pauseReason: null, createdAt: now, index: this.agentsCreated++, payload: body }); return json(201, this.agents.get(id)); } if (c === "issues") { @@ -217,7 +240,7 @@ export class FakePaperclip { this.issues.set(id, { id, companyId, title: body.title, description: body.description, status: "todo", assigneeAgentId: body.assigneeAgentId, projectId: body.projectId ?? null, hiddenAt: null, interruption: null }); const agent = this.agents.get(body.assigneeAgentId); - if (agent && agent.status !== "paused" && agent.status !== "terminated") { + if (agent && agent.status !== "terminated") { const runId = this.id(); this.runs.set(runId, { id: runId, agentId: body.assigneeAgentId, issueId: id, status: "queued", createdAt: now, startedAt: null, finishedAt: null, willFail: false }); } diff --git a/scripts/scale-ramp/ramp.ts b/scripts/scale-ramp/ramp.ts index 9dc68a00faa..848ac9c267c 100644 --- a/scripts/scale-ramp/ramp.ts +++ b/scripts/scale-ramp/ramp.ts @@ -2,7 +2,7 @@ import { readMetrics, type Clock, type Fetcher, type PaperclipClient } from "./c import type { Options, Step } from "./config.ts"; import { evaluate, firstFailure, type CriterionResult, type ServerMetrics, type StepMetrics } from "./criteria.ts"; import { LIVE_RUN_STATUSES } from "./cleanup.ts"; -import { ensureAgents } from "./setup.ts"; +import { AgentsNotReady, describeAgent, ensureAgents, waitForAgentsReady } from "./setup.ts"; import { distribution } from "./stats.ts"; import { mapLimit, taskTag, type RunState, type StateStore } from "./state.ts"; import { runTiming, taskBrief, taskNonce, taskTitle, type RunEvent } from "./workload.ts"; @@ -19,6 +19,7 @@ export const BOARD_MIX = [ const FAILED_RUN = new Set(["failed", "timed_out"]); const RESTING_NOT_DONE = new Set(["cancelled", "blocked", "in_review"]); +const ENDED_RUN = new Set(["failed", "timed_out", "cancelled", "succeeded", "interrupted"]); const RUN_PAGE = 1_000; const IDS_PER_READ = 100; const RETRY_CHECK_AFTER_MS = 60_000; @@ -51,6 +52,9 @@ interface RunRecord { finishedAt: number | null; costUsd: number; sampled: boolean; + error: string | null; + errorCode: string | null; + liveness: string | null; } interface StepAccumulator { @@ -216,14 +220,16 @@ export class Ramp { break; } log(`Step ${step.index + 1}/${options.steps.length}: ${step.concurrency} agents for ${Math.round(step.holdMs / 60_000)} min`); - await ensureAgents({ api: this.deps.api, options, state: this.deps.state, store: this.deps.store, count: step.concurrency }); const accumulator: StepAccumulator = { step, startedAt: clock.now(), endedAt: null, runningSamples: [], boardMs: [], boardRequests: 0, boardFailures: 0, serverSamples: [], ttftMs: [], firstActivityMs: [], sampled: 0 }; this.accumulators.push(accumulator); - this.nextPollAt = 0; - this.nextBoardAt = 0; - const until = accumulator.startedAt + step.holdMs; - stop = await this.loop(until, step.concurrency); + stop = await this.prepareStep(step); + if (!stop) { + this.nextPollAt = 0; + this.nextBoardAt = 0; + accumulator.startedAt = clock.now(); + stop = await this.loop(accumulator.startedAt + step.holdMs, step.concurrency); + } accumulator.endedAt = clock.now(); const atEnd = evaluate(this.metrics(step.index), options.thresholds); results.push({ index: step.index, concurrency: step.concurrency, holdMs: step.holdMs, metrics: this.metrics(step.index), criteriaAtEnd: atEnd, criteriaFinal: atEnd }); @@ -253,6 +259,97 @@ export class Ramp { }; } + private async prepareStep(step: Step): Promise { + try { + if (step.index === 0) { + const stop = await this.preflight(); + if (stop) return stop; + } + if (this.deps.shouldStop()) return { stepIndex: step.index, reason: "interrupted before the step", criterion: null }; + await ensureAgents({ api: this.deps.api, options: this.deps.options, state: this.deps.state, store: this.deps.store, count: step.concurrency }); + return await this.awaitAgents(step.concurrency, step.index); + } catch (error) { + if (!(error instanceof AgentsNotReady)) throw error; + this.deps.log(`Stopping: ${error.message}`); + return { stepIndex: step.index, reason: error.message, criterion: "agents_ready" }; + } + } + + private async awaitAgents(count: number, stepIndex: number): Promise { + const { api, clock, options, state, log, shouldStop } = this.deps; + let stop: StopReason | null = null; + await waitForAgentsReady({ api, clock, companyId: this.companyId, agentIds: state.agentIds.slice(0, count), timeoutMs: options.agentReadyTimeoutMs, + pollMs: Math.min(options.pollMs, 5_000), shouldStop, log, + tick: async () => { + if (!this.tasks.size) return false; + await this.poll(false); + stop = this.immediateStop(stepIndex); + return stop !== null; + } }); + return stop; + } + + private async preflight(): Promise { + const { api, clock, options, state, store, log } = this.deps; + await ensureAgents({ api, options, state, store, count: 1 }); + const notReady = await this.awaitAgents(1, 0); + if (notReady) return notReady; + if (this.deps.shouldStop()) return { stepIndex: 0, reason: "interrupted before the step", criterion: null }; + log(`Preflight: one task on one agent must start within ${Math.round(options.startTimeoutMs / 60_000)} min before the rest are created`); + await this.topUp(1, 0, Number.POSITIVE_INFINITY); + const task = [...this.tasks.values()][0]; + if (!task) return { stepIndex: 0, reason: "the preflight task was not created", criterion: "run_started" }; + for (;;) { + if (this.deps.shouldStop()) return { stepIndex: 0, reason: "interrupted", criterion: null }; + await this.poll(); + const immediate = this.immediateStop(0); + if (immediate) return immediate; + if (this.anyStarted()) { + log(`Preflight passed: the first task started ${Math.round((clock.now() - task.createdAt) / 1_000)} s after it was created`); + this.current().runningSamples.length = 0; + return null; + } + const ended = this.runsOf(task.id).find(run => run.finishedAt !== null || ENDED_RUN.has(run.status)); + if (task.outcome !== "open" || ended) { + return this.stall(0, task, `the preflight task ended before any run started`); + } + const stop = await this.noStartStop(0); + if (stop) return stop; + await clock.sleep(options.pollMs); + } + } + + private anyStarted(): boolean { + for (const run of this.runs.values()) if (run.startedAt !== null || run.status === "running") return true; + return false; + } + + private async noStartStop(stepIndex: number): Promise { + const { clock, options } = this.deps; + if (!this.tasks.size || this.anyStarted()) return null; + const first = [...this.tasks.values()].sort((a, b) => a.createdAt - b.createdAt)[0]!; + if (clock.now() - first.createdAt < options.startTimeoutMs) return null; + return this.stall(stepIndex, first, `no run started within ${Math.round(options.startTimeoutMs / 60_000)} min of the first task`); + } + + private async stall(stepIndex: number, task: TaskRecord, headline: string): Promise { + const { api, log } = this.deps; + const [view, agents] = await Promise.all([ + api.get(`/api/issues/${task.id}`).catch(() => null), + api.get(`/api/companies/${this.companyId}/agents`).catch(() => [] as Json[]), + ]); + const run = this.runsOf(task.id).at(-1); + const agent = agents.find(candidate => String(candidate.id) === task.agentId); + const runLine = run + ? `its run ${run.id} is ${run.status}${run.errorCode ? ` (${run.errorCode})` : ""}${run.error ? `: ${run.error.slice(0, 300)}` : ""}${run.liveness ? `; liveness: ${run.liveness}` : ""}` + : "Paperclip lists no run for it"; + const blocker = view?.executionBlocker ? `; execution blocker: ${JSON.stringify(view.executionBlocker).slice(0, 300)}` : ""; + const reason = `${headline}. Task ${task.nonce} is ${view?.status ?? task.status}` + + `${blocker}; ${runLine}; ${agent ? describeAgent(agent) : `agent ${task.agentId} is not listed`}`; + log(`Stopping: ${reason}`); + return { stepIndex, reason, criterion: "run_started" }; + } + private async loop(until: number, concurrency: number, draining = false): Promise { const { clock, options } = this.deps; const stepIndex = this.current().step.index; @@ -265,7 +362,7 @@ export class Ramp { if (clock.now() >= this.nextPollAt) { this.nextPollAt = clock.now() + options.pollMs; await this.poll(); - const stop = this.immediateStop(stepIndex); + const stop = this.immediateStop(stepIndex) ?? await this.noStartStop(stepIndex); if (stop) return stop; if (!draining) await this.topUp(concurrency, stepIndex, until); else if (this.openTasks().length === 0) return null; @@ -337,13 +434,14 @@ export class Ramp { } } - private async poll(): Promise { + private async poll(recordSample = true): Promise { await this.readRuns(); await this.readTasks(); await this.checkRetry(); await this.sampleEvents(); let running = 0; for (const run of this.runs.values()) if (run.status === "running") running += 1; + if (!recordSample) return; this.current().runningSamples.push(running); if (this.deps.options.metricsUrl) { const sample = await readMetrics(this.deps.fetcher, this.deps.options.metricsUrl, this.deps.metricsToken, this.deps.clock); @@ -362,6 +460,9 @@ export class Ramp { this.runs.set(id, { id, taskId, agentId: String(row.agentId), status: String(row.status), createdAt: ms(row.createdAt), startedAt: ms(row.startedAt), finishedAt: ms(row.finishedAt), costUsd: num(row.costUsd) ?? previous?.costUsd ?? 0, sampled: previous?.sampled ?? false, + error: typeof row.error === "string" && row.error ? row.error : null, + errorCode: typeof row.errorCode === "string" && row.errorCode ? row.errorCode : null, + liveness: typeof row.livenessReason === "string" && row.livenessReason ? row.livenessReason : null, }); const own = this.runsByTask.get(taskId) ?? new Set(); own.add(id); diff --git a/scripts/scale-ramp/scale-ramp.test.ts b/scripts/scale-ramp/scale-ramp.test.ts index 6a34655e617..3eab4e9ac87 100644 --- a/scripts/scale-ramp/scale-ramp.test.ts +++ b/scripts/scale-ramp/scale-ramp.test.ts @@ -349,6 +349,176 @@ describe("ramp against the fake API", () => { assert.equal(result.cleanup!.activeSandboxLeases, 0); }); + it("stops within minutes with Paperclip's reason when the agents never finish setup", async () => { + const out = await tempDir(); + const reason = "Execution configuration check failed. This agent's environment requires a managed AI connection and an isolated Runner home. " + + "Check both in Configuration, then retry. Automatic verification is paused. Update Configuration or choose Retry now."; + const h = harness({ agentSetupError: reason }); + const started = h.clock.now(); + const code = await main(baseArgs(out, ["--steps", "10,50", "--hold-minutes", "20", "--confirm-spend", "100"]), h.deps); + const result = await readResult(out); + assert.equal(code, EXIT.fail); + assert.equal(result.stop!.criterion, "agents_ready"); + assert.ok(result.stop!.reason.includes(reason), result.stop!.reason); + assert.match(result.stop!.reason, /setup state verifying/); + assert.ok(h.clock.now() - started < 5 * 60_000, "the step is not held while nothing can run"); + const agents = h.fake.requests.filter(request => request.method === "POST" && new URL(request.url).pathname.endsWith("/agents")); + assert.equal(agents.length, 1, "only the preflight agent is created"); + assert.equal(h.fake.issues.size, 0); + assertCleanedUp(h.fake); + }); + + it("stops at the preflight with the task, run and agent state when the first task never starts", async () => { + const out = await tempDir(); + const h = harness({ capacity: 0 }); + const started = h.clock.now(); + const code = await main(baseArgs(out, ["--steps", "10,50", "--hold-minutes", "20", "--confirm-spend", "100", "--start-timeout-minutes", "3"]), h.deps); + const result = await readResult(out); + assert.equal(code, EXIT.fail); + assert.equal(result.stop!.criterion, "run_started"); + assert.match(result.stop!.reason, /no run started within 3 min/); + assert.match(result.stop!.reason, /is todo/); + assert.match(result.stop!.reason, /is queued/); + assert.match(result.stop!.reason, /setup state ready/); + assert.ok(h.clock.now() - started < 5 * 60_000); + assert.equal(h.fake.issues.size, 1, "only the preflight task is created"); + assert.equal(result.cleanup!.runsCancelled, 1); + assertCleanedUp(h.fake); + }); + + it("creates the rest of the step only after the preflight task starts", async () => { + const out = await tempDir(); + const h = harness(); + await main(baseArgs(out, ["--steps", "3"]), h.deps); + const posts = h.fake.requests.map(request => request.method === "POST" ? new URL(request.url).pathname : ""); + const firstTask = posts.findIndex(route => route.endsWith("/issues")); + const secondAgent = posts.findIndex((route, index) => route.endsWith("/agents") && posts.slice(0, index).some(earlier => earlier.endsWith("/agents"))); + assert.ok(firstTask >= 0 && secondAgent > firstTask, "the second agent is created after the first task"); + const result = await readResult(out); + assert.equal(result.steps[0]!.metrics.peakRunning, 3); + }); + + const preflightCases: Array<{ name: string; mutate: (issue: Record, run: { status: string; finishedAt: number | null }, now: number) => void; + criterion: string; reason: RegExp }> = [ + { name: "cancelled", criterion: "run_started", reason: /ended before any run started.*is cancelled.*is cancelled/, + mutate: (issue, run, now) => { issue.status = "cancelled"; run.status = "cancelled"; run.finishedAt = now; } }, + { name: "blocked", criterion: "run_started", reason: /ended before any run started.*is blocked.*is queued/, + mutate: issue => { issue.status = "blocked"; } }, + { name: "failed before it started", criterion: "failed_runs_zero", reason: /failed_runs_zero failed/, + mutate: (_issue, run, now) => { run.status = "failed"; run.finishedAt = now; } }, + ]; + for (const preflight of preflightCases) { + it(`stops at once and creates nothing more when the preflight task is ${preflight.name}`, async () => { + const out = await tempDir(); + const h = harness({ capacity: 0 }); + const original = h.deps.fetcher; + h.deps.fetcher = async (url, init) => { + const response = await original(url, init); + if (init.method === "POST" && new URL(url).pathname.endsWith("/issues")) { + const issue = h.fake.issues.get((await response.clone().json() as { id: string }).id)!; + const run = [...h.fake.runs.values()].find(candidate => candidate.issueId === issue.id)!; + preflight.mutate(issue, run, h.clock.now()); + } + return response; + }; + const started = h.clock.now(); + const code = await main(baseArgs(out, ["--steps", "3", "--hold-minutes", "20", "--confirm-spend", "100"]), h.deps); + const result = await readResult(out); + assert.equal(code, EXIT.fail); + assert.equal(result.stop!.criterion, preflight.criterion); + assert.match(result.stop!.reason, preflight.reason); + assert.ok(h.clock.now() - started < 2 * 60_000, "it does not wait for the start timeout"); + assert.equal(h.fake.issues.size, 1); + const agents = h.fake.requests.filter(request => request.method === "POST" && new URL(request.url).pathname.endsWith("/agents")); + assert.equal(agents.length, 1); + assertCleanedUp(h.fake); + }); + } + + it("passes the preflight when its task starts and finishes between two polls", async () => { + const out = await tempDir(); + const h = harness({ startDelayMs: 0, runDurationMs: 1_000 }); + await main(baseArgs(out, ["--steps", "3"]), h.deps); + const result = await readResult(out); + assert.notEqual(result.stop?.criterion, "run_started"); + const agents = h.fake.requests.filter(request => request.method === "POST" && new URL(request.url).pathname.endsWith("/agents")); + assert.equal(agents.length, 3); + assert.ok(result.steps[0]!.metrics.tasksFinished > 1); + }); + + it("keeps reading runs while it waits for the next step's agents, and stops on a run that fails then", async () => { + const out = await tempDir(); + const h = harness({ failWhenRunningAbove: 0, runDurationMs: 3 * 60_000, agentReadyDelayMs: index => index === 0 ? 3_000 : 10 * 60_000 }); + const started = h.clock.now(); + const code = await main(baseArgs(out, ["--steps", "1,3", "--min-concurrency-ratio", "0.5"]), h.deps); + const result = await readResult(out); + assert.equal(code, EXIT.fail); + assert.equal(result.stop!.stepIndex, 1); + assert.equal(result.stop!.criterion, "failed_runs_zero"); + assert.equal(result.steps[0]!.metrics.runsFailed, 1); + assert.ok(h.clock.now() - started < 6 * 60_000, "the failure is seen during the agent wait, not after it"); + assertCleanedUp(h.fake); + }); + + it("reports a step window equal to its hold when the step takes minutes to prepare", async () => { + const out = await tempDir(); + const h = harness({ agentReadyDelayMs: index => index === 0 ? 3_000 : 5 * 60_000 }); + const started = h.clock.now(); + await main(baseArgs(out, ["--steps", "3", "--drain-minutes", "0"]), h.deps); + const result = await readResult(out); + const metrics = result.steps[0]!.metrics; + assert.ok(metrics.startedAt - started >= 5 * 60_000, "the hold starts after the agents finish setup"); + assert.equal(metrics.endedAt! - metrics.startedAt, 2 * 60_000); + }); + + it("keeps waiting for agent setup through a few failed agent list reads", async () => { + const out = await tempDir(); + const h = harness({ failRequest: (method, route, count) => method === "GET" && route.endsWith("/agents") && count <= 3 + ? { status: 500, body: "{\"error\":\"database busy\"}" } : null }); + await main(baseArgs(out, ["--steps", "2"]), h.deps); + const result = await readResult(out); + assert.notEqual(result.stop?.criterion, "agents_ready"); + assert.equal(result.error, null); + assert.equal(result.steps[0]!.metrics.peakRunning, 2); + }); + + it("stops with the status it saw when the agent list keeps failing during setup", async () => { + const out = await tempDir(); + const h = harness({ failRequest: (method, route, count) => method === "GET" && route.endsWith("/agents") && count <= 5 + ? { status: 500, body: "{\"error\":\"database busy\"}" } : null }); + const code = await main(baseArgs(out, ["--steps", "2"]), h.deps); + const result = await readResult(out); + assert.equal(code, EXIT.fail); + assert.equal(result.error, null); + assert.equal(result.stop!.criterion, "agents_ready"); + assert.match(result.stop!.reason, /could not be read 5 times in a row.*returned 500/); + assertCleanedUp(h.fake); + }); + + it("starts cleanup at once when interrupted while agent list reads fail", async () => { + const out = await tempDir(); + let cleaning = false; + let failed = 0; + const h = harness({ failRequest: (method, route) => { + if (cleaning || method !== "GET" || !route.endsWith("/agents")) return null; + failed += 1; + if (failed === 2) h.interrupt(); + return { status: 500, body: "{\"error\":\"database busy\"}" }; + } }); + const out0 = h.deps.out; + h.deps.out = line => { + if (line.startsWith("Cleaning up")) cleaning = true; + out0(line); + }; + const started = h.clock.now(); + await main(baseArgs(out, ["--steps", "2"]), h.deps); + const result = await readResult(out); + assert.equal(failed, 2, "no agent list read is retried after the interrupt"); + assert.match(result.stop!.reason, /interrupted/); + assert.ok(h.clock.now() - started < 15_000, "cleanup starts within one poll interval"); + assertCleanedUp(h.fake); + }); + it("reports missing optional sources as not measured", async () => { const out = await tempDir(); const h = harness(); diff --git a/scripts/scale-ramp/setup.ts b/scripts/scale-ramp/setup.ts index b442f2c859f..a91fd7dee84 100644 --- a/scripts/scale-ramp/setup.ts +++ b/scripts/scale-ramp/setup.ts @@ -1,4 +1,4 @@ -import { ApiError, type PaperclipClient } from "./client.ts"; +import { ApiError, type Clock, type PaperclipClient } from "./client.ts"; import type { AgentProfile, Options } from "./config.ts"; import { agentName, companyName, mapLimit, projectName, secretPrefix, type RunState, type StateStore } from "./state.ts"; @@ -138,3 +138,92 @@ export async function ensureAgents(input: { } export const AGENT_CREATE_PARALLELISM = 8; +export const LIFECYCLE_ERROR_GRACE_MS = 60_000; +export const AGENT_LIST_FAILURE_LIMIT = 5; + +export class AgentsNotReady extends Error { + constructor(message: string) { + super(message); + this.name = "AgentsNotReady"; + } +} + +const NOT_INVOKABLE = new Set(["paused", "terminated", "pending_approval"]); + +export function agentReady(agent: Json): boolean { + if (agent.lifecycleState === "ready") return !NOT_INVOKABLE.has(String(agent.status)); + return agent.lifecycleState == null && ["idle", "active", "running", "error"].includes(String(agent.status)); +} + +export function describeAgent(agent: Json): string { + const parts = [`agent ${agent.name ?? agent.id} is ${agent.status ?? "missing"}`]; + if (agent.lifecycleState) parts.push(`setup state ${agent.lifecycleState}`); + if (agent.pauseReason) parts.push(`pause reason ${agent.pauseReason}`); + if (Array.isArray(agent.lifecycleHolds) && agent.lifecycleHolds.length) parts.push(`holds ${agent.lifecycleHolds.join(", ")}`); + const reason = agent.lifecycleError ?? agent.errorReason; + return `${parts.join(", ")}; ${reason ? `Paperclip says: ${String(reason).slice(0, 400)}` : "Paperclip gave no reason"}`; +} + +export async function waitForAgentsReady(input: { + api: PaperclipClient; + clock: Clock; + companyId: string; + agentIds: readonly string[]; + timeoutMs: number; + pollMs: number; + shouldStop: () => boolean; + log: (line: string) => void; + tick?: () => Promise; +}): Promise { + const { api, clock } = input; + const started = clock.now(); + const erroredSince = new Map(); + let logged = false; + let readFailures = 0; + for (;;) { + if (input.shouldStop()) return false; + let listed: Json[]; + try { + listed = await api.get(`/api/companies/${input.companyId}/agents`); + readFailures = 0; + } catch (error) { + readFailures += 1; + if (input.shouldStop()) return false; + const message = error instanceof Error ? error.message : String(error); + if (readFailures >= AGENT_LIST_FAILURE_LIMIT) { + throw new AgentsNotReady(`the agent list could not be read ${readFailures} times in a row while waiting for agent setup: ${message.slice(0, 300)}`); + } + if (clock.now() - started >= input.timeoutMs) { + throw new AgentsNotReady(`agent setup could not be checked within ${Math.round(input.timeoutMs / 60_000)} min: ${message.slice(0, 300)}`); + } + await clock.sleep(input.pollMs); + continue; + } + const byId = new Map(listed.map(agent => [String(agent.id), agent])); + const waiting = input.agentIds.map(id => byId.get(id) ?? { id, status: null }).filter(agent => !agentReady(agent)); + if (!waiting.length) { + if (logged) input.log(`All ${input.agentIds.length} agents finished setup after ${Math.round((clock.now() - started) / 1_000)} s`); + return true; + } + if (input.shouldStop() || await input.tick?.()) return false; + const now = clock.now(); + for (const agent of waiting) { + const id = String(agent.id); + if (agent.lifecycleError) { + if (!erroredSince.has(id)) erroredSince.set(id, now); + } else erroredSince.delete(id); + } + const stuck = waiting.find(agent => now - (erroredSince.get(String(agent.id)) ?? now) >= LIFECYCLE_ERROR_GRACE_MS); + if (stuck) { + throw new AgentsNotReady(`${waiting.length} of ${input.agentIds.length} agents cannot finish setup: ${describeAgent(stuck)}`); + } + if (now - started >= input.timeoutMs) { + throw new AgentsNotReady(`${waiting.length} of ${input.agentIds.length} agents did not finish setup within ${Math.round(input.timeoutMs / 60_000)} min: ${describeAgent(waiting[0]!)}`); + } + if (!logged) { + input.log(`Waiting for ${waiting.length} agents to finish setup (${describeAgent(waiting[0]!)})`); + logged = true; + } + await clock.sleep(input.pollMs); + } +} From 56654adecdb93bbfb4ee7e66f6c8204cbf5c9b2b Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Sun, 15 Nov 2026 08:09:04 -0600 Subject: [PATCH 4/4] perf(server): reuse sandbox provider schemas for five seconds on the remote-run path (#21758) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Agent runs can use remote sandboxes that a sandbox provider plugin supplies (for example Daytona) > - Each sandbox operation resolves the environment config, and that step reads the provider config schema to find the secret-ref fields > - On a hosted instance with 7 remote runs, this schema read was the most frequent statement: 17.95 per second, about 2.5 per second for each run > - The server runs all agents on one Node main thread, so each statement costs main-thread time; at 1,000 agents this read alone is about 2,500 statements per second > - This pull request reuses the retained schema for a short, bounded time and drops it at once when the plugin registry changes a plugin manifest > - The benefit is that a live remote run reads the schema about once per 5 seconds for each provider, not once per operation ## Linked Issues or Issue Description **What existing behavior does this improve?** Every plugin sandbox operation (exec, file sync in/out, runner ingress attach, capability snapshot, workspace realize, lease resume, lease release) calls `resolveEnvironmentDriverConfigForRuntime`. That call runs the `with selected_provider as materialized ...` statement in `resolvePluginSandboxProviderConfigSchema`, every time. **Subsystem affected** Server: plugin environment driver (`server/src/services/plugin-environment-driver.ts`) and the plugin registry manifest writes. **Current behavior** The schema read runs once per operation. A census test that drives the real runtime calls of one remote run counts 19 schema reads for 19 operations (see the table below). The hosted measurement was 17.95 executions per second with 7 runs. **Proposed behavior** The read runs at most once per 5 seconds for each provider and database client. A plugin install, upgrade or uninstall through the plugin registry in the same process takes effect on the next operation. **Reason and benefit** The schema is instance-wide plugin manifest data. It does not change during normal runs. Re-reading it per operation spends main-thread and database time for no new information. **Breaking changes** None. No API, schema or saved-state change. ## What Changed - `resolvePluginSandboxProviderConfigSchema` now returns the retained schema without a database read when the entry was checked less than `PROVIDER_SCHEMA_REUSE_MS` (5,000 ms) ago and the plugin manifest revision did not change. After that, it uses the existing cheap revision check, as before. - A lookup sequence number stops an older, slower lookup from replacing a newer retained entry. - A missing provider is still never retained, so a provider that becomes available is used on the next operation. - New module `plugin-manifest-revision.ts` holds an in-process manifest revision counter. It is a separate module so that the registry and the driver do not import each other. - `plugin-registry.ts`: `install` (both the new-row and the reinstall paths), `update` and `uninstall` announce a manifest change after the write completes. This is 5 changed lines plus 1 import line. Status-only writes do not announce, because the schema read does not use plugin status. - `plugin-loader.ts`: `installPlugin` runs `registry.install` inside an outer transaction. It now announces the manifest change again after that transaction settles, so a schema read made before the commit cannot be reused after it. This is 1 changed line plus 1 import line. - Statement census per operation, before and after. One remote run, one secret-ref field in the provider config, embedded test database, fake in-process plugin worker: | Operation | Count | Schema reads before | Schema reads after | All statements before | All statements after | | --- | --- | --- | --- | --- | --- | | Lease acquire | 1 | 1 | 1 | 26 | 26 | | Runner attach (ingress endpoint) | 1 | 2 | 0 | 11 | 9 | | Capability snapshot | 1 | 1 | 0 | 6 | 5 | | Exec | 10 | 10 | 0 | 50 | 40 | | File write (sync in) | 1 | 1 | 0 | 5 | 4 | | File read (sync out) | 1 | 1 | 0 | 5 | 4 | | Workspace realize | 1 | 1 | 0 | 5 | 4 | | Lease resume (reattach) | 1 | 1 | 0 | 6 | 5 | | Lease release | 1 | 1 | 0 | 18 | 17 | | **Total** | 18 | **19** | **1** | 132 | 114 | - Other reads that stay on each operation (reported, not changed in this pull request): each exec resolves each secret-ref field with 3 reads (secret, binding, version) and 1 `secret_access_events` insert. Runner attach and the capability snapshot also read the plugin row by id. These are part of the secret authorization and audit path, so they keep their own checks. ## Verification - `cd server && npx vitest run src/__tests__/plugin-sandbox-provider-schema-census.test.ts` (new). On master the census test fails with 19 schema reads. With this change it passes with 1. - The new tests also prove these points: - A registry upgrade that changes the secret-ref fields takes effect on the next call in the same process. - A direct manifest change (as from another server process) takes effect after the 5-second bound, and no read occurs inside the bound. - A registry uninstall takes effect at once. - A plugin reinstall through `pluginLoader.installPlugin` takes effect after its install transaction commits, even when a schema read ran inside the uncommitted transaction. This test failed before the post-commit announcement and passes with it. - A missing provider is not retained. The next call after install reads and uses it. - Two companies share the provider schema but each gets only its own secret values. A cross-company secret id still fails with "Secret must belong to same company". - A new database client (a process restart) starts cold, as before. - `cd server && npx vitest run src/__tests__/plugin-database.test.ts`: passed (plugin install transaction paths). - `cd server && npx vitest run src/__tests__/sandbox-provider-schema-reads.test.ts`: the existing tests now step the clock past the bound where they change the database directly. - `cd server && npx vitest run src/__tests__/environment-runtime.test.ts`: 210 passed. - `cd server && npx vitest run src/__tests__/bundled-plugin-registration.test.ts src/__tests__/external-object-refresh-work.test.ts src/__tests__/plugin-lifecycle-restart.test.ts src/__tests__/plugin-loader-error-retry.test.ts src/__tests__/plugin-environment-driver-sandbox-capabilities.test.ts src/__tests__/plugin-sandbox-provider-config-validation.test.ts src/__tests__/environment-probe.test.ts`: 82 passed, 1 skipped. - `cd server && pnpm typecheck`: passed. ## Risks - Staleness bound: a plugin manifest change made by a different server process (for example during an overlapping deploy) can take up to 5 seconds to apply here. During that time, a secret-ref field that an upgrade adds is not resolved yet, and a field that an upgrade removes is still resolved. The bound is short and it applies only to which config paths are secret refs. - The retained value is instance-wide plugin manifest data, keyed by database client and driver key. It contains no company data and no secret values. It does not take part in an authorization decision. Secret resolution, the environment binding check and the access audit still run on each operation for the calling company. - Memory stays bounded by the existing limits: 32 entries per database client, 64 KiB per schema. - `plugin-registry.ts` has a small edit in `install`, `update` and `uninstall`. Other open work in that file can cause a simple merge conflict. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude Code with tool use (shell, file edit, test runs). ## 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 - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge Refs #17581 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- ...gin-sandbox-provider-schema-census.test.ts | 313 ++++++++++++++++++ .../sandbox-creation-operations.test.ts | 3 + .../sandbox-provider-schema-reads.test.ts | 23 +- .../src/services/plugin-environment-driver.ts | 22 +- server/src/services/plugin-loader.ts | 3 +- .../src/services/plugin-manifest-revision.ts | 9 + server/src/services/plugin-registry.ts | 9 +- 7 files changed, 372 insertions(+), 10 deletions(-) create mode 100644 server/src/__tests__/plugin-sandbox-provider-schema-census.test.ts create mode 100644 server/src/services/plugin-manifest-revision.ts diff --git a/server/src/__tests__/plugin-sandbox-provider-schema-census.test.ts b/server/src/__tests__/plugin-sandbox-provider-schema-census.test.ts new file mode 100644 index 00000000000..1f18c8b5084 --- /dev/null +++ b/server/src/__tests__/plugin-sandbox-provider-schema-census.test.ts @@ -0,0 +1,313 @@ +import { randomUUID } from "node:crypto"; +import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { eq } from "drizzle-orm"; +import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest"; +import { + agents, + companies, + createDb, + environments, + heartbeatRuns, + plugins, + type Db, +} from "@paperclipai/db"; +import type { Environment, PaperclipPluginManifestV1, PluginEnvironmentDriverDeclaration } from "@paperclipai/shared"; +import { environmentRuntimeService } from "../services/environment-runtime.ts"; +import { resolveSandboxProviderSecretRefPaths } from "../services/environment-config.ts"; +import { pluginRegistryService } from "../services/plugin-registry.ts"; +import { pluginLoader } from "../services/plugin-loader.ts"; +import { secretService } from "../services/secrets.ts"; +import type { PluginWorkerManager } from "../services/plugin-worker-manager.ts"; +import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js"; +import { meterDatabaseStatements } from "./helpers/database-statement-meter.js"; + +const support = await getEmbeddedPostgresTestSupport(); +const PROVIDER_SCHEMA_STATEMENT = "with selected_provider as materialized"; +const SCHEMA_REUSE_BOUND_MS = 5_000; + +describe.skipIf(!support.supported)("sandbox provider schema reads on the live remote-run path", () => { + let database: Awaited>; + let seedDb: Db; + const clients: Db[] = []; + const meters: Array> = []; + + beforeAll(async () => { + database = await startEmbeddedPostgresTestDatabase("sandbox-schema-census-"); + seedDb = createDb(database.connectionString); + }, 120_000); + afterEach(async () => { + vi.useRealTimers(); + meters.splice(0).reverse().forEach(meter => meter.uninstall()); + await Promise.all(clients.splice(0).map(client => client.$client.end({ timeout: 1 }))); + }); + afterAll(async () => { + await seedDb?.$client.end({ timeout: 1 }); + await database?.cleanup(); + }); + + function meteredClient() { + const client = createDb(database.connectionString); + clients.push(client); + const meter = meterDatabaseStatements(client, database.connectionString); + meters.push(meter); + return { client, meter }; + } + + function declaration(driverKey: string, secretPaths: string[]): PluginEnvironmentDriverDeclaration { + return { + driverKey, kind: "sandbox_provider", displayName: "Census provider", + sandboxCapabilities: { runnerWebSocketIngress: true }, + configSchema: { type: "object", properties: Object.fromEntries([ + ["template", { type: "string" }], + ...secretPaths.map(path => [path, { type: "string", format: "secret-ref" }]), + ]) }, + } as PluginEnvironmentDriverDeclaration; + } + + function manifest(pluginKey: string, declarations: PluginEnvironmentDriverDeclaration[], version = "1.0.0"): PaperclipPluginManifestV1 { + return { + id: pluginKey, apiVersion: 1, version, displayName: "Census provider", description: "Fixture", + author: "Test", categories: ["automation"], capabilities: ["environment.drivers.register"], + entrypoints: { worker: "worker.js" }, environmentDrivers: declarations, + }; + } + + async function seedPlugin(driverKey: string, secretPaths = ["apiKey"]) { + const pluginKey = `test.census.${randomUUID()}`; + const installed = await pluginRegistryService(seedDb).install( + { packageName: "@test/census" }, manifest(pluginKey, [declaration(driverKey, secretPaths)])); + await seedDb.update(plugins).set({ status: "ready" }).where(eq(plugins.id, installed!.id)); + return { pluginId: installed!.id, pluginKey }; + } + + async function seedCompanyEnvironment(driverKey: string, secretValue: string) { + const companyId = randomUUID(), agentId = randomUUID(), environmentId = randomUUID(), runId = randomUUID(); + await seedDb.insert(companies).values({ id: companyId, name: "Census", status: "active", issuePrefix: `C${companyId.slice(0, 6).toUpperCase()}` }); + await seedDb.insert(agents).values({ + id: agentId, companyId, name: "Runner", role: "engineer", status: "active", + adapterType: "codex_local", adapterConfig: {}, runtimeConfig: {}, permissions: {}, + }); + const secret = await secretService(seedDb).create(companyId, { + name: `census-api-key-${randomUUID()}`, provider: "local_encrypted", value: secretValue, + }); + const config = { provider: driverKey, template: "base", apiKey: secret.id, reuseLease: false }; + const now = new Date(); + await seedDb.insert(environments).values({ + id: environmentId, name: `census-${environmentId.slice(0, 8)}`, driver: "sandbox", status: "active", config, + createdAt: now, updatedAt: now, + }); + await secretService(seedDb).createBinding({ + companyId, secretId: secret.id, targetType: "environment", targetId: environmentId, configPath: "apiKey", + }); + await seedDb.insert(heartbeatRuns).values({ id: runId, companyId, agentId, invocationSource: "manual", status: "running" }); + const environment: Environment = { + id: environmentId, name: `census-${environmentId.slice(0, 8)}`, description: null, driver: "sandbox", + status: "active", config, envVars: {}, metadata: null, createdAt: now, updatedAt: now, + }; + return { companyId, environment, runId, secretId: secret.id }; + } + + function workerManager(pluginId: string, driverKey: string) { + const configs: Array<{ method: string; config: Record }> = []; + const manager = { + isRunning: vi.fn((id: string) => id === pluginId), + getWorker: vi.fn(() => ({ status: "running", supportedMethods: [ + "environmentAcquireLease", "environmentResumeLease", "environmentReleaseLease", "environmentDestroyLease", + "environmentExecute", "environmentSyncIn", "environmentSyncOut", "environmentRealizeWorkspace", + "environmentRunnerIngressEndpoint", + ] })), + call: vi.fn(async (_id: string, method: string, params: { config: Record; path?: string }) => { + configs.push({ method, config: params.config }); + switch (method) { + case "environmentAcquireLease": + case "environmentResumeLease": + return { providerLeaseId: "census-sandbox", metadata: { provider: driverKey, template: "base", remoteCwd: "/workspace" } }; + case "environmentExecute": + return { exitCode: 0, signal: null, timedOut: false, stdout: "ok\n", stderr: "" }; + case "environmentSyncIn": + case "environmentSyncOut": + return { results: [] }; + case "environmentRealizeWorkspace": + return { cwd: "/workspace", metadata: {} }; + case "environmentRunnerIngressEndpoint": + return { kind: "authenticated_websocket", websocketUrl: `wss://runner.example.test${params.path}`, + secretHeaders: [{ name: "x-runner-token", value: "token" }], generation: "g1" }; + case "environmentReleaseLease": + return undefined; + default: + throw new Error(`Unexpected plugin method: ${method}`); + } + }), + } as unknown as PluginWorkerManager; + return { manager, configs }; + } + + async function runCensus(client: Db, meter: ReturnType, driverKey: string, + seeded: Awaited>, pluginId: string) { + const { manager, configs } = workerManager(pluginId, driverKey); + const runtime = environmentRuntimeService(client, { pluginWorkerManager: manager }); + const rows: Array<{ operation: string; providerSchemaReads: number; statements: number }> = []; + async function measure(operation: string, run: () => Promise) { + meter.startLog(); + const value = await run(); + const log = meter.stopLog(); + rows.push({ operation, providerSchemaReads: log.filter(entry => entry.sql.includes(PROVIDER_SCHEMA_STATEMENT)).length, + statements: log.length }); + return value; + } + const { environment } = seeded; + const acquired = await measure("lease acquire", () => runtime.acquireRunLease({ + companyId: seeded.companyId, environment, issueId: null, heartbeatRunId: seeded.runId, persistedExecutionWorkspace: null, + })); + const lease = acquired.lease; + await measure("runner attach (ingress endpoint)", () => runtime.getRunnerIngressEndpoint({ environment, lease, port: 8080, path: "/runner" })); + await measure("capability snapshot", () => runtime.resolveCapabilities({ environment, lease })); + await measure("exec", () => runtime.execute({ environment, lease, command: "true", args: [], cwd: "/workspace", env: {} })); + for (let index = 0; index < 9; index++) { + await measure("exec (repeat)", () => runtime.execute({ environment, lease, command: "true", args: [], cwd: "/workspace", env: {} })); + } + await measure("file write (sync in)", () => runtime.syncIn({ environment, lease, operations: [] })); + await measure("file read (sync out)", () => runtime.syncOut({ environment, lease, operations: [] })); + await measure("workspace realize", () => runtime.realizeWorkspace({ environment, lease, workspace: { remotePath: "/workspace" } })); + await measure("lease resume (reattach)", () => runtime.resumeRunLease({ environment, lease })); + await measure("lease release", () => runtime.releaseRunLeases(seeded.runId)); + const merged = new Map(); + for (const row of rows) { + const entry = merged.get(row.operation) ?? { operation: row.operation, count: 0, providerSchemaReads: 0, statements: 0 }; + entry.count += 1; + entry.providerSchemaReads += row.providerSchemaReads; + entry.statements += row.statements; + merged.set(row.operation, entry); + } + return { table: [...merged.values()], configs }; + } + + it("reads the provider schema at most once per bound across a whole remote run, not once per operation", async () => { + vi.useFakeTimers({ toFake: ["Date"] }); + const driverKey = `census-${randomUUID().slice(0, 8)}`; + const { pluginId } = await seedPlugin(driverKey); + const seeded = await seedCompanyEnvironment(driverKey, "company-a-key"); + const { client, meter } = meteredClient(); + const { table, configs } = await runCensus(client, meter, driverKey, seeded, pluginId); + console.info(`provider schema census\n${table.map(row => + `${row.operation} x${row.count}: provider schema reads=${row.providerSchemaReads}, statements=${row.statements}`).join("\n")}`); + const total = table.reduce((sum, row) => sum + row.providerSchemaReads, 0); + const acquire = table.find(row => row.operation === "lease acquire")!; + expect(acquire.providerSchemaReads).toBeLessThanOrEqual(1); + expect(total).toBeLessThanOrEqual(1); + expect(configs.filter(entry => entry.method !== "environmentAcquireLease").every(entry => entry.config.apiKey === "company-a-key")).toBe(true); + }); + + it("applies a plugin upgrade that changes the schema at once in this process, and a change made elsewhere within the bound", async () => { + vi.useFakeTimers({ toFake: ["Date"] }); + const driverKey = `census-${randomUUID().slice(0, 8)}`; + const { pluginId, pluginKey } = await seedPlugin(driverKey, ["apiKey"]); + const { client, meter } = meteredClient(); + expect(await resolveSandboxProviderSecretRefPaths(client, driverKey)).toEqual(new Set(["apiKey"])); + await pluginRegistryService(seedDb).update(pluginId, { + version: "2.0.0", manifest: manifest(pluginKey, [declaration(driverKey, ["apiKey", "token"])], "2.0.0"), + }); + expect(await resolveSandboxProviderSecretRefPaths(client, driverKey)).toEqual(new Set(["apiKey", "token"])); + + await seedDb.update(plugins).set({ manifestJson: manifest(pluginKey, [declaration(driverKey, ["token"])], "3.0.0") }) + .where(eq(plugins.id, pluginId)); + meter.startLog(); + const withinBound = await resolveSandboxProviderSecretRefPaths(client, driverKey); + expect(meter.stopLog()).toHaveLength(0); + expect([new Set(["apiKey", "token"]), new Set(["token"])]).toContainEqual(withinBound); + vi.setSystemTime(Date.now() + SCHEMA_REUSE_BOUND_MS + 1); + expect(await resolveSandboxProviderSecretRefPaths(client, driverKey)).toEqual(new Set(["token"])); + + await pluginRegistryService(seedDb).uninstall(pluginId, true); + expect(await resolveSandboxProviderSecretRefPaths(client, driverKey)).toEqual(new Set()); + }); + + it("never remembers a missing provider, so a provider that becomes ready is used on the next operation", async () => { + const driverKey = `census-${randomUUID().slice(0, 8)}`; + const { client, meter } = meteredClient(); + expect(await resolveSandboxProviderSecretRefPaths(client, driverKey)).toEqual(new Set()); + await seedDb.insert(plugins).values({ + pluginKey: `test.census.${randomUUID()}`, packageName: "@test/census", version: "1.0.0", installOrder: 0, + status: "ready", manifestJson: manifest(`test.census.late`, [declaration(driverKey, ["apiKey"])]), + }); + meter.startLog(); + expect(await resolveSandboxProviderSecretRefPaths(client, driverKey)).toEqual(new Set(["apiKey"])); + expect(meter.stopLog().filter(entry => entry.sql.includes(PROVIDER_SCHEMA_STATEMENT))).toHaveLength(1); + }); + + it("keeps each company's secret resolution and binding check per operation while the provider schema is shared", async () => { + const driverKey = `census-${randomUUID().slice(0, 8)}`; + const { pluginId } = await seedPlugin(driverKey); + const first = await seedCompanyEnvironment(driverKey, "company-a-key"); + const second = await seedCompanyEnvironment(driverKey, "company-b-key"); + const { client, meter } = meteredClient(); + const a = await runCensus(client, meter, driverKey, first, pluginId); + const b = await runCensus(client, meter, driverKey, second, pluginId); + expect(a.configs.filter(entry => entry.method !== "environmentAcquireLease").map(entry => entry.config.apiKey)) + .toEqual(expect.arrayContaining(["company-a-key"])); + expect(a.configs.some(entry => entry.config.apiKey === "company-b-key")).toBe(false); + expect(b.configs.filter(entry => entry.method !== "environmentAcquireLease").every(entry => entry.config.apiKey === "company-b-key")).toBe(true); + + const crossCompany = { ...second.environment, config: { ...second.environment.config, apiKey: first.secretId } }; + const { manager } = workerManager(pluginId, driverKey); + const runtime = environmentRuntimeService(client, { pluginWorkerManager: manager }); + await expect(runtime.execute({ + environment: crossCompany, + lease: { companyId: second.companyId, environmentId: second.environment.id, issueId: null, providerLeaseId: "census-sandbox", + metadata: { provider: driverKey, pluginId, sandboxProviderPlugin: true, template: "base", apiKey: first.secretId } } as never, + command: "true", args: [], cwd: "/workspace", env: {}, + })).rejects.toThrow("Secret must belong to same company"); + }); + + it("applies a plugin reinstall only after its install transaction commits", async () => { + vi.useFakeTimers({ toFake: ["Date"] }); + const driverKey = `census-${randomUUID().slice(0, 8)}`; + const pluginKey = `test.census.reinstall${randomUUID().slice(0, 8)}`; + await seedDb.insert(plugins).values({ + pluginKey, packageName: pluginKey, version: "1.0.0", installOrder: 0, status: "uninstalled", + manifestJson: manifest(pluginKey, [declaration(driverKey, ["apiKey"])]), + }); + const upgraded = manifest(pluginKey, [declaration(driverKey, ["apiKey", "token"])], "2.0.0"); + const packageRoot = await mkdtemp(path.join(os.tmpdir(), "census-plugin-")); + try { + await writeFile(path.join(packageRoot, "package.json"), JSON.stringify({ + name: pluginKey, version: upgraded.version, type: "module", paperclipPlugin: { manifest: "./manifest.js" }, + })); + await writeFile(path.join(packageRoot, "manifest.js"), `export default ${JSON.stringify(upgraded)};\n`); + await mkdir(path.join(packageRoot, "dist"), { recursive: true }); + await writeFile(path.join(packageRoot, "dist", "worker.js"), "export {};\n"); + const { client: observer } = meteredClient(); + expect(await resolveSandboxProviderSecretRefPaths(observer, driverKey)).toEqual(new Set(["apiKey"])); + const installer = createDb(database.connectionString); + clients.push(installer); + const readBeforeCommit = new Proxy(installer, { + get(target, property, receiver) { + if (property !== "transaction") return Reflect.get(target, property, receiver); + return (work: (tx: unknown) => Promise) => target.transaction(async tx => { + const result = await work(tx); + expect(await resolveSandboxProviderSecretRefPaths(observer, driverKey)).toEqual(new Set(["apiKey"])); + return result; + }); + }, + }); + await pluginLoader(readBeforeCommit, { enableLocalFilesystem: false, enableNpmDiscovery: false }) + .installPlugin({ localPath: packageRoot }); + expect(await resolveSandboxProviderSecretRefPaths(observer, driverKey)).toEqual(new Set(["apiKey", "token"])); + } finally { + await rm(packageRoot, { recursive: true, force: true }); + } + }); + + it("starts cold on a new process, as before", async () => { + const driverKey = `census-${randomUUID().slice(0, 8)}`; + await seedPlugin(driverKey); + const first = meteredClient(); + await resolveSandboxProviderSecretRefPaths(first.client, driverKey); + const restarted = meteredClient(); + restarted.meter.startLog(); + expect(await resolveSandboxProviderSecretRefPaths(restarted.client, driverKey)).toEqual(new Set(["apiKey"])); + expect(restarted.meter.stopLog().filter(entry => entry.sql.includes(PROVIDER_SCHEMA_STATEMENT))).toHaveLength(1); + }); +}); diff --git a/server/src/__tests__/sandbox-creation-operations.test.ts b/server/src/__tests__/sandbox-creation-operations.test.ts index 6a34fe65298..e75ce619707 100644 --- a/server/src/__tests__/sandbox-creation-operations.test.ts +++ b/server/src/__tests__/sandbox-creation-operations.test.ts @@ -21,6 +21,7 @@ import { readProcessStartedAt } from "../services/hot-restart.js"; import { hasRemoteTerminationReceipt, remoteTerminationReceipt, resolveRemoteTerminationLease } from "../services/remote-execution-termination.js"; import { createReusableLeaseHandoff } from "../services/environment-lease-handoff.js"; import type { PluginWorkerManager } from "../services/plugin-worker-manager.js"; +import { announcePluginManifestChange } from "../services/plugin-manifest-revision.js"; const external = resolveExternalTestDatabaseUrl("PAPERCLIP_HISTORY_TEST_DATABASE_URL"); describe("durable sandbox creation through the runtime entry point", () => { @@ -37,6 +38,7 @@ describe("durable sandbox creation through the runtime entry point", () => { }, 90_000); beforeEach(async () => { await db.execute(sql`truncate sandbox_creation_operations, companies, environments, plugins cascade`); + announcePluginManifestChange(); companyId = randomUUID(); environmentId = randomUUID(); pluginId = randomUUID(); runId = randomUUID(); const agentId = randomUUID(); creates = 0; destroys = 0; loseReply = false; failDestroy = false; pluginLogin = false; generatedLoginId = false; foreignReceipt = false; beforeReply = undefined; resources.clear(); spool = await mkdtemp(join(tmpdir(), "empty-sandbox-web-")); @@ -451,6 +453,7 @@ describe("durable sandbox creation through the runtime entry point", () => { await secrets.createBinding({ companyId, secretId: secret.id, targetType: "environment", targetId: environmentId, configPath: "apiKey" }); await db.update(plugins).set({ manifestJson: sql`jsonb_set(${plugins.manifestJson}, '{environmentDrivers,0,configSchema}', '{"type":"object","properties":{"apiKey":{"type":"string","format":"secret-ref"}}}'::jsonb)` }).where(eq(plugins.id, pluginId)); + announcePluginManifestChange(); await db.update(environments).set({ config: { provider: "creation-fixture", image: "fixture", reuseLease: false, apiKey: secret.id } }) .where(eq(environments.id, environmentId)); loseReply = true; diff --git a/server/src/__tests__/sandbox-provider-schema-reads.test.ts b/server/src/__tests__/sandbox-provider-schema-reads.test.ts index fd82c852bbc..bc308a1f374 100644 --- a/server/src/__tests__/sandbox-provider-schema-reads.test.ts +++ b/server/src/__tests__/sandbox-provider-schema-reads.test.ts @@ -1,10 +1,12 @@ 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 { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } 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 { + PROVIDER_SCHEMA_REUSE_MS, resolvePluginSandboxProviderConfigSchema, resolvePluginSandboxProviderDriverByKey, +} from "../services/plugin-environment-driver.js"; import { resolveEnvironmentDriverConfigForRuntime, resolveSandboxProviderSecretRefPaths } from "../services/environment-config.js"; import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js"; @@ -37,6 +39,7 @@ describe.skipIf(!support.supported)("sandbox provider schema reads", () => { return observed; } const lookup = (client: Db, driverKey = key) => resolvePluginSandboxProviderConfigSchema({ db: client, driverKey }); + const expire = () => vi.setSystemTime(Date.now() + PROVIDER_SCHEMA_REUSE_MS); async function measure(client: Db, operation: () => Promise) { const events: Array> = [], now = Date.now(); const capture = createFullDatabaseResponseCapture({ start: now - 100, end: now + 59_000 }, event => events.push(event), () => now); @@ -54,8 +57,8 @@ describe.skipIf(!support.supported)("sandbox provider schema reads", () => { 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())); }); + beforeEach(async () => { vi.useFakeTimers({ toFake: ["Date"] }); await db.delete(plugins); }); + afterEach(async () => { vi.useRealTimers(); 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 () => { @@ -65,15 +68,20 @@ describe.skipIf(!support.supported)("sandbox provider schema reads", () => { 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 reused = await measure(observed, () => resolveSandboxProviderSecretRefPaths(observed, key)); + expire(); const warm = await measure(observed, () => resolveSandboxProviderSecretRefPaths(observed, key)); expect(cold.value).toEqual(new Set(["credentials.token"])); + expect(reused.value).toEqual(cold.value); expect(warm.value).toEqual(cold.value); expect(cold.calls).toBe(1); + expect(reused.calls).toBe(0); 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)); + expire(); 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"); @@ -90,10 +98,13 @@ describe.skipIf(!support.supported)("sandbox provider schema reads", () => { 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)); + expire(); expect((await lookup(observed))).toEqual({ title: "other plugin" }); await db.delete(plugins).where(eq(plugins.id, b)); + expire(); expect((await lookup(observed))).toEqual({ title: "first" }); await db.update(plugins).set({ manifestJson: manifest(a, [driver("replacement")]) }).where(eq(plugins.id, a)); + expire(); expect(await lookup(observed)).toBeNull(); }); @@ -112,6 +123,7 @@ describe.skipIf(!support.supported)("sandbox provider schema reads", () => { const first = await lookup(a); first!.properties = {}; expect(await resolveSandboxProviderSecretRefPaths(a, key)).toEqual(new Set(["token"])); + expire(); const warm = await measure(a, () => lookup(a)), independent = await measure(b, () => lookup(b)); expect(warm.bytes).toBeLessThan(256); expect(independent.bytes).toBeGreaterThan(4096); @@ -125,6 +137,7 @@ describe.skipIf(!support.supported)("sandbox provider schema reads", () => { await seed(declarations); const observed = observer(); for (let index = 0; index < 33; index++) await lookup(observed, `provider-${index}`); + expire(); 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"); @@ -141,6 +154,7 @@ describe.skipIf(!support.supported)("sandbox provider schema reads", () => { return observed.execute(query); } } as unknown as Db; expect((await lookup(guarded, unusual))).toEqual({ title: "exact provider" }); + expire(); fail = true; await expect(lookup(guarded, unusual)).rejects.toThrow("fixture database unavailable"); fail = false; @@ -159,6 +173,7 @@ describe.skipIf(!support.supported)("sandbox provider schema reads", () => { return rows; } } as unknown as Db; expect((await lookup(raced))).toEqual({ title: "old" }); + expire(); pause = true; const oldRead = lookup(raced); await paused; diff --git a/server/src/services/plugin-environment-driver.ts b/server/src/services/plugin-environment-driver.ts index a27edf1c9da..cc8cb37cf14 100644 --- a/server/src/services/plugin-environment-driver.ts +++ b/server/src/services/plugin-environment-driver.ts @@ -29,6 +29,7 @@ import { readConfigValueAtPath, writeConfigValueAtPath, } from "./json-schema-secret-refs.js"; +import { pluginManifestRevision } from "./plugin-manifest-revision.js"; import { pluginRegistryService } from "./plugin-registry.js"; import type { PluginWorkerManager } from "./plugin-worker-manager.js"; @@ -229,10 +230,15 @@ export async function resolvePluginEnvironmentDriverByKey(input: { }); } -type CachedProviderSchema = { pluginId: string; revision: string; schema: Record | null }; +type CachedProviderSchema = { + pluginId: string; revision: string; schema: Record | null; + checkedAt: number; manifestRevision: number; lookup: number; +}; const providerSchemas = new WeakMap>(); const MAX_CACHED_PROVIDER_SCHEMAS = 32; const MAX_CACHED_PROVIDER_SCHEMA_BYTES = 64 * 1024; +export const PROVIDER_SCHEMA_REUSE_MS = 5_000; +let providerSchemaLookups = 0; export async function resolvePluginSandboxProviderConfigSchema(input: { db: Db; driverKey: string; @@ -240,6 +246,13 @@ export async function resolvePluginSandboxProviderConfigSchema(input: { const { db, driverKey } = input; let cache = providerSchemas.get(db); const cached = cache?.get(driverKey); + const manifestRevision = pluginManifestRevision(); + const startedAt = Date.now(); + const lookup = ++providerSchemaLookups; + if (cached && cached.manifestRevision === manifestRevision + && startedAt >= cached.checkedAt && startedAt - cached.checkedAt < PROVIDER_SCHEMA_REUSE_MS) { + return structuredClone(cached.schema); + } const unchanged = sql`coalesce(plugin_id = ${cached?.pluginId ?? null}::uuid and revision = ${cached?.revision ?? null}, false)`; const [row] = await db.execute<{ @@ -272,15 +285,20 @@ export async function resolvePluginSandboxProviderConfigSchema(input: { if (!cached || cached.pluginId !== row.pluginId || cached.revision !== row.revision) { throw new Error("Sandbox provider schema revision did not match the retained definition"); } + if (cache!.get(driverKey) === cached) cache!.set(driverKey, { ...cached, checkedAt: startedAt, manifestRevision, lookup }); return structuredClone(cached.schema); } const schema = row.configSchema && typeof row.configSchema === "object" && !Array.isArray(row.configSchema) ? row.configSchema as Record : null; + const current = cache?.get(driverKey); + if (current && current.lookup > lookup) return schema; cache?.delete(driverKey); if (Buffer.byteLength(JSON.stringify(schema)) <= MAX_CACHED_PROVIDER_SCHEMA_BYTES) { if (!cache) { cache = new Map(); providerSchemas.set(db, cache); } if (cache.size >= MAX_CACHED_PROVIDER_SCHEMAS) cache.delete(cache.keys().next().value!); - cache.set(driverKey, { pluginId: row.pluginId, revision: row.revision, schema: structuredClone(schema) }); + cache.set(driverKey, { + pluginId: row.pluginId, revision: row.revision, schema: structuredClone(schema), checkedAt: startedAt, manifestRevision, lookup, + }); } return schema; } diff --git a/server/src/services/plugin-loader.ts b/server/src/services/plugin-loader.ts index 9a045e60f58..2988e8d7800 100644 --- a/server/src/services/plugin-loader.ts +++ b/server/src/services/plugin-loader.ts @@ -45,6 +45,7 @@ import { logger } from "../middleware/logger.js"; import { pluginManifestValidator } from "./plugin-manifest-validator.js"; import { pluginCapabilityValidator } from "./plugin-capability-validator.js"; import { pluginRegistryService } from "./plugin-registry.js"; +import { announcePluginManifestChange } from "./plugin-manifest-revision.js"; import type { PluginWorkerManager, WorkerStartOptions, WorkerToHostHandlers } from "./plugin-worker-manager.js"; import type { PluginEventBus } from "./plugin-event-bus.js"; import type { PluginJobScheduler } from "./plugin-job-scheduler.js"; @@ -1855,7 +1856,7 @@ export function pluginLoader( { persistFailure: false }, ); } - }); + }).finally(announcePluginManifestChange); log.info( { diff --git a/server/src/services/plugin-manifest-revision.ts b/server/src/services/plugin-manifest-revision.ts new file mode 100644 index 00000000000..1505c2df4e7 --- /dev/null +++ b/server/src/services/plugin-manifest-revision.ts @@ -0,0 +1,9 @@ +let revision = 0; + +export function pluginManifestRevision(): number { + return revision; +} + +export function announcePluginManifestChange(): void { + revision += 1; +} diff --git a/server/src/services/plugin-registry.ts b/server/src/services/plugin-registry.ts index 30f2259d958..3af065b1864 100644 --- a/server/src/services/plugin-registry.ts +++ b/server/src/services/plugin-registry.ts @@ -33,6 +33,7 @@ import type { import { conflict, notFound } from "../errors.js"; import { DELIVERY_QUEUES, notifyDeliveryWork } from "./delivery-work-notifications.js"; import { TERMINAL_WORKSPACE_PLUGIN_HINT } from "./terminal-workspace-work.js"; +import { announcePluginManifestChange } from "./plugin-manifest-revision.js"; function sameBundledPluginRegistration(existing: typeof plugins.$inferSelect, packageName: string, manifest: PaperclipPluginManifestV1): boolean { return existing.pluginKey === manifest.id && existing.packageName === packageName && existing.version === manifest.version && isDeepStrictEqual(existing.manifestJson, manifest); @@ -180,7 +181,8 @@ export function pluginRegistryService(db: Db) { }) .where(eq(plugins.id, existing.id)) .returning() - .then((rows) => rows[0] ?? null); + .then((rows) => rows[0] ?? null) + .finally(announcePluginManifestChange); } const installOrder = await nextInstallOrder(); @@ -202,6 +204,7 @@ export function pluginRegistryService(db: Db) { const rows = await (options.idempotent ? insertion.onConflictDoNothing({ target: plugins.pluginKey }) : insertion).returning(); + announcePluginManifestChange(); if (rows[0]) return rows[0]; const concurrent = await getByKey(manifest.id); if (concurrent && concurrent.status !== "uninstalled" && sameBundledPluginRegistration(concurrent, input.packageName, manifest)) return concurrent; @@ -256,7 +259,7 @@ export function pluginRegistryService(db: Db) { .set(setClause) .where(eq(plugins.id, id)) .returning() - .then((rows) => rows[0] ?? null)); + .then((rows) => rows[0] ?? null)).finally(announcePluginManifestChange); }, // ----- Status --------------------------------------------------------- @@ -334,7 +337,7 @@ export function pluginRegistryService(db: Db) { .where(eq(plugins.id, id)) .returning() .then((rows) => rows[0] ?? null); - }); + }).finally(announcePluginManifestChange); }, // ----- Config ---------------------------------------------------------