Files
PaperClipAI/server/src/services/native-runtime/native-provider-pack-admission.ts
T
DottaandPaperclip 6ad4529c5a fix(native): preserve pack proof across interrupted reattachment (#21246)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - The server can connect again to a live Runner after a restart.
> - Each new controller claim changes provider-pack admission to
pending.
> - The claim kept the previous verified proof only in local memory.
> - If recovery failed before its callback, the next claim lost that
proof.
> - This pull request saves a small reference to the verified proof with
the claim.
> - The next claim can check the same receipt without weakening
admission checks.

## Linked Issues or Issue Description

**What happened?**
A restart recovery attempt timed out before its admission callback. The
next attempt refused the saved pack with `source_state_pending`. It then
failed with `native_provider_artifacts_admission_unverified`.

**Expected behavior**
The next attempt can reuse the previous verified proof for the same
receipt, session, Runner, and lease. Current admission must remain
pending until its normal callback succeeds.

**Steps to reproduce**
1. Save verified provider-pack admission for a run.
2. Claim that run again. Commit the pending admission state.
3. Interrupt recovery before the session admission callback.
4. Claim the same run again and reconnect to the same Runner.
5. Observe that the old code refuses the saved receipt.

Related work: #20682 and #20850 address lock waits. #21085 adds refusal
logs. #21161 addresses command waits after restart. This change
addresses lost admission proof across interrupted claims. The original
transport timeout remains a separate investigation.

## What Changed

- The admission module prepares the claim patch and its recovery source.
- The claim saves a versioned reference with the source run, receipt
digest, and previous verified state. It adds no copy of provider files
or credentials.
- A later pending claim can use that reference only if the receipt is
unchanged. Normal company, agent, session, Runner, and lease checks
still apply.
- Missing proof, unknown state, a changed receipt, or a different Runner
stays refused. The callback clears the reference when it records its
decision.
- The executor uses this helper under its existing claim lock. Existing
artifact-retention and ownership checks stay in place.
- The execution guide states the previous-release behavior. Old verified
records seed the reference. Old pending records without a reference
remain refused. Older readers ignore the field and keep their existing
refusal behavior. No migration is needed.

## Verification

- The new interrupted-claim regression failed before the fix: admission
returned false instead of true.
- Focused admission, PostgreSQL fencing, and executor lease tests passed
after the rebase: 61 tests on commit c8123cc35d.
- The database case saves two interrupted claims, reads their persisted
state, checks a different Runner is refused, and publishes verified
admission for the original Runner.
- Negative cases cover missing proof, unknown state, a changed receipt,
a different source run, a different Runner, and a different lease.
Existing company and claim fences also pass.
- `pnpm verify` returned exit 2 because the execution guide requires
broader CI. Required CI must cover the final commit.
- Local server typecheck was killed with SIGKILL, including its
single-thread retry. This is an environment gap. Required CI must
provide typecheck and build results.
- Repository preflight installed dependencies and built shared packages.
It could not finish Runner preparation because cargo is absent.
- A live OpenCode restart workflow and recovery of the original task are
not verified. No task replay or deployment was performed.

## Risks

- The added profile field carries historical evidence. It does not mark
the current claim verified. Its use is limited to an unchanged receipt
with the normal identity checks.
- Existing pending or unknown incidents without this evidence cannot
gain proof from this fix. They keep their normal recovery path.
- No provider attempt limit, approval gate, workspace hold, or company
boundary changes.

## Model Used

OpenAI GPT-6, through Codex, with code search, tool use, and local test
execution.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-11-13 12:56:57 -06:00

253 lines
16 KiB
TypeScript

import { and, eq, gt, isNull, sql } from "drizzle-orm";
import { createHash } from "node:crypto";
import { heartbeatRuns, nativeRunFinalizations, type Db } from "@paperclipai/db";
import type { NativeSession } from "../../vendor/paperclip-runner/index.js";
import { canonicalProviderPackJson, type ProviderPackIdentity } from "./remote-provider-pack-verification.js";
import { assertNativeRunnerCheckpointOwner } from "./native-runner-checkpoint.js";
import { isTransientLockContention, postgresErrorCode } from "../transient-lock-contention.js";
type Selection = {
admittedRunId: string;
companyId: string;
agentId: string;
sessionId: string;
runnerInstanceId: string;
environmentLeaseId: string;
providerPackDigest: string;
opencodeProxySha256: string;
sourceRevision: string;
};
export type NativeProviderPackAdmission = Omit<Selection, "admittedRunId" | "environmentLeaseId"> & {
schema: "paperclip.native-provider-pack-admission.v1";
stage: "session_admitted";
authority: "core_verified_selection";
runId: string;
runnerEnvironmentLeaseId: string;
inheritedFromRunId?: string;
};
const admitted = new WeakMap<NativeSession, Readonly<Selection>>();
const digest = /^sha256:[a-f0-9]{64}$/;
type NativeRunIdentity = ReturnType<NativeSession["identity"]>;
export type NativeProviderPackAdmissionRefusal = "session_identity_unavailable" | "session_identity_differs"
| "source_state_pending" | "source_state_unknown" | "source_state_missing" | "receipt_missing"
| "runner_instance_differs" | "environment_lease_differs" | "receipt_invalid";
export type NativeProviderPackAdmissionSource ={ runId: string; receipt: unknown; state: unknown; artifacts?: unknown };
export function nativeProviderPackAdmissionPending(admissionEpoch: string) {
return { schema: "paperclip.native-provider-pack-admission-state.v1" as const, state: "pending" as const, admissionEpoch };
}
/** Called under the executor's claim lock, before provider admission. */
export function prepareNativeProviderPackAdmission(runId: string, profile: Record<string, unknown> | null | undefined, admissionEpoch: string) {
const receipt = profile?.nativeProviderPackAdmission;
let state = profile?.nativeProviderPackAdmissionState;
const saved = profile?.nativeProviderPackAdmissionRecovery as Record<string, unknown> | null | undefined;
const receiptDigest = receipt && typeof receipt === "object" && !Array.isArray(receipt)
? `sha256:${createHash("sha256").update(canonicalProviderPackJson(receipt)).digest("hex")}` : null;
// A pending claim has not selected a different pack. It can carry forward
// the exact verified proof that the previous claim captured under its lock.
// Unknown state means selection was refused and must never regain that proof.
if (admissionState(state, "pending")
&& saved?.schema === "paperclip.native-provider-pack-admission-recovery.v1"
&& Object.keys(saved).sort().join(",") === "receiptDigest,runId,schema,state"
&& saved.runId === runId && receiptDigest !== null && saved.receiptDigest === receiptDigest
&& verifiedState(saved.state)) state = saved.state;
const recovery = receiptDigest !== null && verifiedState(state)
? { schema: "paperclip.native-provider-pack-admission-recovery.v1", runId, receiptDigest, state } : null;
return {
source: { runId, receipt, state, artifacts: profile?.nativeProviderArtifacts },
patch: { nativeProviderPackAdmissionState: nativeProviderPackAdmissionPending(admissionEpoch),
nativeProviderPackAdmissionRecovery: recovery },
};
}
function verifiedState(value: unknown): boolean {
return admissionState(value, "verified");
}
function admissionState(value: unknown, expected: "pending" | "verified"): boolean {
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
const state = value as Record<string, unknown>;
return Object.keys(state).sort().join(",") === "admissionEpoch,schema,state"
&& state.schema === "paperclip.native-provider-pack-admission-state.v1" && state.state === expected
&& typeof state.admissionEpoch === "string" && /^[a-f0-9-]{36}$/.test(state.admissionEpoch);
}
function rememberSelection(session: NativeSession, selected: Selection): boolean {
const prior = admitted.get(session);
if (prior && canonicalProviderPackJson(prior) === canonicalProviderPackJson({ ...selected, admittedRunId: prior.admittedRunId })) return true;
admitted.set(session, Object.freeze(selected));
return true;
}
export function rememberAdmittedNativeProviderPack(session: NativeSession, input: {
identity: NativeRunIdentity;
runnerInstanceId: string;
environmentLeaseId: string;
manifest: ProviderPackIdentity;
}): boolean {
const unavailable = () => { admitted.delete(session); return false; };
if (typeof session.identity !== "function") return unavailable();
const actual = session.identity();
if (canonicalProviderPackJson(actual) !== canonicalProviderPackJson(input.identity)) return unavailable();
const proxy = input.manifest.payload.artifacts.opencodeProxy?.sha256;
const revision = input.manifest.payload.runnerSourceRevision;
if (!digest.test(input.manifest.digest)
|| input.manifest.digest !== `sha256:${createHash("sha256").update(canonicalProviderPackJson(input.manifest.payload)).digest("hex")}`
|| !digest.test(proxy ?? "") || !/^[a-f0-9]{40}$/.test(revision)
|| !input.runnerInstanceId || !input.environmentLeaseId) return unavailable();
const selected: Selection = {
admittedRunId: actual.runId,
companyId: actual.companyId, agentId: actual.agentId, sessionId: actual.sessionId,
runnerInstanceId: input.runnerInstanceId, environmentLeaseId: input.environmentLeaseId,
providerPackDigest: input.manifest.digest, opencodeProxySha256: proxy!, sourceRevision: revision,
};
return rememberSelection(session, selected);
}
export async function rememberRecoveredNativeProviderPack(db: Db, session: NativeSession, input: {
identity: NativeRunIdentity;
sourceRunId: string;
runnerInstanceId: string;
environmentLeaseId: string;
source?: NativeProviderPackAdmissionSource;
/** Diagnostics only: names the check that refused the saved admission. */
onRefused?: (reason: NativeProviderPackAdmissionRefusal) => void | Promise<void>;
}): Promise<boolean> {
admitted.delete(session);
const refuse = async (reason: NativeProviderPackAdmissionRefusal) => {
try { await input.onRefused?.(reason); } catch { /* diagnostics never change admission */ }
return false;
};
if (typeof session.identity !== "function") return refuse("session_identity_unavailable");
if (canonicalProviderPackJson(session.identity()) !== canonicalProviderPackJson(input.identity)) return refuse("session_identity_differs");
const source = input.source?.runId === input.sourceRunId ? input.source : (await db.select({
receipt: sql<unknown>`${heartbeatRuns.runnerProfileJson}->'nativeProviderPackAdmission'`,
state: sql<unknown>`${heartbeatRuns.runnerProfileJson}->'nativeProviderPackAdmissionState'`,
}).from(heartbeatRuns).where(and(eq(heartbeatRuns.id, input.sourceRunId), eq(heartbeatRuns.companyId, input.identity.companyId),
eq(heartbeatRuns.agentId, input.identity.agentId), eq(heartbeatRuns.runtimeMode, "native"))).limit(1))[0];
if (!verifiedState(source?.state)) {
const state = source?.state && typeof source.state === "object" ? (source.state as Record<string, unknown>).state : undefined;
return refuse(state === "pending" ? "source_state_pending" : state === "unknown" ? "source_state_unknown" : "source_state_missing");
}
const value = source?.receipt;
if (!value || typeof value !== "object" || Array.isArray(value)) return refuse("receipt_missing");
const receipt = value as Record<string, unknown>;
if (receipt.runnerInstanceId !== input.runnerInstanceId) return refuse("runner_instance_differs");
if (receipt.runnerEnvironmentLeaseId !== input.environmentLeaseId) return refuse("environment_lease_differs");
const keys = new Set(["schema", "stage", "authority", "companyId", "agentId", "runId", "sessionId", "runnerInstanceId",
"runnerEnvironmentLeaseId", "providerPackDigest", "opencodeProxySha256", "sourceRevision", "inheritedFromRunId"]);
if (Object.keys(receipt).some(key => !keys.has(key)) || receipt.schema !== "paperclip.native-provider-pack-admission.v1"
|| receipt.stage !== "session_admitted" || receipt.authority !== "core_verified_selection"
|| receipt.runId !== input.sourceRunId || receipt.companyId !== input.identity.companyId || receipt.agentId !== input.identity.agentId
|| receipt.sessionId !== input.identity.sessionId || receipt.runnerInstanceId !== input.runnerInstanceId
|| receipt.runnerEnvironmentLeaseId !== input.environmentLeaseId || !digest.test(String(receipt.providerPackDigest))
|| !digest.test(String(receipt.opencodeProxySha256)) || !/^[a-f0-9]{40}$/.test(String(receipt.sourceRevision))
|| (receipt.inheritedFromRunId !== undefined && (typeof receipt.inheritedFromRunId !== "string" || !receipt.inheritedFromRunId))) return refuse("receipt_invalid");
return rememberSelection(session, { admittedRunId: String(receipt.inheritedFromRunId ?? receipt.runId),
companyId: input.identity.companyId, agentId: input.identity.agentId, sessionId: input.identity.sessionId,
runnerInstanceId: input.runnerInstanceId, environmentLeaseId: input.environmentLeaseId,
providerPackDigest: String(receipt.providerPackDigest), opencodeProxySha256: String(receipt.opencodeProxySha256),
sourceRevision: String(receipt.sourceRevision) });
}
export function admittedNativeProviderPack(session: NativeSession, identity: NativeRunIdentity): NativeProviderPackAdmission | null {
const selected = admitted.get(session);
if (!selected) return null;
const actual = session.identity();
if (canonicalProviderPackJson(actual) !== canonicalProviderPackJson(identity)
|| actual.companyId !== selected.companyId || actual.agentId !== selected.agentId || actual.sessionId !== selected.sessionId) return null;
const { admittedRunId, environmentLeaseId, ...identityFields } = selected;
return { schema: "paperclip.native-provider-pack-admission.v1", stage: "session_admitted",
authority: "core_verified_selection", ...identityFields, runId: actual.runId, runnerEnvironmentLeaseId: environmentLeaseId,
...(admittedRunId === actual.runId ? {} : { inheritedFromRunId: admittedRunId }) };
}
type AdmissionInput = {
session: NativeSession;
identity: NativeRunIdentity;
admissionEpoch: string;
claim: { leaseOwner: string; attempt: number; controllerGeneration: number; controllerBootId: string };
waitForClaim?: boolean;
};
/** Attempts of one admission write while its claim is contended. */
export const NATIVE_PROVIDER_PACK_ADMISSION_ATTEMPTS = 5;
export const nativeProviderPackAdmissionFailureCode = postgresErrorCode;
/**
* Saves the session's verified provider-pack admission on its run row. A run
* that waits for its claim retries a contended write: the runner's durable
* checkpoint writes hold the same coordinator row, and on a loaded database one
* can outlast a single lock wait. Each attempt is a new transaction that
* re-proves the claim, the run and the admission epoch, so a retry never
* admits anything the first attempt would have refused. Only contention is
* retried; a stale claim still returns false and other errors still throw.
*/
export async function recordNativeProviderPackAdmission(db: Db, input: AdmissionInput): Promise<boolean> {
for (let attempt = 1; ; attempt += 1) {
try {
return await recordNativeProviderPackAdmissionOnce(db, input);
} catch (error) {
if (!input.waitForClaim || attempt >= NATIVE_PROVIDER_PACK_ADMISSION_ATTEMPTS
|| !isTransientLockContention(error)) throw error;
await new Promise(resolve => setTimeout(resolve, 100 * attempt));
}
}
}
async function recordNativeProviderPackAdmissionOnce(db: Db, input: AdmissionInput): Promise<boolean> {
const receipt = admittedNativeProviderPack(input.session, input.identity);
return db.transaction(async tx => {
// Bounds every lock wait below, including the run-row lock. A run-event
// append holds that row FOR UPDATE for milliseconds; NOWAIT there lost the
// admission and then failed the run as admission_unverified.
await tx.execute(sql`select set_config('lock_timeout', '1000ms', true)`);
if (input.waitForClaim) {
await assertNativeRunnerCheckpointOwner(tx, { companyId: input.identity.companyId,
issueId: input.identity.issueId, runId: input.identity.runId, authorityRunId: input.identity.runId,
bootId: input.claim.controllerBootId, leaseOwner: input.claim.leaseOwner,
generation: input.claim.controllerGeneration }, false);
}
const [owner] = await tx.select({ runId: nativeRunFinalizations.runId }).from(nativeRunFinalizations).where(and(
eq(nativeRunFinalizations.runId, input.identity.runId), eq(nativeRunFinalizations.companyId, input.identity.companyId),
eq(nativeRunFinalizations.issueId, input.identity.issueId), eq(nativeRunFinalizations.leaseOwner, input.claim.leaseOwner),
eq(nativeRunFinalizations.attempt, input.claim.attempt), eq(nativeRunFinalizations.controllerGeneration, input.claim.controllerGeneration),
eq(nativeRunFinalizations.controllerBootId, input.claim.controllerBootId), gt(nativeRunFinalizations.leaseExpiresAt, sql`now()`),
eq(nativeRunFinalizations.phase, "observed"), isNull(nativeRunFinalizations.resultId),
)).for("update", { noWait: true }).limit(1);
if (!owner) return false;
const [run] = await tx.select({ profile: heartbeatRuns.runnerProfileJson }).from(heartbeatRuns).where(and(
eq(heartbeatRuns.id, input.identity.runId), eq(heartbeatRuns.companyId, input.identity.companyId),
eq(heartbeatRuns.agentId, input.identity.agentId), eq(heartbeatRuns.nativeIssueId, input.identity.issueId),
eq(heartbeatRuns.runtimeMode, "native"), eq(heartbeatRuns.status, "running"),
)).for("update").limit(1);
if (!run) return false;
const current = run.profile?.nativeProviderPackAdmissionState as Record<string, unknown> | undefined;
if (current?.schema !== "paperclip.native-provider-pack-admission-state.v1" || current.admissionEpoch !== input.admissionEpoch
|| !["pending", "verified", "unknown"].includes(String(current.state))) return false;
if (current.state === "unknown") return false;
const previous = run.profile?.nativeProviderPackAdmission;
const verified = receipt != null && (previous == null ? current.state === "pending"
: canonicalProviderPackJson({ ...(previous as Record<string, unknown>), inheritedFromRunId: null })
=== canonicalProviderPackJson({ ...receipt, inheritedFromRunId: null }));
if (verified && current.state === "verified") return true;
const patch = { ...(verified && previous == null ? { nativeProviderPackAdmission: receipt } : {}),
...(run.profile?.nativeProviderPackAdmissionRecovery != null ? { nativeProviderPackAdmissionRecovery: null } : {}),
nativeProviderPackAdmissionState: { ...nativeProviderPackAdmissionPending(input.admissionEpoch), state: verified ? "verified" : "unknown" } };
const saved = await tx.update(heartbeatRuns).set({
runnerProfileJson: sql`coalesce(${heartbeatRuns.runnerProfileJson}, '{}'::jsonb) || ${JSON.stringify(patch)}::jsonb`,
updatedAt: new Date(),
}).where(and(eq(heartbeatRuns.id, input.identity.runId), eq(heartbeatRuns.companyId, input.identity.companyId),
eq(heartbeatRuns.agentId, input.identity.agentId), eq(heartbeatRuns.nativeIssueId, input.identity.issueId),
eq(heartbeatRuns.runtimeMode, "native"), eq(heartbeatRuns.status, "running"),
)).returning({ id: heartbeatRuns.id });
return verified && saved.length === 1;
});
}