Files
PaperClipAI/server/src/services/native-runtime/native-provider-pack-admission.ts
T
DottaandClaude Opus 5.5 3eca7a6112 fix(runner): log which check refuses a saved provider-pack admission on reattach (#21085)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - OpenCode turns run in a remote Runner. When a server restarts, the
new server reconnects to the Runner and reuses the provider pack
admission that the run saved earlier.
> - On staging, a run reconnected cleanly after an upgrade but then
failed with `native_provider_artifacts_admission_unverified`. Its saved
admission state stayed "pending".
> - The reuse step refuses a saved admission for several reasons. It
returns only false and logs nothing, so we cannot tell which check
refused it.
> - This pull request adds diagnostics only. It names the refused check
in the run log and the server log. It also logs when the admission stays
unverified for a session that needs it.
> - The benefit is that the next upgrade audit shows the real cause, so
the next fix can target it.

## Linked Issues or Issue Description

**What happened?**
After an automatic staging upgrade, a run reconnected to its live Runner
without a new process. The next checkpoint failed with
`native_provider_artifacts_admission_unverified`, which used one of the
run's 3 attempts. The run log had no line that explained why the saved
admission was not reused.

**Expected behavior**
When a saved admission is not reused, the run log and the server log
name the check that refused it.

**Steps to reproduce**
1. Start an OpenCode run on a remote sandbox.
2. Restart the server, so the run reconnects to its Runner.
3. If the saved admission is refused, the run fails later with
`native_provider_artifacts_admission_unverified` and no reason in the
logs.

## What Changed

- `native-provider-pack-admission.ts`:
`rememberRecoveredNativeProviderPack` accepts an optional `onRefused`
callback. It is called with one reason: `source_state_pending`,
`source_state_unknown`, `source_state_missing`, `receipt_missing`,
`runner_instance_differs`, `environment_lease_differs`,
`receipt_invalid`, or a session identity reason. The result of every
check stays the same. An error in the callback is ignored.
- `native-session-executor.ts`: the reattach path logs the reason to the
run log and the server log. When `recordNativeProviderPackAdmission`
returns false for a session that requires admission, it logs that too.
- `native-provider-pack-admission.test.ts`: each refusal names its
reason, and a reused admission reports nothing.

## Verification

- `npx vitest run
src/services/native-runtime/native-provider-pack-admission.test.ts`
passes 46/46. The new reason tests fail on the old code because
`onRefused` is never called.
- `npx vitest run
src/services/native-runtime/native-session-executor.test.ts` passes
1412/1412.
- `npx tsc --noEmit -p server/tsconfig.json` passes.

## Risks

- Low risk. This change adds diagnostics only, and admission decisions
do not change. The new log lines contain only a fixed reason code and
run ids. They do not contain secrets or file paths.

> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Claude Code agent with tool use
(shell, code search, 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

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 05:38:23 -06:00

224 lines
14 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 };
}
function verifiedState(value: unknown): 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 === "verified"
&& 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 } : {}),
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;
});
}