mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-05 23:06:17 +01:00
Merge current master into external agent sleep recovery
This commit is contained in:
commit
e5604f3e4d
88 files changed
+3360
-350
No files matched your search
@@ -3,6 +3,7 @@ import type { SQL } from "drizzle-orm";
|
||||
import { PgDialect } from "drizzle-orm/pg-core";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import { startNativeSessionExecutionLeaseRenewal } from "./native-execution-lease.js";
|
||||
import { startServerMetrics, stopServerMetrics } from "../server-metrics.js";
|
||||
|
||||
const dialect = new PgDialect();
|
||||
|
||||
@@ -134,6 +135,24 @@ describe("native execution renewal ownership", () => {
|
||||
expect(returning).toHaveBeenCalledTimes(1);
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
});
|
||||
it("counts a renewal deadline that passes as a missed lease renewal for the server metrics", async () => {
|
||||
const metrics = startServerMetrics();
|
||||
try {
|
||||
vi.useFakeTimers();
|
||||
const { input, returning } = fixture();
|
||||
let complete!: (value: { runId: string }[]) => void;
|
||||
returning.mockImplementationOnce(() => new Promise(resolve => { complete = resolve; }));
|
||||
const guard = startNativeSessionExecutionLeaseRenewal(input);
|
||||
await vi.advanceTimersByTimeAsync(30_000);
|
||||
expect(metrics.snapshot().leaseRenewalsMissed).toBe(0);
|
||||
await vi.advanceTimersByTimeAsync(30_000);
|
||||
expect(metrics.snapshot().leaseRenewalsMissed).toBe(1);
|
||||
complete([{ runId: "run" }]);
|
||||
await expect(guard.stop()).rejects.toThrow("native_session_lease_renewal_deadline");
|
||||
} finally {
|
||||
stopServerMetrics(metrics);
|
||||
}
|
||||
});
|
||||
it("hands preparation renewal to the same owner's executor at the next attempt", async () => {
|
||||
vi.useFakeTimers();
|
||||
const { input, returning } = fixture();
|
||||
|
||||
@@ -5,6 +5,7 @@ import { currentNativeControllerIdentity, type NativeControllerIdentity } from "
|
||||
import { OPERATOR_ATTESTED_CONTROLLER_HOST } from "./native-controller-host-recovery.js";
|
||||
import { NATIVE_OWNERSHIP_UNVERIFIED_ERROR_CODE } from "./native-runner-ownership.js";
|
||||
import { REMOTE_CONTROLLER_LEASE_MS } from "./native-runner-recovery-contract.js";
|
||||
import { recordMissedLeaseRenewal } from "../server-metrics.js";
|
||||
|
||||
export const NATIVE_SESSION_EXECUTION_LEASE_TTL_MS = 20 * 60_000;
|
||||
const NATIVE_SESSION_EXECUTION_LEASE_RENEW_INTERVAL_MS = 5 * 60_000;
|
||||
@@ -613,7 +614,10 @@ export function startNativeSessionExecutionLeaseRenewal(input: RenewalInput): Na
|
||||
state!.loss = Promise.resolve().then(state!.input.onLost).catch(() => undefined);
|
||||
};
|
||||
const deadline = (delay: number) => {
|
||||
const timer = setTimeout(() => lose(new Error("native_session_lease_renewal_deadline")), Math.max(0, delay));
|
||||
const timer = setTimeout(() => {
|
||||
recordMissedLeaseRenewal();
|
||||
lose(new Error("native_session_lease_renewal_deadline"));
|
||||
}, Math.max(0, delay));
|
||||
timer.unref?.();
|
||||
return timer;
|
||||
};
|
||||
|
||||
@@ -16756,6 +16756,7 @@ async function createRunnerdBackendWithinSessionClaim(
|
||||
configuredEnvironment: taskConfiguredEnvironment,
|
||||
releaseResumeVersion: description.releaseResumeVersion,
|
||||
resumeLaunchInputsVersion: description.resumeLaunchInputsVersion,
|
||||
launchDigestVersion: description.launchDigestVersion,
|
||||
authorityRunId: description.releaseResumeVersion === 1 ? input.execution.binding.runId : undefined,
|
||||
releasedSource: input.remoteWarmRecovery?.releasedSource,
|
||||
sessionHandoff: !!input.remoteWarmRecovery?.portableSourceTaskId,
|
||||
|
||||
@@ -2,6 +2,7 @@ import { nativeResponsePresentationWork } from "./native-response-presentation-w
|
||||
import { resolveExternalTestDatabaseUrl } from "../../__tests__/helpers/external-test-database.js";
|
||||
import { plugins } from "@paperclipai/db";
|
||||
import { readTaskPanelActivations } from "../plugin-task-panels.js";
|
||||
import { startServerMetrics, stopServerMetrics } from "../server-metrics.js";
|
||||
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
||||
import { and, asc, eq, sql } from "drizzle-orm";
|
||||
import { createHash, generateKeyPairSync, randomUUID } from "node:crypto";
|
||||
@@ -548,6 +549,21 @@ describe("PaperclipControlPlanePort conformance", () => {
|
||||
payload: { itemId: "ending-item", kind: "commandExecution", text: "***REDACTED***" } }]);
|
||||
});
|
||||
|
||||
it("records the lateness of each committed runner event once for the server metrics", async () => {
|
||||
const metrics = startServerMetrics();
|
||||
try {
|
||||
const f = await terminalObserverFixture();
|
||||
const event = { ...f.event, emittedAt: new Date(Date.now() - 2_000).toISOString() };
|
||||
await f.port.appendEvent(event);
|
||||
await f.port.appendEvent(event);
|
||||
const snapshot = metrics.snapshot();
|
||||
expect(snapshot.runEventLatenessSamples).toBe(1);
|
||||
expect(snapshot.runEventLatenessP99Ms).toBeGreaterThanOrEqual(1_900);
|
||||
} finally {
|
||||
stopServerMetrics(metrics);
|
||||
}
|
||||
});
|
||||
|
||||
it("completes a native run when a bound secret equals a protocol word", async () => {
|
||||
const observed: PrpEvent[] = [];
|
||||
const f = await terminalObserverFixture({ secrets: ["interrupted", "completed", "succeeded", "satisfied"],
|
||||
@@ -1020,6 +1036,27 @@ describe("PaperclipControlPlanePort conformance", () => {
|
||||
return { port, binding, identity, runnerId, event, stored, streamed };
|
||||
};
|
||||
|
||||
it("measures every row of a streaming batch from the batch commit, not after earlier rows' observers", async () => {
|
||||
const metrics = startServerMetrics();
|
||||
const recorded: number[] = [];
|
||||
const record = metrics.recordRunEventLatenessMs.bind(metrics);
|
||||
metrics.recordRunEventLatenessMs = (ms: number) => { recorded.push(ms); record(ms); };
|
||||
try {
|
||||
const f = await streamingFixture({ streamingBatchMs: 600_000, onCommittedEvent: async (event) => {
|
||||
if (event.sourceSeq === 2) await new Promise(resolve => setTimeout(resolve, 1_200));
|
||||
} });
|
||||
await f.port.appendEvent(f.event(1), f.streamed);
|
||||
const deltas = [2, 3, 4].map(sourceSeq => f.port.appendEvent(f.event(sourceSeq), f.streamed));
|
||||
await f.port.appendEvent(f.event(5, "tool.execution.started"));
|
||||
await Promise.all(deltas);
|
||||
const batch = recorded.slice(1, 4);
|
||||
expect(batch).toHaveLength(3);
|
||||
expect(Math.max(...batch) - Math.min(...batch)).toBeLessThan(500);
|
||||
} finally {
|
||||
stopServerMetrics(metrics);
|
||||
}
|
||||
});
|
||||
|
||||
it("commits the first text delta at once and later deltas in one batch before the next other event", async () => {
|
||||
const committed: number[] = [];
|
||||
// A timer this long would time the test out: only the first delta and the
|
||||
|
||||
@@ -39,6 +39,7 @@ import { eligibleNativeTaskSessionPublication, publishNativeTaskSessionInTransac
|
||||
import { lockNativeRunnerCheckpointOwner, nativeRunnerCheckpointOwnerLock, validateNativeRunnerCheckpointOwner, inspectNativeRunnerUpgradeHeader, type NativeRunnerCheckpointOwner } from "./native-runner-checkpoint.js";
|
||||
import { crashPoint } from "@paperclipai/shared/crash-points";
|
||||
import { NATIVE_PROVIDER_DURABLE_EVENT_TYPES } from "./native-retired-backup-source.js";
|
||||
import { recordRunEventCommitted } from "../server-metrics.js";
|
||||
|
||||
export interface PaperclipControlPlaneBinding {
|
||||
companyId: string;
|
||||
@@ -476,10 +477,11 @@ export class PaperclipControlPlanePort implements ControlPlanePort {
|
||||
this.#assertActive(options);
|
||||
const pendingObservation = this.#deferredEventObservers.get(observerKey);
|
||||
const persisted = await appendHeartbeatRunEvent(this.#db, input);
|
||||
const committedAtMs = Date.now();
|
||||
this.#assertActive(options);
|
||||
const persistenceEndedAt = persistenceStartedAt + performance.now() - persistenceClock;
|
||||
let observation = pendingObservation ?? this.#deferredEventObservers.get(observerKey);
|
||||
if (!observation) observation = this.#observePersistedEvent(event, persisted, persistenceStartedAt, persistenceEndedAt);
|
||||
if (!observation) observation = this.#observePersistedEvent(event, persisted, persistenceStartedAt, persistenceEndedAt, committedAtMs);
|
||||
if (options?.deferPostCommitObservers) {
|
||||
this.#deferredEventObservers.set(observerKey, observation);
|
||||
void observation.then(() => {
|
||||
@@ -503,9 +505,11 @@ export class PaperclipControlPlanePort implements ControlPlanePort {
|
||||
persisted: AppendHeartbeatRunEventResult,
|
||||
persistenceStartedAt: number,
|
||||
persistenceEndedAt: number,
|
||||
committedAtMs: number,
|
||||
): Promise<void> {
|
||||
try { await this.#onEventPersistence?.(event, persistenceStartedAt, persistenceEndedAt); } catch {}
|
||||
if (persisted.disposition === "committed") {
|
||||
recordRunEventCommitted(event.emittedAt, committedAtMs);
|
||||
try {
|
||||
publishLiveEvent({
|
||||
companyId: this.#binding.companyId,
|
||||
@@ -590,11 +594,12 @@ export class PaperclipControlPlanePort implements ControlPlanePort {
|
||||
for (const pending of batch) pending.reject(error);
|
||||
return;
|
||||
}
|
||||
const committedAtMs = Date.now();
|
||||
for (const [index, pending] of batch.entries()) {
|
||||
const persisted = receipts[index]!;
|
||||
const endedAt = pending.startedAtMs + performance.now() - pending.startedClock;
|
||||
try {
|
||||
await this.#observePersistedEvent(pending.event, persisted, pending.startedAtMs, endedAt);
|
||||
await this.#observePersistedEvent(pending.event, persisted, pending.startedAtMs, endedAt, committedAtMs);
|
||||
} catch (error) {
|
||||
pending.reject(error);
|
||||
continue;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import type { RunnerProviderLaunchRequirements } from "@paperclipai/paperclip-runner";
|
||||
import type { RunnerProcessLaunchSpec } from "../../vendor/paperclip-runner/index.js";
|
||||
import { runnerLaunchPreparationDigest, runnerLaunchRunDigest, type RunnerProcessLaunchSpec } from "../../vendor/paperclip-runner/index.js";
|
||||
import { createPluginRunnerTaskOwner } from "./plugin-runner-task.js";
|
||||
import { NativeExecutionContext } from "./native-execution-context.js";
|
||||
|
||||
@@ -831,6 +831,66 @@ it.each(["codex", "claude"])("reuses a warm %s process across run authorities wi
|
||||
expect(nextTask.mock.calls.filter(([op])=>op.kind==="stop")).toHaveLength(1);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["advertised", 1 as const],
|
||||
["not advertised", undefined],
|
||||
] as const)("launch digests are sent on prepare only when the plugin has %s them", async (_label, version) => {
|
||||
const {task} = provider();
|
||||
ingress.connect.mockReturnValue({ready:Promise.resolve(),close:async()=>{}});
|
||||
const input = {taskId:"task",task,projectIds:[],harness:"codex",projectAuthCheckVersion:1 as const,warmTaskVersion:1 as const,
|
||||
accountIdentity:"account",credentialIdentity:"revision",pollMs:1,launchDigestVersion:version};
|
||||
const owner = createPluginRunnerTaskOwner(input);
|
||||
await prepare(owner, launchRequirements("codex"));
|
||||
const registration = await owner.registration({} as never,"run");
|
||||
const spec = launchSpec(); spec.nativeRunner!.lifecyclePolicy = {mode:"warm",idleTimeoutMs:300000};
|
||||
const handle = owner.launcher(spec); registration.activate(); await registration.ready();
|
||||
const nextIdentity={...requirements.identity,runId:"next-run",turnId:"next-turn",itemId:"next-item"};
|
||||
const nextRegistration=await owner.registration({} as never,"next-run");
|
||||
await owner.driver.prepareLaunch!({...launchRequirements("codex"),identity:nextIdentity});
|
||||
const prepares=task.mock.calls.map(([op])=>op).filter(op=>op.kind==="prepare");
|
||||
expect(prepares).toHaveLength(2);
|
||||
if (version === 1) {
|
||||
const [first, next] = prepares as Array<{preparationDigest?:string;runDigest?:string}>;
|
||||
expect(first.preparationDigest).toBe(runnerLaunchPreparationDigest(launchRequirements("codex")));
|
||||
expect(next.preparationDigest).toBe(first.preparationDigest);
|
||||
expect(first.runDigest).toBe(runnerLaunchRunDigest(first.preparationDigest!, launchRequirements("codex")));
|
||||
expect(next.runDigest).toBe(runnerLaunchRunDigest(first.preparationDigest!, {...launchRequirements("codex"),identity:nextIdentity}));
|
||||
expect(next.runDigest).not.toBe(first.runDigest);
|
||||
} else {
|
||||
for (const op of prepares) expect(op).not.toHaveProperty("preparationDigest");
|
||||
for (const op of prepares) expect(op).not.toHaveProperty("runDigest");
|
||||
}
|
||||
await registration.release(); nextRegistration.activate(); await nextRegistration.ready();
|
||||
await nextRegistration.release(); await nextRegistration.checkpoint("settled"); await handle.completion;
|
||||
});
|
||||
|
||||
it.each([
|
||||
["checked inside prepare", true, ["prepare"]],
|
||||
["left to Core", false, ["prepare", "check_project_auth"]],
|
||||
] as const)("a warm attach whose project authentication is %s makes only the round trips it needs", async (_label, checked, kinds) => {
|
||||
const {task} = provider();
|
||||
ingress.connect.mockReturnValue({ready:Promise.resolve(),close:async()=>{}});
|
||||
const input = {taskId:"task",task,projectIds:[],harness:"codex",projectAuthCheckVersion:1 as const,warmTaskVersion:1 as const,
|
||||
accountIdentity:"account",credentialIdentity:"revision",pollMs:1};
|
||||
const owner = createPluginRunnerTaskOwner(input);
|
||||
await prepare(owner, launchRequirements("codex"));
|
||||
const registration = await owner.registration({} as never,"run");
|
||||
const spec = launchSpec(); spec.nativeRunner!.lifecyclePolicy = {mode:"warm",idleTimeoutMs:300000};
|
||||
const handle = owner.launcher(spec); registration.activate(); await registration.ready();
|
||||
const originalTask=task.getMockImplementation()!;
|
||||
const nextTask=vi.fn(async op=>{
|
||||
const result=await originalTask(op) as Record<string,unknown>;
|
||||
return op.kind === "prepare" && checked ? {...result,projectAuthChecked:true} : result;
|
||||
});
|
||||
owner.rebind({...input,task:nextTask});
|
||||
const nextRegistration=await owner.registration({} as never,"next-run");
|
||||
const nextIdentity={...requirements.identity,runId:"next-run",turnId:"next-turn",itemId:"next-item"};
|
||||
await owner.driver.prepareLaunch!({...launchRequirements("codex"),identity:nextIdentity});
|
||||
expect(nextTask.mock.calls.map(([op])=>op.kind)).toEqual(kinds);
|
||||
await registration.release(); nextRegistration.activate(); await nextRegistration.ready();
|
||||
await nextRegistration.release(); await nextRegistration.checkpoint("settled"); await handle.completion;
|
||||
});
|
||||
|
||||
it.each(["codex", "claude"])("adopts a verified retained %s task without submitting a replacement", async harness => {
|
||||
const {task}=provider();
|
||||
ingress.connect.mockReturnValue({ready:Promise.resolve(),close:async()=>{}});
|
||||
|
||||
@@ -3,7 +3,7 @@ import { createHash } from "node:crypto";
|
||||
import { setTimeout as delay } from "node:timers/promises";
|
||||
import { environmentTaskOperationSchema, environmentTaskResultSchema, parseEnvironmentTaskResult, type PluginEnvironmentTaskOperation, type PluginEnvironmentTaskResult, type PluginEnvironmentTaskCredential } from "@paperclipai/plugin-sdk";
|
||||
import type { RunnerIngressEndpoint } from "@paperclipai/adapter-utils/runner-connectivity";
|
||||
import { RUNNER_PRP_PROTOCOL_MIN, RUNNER_PRP_PROTOCOL_MAX, type RunnerProcessHandle, type RunnerProcessLaunchSpec,
|
||||
import { RUNNER_PRP_PROTOCOL_MIN, RUNNER_PRP_PROTOCOL_MAX, runnerLaunchPreparationDigest, runnerLaunchRunDigest, type RunnerProcessHandle, type RunnerProcessLaunchSpec,
|
||||
type DurablePrpControlPlane, type RunnerExecutionDriver, type RunnerLaunchPreparer, type DurableRecoveryIdentity, type PrpEvent } from "../../vendor/paperclip-runner/index.js";
|
||||
import { connectRunnerPrpIngress } from "../../realtime/runner-prp-outbound.js";
|
||||
import type { NativeExecutionContext } from "./native-execution-context.js";
|
||||
@@ -50,6 +50,7 @@ export function createPluginRunnerTaskOwner(input: {
|
||||
warmTaskVersion?: 1;
|
||||
releaseResumeVersion?: 1;
|
||||
resumeLaunchInputsVersion?: 1;
|
||||
launchDigestVersion?: 1;
|
||||
releasedSource?: DurableRecoveryIdentity;
|
||||
sessionHandoff?: boolean;
|
||||
onResumed?: (identity: DurableRecoveryIdentity) => Promise<void>;
|
||||
@@ -143,7 +144,9 @@ export function createPluginRunnerTaskOwner(input: {
|
||||
if (input.githubBroker && input.githubCredentialBrokerVersion !== 1) {
|
||||
throw new Error("Update the environment plugin to support the GitHub credential broker v1");
|
||||
}
|
||||
const preparationDigest = input.launchDigestVersion === 1 ? runnerLaunchPreparationDigest(requirements) : undefined;
|
||||
const result = await call(environmentTaskOperationSchema.parse({ kind: "prepare", requirements,
|
||||
...(preparationDigest ? { preparationDigest, runDigest: runnerLaunchRunDigest(preparationDigest, requirements) } : {}),
|
||||
...(input.githubBroker ? { githubBroker: input.githubBroker } : {}),
|
||||
projectIds: [...input.projectIds], ...(recovery ? { recovery } : {}),
|
||||
...(input.resumeFrom && (!authorityRunId || !launchIdentity || launchIdentity.runId === authorityRunId || sourceRecovery)
|
||||
@@ -155,7 +158,7 @@ export function createPluginRunnerTaskOwner(input: {
|
||||
if (released || stopRequested) throw new Error("Plugin Runner preparation cancelled");
|
||||
if (result.kind !== "prepared") throw new Error("Plugin Runner preparation unavailable");
|
||||
if (input.projectAuthCheckVersion !== 1) throw new Error("Plugin Runner managed project authentication validation unavailable");
|
||||
if (launched || !result.projectAuthCheckAtSubmit) await checkProjectAuth(result.launch.configurationId);
|
||||
if (!result.projectAuthChecked && (launched || !result.projectAuthCheckAtSubmit)) await checkProjectAuth(result.launch.configurationId);
|
||||
preparedLaunchId = result.launch.configurationId;
|
||||
preparedIdentity = requirements.identity;
|
||||
return result.launch;
|
||||
|
||||
Reference in new issue
Block a user