fix(native-runtime): wait for prior lease release and read same-lease plugin checkpoint (#23768)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - The native runtime coordinates per-turn and plugin-task runner state
across consecutive runs in
`server/src/services/native-runtime/native-session-executor.ts`.
> - A committed per-turn plugin run can finish while its async
environment lease cleanup is still running, so a follow-up run hits
`retirement_refused=prior_lease_active`, quarantines the scoped runner
root, and fails.
> - A same-run plugin-task retry that reuses the same environment lease
without restart recovery also skips `read_state` when local runner
authority is absent, which triggers `authority_indeterminate` and
quarantines the root.
> - This pull request adds a bounded wait for prior lease teardown
before refusing `prior_lease_active`, skips quarantine when the prior
lease stays active, and reads the plugin checkpoint on same-lease
retries when local authority is absent.
> - The benefit is that follow-up runs retire finished per-turn owners
cleanly instead of poisoning the scoped runner root, and same-lease
plugin retries verify their checkpoint instead of failing with
`authority_indeterminate`.

## Linked Issues or Issue Description

**What happened?**
When a per-turn plugin run commits its terminal result and its async
environment lease teardown is still in flight, a follow-up run fails
with `runner_state_identity_mismatch:
prior_owner_terminal_state_indeterminate;
retirement_refused=prior_lease_active` and quarantines the scoped runner
state root. On a same-run plugin-task retry that reuses the same
environment lease without restart recovery, `migrateRunnerdStateRoot`
skips reading the plugin runner checkpoint when local runner authority
is absent, which causes `runner_state_identity_mismatch:
authority_indeterminate` and quarantines the scoped root.

**Expected behavior**
Follow-up runs wait briefly for an in-flight prior lease release to
finish and then retire the finished per-turn owner cleanly. If the prior
lease remains active after the bounded wait, the run still refuses with
`retirement_refused=prior_lease_active` without retiring into
`continuity-breaks` and without quarantining the scoped root. Same-run
plugin-task retries on the same lease read and verify the plugin
checkpoint via `read_state` when local runner authority is absent and
unclaimed bootstrap retry does not apply.

**Steps to reproduce**
1. Commit a per-turn plugin run with a bound stop receipt while its
`environment_leases` row is still `status: "active"` and `releasedAt:
null`.
2. Start a follow-up run on a replacement lease before async lease
teardown marks the prior lease released.
3. Observe `migrateRunnerdStateRoot` refuse with
`retirement_refused=prior_lease_active` and move the scoped state root
into `quarantine/`.
4. Start a same-run plugin-task retry reusing
`identity.environmentLeaseId` without `restartRecovery` and without a
local `runner/runner-state.json`.
5. Observe `migrateRunnerdStateRoot` throw
`runner_state_identity_mismatch: authority_indeterminate` and quarantine
the root.

**Paperclip version or commit**
`master` (`f4baaa4f48`)

## What Changed

- Added `priorLeaseReleaseWait` (`5_000 ms` timeout, `100 ms` poll
interval), `isPriorRemoteSandboxLeaseEnded`, and
`waitForPriorRemoteSandboxLeasesToEnd` in
`server/src/services/native-runtime/native-session-executor.ts`.
- Updated `migrateRunnerdStateRoot` to wait for in-flight prior remote
sandbox lease release when `retireFinishedPerTurnRunnerdOwner` returns
`prior_lease_active`, and to retry retirement once if the prior lease
ends during the wait.
- Updated `migrateRunnerdStateRoot` to skip quarantining `scoped` when
retirement still refuses with `prior_lease_active`, matching the
existing non-quarantine behavior for `"active"` and `"unavailable"`.
- Updated `migrateRunnerdStateRoot` to call `read_state` and
`savePluginRunnerCheckpoint` on same-run, same-lease plugin-task retries
without `restartRecovery` when `admitUnclaimedNativeBootstrapRetry` does
not apply and `runnerdAuthorityLifecycle` is `"absent"`.
- Kept this minimal bugfix inside
`server/src/services/native-runtime/native-session-executor.ts` (which
already exceeds 1,000 lines) because it modifies existing state
migration and lease-retirement checks directly in their owning module
without introducing a new subsystem.
- Added red-then-green regression tests in
`server/src/services/native-runtime/native-session-executor.test.ts`
covering in-flight prior lease release, persistent unreleased prior
lease (no retirement and no quarantine), and same-lease plugin
checkpoint verification and mismatch rejection.

## Verification

- Verified all 4 new regression tests failed before the fix
(`retirement_refused=prior_lease_active`, `scoped` moved to quarantine,
and `authority_indeterminate`).
- Ran focused tests after the fix:
- `pnpm --dir server exec vitest run
src/services/native-runtime/native-session-executor.test.ts -t "handles
unconfirmed plugin checkpoint status on replacement lease|retires a
finished per-turn plugin owner|waits briefly for a stopped per-turn
prior lease|admits only an authorized same-run plugin checkpoint|reads
same-lease plugin checkpoint instead of quarantining|reattaches a
surviving plugin task"` (27 passed, including existing
`stopped-lease-unreleased`).
- Ran server typecheck:
  - `pnpm --dir server typecheck` (passed).

## Risks

- Low risk. The bounded wait applies only when
`retireFinishedPerTurnRunnerdOwner` refuses with `prior_lease_active`,
exits early when the prior lease holds the same `providerLeaseId` as the
current run or no prior leases exist, and re-runs the full retirement
proof before retiring. Same-lease `read_state` runs only after unclaimed
bootstrap retry checks and only when local runner authority is
`"absent"`, preserving fail-closed identity verification via
`savePluginRunnerCheckpoint`.

## Model Used

- Google DeepMind Gemini 4 Neon (Medium reasoning budget) with 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

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip authored and GitHub committed 2026-12-04 14:08:51 -06:00
1 parent f5457565de
commit 686215ecdb
2 files changed
+299 -11

No files matched your search

@@ -450,6 +450,7 @@ import {
cancelNativeSession,
closeWarmNativeSessionsForEnvironment,
claimWarmNativeInstructionCopy,
priorLeaseReleaseWait,
warmRetirementDirectoryWait,
warmSessionReleaseWait,
nativeSessionWorkspaceScope,
@@ -20206,6 +20207,10 @@ describe("runnerd provider runtime wiring", () => {
const home = join(isolatedStateDirectory, `checkpoint-unconfirmed-${mode}`);
await mkdir(home, { recursive: true });
await writeFile(join(home, "auth.json"), JSON.stringify({ OPENAI_API_KEY: "synthetic-fixture" }), { mode: 0o600 });
const originalLeaseWait = { ...priorLeaseReleaseWait };
if (mode === "stopped-lease-unreleased") {
Object.assign(priorLeaseReleaseWait, { timeoutMs: 25, pollMs: 5 });
}
try {
const launch = {
db, execution: next, runnerInstanceId: "replacement-runner", runnerIngressAuthorized: true,
@@ -20234,6 +20239,7 @@ describe("runnerd provider runtime wiring", () => {
expect(existsSync(join(scoped, "continuity-breaks"))).toBe(false);
}
} finally {
Object.assign(priorLeaseReleaseWait, originalLeaseWait);
resume.mockRestore();
}
},
@@ -20426,6 +20432,156 @@ describe("runnerd provider runtime wiring", () => {
},
);
it.each(["releases-during-wait", "remains-active-past-wait"] as const)(
"waits briefly for a stopped per-turn prior lease to finish releasing and skips quarantine when it stays active: %s",
async mode => {
const first = {
...scopedNativeExecution(`plugin-prior-lease-wait-${mode}`),
schema: "paperclip.native-execution-input.v5", executionMode: "default", planningContext: null, runtimeContext: nativeRuntimeContextFixture(),
provider: { kind: "codex", model: null, approvalPolicy: "never" },
session: {
...execution.session, driverKind: "codex_app_server",
normalizedSessionId: `plugin-prior-lease-wait-${mode}`, lifecyclePolicy: { mode: "per_turn", idleTimeoutMs: null },
},
} as NativeExecutionInput;
parseNativeExecutionInput(first);
const next = { ...first, binding: { ...first.binding, runId: `${first.binding.runId}-followup` } };
const identity = {
runId: first.binding.runId, normalizedSessionId: first.session.normalizedSessionId!,
runnerInstanceId: "plugin-runner", environmentLeaseId: "old-lease", turnId: "old-turn", itemId: "old-item",
};
const scoped = await initializeScopedRunnerRoot(first, identity.runnerInstanceId);
await mkdir(join(scoped, "control-plane"), { recursive: true });
const journal = JSON.stringify({
...durableControlPlaneState(identity),
commands: [{ type: "turn.start", status: "completed" }],
committedEvents: [{ eventType: "run.terminal", envelope: { ...identity, payload: { reportedWorkDisposition: "done" } } }],
});
await writeFile(join(scoped, "control-plane/control-plane-state.json"), journal);
const db = leaseDb(next);
const ordinarySelect = db.select.bind(db);
const { currentNativeControllerIdentity } = await import("./native-restart-recovery.js");
const controller = await currentNativeControllerIdentity();
const committedPrior = {
run: {
id: first.binding.runId, companyId: first.binding.companyId, agentId: first.binding.agentId,
nativeIssueId: first.binding.issueId, runtimeMode: "native", status: "succeeded",
runnerProfileJson: { nativeExecutionInput: first },
processPid: null, processGroupId: null, processStartedAt: null,
},
owner: {
runId: first.binding.runId, companyId: first.binding.companyId, issueId: first.binding.issueId,
phase: "committed", resultId: "result-1", leaseOwner: null, recoveryState: null,
controllerPid: controller.pid, controllerProcessStartedAt: controller.processStartedAt,
controllerBootId: controller.bootId,
},
};
let leaseStatusChecks = 0;
const priorLease = () => {
leaseStatusChecks += 1;
const releasedNow = mode === "releases-during-wait" && leaseStatusChecks >= 3;
return {
id: "old-lease", companyId: first.binding.companyId, heartbeatRunId: first.binding.runId,
status: releasedNow ? "failed" : "active",
releasedAt: releasedNow ? new Date() : null,
cleanupStatus: releasedNow ? "success" : null,
provider: "plugin:test:tasks", providerLeaseId: "old-task",
metadata: {
driver: "plugin",
runnerTaskExecutionStopped: true,
runnerTaskSessionRetained: false,
remoteExecutionTermination: {
schema: "paperclip.remote-termination.v1",
companyId: first.binding.companyId,
runId: first.binding.runId,
leaseId: "old-lease",
provider: "plugin:test:tasks",
providerLeaseId: "old-task",
state: "stopped",
confirmedAt: new Date().toISOString(),
},
},
};
};
db.select = ((fields?: Record<string, unknown>) => {
if (fields?.status === heartbeatRuns.status && fields?.runnerProfileJson === heartbeatRuns.runnerProfileJson) {
return priorNativeRunDb(first, "succeeded").select(fields as never);
}
if (fields && "run" in fields && "owner" in fields) {
return {
from: () => ({
innerJoin: () => ({
where: () => ({ limit: async () => [committedPrior] }),
}),
}),
};
}
if (fields && "providerLeaseId" in fields && "status" in fields) {
return { from: () => ({ where: async () => [priorLease()] }) };
}
if (fields === undefined) {
return {
from: (table: unknown) => table === environmentLeases
? { where: async () => [priorLease()] }
: ordinarySelect().from(table as never),
};
}
return ordinarySelect(fields as never);
}) as Db["select"];
const resume = vi.spyOn(environmentTaskRuntime, "resolvePluginTaskResume").mockResolvedValue("old-task");
const task = vi.fn(async (operation: any) => {
environmentTaskOperationSchema.parse(operation);
if (operation.kind === "read_state") {
throw environmentTaskRuntime.createUnconfirmedPluginCheckpointError({
executionStopped: true,
sessionStateAvailable: false,
});
}
return {
kind: "description", taskId: "replacement-task", launchPreparationVersion: 1, projectAuthCheckVersion: 1, warmTaskVersion: 1,
runner: { version: "fixture", digest: `sha256:${"a".repeat(64)}` },
};
});
state.createBackend.mockClear();
const home = join(isolatedStateDirectory, `prior-lease-wait-${mode}`);
await mkdir(home, { recursive: true });
await writeFile(join(home, "auth.json"), JSON.stringify({ OPENAI_API_KEY: "synthetic-fixture" }), { mode: 0o600 });
const originalLeaseWait = { ...priorLeaseReleaseWait };
Object.assign(priorLeaseReleaseWait, { timeoutMs: mode === "releases-during-wait" ? 500 : 40, pollMs: 5 });
try {
const launch = {
db, execution: next, runnerInstanceId: "replacement-runner", runnerIngressAuthorized: true,
managedAiCredentialHome: home, managedAiCredentialIdentity: "revision", managedAiAccountIdentity: "account",
runnerEnvironment: { ANTHROPIC_API_KEY: "synthetic-fixture" },
runnerExecutionTarget: {
kind: "remote", transport: "sandbox", remoteCwd: ".", leaseId: "replacement-lease", runnerTask: task,
sandboxLeaseAcquisition: { outcome: "replacement", providerLeaseId: "replacement-task" },
} as never,
};
const quarantineDir = join(dirname(scoped), "quarantine");
if (mode === "releases-during-wait") {
await expect(createRunnerdBackend(launch)).resolves.toBeDefined();
expect(state.createBackend).toHaveBeenCalledOnce();
expect(existsSync(join(scoped, "continuity-breaks"))).toBe(true);
} else {
await expect(createRunnerdBackend(launch)).rejects.toThrow("retirement_refused=prior_lease_active");
expect(state.createBackend).not.toHaveBeenCalled();
expect(existsSync(join(scoped, "continuity-breaks"))).toBe(false);
}
expect(existsSync(scoped)).toBe(true);
const quarantinedEntries = existsSync(quarantineDir)
? (await readdir(quarantineDir)).filter(name => name.startsWith(`${basename(scoped)}.`))
: [];
expect(quarantinedEntries).toEqual([]);
} finally {
Object.assign(priorLeaseReleaseWait, originalLeaseWait);
resume.mockRestore();
}
},
);
it.each(["verified", "wrong-state", "no-stop-proof", "disposition-retry", "disposition-wrong-state", "disposition-no-stop-proof"] as const)("admits only an authorized same-run plugin checkpoint: %s", async mode => {
const current = scopedNativeExecution(`plugin-crash-${mode}`);
const identity = { runId: current.binding.runId, normalizedSessionId: current.session.normalizedSessionId!,
@@ -20466,6 +20622,68 @@ describe("runnerd provider runtime wiring", () => {
} finally { resume.mockRestore(); }
});
it.each(["verified", "wrong-state"] as const)(
"reads same-lease plugin checkpoint instead of quarantining as authority_indeterminate: %s",
async mode => {
const current = scopedNativeExecution(`plugin-same-lease-retry-${mode}`);
const identity = {
runId: current.binding.runId, normalizedSessionId: current.session.normalizedSessionId!,
runnerInstanceId: "plugin-runner", environmentLeaseId: "same-task-lease", turnId: "old-turn", itemId: "old-item",
};
const root = await initializeScopedRunnerRoot(current, identity.runnerInstanceId);
await mkdir(join(root, "control-plane"), { recursive: true });
const journal = JSON.stringify(durableControlPlaneState(identity));
await writeFile(join(root, "control-plane/control-plane-state.json"), journal);
const task = vi.fn(async (operation: any) => {
environmentTaskOperationSchema.parse(operation);
if (operation.kind === "read_state") {
return {
kind: "state",
taskId: "same-task",
state: {
...durableRunnerState(identity, "ready"),
...(mode === "wrong-state" ? { itemId: "other" } : {}),
},
};
}
return {
kind: "description", launchPreparationVersion: 1, projectAuthCheckVersion: 1, taskId: "same-task",
runner: { version: "fixture", digest: `sha256:${"a".repeat(64)}` },
};
});
state.createBackend.mockClear();
const backend = createRunnerdBackend({
db: leaseDb(current),
execution: current,
runnerInstanceId: identity.runnerInstanceId,
runnerIngressAuthorized: true,
runnerExecutionTarget: {
kind: "remote",
transport: "sandbox",
remoteCwd: ".",
leaseId: identity.environmentLeaseId,
runnerTask: task,
},
});
const quarantineDir = join(dirname(root), "quarantine");
if (mode === "verified") {
await expect(backend).resolves.toBeDefined();
expect(state.createBackend).toHaveBeenCalledOnce();
expect(JSON.parse(await readFile(join(root, "plugin-runner-state.json"), "utf8"))).toMatchObject({ ...identity, lifecycle: "ready" });
} else {
await expect(backend).rejects.toThrow("checkpoint identity mismatch");
expect(state.createBackend).not.toHaveBeenCalled();
}
expect(await readFile(join(root, "control-plane/control-plane-state.json"), "utf8")).toBe(journal);
expect(task).toHaveBeenCalledWith({ kind: "read_state", identity });
expect(existsSync(root)).toBe(true);
const quarantinedEntries = existsSync(quarantineDir)
? (await readdir(quarantineDir)).filter(name => name.startsWith(`${basename(root)}.`))
: [];
expect(quarantinedEntries).toEqual([]);
},
);
it.each(["verified", "portable", "wrong-claim", "wrong-state", "wrong-lease"] as const)("reattaches a surviving plugin task through its owner: %s", async mode => {
const current = scopedNativeExecution(`plugin-live-${mode}`);
const moved = mode === "portable" || mode === "wrong-claim";
@@ -6411,9 +6411,11 @@ async function priorRunParkedOnGovernedWait(db: Db, input: { companyId: string;
}
}
async function priorRemoteSandboxLeasesEnded(db: Db, input: {
export const priorLeaseReleaseWait = { timeoutMs: 5_000, pollMs: 100 };
async function inspectPriorRemoteSandboxLeases(db: Db, input: {
companyId: string; runId: string; currentProviderLeaseId?: string;
}): Promise<boolean> {
}): Promise<"ended" | "active" | "permanent_refusal"> {
try {
const leases = await db.select({
status: environmentLeases.status,
@@ -6422,20 +6424,63 @@ async function priorRemoteSandboxLeasesEnded(db: Db, input: {
providerLeaseId: environmentLeases.providerLeaseId,
}).from(environmentLeases)
.where(and(eq(environmentLeases.companyId, input.companyId), eq(environmentLeases.heartbeatRunId, input.runId)));
return leases.length > 0 && leases.every(lease =>
if (
leases.length === 0
|| (input.currentProviderLeaseId !== undefined
&& leases.some(lease => lease.providerLeaseId === input.currentProviderLeaseId))
) {
return "permanent_refusal";
}
const allEnded = leases.every(lease =>
(lease.status === "released" || lease.status === "expired"
|| (lease.status === "failed" && lease.cleanupStatus === "success"))
&& lease.cleanupStatus !== "failed"
&& lease.releasedAt !== null
&& lease.providerLeaseId !== input.currentProviderLeaseId);
return allEnded ? "ended" : "active";
} catch {
return false;
return "permanent_refusal";
}
}
async function priorRemoteSandboxLeasesEnded(db: Db, input: {
companyId: string; runId: string; currentProviderLeaseId?: string;
}): Promise<boolean> {
return await inspectPriorRemoteSandboxLeases(db, input) === "ended";
}
async function waitForPriorRemoteSandboxLeasesToEnd(db: Db, input: {
companyId: string; runId: string; currentProviderLeaseId?: string;
}): Promise<boolean> {
if (priorLeaseReleaseWait.timeoutMs <= 0) return false;
const deadline = Date.now() + priorLeaseReleaseWait.timeoutMs;
const pollMs = Math.max(1, priorLeaseReleaseWait.pollMs);
for (;;) {
const state = await inspectPriorRemoteSandboxLeases(db, input);
if (state === "ended") return true;
if (state === "permanent_refusal") return false;
const remainingMs = deadline - Date.now();
if (remainingMs <= 0) return false;
await new Promise(resolve => setTimeout(resolve, Math.min(pollMs, remainingMs)));
}
}
async function retireFinishedPerTurnRunnerdOwner(input: Parameters<typeof inspectFinishedPerTurnRunnerdOwner>[0])
: Promise<{ retired: true } | { retired: false; refused: string }> {
const proof = await inspectFinishedPerTurnRunnerdOwner(input);
let proof = await inspectFinishedPerTurnRunnerdOwner(input);
if (!proof.finished && proof.refused === "prior_lease_active" && typeof input.identity.runId === "string" && input.identity.runId) {
const target = input.runnerExecutionTarget;
const currentProviderLeaseId = target?.kind === "remote" && target.transport === "sandbox"
? target.sandboxLeaseAcquisition?.providerLeaseId
: undefined;
if (await waitForPriorRemoteSandboxLeasesToEnd(input.db, {
companyId: input.execution.binding.companyId,
runId: input.identity.runId,
currentProviderLeaseId,
})) {
proof = await inspectFinishedPerTurnRunnerdOwner(input);
}
}
if (!proof.finished) return { retired: false, refused: proof.refused };
const changed = await proof.recheck();
if (changed) return { retired: false, refused: changed };
@@ -6556,6 +6601,20 @@ async function assertPluginTaskReattachmentBinding(input: {
return taskId;
}
async function readAndSavePluginRunnerCheckpoint(
root: string,
runnerTask: NonNullable<Extract<AdapterExecutionTarget, { kind: "remote"; transport: "sandbox" }>["runnerTask"]>,
identity: RunnerdDurableIdentity,
resumeFrom?: string,
): Promise<void> {
const operation = resumeFrom !== undefined
? { kind: "read_state" as const, identity, resumeFrom }
: { kind: "read_state" as const, identity };
const result = environmentTaskResultSchema.parse(await runnerTask(operation));
if (result.kind !== "state") throw new Error("Plugin Runner checkpoint unavailable");
savePluginRunnerCheckpoint(root, result.state, identity);
}
async function migrateRunnerdStateRootForExecution(
input: Omit<Parameters<typeof migrateRunnerdStateRoot>[0], "onPluginCheckpointRetired">,
): Promise<{ binding?: VerifiedWarmTransitionBinding; pluginCheckpointRetired: boolean }> {
@@ -6660,9 +6719,7 @@ async function migrateRunnerdStateRoot(input: {
|| (!input.restartRecovery && identity.environmentLeaseId !== taskTarget.leaseId))) {
const resumeFrom = taskTarget.sandboxLeaseAcquisition?.outcome === "resumed" ? undefined : await resolvePluginTaskResume(input.db, { companyId: input.execution.binding.companyId,
leaseId: taskTarget.leaseId, priorIdentity: identity });
const result = environmentTaskResultSchema.parse(await taskTarget.runnerTask({ kind: "read_state", identity, resumeFrom }));
if (result.kind !== "state") throw new Error("Plugin Runner checkpoint unavailable");
savePluginRunnerCheckpoint(scoped, result.state, identity);
await readAndSavePluginRunnerCheckpoint(scoped, taskTarget.runnerTask, identity, resumeFrom);
}
if (input.restartRecovery?.kind === "bootstrap_incomplete" && identity.runId === input.execution.binding.runId) {
// A local runner's process ids belong to this host, so a fresh provider
@@ -6721,6 +6778,12 @@ async function migrateRunnerdStateRoot(input: {
leaseOwner: input.bootstrapRetryLeaseOwner, preparedExecutionAdmission: input.preparedExecutionAdmission,
localStateContents: readBoundedNativeFile(resolve(scoped, "control-plane", "control-plane-state.json"),
8 * 1024 * 1024, "native_runner_checkpoint_invalid").toString("utf8") })) return;
if (!input.restartRecovery
&& taskTarget?.kind === "remote" && taskTarget.transport === "sandbox" && taskTarget.runnerTask && taskTarget.leaseId
&& identity.environmentLeaseId === taskTarget.leaseId
&& runnerdAuthorityLifecycle(scoped, identity) === "absent") {
await readAndSavePluginRunnerCheckpoint(scoped, taskTarget.runnerTask, identity);
}
if (
runnerdAuthorityLifecycleWithVerifiedBackup({
root: scoped,
@@ -6745,7 +6808,7 @@ async function migrateRunnerdStateRoot(input: {
});
// Name the failed retirement proof: the shared error otherwise hides
// which of several independent fences held the follow-up.
let retirementRefusal = "";
let retirementRefusedReason: string | null = null;
if (verification === "terminal_state_indeterminate" && !input.retainedWarmOwnerRunId
&& (!input.restartRecovery || input.restartRecovery.kind === "bootstrap_incomplete")) {
const retirement = await retireFinishedPerTurnRunnerdOwner({ ...input, root: scoped, identity, pluginCheckpointUnavailableConfirmed });
@@ -6753,13 +6816,20 @@ async function migrateRunnerdStateRoot(input: {
if (pluginCheckpointUnavailableConfirmed) input.onPluginCheckpointRetired?.();
return;
}
if (retirement.refused !== "lifecycle_not_per_turn") retirementRefusal = `; retirement_refused=${retirement.refused}`;
retirementRefusedReason = retirement.refused;
}
const retirementRefusal = retirementRefusedReason && retirementRefusedReason !== "lifecycle_not_per_turn"
? `; retirement_refused=${retirementRefusedReason}`
: "";
if (
verification !== "verified" &&
verification !== "retained_warm_runner"
) {
if (verification !== "active" && verification !== "unavailable") {
if (
verification !== "active"
&& verification !== "unavailable"
&& retirementRefusedReason !== "prior_lease_active"
) {
quarantineRunnerdStateRoot(
scoped,
verification === "scope_mismatch"