mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-04 04:29:01 +01:00
refactor(runner): remove the unused plugin task source recovery path (#23590)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - An agent run uses a Runner task that an environment plugin provides. When a Runner stops, the next run can need its saved session > - #19134 and #19196 added one way to do this. The next run claims the stopped Runner's task, and then starts that task again under its own control > - Those pull requests added the claim and its checks. They did not add a caller. #19157 was to add the caller, and it did not merge > - Nothing on `master` calls the claim. No lease gets the two records that the claim writes, so every check of those records does nothing > - The unused path still looks active. A reader can change it, and can think that the change fixes a failure > - This pull request removes the claim and all code that only reads its records > - The benefit is that the code shows only the recovery paths that can run ## Linked Issues or Issue Description Refs #19134, #19196 (added the path), #19157 (closed draft that called it). **Issue type** Dead code **What happened?** `claimPluginTaskSourceRecovery` has no caller on `master`. Only the claim writes `runnerTaskSourceConsumer` and `runnerTaskSourceRecovery` to a lease. Six other server files read those records. **Expected behavior** The server contains only recovery code that can run. **Steps to reproduce** 1. Run `git grep claimPluginTaskSourceRecovery master -- server`. 2. See only the definition. 3. Run `git log -G claimPluginTaskSourceRecovery master`. 4. See that the commits added the path, and later removed its tests. No commit added a caller. ## What Changed - Removed the source recovery claim and its checks (`plugin-task-source-recovery.ts`). - Removed the special handling of a claimed source from plugin task dispatch, task resume, checkpoint writes, task ownership, and retained and warm sandbox expiry. - A Runner task owner no longer takes `codexSourceRecoveryVersion`. Nothing set it, so the owner always refused to prepare a predecessor's launch. It still refuses. - The checkpoint writer still locks both runs, and still refuses a late write from a session that moved to another task. - The plugin SDK still accepts `codexSourceRecoveryVersion` and `acpxSourceRecoveryVersion`, so a plugin that sends them does not fail. The guide now says that Core does not use them. - The Runner package does not change. ## Verification - `npx vitest run` on eight test files for the changed code: 319 tests pass. - `npx tsc --noEmit` in `server` has no errors. - The test of a late write to a retired checkpoint used the removed records. It now uses the records of a session that moved to another task. - Not run locally: the suites that start a real Runner. CI runs them. ## Risks - No production code wrote these records, so no saved lease should contain them. A lease that does contain them is no longer held by them. - #19157 depended on this path. It is closed and did not merge. - No migration. No change to the plugin or Runner protocol. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, in Claude Code, with extended thinking, tool use and code 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 - [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 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
0134081be8
commit
dc16c47362
12 files changed
+36
-394
No files matched your search
@@ -387,48 +387,12 @@ authority as submission.
|
||||
Core requires preparation version 1 for native plugin execution. It validates
|
||||
and saves the result before it submits its configuration ID.
|
||||
|
||||
### Stopped source reconciliation
|
||||
### Stopped source fields
|
||||
|
||||
A plugin’s `describe` response advertises `codexSourceRecoveryVersion: 1` for
|
||||
Codex App Server and `acpxSourceRecoveryVersion: 1` for ACPX. It can advertise
|
||||
either, both, or neither. Each field means the host can verify and restore a
|
||||
stopped source for that provider without starting another turn. Core requires
|
||||
the field for the selected provider and verifies the run’s eligibility.
|
||||
|
||||
Core admission recognizes native Codex and qualified Claude through ACPX. ACPX
|
||||
Codex is a different provider and cannot use either attestation. Claude admission
|
||||
checks both saved and current profiles against Runner’s qualified catalog;
|
||||
decodable historical profiles do not authorize recovery. Preparation, submission
|
||||
and attachment retain that provider binding. Runner’s launch factory normalizes
|
||||
Claude’s model, mode, permissions, effort and runtime content before Core compares
|
||||
them with the saved source or current owner. Core revalidates the claim and
|
||||
profiles after worker replies. This admission does not activate executor recovery.
|
||||
It grants no replacement authority or exception to deterministic recovery refusals.
|
||||
|
||||
The authenticated request belongs to
|
||||
the current run while `prepare` and `submit` carry the predecessor Runner identity.
|
||||
Core derives this relationship from its saved source-consumer claim; a mismatched
|
||||
run ID alone never grants recovery. Both operations must name the same `resumeFrom`, exact source Runner identity, and current
|
||||
`accountIdentity`. The request and lease still belong to the current run.
|
||||
Preparation must save this source binding with its new configuration. Submission
|
||||
must verify the same binding before it starts the source process.
|
||||
|
||||
Core requires the source run to have a committed successful result, an encrypted
|
||||
PRP journal, confirmed physical termination, and no other source consumer. Core
|
||||
claims the source under the current native controller lease. This does not change
|
||||
the source run's status or result. A stale source controller cannot write its
|
||||
journal after this claim. Workspace export and settlement holds still apply.
|
||||
After source submission, the same current owner can prepare its attachment with
|
||||
the exact source as `priorIdentity`. This does not grant ordinary warm reuse.
|
||||
|
||||
The provider must verify the original account, workspace, runtime, and source
|
||||
ownership before launch. The provider must reject saved active goals, pending tools, ambiguous starts, and
|
||||
uncertain work before launch. Runner verifies that a saved idle provider remains
|
||||
idle when restored.
|
||||
Until the existing authenticated `run.attach` operation changes authority, the
|
||||
Core retains semantic inputs and sends no fresh predecessor business commands
|
||||
while the restored source reconciles its journal and known cleanup. Ordinary suspended recovery and live attachment keep their existing
|
||||
checks. Providers that omit the capability do not support predecessor recovery.
|
||||
A `describe` response can include `codexSourceRecoveryVersion: 1` and
|
||||
`acpxSourceRecoveryVersion: 1`. Core accepts these fields for compatibility and
|
||||
does not use them. Core does not prepare or submit a predecessor's launch under
|
||||
a later run.
|
||||
|
||||
## Launch authentication validation
|
||||
|
||||
|
||||
@@ -170,8 +170,7 @@ databaseSuite("environment task lease authority", () => {
|
||||
await db.insert(environmentLeases).values({ id: leaseId, companyId, environmentId, heartbeatRunId: runId,
|
||||
provider: "plugin:fixture:tasks", providerLeaseId: "tombstoned-task", status: "active", leasePolicy: "reuse_by_environment",
|
||||
metadata: { driver: "plugin", pluginId, pluginKey: pluginId, driverKey: "tasks", runnerTaskLease: true, runnerTaskReused: false,
|
||||
runnerTaskDispatched: false, runnerTaskExecutionStopped: true, runnerTaskSessionRetained: retained,
|
||||
runnerTaskSourceRecovery: { schema: "fixture" } } });
|
||||
runnerTaskDispatched: false, runnerTaskExecutionStopped: true, runnerTaskSessionRetained: retained } });
|
||||
const calls: string[] = [];
|
||||
const workers = { getWorker: () => ({ supportedMethods: ["environmentTask", "environmentAcquireLease"] }),
|
||||
call: async (_plugin: string, method: string, params: any, _timeout?: number, _sink?: unknown, settled?: () => void) => {
|
||||
@@ -196,7 +195,7 @@ databaseSuite("environment task lease authority", () => {
|
||||
expect(calls).toEqual(["status:tombstoned-task", "complete:tombstoned-task", "environmentAcquireLease", "describe:replacement-task"]);
|
||||
expect(lease.providerLeaseId).toBe("replacement-task");
|
||||
expect(lease.metadata).toMatchObject({ runnerTaskExecutionStopped: false, runnerTaskDispatched: false,
|
||||
runnerTaskSessionRetained: false, runnerTaskSourceRecovery: { schema: "fixture" } });
|
||||
runnerTaskSessionRetained: false });
|
||||
} else {
|
||||
expect(calls).toEqual(["describe:tombstoned-task"]);
|
||||
expect(lease.providerLeaseId).toBe("tombstoned-task");
|
||||
|
||||
@@ -112,7 +112,7 @@ export function softlyHeldSql(now?: Date) {
|
||||
|
||||
function alwaysHeldSql() {
|
||||
return sql`(${environmentLeases.metadata} ?| array['nativeWorkspaceExportResume', 'sandboxStopAndRetain',
|
||||
'workspaceRestoreRecovery', 'workspaceRecoveryCleanup', 'runnerTaskSourceConsumer', ${REUSABLE_SANDBOX_KEPT_AFTER_REPLACEMENT_KEY}]
|
||||
'workspaceRestoreRecovery', 'workspaceRecoveryCleanup', ${REUSABLE_SANDBOX_KEPT_AFTER_REPLACEMENT_KEY}]
|
||||
or ${abandonedWorkspaceFilesHeldOnLeaseRowSql()}
|
||||
or coalesce(${environmentLeases.metadata}->>'pendingCleanupInFlight', 'false') = 'true'
|
||||
or coalesce(${environmentLeases.metadata}#>>'{legacyShutdownWorkspaceSettlement,state}' = 'pending', false)
|
||||
@@ -190,8 +190,8 @@ export async function nextRetainedOrphanDueAt(db: Db, now: Date): Promise<Date |
|
||||
* - the run is terminal;
|
||||
* - always held: an active operation on the sandbox (a native export resume,
|
||||
* a stop-and-retain intent, an in-flight cleanup claim, a workspace restore
|
||||
* recovery, a pending legacy shutdown fence, a bound source-recovery
|
||||
* consumer) or another live lease on the same provider resource;
|
||||
* recovery, a pending legacy shutdown fence) or another live lease on the
|
||||
* same provider resource;
|
||||
* - always held: a pending native workspace export or preservation fence;
|
||||
* - held while the stop receipt is still a usable workspace source (the
|
||||
* lease's provider-attested `expiresAt` has not passed): an open recovery
|
||||
@@ -258,7 +258,6 @@ async function heldBy(tx: Db, lease: LeaseRow, runId: string, now: Date): Promis
|
||||
if (metadata.pendingCleanupInFlight === true) return "cleanup_claim_in_flight";
|
||||
if (metadata.workspaceRestoreRecovery !== undefined) return "workspace_restore_recovery";
|
||||
if (metadata.workspaceRecoveryCleanup !== undefined) return "workspace_recovery_cleanup";
|
||||
if (metadata.runnerTaskSourceConsumer !== undefined) return "source_recovery_consumer";
|
||||
if (metadata[REUSABLE_SANDBOX_KEPT_AFTER_REPLACEMENT_KEY] !== undefined) return "kept_after_replacement";
|
||||
const shutdown = metadata.legacyShutdownWorkspaceSettlement as Record<string, unknown> | undefined;
|
||||
if (shutdown?.state === "pending") return "legacy_shutdown_fence";
|
||||
|
||||
@@ -18,7 +18,6 @@ import { pluginRegistryService } from "./plugin-registry.js";
|
||||
import { remoteTerminationReceipt } from "./remote-execution-termination.js";
|
||||
import type { PluginWorkerManager } from "./plugin-worker-manager.js";
|
||||
import { NativeExecutionContext } from "./native-runtime/native-execution-context.js";
|
||||
import { assertPluginTaskSourceAttachment, assertPluginTaskSourceRecovery } from "./native-runtime/plugin-task-source-recovery.js";
|
||||
import { pluginAgentRuntimeIdentity } from "./plugin-agent-runtime-state.js";
|
||||
import { runnerLaunchPreparationDigest, runnerLaunchRunDigest } from "../vendor/paperclip-runner/index.js";
|
||||
import { assertPluginTaskOwnershipDispatch, PluginTaskOwnershipPendingError, readyPortableTaskSource, reconcilePluginTaskAdmission } from "./plugin-task-ownership.js";
|
||||
@@ -212,11 +211,6 @@ export async function executeEnvironmentTask(db: Db, workers: Pick<PluginWorkerM
|
||||
}
|
||||
assertPluginTaskOwnershipDispatch(lease, operation);
|
||||
}
|
||||
// A different launch identity is authorized by the saved consumer claim, never by the mismatch alone.
|
||||
const sourceRecovery = run && ((operation.kind === "prepare" && operation.requirements.identity.runId !== run.id && metadata.runnerTaskSourceRecovery) ||
|
||||
(operation.kind === "submit" && operation.runner.runId !== run.id && metadata.runnerTaskSourceRecovery))
|
||||
? await assertPluginTaskSourceRecovery(db, { companyId: input.companyId, leaseId: lease.id,
|
||||
context: context instanceof NativeExecutionContext ? context : undefined, operation }) : undefined;
|
||||
const probe = metadata.runnerTaskProbe as { runId?: unknown; sessionId?: unknown; expiresAtMs?: unknown } | undefined;
|
||||
const activeProbe = lease.heartbeatRunId === null && lease.issueId === null && probe
|
||||
&& typeof probe.runId === "string" && typeof probe.sessionId === "string"
|
||||
@@ -265,14 +259,10 @@ export async function executeEnvironmentTask(db: Db, workers: Pick<PluginWorkerM
|
||||
if ((operation.kind === "read_file" || operation.kind === "describe" || operation.kind === "prepare" || operation.kind === "submit" || (operation.kind === "connection" && !retainedConnection) || (operation.kind === "read_state" && metadata.runnerTaskExecutionStopped !== true && !retainedCheckpointRead) || operation.kind === "archive_state" || operation.kind === "check_project_auth" || operation.kind === "copilot_metadata") &&
|
||||
(metadata.runnerTaskRetiring === true || !environment || (!activeProbe && run?.status !== "running") || lease.status !== "active" || (lease.expiresAt && lease.expiresAt.getTime() <= Date.now()))) throw new Error("Plugin-provided Runner execution lease is not active");
|
||||
if (operation.kind === "copilot_metadata" && !activeProbe) throw new Error("Copilot metadata requires a private setup lease");
|
||||
const sourceReference = metadata.runnerTaskSourceRecovery as { identity?: { runId?: unknown } } | undefined;
|
||||
const sourceAttachment = operation.kind === "prepare" && prior && sourceReference?.identity?.runId === prior.runId
|
||||
? await assertPluginTaskSourceAttachment(db, { companyId: input.companyId, leaseId: lease.id,
|
||||
context: context instanceof NativeExecutionContext ? context : undefined, operation }) : undefined;
|
||||
const portableAttachment = prior && !sourceAttachment && metadata.runnerTaskReused !== true &&
|
||||
const portableAttachment = prior && metadata.runnerTaskReused !== true &&
|
||||
metadata.portableTaskPredecessor !== undefined
|
||||
? (await readyPortableTaskSource(db, input.companyId, lease.id, prior))?.taskId : undefined;
|
||||
const warmAttachment = !!prior && (metadata.runnerTaskReused === true || !!sourceAttachment || !!portableAttachment) &&
|
||||
const warmAttachment = !!prior && (metadata.runnerTaskReused === true || !!portableAttachment) &&
|
||||
(portableAttachment && !savedIdentity || matches(prior, savedIdentity) ||
|
||||
matches(prior, priorSaved) && operation.kind === "prepare" && matches(operation.requirements.identity, savedIdentity)) &&
|
||||
runner?.runnerId === prior.runnerInstanceId &&
|
||||
@@ -284,12 +274,12 @@ export async function executeEnvironmentTask(db: Db, workers: Pick<PluginWorkerM
|
||||
and coalesce(${environmentLeases.metadata}->>'portableTaskCheckpointUnavailable', 'false') != 'true'
|
||||
and ${environmentLeases.metadata}->'portableTaskPredecessor' = ${JSON.stringify(metadata.portableTaskPredecessor)}::jsonb`
|
||||
: undefined;
|
||||
if (runner && !sourceRecovery && ((!checkpointIdentity || !resumeFrom) && !(ownCheckpoint && operation.kind !== "read_file") && runner.runId !== (activeProbe ? probe.runId : run?.id) || (!resumeFrom && runner.leaseId !== lease.id && !ownCheckpoint && !warmAttachment)
|
||||
if (runner && ((!checkpointIdentity || !resumeFrom) && !(ownCheckpoint && operation.kind !== "read_file") && runner.runId !== (activeProbe ? probe.runId : run?.id) || (!resumeFrom && runner.leaseId !== lease.id && !ownCheckpoint && !warmAttachment)
|
||||
|| (activeProbe && (runner.sessionId !== probe.sessionId || (launches && operation.projectIds.length > 0))))) {
|
||||
throw new Error("Plugin-provided Runner execution identity mismatch");
|
||||
}
|
||||
let stoppedSourceCheckpoint = false;
|
||||
if (runner && resumeFrom && !sourceRecovery) {
|
||||
if (runner && resumeFrom) {
|
||||
const inspectCheckpoint = operation.kind === "read_state";
|
||||
const sources = await db.select({ id: environmentLeases.id, runId: environmentLeases.heartbeatRunId, metadata: environmentLeases.metadata }).from(environmentLeases).where(and(
|
||||
eq(environmentLeases.companyId, input.companyId), eq(environmentLeases.provider, lease.provider!),
|
||||
@@ -648,14 +638,6 @@ export async function executeEnvironmentTask(db: Db, workers: Pick<PluginWorkerM
|
||||
if (stoppedSourceCheckpoint && parsed.kind === "state" && isSettledReadyRunnerState(parsed.state)) {
|
||||
parsed.state = { ...parsed.state, lifecycle: "suspended" };
|
||||
}
|
||||
if (sourceRecovery && (operation.kind === "prepare" || operation.kind === "submit")) {
|
||||
await assertPluginTaskSourceRecovery(db, { companyId: input.companyId, leaseId: lease.id,
|
||||
context: context instanceof NativeExecutionContext ? context : undefined, operation });
|
||||
}
|
||||
if (sourceAttachment && operation.kind === "prepare") {
|
||||
await assertPluginTaskSourceAttachment(db, { companyId: input.companyId, leaseId: lease.id,
|
||||
context: context instanceof NativeExecutionContext ? context : undefined, operation });
|
||||
}
|
||||
if (portableCheckpoint && operation.kind === "read_state" || portableAttachment && operation.kind === "prepare") {
|
||||
const identity = operation.kind === "read_state" ? operation.identity : operation.priorIdentity;
|
||||
const sourceTaskId = (await readyPortableTaskSource(db, input.companyId, lease.id, identity))?.taskId;
|
||||
|
||||
+3
-4
@@ -515,12 +515,11 @@ describeEmbeddedPostgres("durable native provider backups", () => {
|
||||
await f.db.update(environmentLeases).set({ metadata: { remoteExecutionTermination: {
|
||||
schema: "paperclip.remote-termination.v1", companyId: f.companyId, runId: f.runId, leaseId, provider: "daytona",
|
||||
providerLeaseId, state: "destroyed", confirmedAt: confirmedAt.toISOString() },
|
||||
runnerTaskSourceConsumer: { leaseId: consumerLeaseId, runId: consumerRunId, accountIdentity: "owned-fixture-account", identity } } })
|
||||
portableTaskSuccessor: { targetLeaseId: consumerLeaseId, sourceLeaseId: leaseId, operation: { identity } } } })
|
||||
.where(eq(environmentLeases.id, leaseId));
|
||||
await f.db.insert(environmentLeases).values({ id: consumerLeaseId, companyId: f.companyId, heartbeatRunId: consumerRunId,
|
||||
issueId: f.issueId, provider: "daytona", providerLeaseId: randomUUID(), status: "active", metadata: { runnerTaskSourceRecovery: {
|
||||
schema: "paperclip.runner.source-recovery.v1", sourceLeaseId: leaseId, consumerLeaseId, consumerRunId,
|
||||
accountIdentity: "owned-fixture-account", controllerBootId: f.owner.bootId, controllerGeneration: 1, identity } } });
|
||||
issueId: f.issueId, provider: "daytona", providerLeaseId: randomUUID(), status: "active", metadata: { portableTaskOwnershipReady: true,
|
||||
portableTaskPredecessor: { targetLeaseId: consumerLeaseId, sourceLeaseId: leaseId, operation: { identity } } } });
|
||||
const lateCheckpoint = { ...checkpoint, reset: false, changedRecords: new Map([["cursor", checkpoint.records.get("cursor")!]]), removedRecords: [] };
|
||||
await expect(nativeRunnerCheckpointWriter(f.db, { ...f.owner, authorityRunId: consumerRunId, generation: 1,
|
||||
leaseOwner: "late-source-consumer" })(lateCheckpoint)).rejects.toThrow("native_runner_checkpoint_retired");
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { and, asc, eq, exists, inArray, or, sql } from "drizzle-orm";
|
||||
import { and, asc, eq, exists, inArray, sql } from "drizzle-orm";
|
||||
import { environmentLeases, nativeRunFinalizations, nativeRunnerCheckpoints, type Db } from "@paperclipai/db";
|
||||
import { inspectDurablePrpCheckpointHeader, type DurablePrpCheckpoint } from "../../vendor/paperclip-runner/index.js";
|
||||
import { nativeSha256 } from "./canonical.js";
|
||||
@@ -19,8 +19,7 @@ export async function readNativeSourceConsumers(tx: Transaction, companyId: stri
|
||||
sql`${nativeRunnerCheckpoints.material}->>'schema' like 'paperclip.native-runner-checkpoint-retirement.%'`)));
|
||||
return tx.select({ id: environmentLeases.id, metadata: environmentLeases.metadata, retired }).from(environmentLeases).where(and(
|
||||
eq(environmentLeases.companyId, companyId), eq(environmentLeases.heartbeatRunId, runId),
|
||||
or(sql`${environmentLeases.metadata}->'runnerTaskSourceConsumer' is not null`,
|
||||
sql`${environmentLeases.metadata}->'portableTaskSuccessor' is not null`)));
|
||||
sql`${environmentLeases.metadata}->'portableTaskSuccessor' is not null`));
|
||||
}
|
||||
|
||||
/** Physical source consumption revokes the completed controller's late writer. */
|
||||
@@ -36,29 +35,12 @@ export async function assertNativeSourceCheckpointConsumer(tx: Transaction, owne
|
||||
const header = checkpoint.records.get("header");
|
||||
const identity = header ? inspectDurablePrpCheckpointHeader(header) : null;
|
||||
const portable = record(source.metadata?.portableTaskSuccessor);
|
||||
if (source.metadata?.portableTaskSuccessor !== undefined) {
|
||||
if (typeof portable.targetLeaseId !== "string" || portable.sourceLeaseId !== source.id ||
|
||||
!identity || nativeSha256(record(portable.operation).identity ?? null) !== nativeSha256(identity)) return deny();
|
||||
const [target] = await tx.select().from(environmentLeases).where(and(eq(environmentLeases.companyId, owner.companyId),
|
||||
eq(environmentLeases.id, portable.targetLeaseId)));
|
||||
if (!target || target.heartbeatRunId !== owner.authorityRunId || target.status !== "active" || target.releasedAt ||
|
||||
target.expiresAt && target.expiresAt.getTime() <= Date.now() ||
|
||||
target.metadata?.portableTaskOwnershipReady !== true || target.metadata.portableTaskSuccessor !== undefined ||
|
||||
nativeSha256(target.metadata.portableTaskPredecessor ?? null) !== nativeSha256(portable)) return deny();
|
||||
return;
|
||||
}
|
||||
const consumer = record(source.metadata?.runnerTaskSourceConsumer);
|
||||
if (typeof consumer.leaseId !== "string" || consumer.runId !== owner.authorityRunId) return deny();
|
||||
const [lease] = await tx.select().from(environmentLeases).where(and(eq(environmentLeases.companyId, owner.companyId),
|
||||
eq(environmentLeases.id, consumer.leaseId)));
|
||||
const recovery = record(lease?.metadata?.runnerTaskSourceRecovery);
|
||||
const expected = record(recovery.identity);
|
||||
if (!lease || lease.heartbeatRunId !== owner.authorityRunId || lease.status !== "active" || lease.releasedAt ||
|
||||
lease.expiresAt && lease.expiresAt.getTime() <= Date.now() ||
|
||||
recovery.schema !== "paperclip.runner.source-recovery.v1" || recovery.sourceLeaseId !== source.id ||
|
||||
recovery.consumerLeaseId !== lease.id || recovery.consumerRunId !== owner.authorityRunId ||
|
||||
typeof recovery.accountIdentity !== "string" || recovery.accountIdentity !== consumer.accountIdentity ||
|
||||
recovery.controllerBootId !== owner.bootId || recovery.controllerGeneration !== owner.generation ||
|
||||
["runnerInstanceId", "environmentLeaseId", "runId", "normalizedSessionId", "turnId", "itemId"].some(key =>
|
||||
typeof expected[key] !== "string" || expected[key] !== record(identity)[key] || expected[key] !== record(consumer.identity)[key])) return deny();
|
||||
if (typeof portable.targetLeaseId !== "string" || portable.sourceLeaseId !== source.id ||
|
||||
!identity || nativeSha256(record(portable.operation).identity ?? null) !== nativeSha256(identity)) return deny();
|
||||
const [target] = await tx.select().from(environmentLeases).where(and(eq(environmentLeases.companyId, owner.companyId),
|
||||
eq(environmentLeases.id, portable.targetLeaseId)));
|
||||
if (!target || target.heartbeatRunId !== owner.authorityRunId || target.status !== "active" || target.releasedAt ||
|
||||
target.expiresAt && target.expiresAt.getTime() <= Date.now() ||
|
||||
target.metadata?.portableTaskOwnershipReady !== true || target.metadata.portableTaskSuccessor !== undefined ||
|
||||
nativeSha256(target.metadata.portableTaskPredecessor ?? null) !== nativeSha256(portable)) return deny();
|
||||
}
|
||||
@@ -59,21 +59,16 @@ describe("plugin native Runner ownership", () => {
|
||||
|
||||
it("publishes current trusted recovery authority through warm owner rebind", () => {
|
||||
const { task } = provider();
|
||||
const input = { taskId: "task", task, projectIds: [], harness: "codex", authorityRunId: "first-owner", codexSourceRecoveryVersion: 1 as const, adoptIdentity: requirements.identity };
|
||||
const input = { taskId: "task", task, projectIds: [], harness: "codex", authorityRunId: "first-owner", adoptIdentity: requirements.identity };
|
||||
const owner = createPluginRunnerTaskOwner(input);
|
||||
expect(owner.driver.authorityRunId).toBe("first-owner");
|
||||
expect(owner.driver.codexSourceRecoveryVersion).toBe(1);
|
||||
owner.rebind({ ...input, authorityRunId: "next-owner", codexSourceRecoveryVersion: undefined });
|
||||
owner.rebind({ ...input, authorityRunId: "next-owner" });
|
||||
expect(owner.driver.authorityRunId).toBe("next-owner");
|
||||
expect(owner.driver.codexSourceRecoveryVersion).toBeUndefined();
|
||||
});
|
||||
it.each(["capability", "source", "identity", "account", "provider", "adoption"])("refuses an unqualified predecessor preparation: %s", async mode => {
|
||||
it.each(["codex", "claude"])("refuses to prepare a predecessor's %s launch", async harness => {
|
||||
const { task } = provider();
|
||||
const owner = createPluginRunnerTaskOwner({ taskId: "task", task, projectIds: [], harness: mode === "provider" ? "claude" : "codex",
|
||||
authorityRunId: "next", codexSourceRecoveryVersion: mode === "capability" ? undefined : 1,
|
||||
resumeFrom: mode === "source" ? undefined : "source-task", priorIdentity: mode === "identity" ? undefined : requirements.identity,
|
||||
accountIdentity: mode === "account" ? undefined : "selected-account", ...(mode === "adoption" ? { adoptIdentity: requirements.identity } : {}),
|
||||
});
|
||||
const owner = createPluginRunnerTaskOwner({ taskId: "task", task, projectIds: [], harness, authorityRunId: "next",
|
||||
resumeFrom: "source-task", priorIdentity: requirements.identity, accountIdentity: "selected-account" });
|
||||
await expect(prepare(owner)).rejects.toThrow("source reconciliation unavailable");
|
||||
expect(task).not.toHaveBeenCalled();
|
||||
});
|
||||
@@ -88,7 +83,7 @@ describe("plugin native Runner ownership", () => {
|
||||
expect(task.mock.calls.map(([operation]) => operation.kind)).toEqual(["check_project_auth"]);
|
||||
} finally { context.finish(); }
|
||||
});
|
||||
it.each(["same-run", "suspended-predecessor"])("keeps ordinary %s preparation independent of predecessor capability", async mode => {
|
||||
it.each(["same-run", "suspended-predecessor"])("keeps ordinary %s preparation", async mode => {
|
||||
const { task } = provider();
|
||||
const identity = mode === "same-run" ? requirements.identity : { ...requirements.identity, runId: "next" };
|
||||
const owner = createPluginRunnerTaskOwner({ taskId: "task", task, projectIds: [], harness: "codex", projectAuthCheckVersion: 1,
|
||||
@@ -110,28 +105,6 @@ describe("plugin native Runner ownership", () => {
|
||||
expect(task.mock.calls.map(([op]) => op).filter(op => op.kind === "prepare").at(-1)).toMatchObject({ resumeFrom: "source-task" });
|
||||
} finally { await registration.release("detach"); }
|
||||
});
|
||||
it("prepares and submits exact A, then prepares B without copying or reconciling A again", async () => {
|
||||
const { task } = provider();
|
||||
const owner = createPluginRunnerTaskOwner({ taskId: "task", task, projectIds: [], harness: "codex", projectAuthCheckVersion: 1, pollMs: 1,
|
||||
authorityRunId: "next", codexSourceRecoveryVersion: 1, resumeFrom: "source-task", priorIdentity: requirements.identity,
|
||||
accountIdentity: "selected-account" });
|
||||
await expect(prepare(owner, { ...requirements, identity: { ...requirements.identity, runId: "foreign" } })).rejects.toThrow("source reconciliation unavailable");
|
||||
await prepare(owner);
|
||||
const registration = await owner.registration({} as never, "run");
|
||||
try {
|
||||
owner.launcher(launchSpec());
|
||||
await vi.waitFor(() => expect(task.mock.calls.some(([op]) => op.kind === "submit")).toBe(true));
|
||||
const initial = task.mock.calls.map(([op]) => op).filter(op => ["prepare", "submit"].includes(op.kind));
|
||||
expect(initial).toEqual([expect.objectContaining({ kind: "prepare", resumeFrom: "source-task", requirements: expect.objectContaining({ identity: requirements.identity }) }),
|
||||
expect.objectContaining({ kind: "submit", resumeFrom: "source-task", runner: expect.objectContaining({ runId: "run", turnId: "turn", itemId: "item" }) })]);
|
||||
await prepare(owner);
|
||||
expect(task.mock.calls.map(([op]) => op).filter(op => op.kind === "prepare").at(-1)).toMatchObject({ resumeFrom: "source-task" });
|
||||
await prepare(owner, { ...requirements, identity: { ...requirements.identity, runId: "next", turnId: "next-turn", itemId: "next-item" } });
|
||||
const attached = task.mock.calls.map(([op]) => op).filter(op => op.kind === "prepare").at(-1);
|
||||
expect(attached).toMatchObject({ priorIdentity: requirements.identity, requirements: { identity: { runId: "next" } } });
|
||||
expect(attached).not.toHaveProperty("recoveryPurpose"); expect(attached).not.toHaveProperty("resumeFrom");
|
||||
} finally { await registration.release("detach"); }
|
||||
});
|
||||
it.each(["finish", "rebind"])("does not send startup Stop after the context %s", mode => {
|
||||
const context = new NativeExecutionContext({ binding: { companyId: "company", agentId: "agent", runId: "run" } } as never, 1_000);
|
||||
const next = new NativeExecutionContext(context.execution, 1_000);
|
||||
|
||||
@@ -41,7 +41,6 @@ export function createPluginRunnerTaskOwner(input: {
|
||||
priorIdentity?: DurableRecoveryIdentity;
|
||||
/** Current authenticated lease owner; the restored PRP identity may belong to its predecessor. */
|
||||
authorityRunId?: string;
|
||||
codexSourceRecoveryVersion?: 1;
|
||||
credentialIdentity?: string;
|
||||
accountIdentity?: string;
|
||||
credential?: PluginEnvironmentTaskCredential;
|
||||
@@ -147,10 +146,7 @@ export function createPluginRunnerTaskOwner(input: {
|
||||
return recovery;
|
||||
}
|
||||
const authorityRunId = input.authorityRunId ?? input.executionContext?.execution.binding.runId;
|
||||
const sourceRecovery = !!authorityRunId && requirements.identity.runId !== authorityRunId;
|
||||
if (sourceRecovery && (input.codexSourceRecoveryVersion !== 1 || !input.resumeFrom || !input.priorIdentity || !input.accountIdentity ||
|
||||
input.harness !== "codex" || input.adoptIdentity || Object.entries(input.priorIdentity).some(([key, value]) =>
|
||||
requirements.identity[key as keyof DurableRecoveryIdentity] !== value))) {
|
||||
if (authorityRunId && requirements.identity.runId !== authorityRunId) {
|
||||
throw new Error("Plugin Runner source reconciliation unavailable");
|
||||
}
|
||||
if (input.githubBroker && input.githubCredentialBrokerVersion !== 1) {
|
||||
@@ -161,7 +157,7 @@ export function createPluginRunnerTaskOwner(input: {
|
||||
...(preparationDigest ? { preparationDigest, runDigest: runnerLaunchRunDigest(preparationDigest, requirements) } : {}),
|
||||
...(input.githubBroker ? { githubBroker: input.githubBroker } : {}),
|
||||
projectIds: [...input.projectIds], ...(recovery ? { recovery } : {}),
|
||||
...(input.resumeFrom && (!authorityRunId || !launchIdentity || launchIdentity.runId === authorityRunId || sourceRecovery)
|
||||
...(input.resumeFrom && (!authorityRunId || !launchIdentity || launchIdentity.runId === authorityRunId)
|
||||
? { resumeFrom: input.resumeFrom } : {}),
|
||||
...(input.accountIdentity ? { accountIdentity: input.accountIdentity } : {}),
|
||||
...(launched && preparedIdentity && requirements.identity.runId !== preparedIdentity.runId
|
||||
@@ -468,7 +464,6 @@ export function createPluginRunnerTaskOwner(input: {
|
||||
},
|
||||
get authorityRunId() { return input.authorityRunId ?? input.executionContext?.execution.binding.runId; },
|
||||
get relaunchReleasedRunner() { return launched && input.resumeIdentityVersion === 1 ? input.relaunch?.source : undefined; },
|
||||
get codexSourceRecoveryVersion() { return input.codexSourceRecoveryVersion; },
|
||||
prepareLaunch, authorizeRunnerAdoption, readRunnerState, runnerProcessLauncher: launcher,
|
||||
// The provider resolves the authorized retained task before each state operation.
|
||||
prepareExternalRunnerState: async () => {},
|
||||
|
||||
@@ -1,247 +0,0 @@
|
||||
import { and, eq, inArray, sql } from "drizzle-orm";
|
||||
import { agents, companies, environmentLeases, heartbeatRuns, issues, nativeRunFinalizations, type Db } from "@paperclipai/db";
|
||||
import { environmentTaskOperationSchema, type PluginEnvironmentTaskOperation } from "@paperclipai/plugin-sdk";
|
||||
import { createRunnerProviderLaunch, parseNativeExecutionInput, parseNativeRuntimeContext, QUALIFIED_ACPX_PROFILES, inspectDurablePrpCheckpointHeader, type NativeExecutionInput } from "../../vendor/paperclip-runner/index.js";
|
||||
import { resolvePluginTaskResume } from "../plugin-task-resume.js";
|
||||
import { legacyShutdownWorkspaceResourceProtected } from "../legacy-shutdown-workspace-settlement.js";
|
||||
import { NativeExecutionContext } from "./native-execution-context.js";
|
||||
import { isCurrentNativeControllerProcess } from "./native-restart-recovery.js";
|
||||
import { nativeWorkspaceExportPendingForResource } from "./native-workspace-finalization-state.js";
|
||||
import { lockSourceRecoveryCoordinators } from "./native-source-recovery-ownership.js";
|
||||
import { loadNativeRunnerCheckpointHeader } from "./native-runner-checkpoint.js";
|
||||
import { nativeSha256 as fingerprint } from "./canonical.js";
|
||||
|
||||
type Requirements = Extract<PluginEnvironmentTaskOperation, { kind: "prepare" }>["requirements"];
|
||||
type Identity = Requirements["identity"];
|
||||
type Harness = "codex" | "claude";
|
||||
type Transaction = Parameters<Parameters<Db["transaction"]>[0]>[0];
|
||||
const keys = ["runnerInstanceId", "environmentLeaseId", "runId", "normalizedSessionId", "turnId", "itemId"] as const;
|
||||
const record = (value: unknown): Record<string, unknown> => value !== null && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {};
|
||||
const deny = (): never => { throw new Error("native_source_recovery_ownership_unverified"); };
|
||||
|
||||
function sourceHarness(execution: NativeExecutionInput): Harness | null {
|
||||
const provider = execution.provider;
|
||||
if (provider.kind === "codex") return "codex";
|
||||
if (provider.kind !== "acpx" || provider.agent !== "claude") return null;
|
||||
const qualified = QUALIFIED_ACPX_PROFILES.claude;
|
||||
return qualified.qualificationStatus !== "pending" && Object.entries(provider.profile).every(([key, value]) =>
|
||||
qualified[key as keyof typeof qualified] === value) ? "claude" : null;
|
||||
}
|
||||
|
||||
function requestHarness(requirements: Requirements): Harness | null {
|
||||
return requirements.provider === "codex" ? "codex"
|
||||
: requirements.provider === "acpx" && requirements.settings.acpxAgent === "claude" ? "claude" : null;
|
||||
}
|
||||
|
||||
function matchesLaunchPolicy(requirements: Requirements, execution: NativeExecutionInput): boolean {
|
||||
if (requestHarness(requirements) !== sourceHarness(execution)) return false;
|
||||
const provider = execution.provider;
|
||||
if (provider.kind !== "acpx") return true;
|
||||
let prepared: Record<string, unknown>;
|
||||
try {
|
||||
prepared = createRunnerProviderLaunch({ ...requirements, provider: "acpx", settings: {
|
||||
acpxAgent: "claude", acpxMode: requirements.settings.acpxMode,
|
||||
acpxPermissionMode: requirements.settings.acpxPermissionMode,
|
||||
acpxPermissionModePinned: requirements.settings.acpxPermissionModePinned, claudeEffort: requirements.settings.claudeEffort,
|
||||
}, runtimeContext: requirements.runtimeContext === null ? null : parseNativeRuntimeContext(requirements.runtimeContext) }, {
|
||||
options: {}, root: "/", cwd: "/", codexHome: "/", providerNodeCommand: "", opencodeProxyPath: "", acpxSidecarPath: "",
|
||||
});
|
||||
} catch { return false; }
|
||||
return prepared.model === provider.model && prepared.agent === provider.agent && prepared.mode === provider.mode &&
|
||||
prepared.permissionMode === (provider.permissionMode ?? "approve-all") && prepared.permissionModePinned === true &&
|
||||
prepared.claudeEffort === ("claudeEffort" in provider ? provider.claudeEffort : undefined) &&
|
||||
record(prepared.providerPolicy).readOnly === ("executionMode" in execution && execution.executionMode === "plan") &&
|
||||
record(prepared.runtimeContext).aggregateDigest === ("runtimeContext" in execution ? execution.runtimeContext.aggregateDigest : undefined);
|
||||
}
|
||||
|
||||
export type PluginTaskSourceRecovery = {
|
||||
schema: "paperclip.runner.source-recovery.v1";
|
||||
resumeFrom: string;
|
||||
sourceLeaseId: string;
|
||||
identity: Identity;
|
||||
consumerLeaseId: string;
|
||||
consumerRunId: string;
|
||||
controllerBootId: string;
|
||||
controllerGeneration: number;
|
||||
contextId: string;
|
||||
accountIdentity: string;
|
||||
sourceProfileSha256: string;
|
||||
consumerProfileSha256: string;
|
||||
};
|
||||
|
||||
function readRecovery(value: unknown): PluginTaskSourceRecovery | null {
|
||||
const v = record(value);
|
||||
const identity = environmentTaskOperationSchema.safeParse({ kind: "read_state", identity: v.identity });
|
||||
return v.schema === "paperclip.runner.source-recovery.v1" && identity.success &&
|
||||
["resumeFrom", "sourceLeaseId", "consumerLeaseId", "consumerRunId", "controllerBootId", "contextId", "accountIdentity"].every(key => typeof v[key] === "string" && v[key] !== "") &&
|
||||
Number.isSafeInteger(v.controllerGeneration) && Number(v.controllerGeneration) >= 0 &&
|
||||
[v.sourceProfileSha256, v.consumerProfileSha256].every(hash => typeof hash === "string" && /^[a-f0-9]{64}$/.test(hash))
|
||||
? v as unknown as PluginTaskSourceRecovery : null;
|
||||
}
|
||||
|
||||
function pinnedSource(recovery: PluginTaskSourceRecovery) {
|
||||
const { controllerBootId: _boot, controllerGeneration: _generation, contextId: _context, ...source } = recovery;
|
||||
return source;
|
||||
}
|
||||
|
||||
async function inspect(tx: Transaction, input: {
|
||||
companyId: string; leaseId: string; context: NativeExecutionContext; identity: Identity; resumeFrom: string; accountIdentity: string;
|
||||
}, expected?: PluginTaskSourceRecovery) {
|
||||
input.context.assertOpen();
|
||||
const binding = input.context.execution.binding;
|
||||
if (binding.companyId !== input.companyId || input.identity.runId === binding.runId) return deny();
|
||||
await tx.execute(sql`select set_config('statement_timeout', '15000', true), set_config('lock_timeout', '1000', true)`);
|
||||
const owners = await lockSourceRecoveryCoordinators(tx, input.companyId, [input.identity.runId, binding.runId]);
|
||||
const owner = owners.find(value => value.runId === binding.runId), prior = owners.find(value => value.runId === input.identity.runId);
|
||||
// NOWAIT preserves the established coordinator-first order without waiting
|
||||
// behind a workspace-maintenance path which already holds the issue.
|
||||
const [issue] = await tx.select().from(issues).where(and(eq(issues.companyId, input.companyId), eq(issues.id, binding.issueId))).for("update", { noWait: true });
|
||||
const runs = await tx.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, input.companyId),
|
||||
inArray(heartbeatRuns.id, [input.identity.runId, binding.runId])));
|
||||
const current = runs.find(value => value.id === binding.runId), source = runs.find(value => value.id === input.identity.runId);
|
||||
const [lease] = await tx.select().from(environmentLeases).where(and(eq(environmentLeases.companyId, input.companyId), eq(environmentLeases.id, input.leaseId))).for("update");
|
||||
const [agent] = await tx.select().from(agents).where(and(eq(agents.companyId, input.companyId), eq(agents.id, binding.agentId)));
|
||||
const [company] = await tx.select().from(companies).where(eq(companies.id, input.companyId));
|
||||
if (!owner || !owner.leaseOwner || !owner.leaseExpiresAt || owner.leaseExpiresAt.getTime() <= Date.now() ||
|
||||
!isCurrentNativeControllerProcess(owner) || owner.resultId || ["committed", "applied", "terminal_failure"].includes(owner.phase) ||
|
||||
!prior || prior.phase !== "committed" || !prior.resultId || prior.leaseOwner ||
|
||||
!current || current.status !== "running" || current.nativeIssueId !== binding.issueId || current.agentId !== binding.agentId || current.resultJson?.nativeCancellation ||
|
||||
!source || source.status !== "succeeded" || !source.finishedAt || source.runtimeMode !== "native" || source.agentId !== binding.agentId || source.nativeIssueId !== binding.issueId ||
|
||||
source.runnerInstanceId !== input.identity.runnerInstanceId || source.nativeSessionId !== input.identity.normalizedSessionId ||
|
||||
!issue || issue.executionRunId !== binding.runId || issue.assigneeAgentId !== binding.agentId || issue.status !== "in_progress" ||
|
||||
company?.status !== "active" || agent?.lifecycleState !== "ready" || ["paused", "terminated", "pending_approval"].includes(agent.status) ||
|
||||
!lease || lease.heartbeatRunId !== binding.runId || lease.issueId !== binding.issueId || lease.status !== "active" || lease.releasedAt ||
|
||||
lease.expiresAt && lease.expiresAt.getTime() <= Date.now() || lease.metadata?.runnerTaskRetiring === true) return deny();
|
||||
input.context.assertNativeLease({ bootId: owner.controllerBootId!, leaseOwner: owner.leaseOwner, generation: owner.controllerGeneration });
|
||||
const header = await loadNativeRunnerCheckpointHeader(tx, { companyId: input.companyId, issueId: binding.issueId, runId: source.id });
|
||||
const protocolIdentity = header ? inspectDurablePrpCheckpointHeader(header) : null;
|
||||
if (!protocolIdentity || keys.some(key => protocolIdentity[key] !== input.identity[key])) return deny();
|
||||
const sourceExecution = parseNativeExecutionInput(source.runnerProfileJson?.nativeExecutionInput);
|
||||
const consumerExecution = parseNativeExecutionInput(current.runnerProfileJson?.nativeExecutionInput);
|
||||
const harness = sourceHarness(sourceExecution);
|
||||
if (!harness || harness !== sourceHarness(consumerExecution) ||
|
||||
sourceExecution.binding.companyId !== input.companyId || sourceExecution.binding.issueId !== binding.issueId ||
|
||||
sourceExecution.binding.agentId !== binding.agentId || sourceExecution.binding.runId !== source.id ||
|
||||
sourceExecution.session.normalizedSessionId !== input.identity.normalizedSessionId ||
|
||||
fingerprint(consumerExecution) !== fingerprint(input.context.execution)) return deny();
|
||||
const sourceTask = await resolvePluginTaskResume(tx as unknown as Db, { companyId: input.companyId, leaseId: input.leaseId,
|
||||
priorIdentity: input.identity, inspectCheckpoint: true });
|
||||
if (sourceTask !== input.resumeFrom) return deny();
|
||||
const sources = await tx.select().from(environmentLeases).where(and(eq(environmentLeases.companyId, input.companyId),
|
||||
eq(environmentLeases.heartbeatRunId, source.id), eq(environmentLeases.providerLeaseId, sourceTask))).for("update");
|
||||
if (sources.length !== 1) return deny();
|
||||
const sourceLease = sources[0]!;
|
||||
const saved = record(sourceLease.metadata?.runnerTaskIdentity);
|
||||
const aliases = { runnerInstanceId: "runnerId", environmentLeaseId: "leaseId", runId: "runId", normalizedSessionId: "sessionId", turnId: "turnId", itemId: "itemId" } as const;
|
||||
if (keys.some(key => saved[aliases[key]] !== input.identity[key]) ||
|
||||
await nativeWorkspaceExportPendingForResource(tx as unknown as Db, sourceLease, binding.runId) ||
|
||||
await legacyShutdownWorkspaceResourceProtected(tx as unknown as Db, sourceLease)) return deny();
|
||||
const allocations = await tx.select().from(environmentLeases).where(and(eq(environmentLeases.provider, sourceLease.provider!),
|
||||
eq(environmentLeases.providerLeaseId, sourceTask)));
|
||||
if (allocations.some(value => value.companyId !== input.companyId ||
|
||||
value.id !== sourceLease.id && value.id !== lease.id && ["active", "retained", "pending_cleanup"].includes(value.status))) return deny();
|
||||
const recovery: PluginTaskSourceRecovery = { schema: "paperclip.runner.source-recovery.v1", identity: input.identity,
|
||||
resumeFrom: sourceTask, sourceLeaseId: sourceLease.id, consumerLeaseId: lease.id, consumerRunId: binding.runId,
|
||||
controllerBootId: owner.controllerBootId!, controllerGeneration: owner.controllerGeneration, contextId: input.context.id, accountIdentity: input.accountIdentity,
|
||||
sourceProfileSha256: fingerprint(source.runnerProfileJson?.nativeExecutionInput), consumerProfileSha256: fingerprint(current.runnerProfileJson?.nativeExecutionInput) };
|
||||
if (expected && fingerprint(recovery) !== fingerprint(expected)) return deny();
|
||||
input.context.assertOpen();
|
||||
if (owner.leaseExpiresAt.getTime() <= Date.now() || lease.expiresAt && lease.expiresAt.getTime() <= Date.now()) return deny();
|
||||
return { recovery, sourceLease, lease, sourceExecution, consumerExecution, owner };
|
||||
}
|
||||
|
||||
/** Only current B's native authority can consume succeeded A for maintenance. */
|
||||
export async function claimPluginTaskSourceRecovery(db: Db, input: {
|
||||
companyId: string; leaseId: string; context: NativeExecutionContext; identity: Identity; resumeFrom: string; accountIdentity: string;
|
||||
codexSourceRecoveryVersion?: 1; acpxSourceRecoveryVersion?: 1;
|
||||
matchesExecution(source: NativeExecutionInput): boolean;
|
||||
}): Promise<PluginTaskSourceRecovery> {
|
||||
const harness = sourceHarness(input.context.execution);
|
||||
if (!harness || (harness === "codex" ? input.codexSourceRecoveryVersion : input.acpxSourceRecoveryVersion) !== 1 || !input.accountIdentity) return deny();
|
||||
return db.transaction(async tx => {
|
||||
const inspected = await inspect(tx, input);
|
||||
if (!input.matchesExecution(inspected.sourceExecution)) return deny();
|
||||
const { recovery, sourceLease, lease } = inspected;
|
||||
if (Object.hasOwn(lease.metadata ?? {}, "runnerTaskSourceRecovery")) {
|
||||
const saved = readRecovery(lease.metadata?.runnerTaskSourceRecovery);
|
||||
if (!saved || fingerprint(pinnedSource(saved)) !== fingerprint(pinnedSource(recovery))) return deny();
|
||||
}
|
||||
const consumer = { leaseId: lease.id, runId: recovery.consumerRunId, resumeFrom: recovery.resumeFrom,
|
||||
identity: recovery.identity, accountIdentity: recovery.accountIdentity };
|
||||
const existing = sourceLease.metadata?.runnerTaskSourceConsumer;
|
||||
if (existing && fingerprint(existing) !== fingerprint(consumer)) return deny();
|
||||
const others = await tx.select({ id: environmentLeases.id }).from(environmentLeases).where(and(
|
||||
eq(environmentLeases.companyId, input.companyId), eq(environmentLeases.provider, sourceLease.provider!),
|
||||
sql`${environmentLeases.id} <> ${lease.id}`,
|
||||
sql`${environmentLeases.metadata}->>'runnerTaskResumeFrom' = ${input.resumeFrom}`));
|
||||
if (others.length) return deny();
|
||||
input.context.assertOpen();
|
||||
if (inspected.owner.leaseExpiresAt!.getTime() <= Date.now()) return deny();
|
||||
await tx.update(environmentLeases).set({ metadata: sql`coalesce(${environmentLeases.metadata}, '{}'::jsonb) || ${JSON.stringify({ runnerTaskSourceConsumer: consumer })}::jsonb` })
|
||||
.where(eq(environmentLeases.id, sourceLease.id));
|
||||
await tx.update(environmentLeases).set({ metadata: sql`coalesce(${environmentLeases.metadata}, '{}'::jsonb) || ${JSON.stringify({ runnerTaskSourceRecovery: recovery })}::jsonb` })
|
||||
.where(eq(environmentLeases.id, lease.id));
|
||||
return recovery;
|
||||
});
|
||||
}
|
||||
|
||||
async function assertSourceIdentity(db: Db, input: {
|
||||
companyId: string; leaseId: string; context: NativeExecutionContext | undefined;
|
||||
identity: Identity; harness: Harness; requirements?: Requirements; accountIdentity?: string; resumeFrom?: string; requireDispatched?: boolean;
|
||||
}): Promise<PluginTaskSourceRecovery> {
|
||||
if (!input.context) return deny();
|
||||
const { identity } = input;
|
||||
return db.transaction(async tx => {
|
||||
const [lease] = await tx.select({ metadata: environmentLeases.metadata }).from(environmentLeases).where(and(
|
||||
eq(environmentLeases.companyId, input.companyId), eq(environmentLeases.id, input.leaseId)));
|
||||
const expected = readRecovery(lease?.metadata?.runnerTaskSourceRecovery);
|
||||
if (!expected || keys.some(key => expected.identity[key] !== identity[key]) ||
|
||||
input.resumeFrom !== undefined && expected.resumeFrom !== input.resumeFrom || expected.accountIdentity !== input.accountIdentity) return deny();
|
||||
const inspected = await inspect(tx, { ...input, context: input.context!, resumeFrom: expected.resumeFrom, accountIdentity: expected.accountIdentity }, expected);
|
||||
if (sourceHarness(inspected.sourceExecution) !== input.harness) return deny();
|
||||
if (input.requirements) {
|
||||
const execution = input.requirements.identity.runId === expected.identity.runId ? inspected.sourceExecution
|
||||
: input.requirements.identity.runId === expected.consumerRunId ? inspected.consumerExecution : undefined;
|
||||
if (!execution || !matchesLaunchPolicy(input.requirements, execution)) return deny();
|
||||
}
|
||||
if (input.requireDispatched && (inspected.lease.metadata?.runnerTaskDispatched !== true ||
|
||||
inspected.lease.metadata?.runnerTaskExecutionStopped === true)) return deny();
|
||||
const consumer = record(inspected.sourceLease.metadata?.runnerTaskSourceConsumer);
|
||||
if (consumer.leaseId !== input.leaseId || consumer.runId !== expected.consumerRunId || consumer.resumeFrom !== expected.resumeFrom || consumer.accountIdentity !== expected.accountIdentity ||
|
||||
fingerprint(consumer.identity) !== fingerprint(identity)) return deny();
|
||||
return expected;
|
||||
});
|
||||
}
|
||||
|
||||
/** The worker never derives this exception from an arbitrary mismatched run ID. */
|
||||
export async function assertPluginTaskSourceRecovery(db: Db, input: {
|
||||
companyId: string; leaseId: string; context: NativeExecutionContext | undefined;
|
||||
operation: Extract<PluginEnvironmentTaskOperation, { kind: "prepare" | "submit" }>;
|
||||
}): Promise<PluginTaskSourceRecovery> {
|
||||
const operation = input.operation;
|
||||
const harness = operation.kind === "prepare" ? requestHarness(operation.requirements)
|
||||
: operation.runner.harness === "codex" || operation.runner.harness === "claude" ? operation.runner.harness : null;
|
||||
if (!harness || !operation.resumeFrom || !operation.accountIdentity ||
|
||||
(operation.kind === "prepare" ? !!operation.priorIdentity : !operation.preparedLaunchId || !operation.launch)) return deny();
|
||||
const identity = operation.kind === "prepare" ? operation.requirements.identity : {
|
||||
runnerInstanceId: operation.runner.runnerId, environmentLeaseId: operation.runner.leaseId, runId: operation.runner.runId,
|
||||
normalizedSessionId: operation.runner.sessionId, turnId: operation.runner.turnId, itemId: operation.runner.itemId,
|
||||
};
|
||||
return assertSourceIdentity(db, { ...input, identity, harness, ...(operation.kind === "prepare" ? { requirements: operation.requirements } : {}),
|
||||
resumeFrom: operation.resumeFrom, accountIdentity: operation.accountIdentity });
|
||||
}
|
||||
|
||||
/** A fresh source incarnation can attach B without pretending it was warm reuse. */
|
||||
export async function assertPluginTaskSourceAttachment(db: Db, input: {
|
||||
companyId: string; leaseId: string; context: NativeExecutionContext | undefined;
|
||||
operation: Extract<PluginEnvironmentTaskOperation, { kind: "prepare" }>;
|
||||
}): Promise<PluginTaskSourceRecovery> {
|
||||
const { operation } = input, target = operation.requirements.identity;
|
||||
const harness = requestHarness(operation.requirements);
|
||||
if (!harness || !operation.priorIdentity || operation.resumeFrom) return deny();
|
||||
const recovery = await assertSourceIdentity(db, { ...input, harness, requirements: operation.requirements, identity: operation.priorIdentity,
|
||||
accountIdentity: operation.accountIdentity, requireDispatched: true });
|
||||
if (target.runId !== recovery.consumerRunId || ["runnerInstanceId", "environmentLeaseId", "normalizedSessionId"].some(key =>
|
||||
target[key as keyof Identity] !== recovery.identity[key as keyof Identity])) return deny();
|
||||
return recovery;
|
||||
}
|
||||
@@ -107,7 +107,6 @@ async function ownershipClaim(db: Db, input: {
|
||||
typeof source.metadata.driverKey !== "string" || source.metadata.driverKey !== target.metadata.driverKey ||
|
||||
source.metadata.runnerTaskLease !== true || target.metadata.runnerTaskLease !== true ||
|
||||
source.metadata.runnerTaskRetiring === true || source.metadata.reusableLeaseSuccessor !== undefined ||
|
||||
source.metadata.runnerTaskSourceConsumer !== undefined ||
|
||||
!["retained", "released", "expired"].includes(source.status) ||
|
||||
target.status !== "active" || target.releasedAt || target.metadata.runnerTaskRetiring === true ||
|
||||
target.expiresAt && target.expiresAt.getTime() <= Date.now() ||
|
||||
|
||||
@@ -71,11 +71,8 @@ export async function resolvePluginTaskResume(db: Db, input: {
|
||||
// A retained PRP lease is logical; later provider tasks have different physical lease IDs.
|
||||
const candidates = rows.filter(row => {
|
||||
const identity = row.lease.metadata?.runnerTaskIdentity as Record<string, unknown> | undefined;
|
||||
const consumer = row.lease.metadata?.runnerTaskSourceConsumer as { leaseId?: unknown; runId?: unknown; resumeFrom?: unknown } | null | undefined;
|
||||
return row.lease.id !== input.leaseId && row.run.id === input.priorIdentity.runId &&
|
||||
row.lease.metadata?.portableTaskSuccessor === undefined &&
|
||||
(!Object.hasOwn(row.lease.metadata ?? {}, "runnerTaskSourceConsumer") ||
|
||||
consumer?.leaseId === input.leaseId && consumer.runId === next?.run.id && consumer.resumeFrom === row.lease.providerLeaseId) &&
|
||||
(input.inspectCheckpoint || row.lease.metadata?.runnerTaskSessionRetained === true) &&
|
||||
identity?.runnerId === input.priorIdentity.runnerInstanceId && identity.leaseId === input.priorIdentity.environmentLeaseId &&
|
||||
identity.sessionId === input.priorIdentity.normalizedSessionId && identity.runId === input.priorIdentity.runId &&
|
||||
|
||||
@@ -76,7 +76,7 @@ export function warmSandboxExpiryCandidateCondition() {
|
||||
sql`${environmentLeases.provider} is not null and ${environmentLeases.provider} <> 'local'`,
|
||||
sql`${environmentLeases.providerLeaseId} is not null`,
|
||||
sql`not (coalesce(${environmentLeases.metadata}, '{}'::jsonb) ?| array['nativeWorkspaceExportResume',
|
||||
'sandboxStopAndRetain', 'workspaceRestoreRecovery', 'workspaceRecoveryCleanup', 'runnerTaskSourceConsumer',
|
||||
'sandboxStopAndRetain', 'workspaceRestoreRecovery', 'workspaceRecoveryCleanup',
|
||||
'portableTaskSuccessor', 'reusableLeaseSuccessor', 'reusableSandboxLeaseSuperseded',
|
||||
${REUSABLE_SANDBOX_KEPT_AFTER_REPLACEMENT_KEY}])`,
|
||||
sql`coalesce(${environmentLeases.metadata}->>'pendingCleanupInFlight', 'false') <> 'true'`,
|
||||
|
||||
Reference in new issue
Block a user