mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-02 08:28:48 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - The web server owns request handling and remote execution coordination. > - Deployment must start a ready replacement while the old server still serves. > - An outage test does not prove that two live servers can overlap safely. > - This pull request adds a separate Product E2E cell for that boundary. > - The existing run, file, recovery, and retained-session checks still apply. ## Linked Issues or Issue Description Refs #18518. The runtime prerequisite is merged; this PR qualifies its ephemeral server and deployment contracts. ## What Changed - Add the explicit `rolling-web-deployment` Codex Daytona workflow. - Start independent A/B/C homes and compiled builds behind a test ingress. - Wait for readiness before routing, then drain and delete the old home. - Observe active authority before handoff and use the existing read-only recovery oracle. - Require ordinary reads and saves to succeed throughout replacement. Read back every accepted save exactly once. - Preserve the five-minute outage suites and their existing validators. - Add a model-free supervisor smoke and an unready replacement control. - Require graceful exit before deleting an old home; forced cleanup cannot satisfy the oracle. - Preserve a durable Stop through lease release/expiry until the recovered execution owner acknowledges it. Permit only fenced reattachment of the original execution for Stop cleanup; submit no new turn. - Exclude events saved by A during shutdown from evidence of B making progress. ## Verification - E2E TypeScript check passed. - Affected harness checks: 143 passed. Catalog, fixture and report checks: 120 passed. - Actual supervisor smoke passed two replacements: 436 reads, 45 saves, zero request failures, and confirmed owned resource cleanup. - B became ready in 18.7 seconds; C became ready in 109.2 seconds. A prior C timeout remains failed evidence. - Fresh browser proof: 11 checks passed, 246 reads, 50 acknowledged saves, zero failures, 1,058ms reconnect, both old homes deleted and cleanup confirmed. - Stop lease-gap regression: three PostgreSQL delivery tests passed with a simulated provider edge. Current server TypeScript build/vendoring passed. - Full harness: 5,814 passed, 17 failed, four skipped. Two shutdown races passed the focused file; two report timeouts passed an isolated 42-test rerun. Onboarding/workflow-security/Pi/date-expired fixtures are unchanged on inspected master; the host embedded PostgreSQL fixture remains a setup limitation. This is not a green full local suite. - CI at `172509b8be` passed all gates. Greptile is 5/5 with every review thread resolved. The earlier access-service race failure passed its isolated regression and the subsequent full CI. - Final review corrections: six focused executor cases, three PostgreSQL command-delivery cases, 19 harness cases and server/E2E typechecks passed. - Three live attempts failed before agent creation: two harness setup gaps were fixed, then provider authentication failed. The saved OpenAI key returns 401; a refresh is pending. The Daytona probe reported cleanup uncertain, and no sandbox with that attempt label was found through the authenticated staging manager. No live model execution is claimed. - Live Runner overlap, released-container qualification and hosted deployment proof remain pending. Merging this opt-in qualification lane does not claim those results. ## Risks - The source lane shares workspace dependencies and does not establish container packaging correctness. - The live workflow needs an explicitly owned S3 bucket, PostgreSQL, pinned remote image and provider credentials. - Qualification cleanup stops all owned processes after failure. A failed replacement must not be reported as a pass. ## Model Used OpenAI Codex, GPT-6. Tool use, code execution and repository review. The runtime does not expose a more specific model ID or context-window size. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
187 lines
12 KiB
TypeScript
187 lines
12 KiB
TypeScript
/** Read-only qualification observer. This never calls recovery, renews a lease,
|
|
* parses checkpoint records, or interprets an underlying harness protocol. */
|
|
import { readFile } from "node:fs/promises";
|
|
import { setTimeout as delay } from "node:timers/promises";
|
|
import { createRequire } from "node:module";
|
|
const { sql }: typeof import("../../packages/db/node_modules/drizzle-orm/index.js") =
|
|
createRequire(new URL("../../packages/db/package.json", import.meta.url))("drizzle-orm");
|
|
import { createDb, type Db } from "../../packages/db/src/index.js";
|
|
import { paperclipConfigSchema } from "../../packages/shared/src/config-schema.js";
|
|
import { loadNativeRunnerCheckpoint } from "../../server/src/services/native-runtime/native-runner-checkpoint.js";
|
|
import type { ControllerReplacementReceipt } from "./controller-replacement.js";
|
|
|
|
export interface RecoveryBinding { companyId: string; issueId: string; runId: string }
|
|
export interface RecoverySnapshot {
|
|
runId: string; runnerInstanceId: string; nativeSessionId: string;
|
|
bootId: string; generation: number; attempt: number; leaseExpiresAt: string | null;
|
|
sourceSeq: number; history: Array<Record<string, unknown>>;
|
|
authenticatedConnectionCount: number;
|
|
checkpointSourceSeq: number;
|
|
}
|
|
export interface ControllerRecoveryReceipt {
|
|
binding: RecoveryBinding;
|
|
runnerInstanceId: string;
|
|
nativeSessionId: string;
|
|
previousGeneration: number;
|
|
generation: number;
|
|
previousBootId: string;
|
|
bootId: string;
|
|
previousLeaseExpiresAt: string | null;
|
|
ownershipAcquiredAt: string;
|
|
ownershipObservedAfterMs: number;
|
|
authenticatedAttachmentObservedAfterMs: number;
|
|
resumedProcessingObservedAfterMs: number;
|
|
runnerSourceSeqBefore: number;
|
|
runnerSourceSeqAfter: number;
|
|
previousAuthenticatedConnectionCount: number;
|
|
authenticatedConnectionCount: number;
|
|
attachmentEvidence: "runner_checkpoint_authenticated_connection";
|
|
}
|
|
export function parseRecoveryBinding(value: unknown): RecoveryBinding {
|
|
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Invalid controller recovery binding");
|
|
const row = value as Record<string, unknown>;
|
|
if (Object.keys(row).length !== 3 || !["companyId", "issueId", "runId"].every(key =>
|
|
typeof row[key] === "string" && /^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(row[key] as string))) {
|
|
throw new Error("Invalid controller recovery binding");
|
|
}
|
|
return row as unknown as RecoveryBinding;
|
|
}
|
|
|
|
export function recoveryObservation(before: RecoverySnapshot, after: RecoverySnapshot, fault: ControllerReplacementReceipt,
|
|
binding: RecoveryBinding, observedAfterMs: number): ControllerRecoveryReceipt | null {
|
|
if (before.runId !== binding.runId || after.runId !== before.runId || after.runnerInstanceId !== before.runnerInstanceId
|
|
|| after.nativeSessionId !== before.nativeSessionId || after.attempt !== before.attempt) {
|
|
throw new Error("Controller replacement changed the admitted execution");
|
|
}
|
|
if (after.bootId === before.bootId || after.generation <= before.generation) return null;
|
|
const claim = after.history.findLast(entry => entry.controllerBootId === after.bootId
|
|
&& entry.controllerGeneration === after.generation);
|
|
if (!claim || claim.disposition !== "reattach_remote_runner" || typeof claim.at !== "string") {
|
|
throw new Error("Replacement did not naturally adopt the original remote runner");
|
|
}
|
|
const claimedAt = Date.parse(claim.at);
|
|
if (!Number.isFinite(claimedAt) || claimedAt < Date.parse(fault.startedAt)
|
|
|| (fault.signal === "SIGKILL" && before.leaseExpiresAt && claimedAt < Date.parse(before.leaseExpiresAt))) {
|
|
throw new Error("Replacement bypassed natural controller lease expiry");
|
|
}
|
|
if (after.authenticatedConnectionCount <= before.authenticatedConnectionCount || after.sourceSeq <= before.sourceSeq) return null;
|
|
// The runner-owned projection counts successful authentications. New canonical
|
|
// receipts separately prove ingestion beyond both the saved checkpoint and DB
|
|
// cursor. Replaying an old saved event alone cannot pass either boundary.
|
|
return { binding, runnerInstanceId: before.runnerInstanceId, nativeSessionId: before.nativeSessionId,
|
|
previousGeneration: before.generation, generation: after.generation, previousBootId: before.bootId,
|
|
bootId: after.bootId, previousLeaseExpiresAt: before.leaseExpiresAt, ownershipAcquiredAt: claim.at,
|
|
ownershipObservedAfterMs: observedAfterMs, authenticatedAttachmentObservedAfterMs: observedAfterMs,
|
|
resumedProcessingObservedAfterMs: observedAfterMs, runnerSourceSeqBefore: before.sourceSeq,
|
|
runnerSourceSeqAfter: after.sourceSeq, previousAuthenticatedConnectionCount: before.authenticatedConnectionCount,
|
|
authenticatedConnectionCount: after.authenticatedConnectionCount, attachmentEvidence: "runner_checkpoint_authenticated_connection" };
|
|
}
|
|
|
|
/** B can claim before A exits. Preserve A's original owner/authentication
|
|
* identity while excluding every event committed through A's final exit. */
|
|
export function advanceRecoveryCursor(before: RecoverySnapshot, stopped: RecoverySnapshot): RecoverySnapshot {
|
|
if (before.runId !== stopped.runId || before.runnerInstanceId !== stopped.runnerInstanceId
|
|
|| before.nativeSessionId !== stopped.nativeSessionId || before.attempt !== stopped.attempt) {
|
|
throw new Error("Controller replacement changed the admitted execution");
|
|
}
|
|
return { ...before, sourceSeq: Math.max(before.sourceSeq, stopped.sourceSeq, stopped.checkpointSourceSeq) };
|
|
}
|
|
|
|
export function validControllerRecoveryReceipt(fault: ControllerReplacementReceipt | undefined): boolean {
|
|
const r = fault?.recovery;
|
|
return Boolean(r && r.bootId !== r.previousBootId && r.generation > r.previousGeneration
|
|
&& r.runnerSourceSeqAfter > r.runnerSourceSeqBefore && r.authenticatedConnectionCount > r.previousAuthenticatedConnectionCount
|
|
&& r.attachmentEvidence === "runner_checkpoint_authenticated_connection"
|
|
&& [r.ownershipObservedAfterMs, r.authenticatedAttachmentObservedAfterMs, r.resumedProcessingObservedAfterMs]
|
|
.every(ms => Number.isFinite(ms) && ms >= fault!.readyAfterMs! && ms < 420_000));
|
|
}
|
|
|
|
export async function readControllerRecoverySnapshot(db: Db, binding: RecoveryBinding): Promise<RecoverySnapshot> {
|
|
return db.transaction(async tx => {
|
|
const [row] = await tx.execute(sql`select r.id as "runId", r.runner_instance_id as "runnerInstanceId",
|
|
r.native_session_id as "nativeSessionId", f.controller_boot_id as "bootId", f.controller_generation as generation,
|
|
f.attempt, f.lease_expires_at::text as "leaseExpiresAt", f.recovery_history as history,
|
|
coalesce((select max(e.source_seq) from heartbeat_run_events e where e.run_id = r.id
|
|
and e.company_id = r.company_id and e.source_instance_id = r.runner_instance_id::text), 0)::float8 as "sourceSeq"
|
|
from heartbeat_runs r join native_run_finalizations f on f.run_id = r.id and f.company_id = r.company_id
|
|
where r.id = ${binding.runId} and r.company_id = ${binding.companyId} and r.native_issue_id = ${binding.issueId}`);
|
|
if (!row?.runnerInstanceId || !row.nativeSessionId || !row.bootId) throw new Error("Recovery binding has no admitted native owner");
|
|
if (!Array.isArray(row.history) || row.history.some(entry => entry === null
|
|
|| typeof entry !== "object" || Array.isArray(entry))) {
|
|
throw new Error("Recovery history must be an array of records");
|
|
}
|
|
// Use the existing server loader and Runner's public diagnostic projection.
|
|
// The qualification code never reads encrypted material or private formats.
|
|
const checkpoint = await loadNativeRunnerCheckpoint(tx as unknown as Db, binding);
|
|
const evidence = checkpoint?.recoveryEvidence;
|
|
if (!evidence || evidence.runnerInstanceId !== row.runnerInstanceId || evidence.normalizedSessionId !== row.nativeSessionId) {
|
|
throw new Error("Recovery checkpoint has no matching runner evidence");
|
|
}
|
|
return { ...row, authenticatedConnectionCount: evidence.authenticatedConnectionCount,
|
|
checkpointSourceSeq: evidence.highestRecordedSourceSeq } as RecoverySnapshot;
|
|
}, { isolationLevel: "repeatable read", accessMode: "read only" });
|
|
}
|
|
|
|
export async function createControllerRecoveryObserver(configPath: string, binding: RecoveryBinding) {
|
|
const config = paperclipConfigSchema.parse(JSON.parse(await readFile(configPath, "utf8")));
|
|
const url = config.database.mode === "postgres" ? config.database.connectionString
|
|
: `postgres://paperclip:paperclip@127.0.0.1:${config.database.embeddedPostgresPort}/paperclip`;
|
|
if (!url) throw new Error("Qualification database is unavailable");
|
|
const db = createDb(url);
|
|
let before: RecoverySnapshot | undefined;
|
|
const read = () => readControllerRecoverySnapshot(db, binding);
|
|
const capture = async (fault: ControllerReplacementReceipt) => {
|
|
before = await read();
|
|
before.sourceSeq = Math.max(before.sourceSeq, before.checkpointSourceSeq);
|
|
fault.recoveryProgress = { binding, previousBootId: before.bootId, previousGeneration: before.generation,
|
|
previousLeaseExpiresAt: before.leaseExpiresAt, runnerSourceSeqBefore: before.sourceSeq,
|
|
previousAuthenticatedConnectionCount: before.authenticatedConnectionCount,
|
|
runnerInstanceId: before.runnerInstanceId, nativeSessionId: before.nativeSessionId };
|
|
};
|
|
return {
|
|
beforeHandoff: capture,
|
|
// Called only after the old server is confirmed dead. This also excludes
|
|
// receipts committed while it was stopping from replacement evidence.
|
|
stopped: capture,
|
|
stoppedAfterHandoff: async (fault: ControllerReplacementReceipt) => {
|
|
if (!before) throw new Error("Missing pre-handoff controller observation");
|
|
before = advanceRecoveryCursor(before, await read());
|
|
fault.recoveryProgress = { ...fault.recoveryProgress, runnerSourceSeqBefore: before.sourceSeq };
|
|
},
|
|
recovered: async (fault: ControllerReplacementReceipt, record: () => Promise<void>, cancelled: () => boolean) => {
|
|
if (!before) throw new Error("Missing controller boundary observation");
|
|
const deadline = Date.parse(fault.startedAt) + 420_000;
|
|
let ownershipObservedAfterMs: number | undefined;
|
|
let authenticatedObservedAfterMs: number | undefined;
|
|
while (Date.now() < deadline && !cancelled()) {
|
|
const current = await read();
|
|
const elapsed = Date.now() - Date.parse(fault.startedAt);
|
|
if (current.bootId !== before.bootId && current.generation > before.generation && ownershipObservedAfterMs === undefined) {
|
|
ownershipObservedAfterMs = elapsed;
|
|
fault.recoveryProgress = { ...fault.recoveryProgress, bootId: current.bootId, generation: current.generation,
|
|
ownershipObservedAfterMs };
|
|
await record();
|
|
}
|
|
if (ownershipObservedAfterMs !== undefined && current.authenticatedConnectionCount > before.authenticatedConnectionCount
|
|
&& authenticatedObservedAfterMs === undefined) {
|
|
authenticatedObservedAfterMs = elapsed;
|
|
fault.recoveryProgress = { ...fault.recoveryProgress, authenticatedConnectionCount: current.authenticatedConnectionCount,
|
|
authenticatedAttachmentObservedAfterMs: elapsed };
|
|
await record();
|
|
}
|
|
const recovered = recoveryObservation(before, current, fault, binding, elapsed);
|
|
if (recovered) {
|
|
recovered.ownershipObservedAfterMs = ownershipObservedAfterMs!;
|
|
recovered.authenticatedAttachmentObservedAfterMs = authenticatedObservedAfterMs!;
|
|
fault.recovery = recovered;
|
|
await record();
|
|
return;
|
|
}
|
|
await delay(250);
|
|
}
|
|
throw new Error("Original runner did not reattach and resume ingestion within its original 420-second grace");
|
|
},
|
|
close: () => db.$client.end(),
|
|
};
|
|
}
|