Merge commit '56654adecdb93bbfb4ee7e66f6c8204cbf5c9b2b' into codex/photon-managed-lock-policy

* commit '56654adecdb93bbfb4ee7e66f6c8204cbf5c9b2b':
  perf(server): reuse sandbox provider schemas for five seconds on the remote-run path (#21758)
  test(scaling): wait for agent setup and gate the ramp on a first started run (#21757)
  fix(queue): keep a message a starting run's first turn took out of the queue (#21747)
  perf(release): stage the verified host release daemon instead of compiling it in publish_canary (#21555)
This commit is contained in:
Codex committed 2026-11-15 08:28:19 -06:00
commit 63f8a1cd48
25 files changed
+1035 -30

No files matched your search

+7
View File
@@ -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
@@ -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 <run id>`, or
uses `--company <id>` (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-<nonce>.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
+1 -1
View File
@@ -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",
@@ -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;
});
}
@@ -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);
@@ -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 });
}
});
+6
View File
@@ -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,
+26 -3
View File
@@ -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<string, number>();
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 });
}
+109 -8
View File
@@ -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<StopReason | null> {
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<StopReason | null> {
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<StopReason | null> {
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<StopReason | null> {
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<StopReason> {
const { api, log } = this.deps;
const [view, agents] = await Promise.all([
api.get<Json>(`/api/issues/${task.id}`).catch(() => null),
api.get<Json[]>(`/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<StopReason | null> {
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<void> {
private async poll(recordSample = true): Promise<void> {
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<string>();
own.add(id);
+170
View File
@@ -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<string, any>, 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();
+90 -1
View File
@@ -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<boolean>;
}): Promise<boolean> {
const { api, clock } = input;
const started = clock.now();
const erroredSince = new Map<string, number>();
let logged = false;
let readFailures = 0;
for (;;) {
if (input.shouldStop()) return false;
let listed: Json[];
try {
listed = await api.get<Json[]>(`/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);
}
}
@@ -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();
@@ -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<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
let seedDb: Db;
const clients: Db[] = [];
const meters: Array<ReturnType<typeof meterDatabaseStatements>> = [];
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<string, unknown> }> = [];
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<string, unknown>; 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<typeof meterDatabaseStatements>, driverKey: string,
seeded: Awaited<ReturnType<typeof seedCompanyEnvironment>>, 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<T>(operation: string, run: () => Promise<T>) {
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<string, { operation: string; count: number; providerSchemaReads: number; statements: number }>();
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<unknown>) => 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);
});
});
@@ -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",
@@ -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;
@@ -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<T>(client: Db, operation: () => Promise<T>) {
const events: Array<Record<string, unknown>> = [], now = Date.now();
const capture = createFullDatabaseResponseCapture({ start: now - 100, end: now + 59_000 }, event => events.push(event), () => now);
@@ -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;
+3
View File
@@ -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<string[] | null>`${heartbeatRuns.contextSnapshot} -> 'wakeCommentIds'`,
// Queued messages this run's own accepted first turn took.
firstTurnCommentIds: acceptedFirstTurnCommentIdsSql(heartbeatRuns),
queuedCommentSourceWakeIds: sql<string[] | null>`${heartbeatRuns.contextSnapshot} -> 'queuedCommentSourceWakeIds'`,
wakeCommentId: sql<string | null>`${heartbeatRuns.contextSnapshot} ->> 'wakeCommentId'`,
contextCommentId: sql<string | null>`${heartbeatRuns.contextSnapshot} ->> 'commentId'`,
@@ -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<string, unknown> | null };
type CachedProviderSchema = {
pluginId: string; revision: string; schema: Record<string, unknown> | null;
checkedAt: number; manifestRevision: number; lookup: number;
};
const providerSchemas = new WeakMap<Db, Map<string, CachedProviderSchema>>();
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<string, unknown> : 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;
}
+2 -1
View File
@@ -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(
{
@@ -0,0 +1,9 @@
let revision = 0;
export function pluginManifestRevision(): number {
return revision;
}
export function announcePluginManifestChange(): void {
revision += 1;
}
+6 -3
View File
@@ -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 ---------------------------------------------------------
@@ -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<string[] | null>`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<Db, "select">, input: {
companyId: string; issueId: string; agentId: string; commentIds: string[];
+2
View File
@@ -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;
+36
View File
@@ -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" }));
+10 -2
View File
@@ -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) => {