mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-10-30 13:20:54 +01:00
## Thinking Path > - Paperclip manages agents, tasks and their durable native results. > - Changed evidence, task authority or review retirement can require a new status assessment. > - Periodic orphan recovery repeatedly reads history to find these changes. > - This change gives reassessment an owner driven by committed changes and saved deadlines. > - Existing result, assessment, decision and task rows remain durable truth. > - The status committer still verifies current sources and authority before writing. > - Settled or insufficient evidence becomes quiet until a supported producer changes it. ## Linked Issues or Issue Description Refs #17702 (merged), #17679 and #17680. This is slice 50, now based on master. It owns native status reassessment; workspace settlement, retained sessions and other orphan duties remain separate. **What happened?** Periodic recovery repeatedly inspects completed native results. Removing that scan without complete writer coverage or current authority checks could strand new evidence or commit an old result over newer work. **Expected behavior** Reassess from existing durable facts after relevant outer transactions commit. Retain real retry/lease deadlines and restart/drain recovery. Preserve current authority, quality-review and supersession checks. Make no recurring SQL when work is settled or dormant. **Steps to reproduce** Complete a native result awaiting evidence or review, leave it idle, then approve a real work product or retire the selected automatic review. Its saved result should advance once when authorized, or record the existing nonterminal business gate, without a periodic scan. ## What Changed - Extract reassessment and its pure status policy from finalization recovery into their owning modules. Add a scoped worker using the existing delivery coordinator and scheduler; no queue table or migration is added. - Retain the three durable discovery triggers: changed work-product history, authoritative task status/version, or retirement of the selected automatic completion review. Preserve selected-source, ownership, effects, retry and lease fences under the existing committer. - Notify from actual task/work-product, claim release, approval, interaction, OAuth, event evidence and workspace-settlement owners before their transaction writes. Keep provider calls outside short transactions and nested writes behind outer commit. - Scope ordinary milestone/finalization/coalesced-input wakes to an issue/run. Keep genuine company authority restoration explicit. Real Photon and coalescer regressions cover all three response/status queues. - Move the current parent's required quality policy into the owner and apply it to every reassessment that could complete a task. An unmet review records the existing in-progress decision and next action, avoiding an operational retry loop. Preserve conversation/session reset locks and the workspace omission-barrier signal. - Skip reassessment in periodic recovery while preserving explicit/startup recovery and the historical supersession guard before independent workspace work. Document the source contract, producer inventory, failures and qualifications in the linked audit. ## Verification - Broad source `9fddb3f0b1157df32b64fb1f22e9d6e9624470e8` passes **2731 distinct cases in 28 complete files**, with no skips: 2458 producer/owner/authority/workspace/quality cases in 394.43 seconds and all 273 governed-response cases in 53.74 seconds. Nineteen dedicated fresh PostgreSQL 17 databases migrate through 0413; eighteen embedded-only invocations preserve fresh-per-call isolation through the existing recovery helper. All 22 temporary imports restore exactly and all 28 hashes match. - Final runtime source `5ea3b0fd016bf7e63ba82a7044825a46a0cd2082` passes **1211 cases in five complete affected files** in 108.23 seconds after the narrowly reproduced evidence-trigger fix: all 43 worker, 145 corpus, 32 finalization-recovery, 968 native-session and 23 quality-review cases. Four fresh databases plus the quality helper's own fresh fixture use PostgreSQL 17. Its one adapted import restores exactly; all five hashes match. The other 27 broad-run test files are unchanged. These qualifications are source-scoped and not cumulatively double-counted. - Required/optional real regressions reproduce retry loops on retired-review and evidence-approval paths before repair; both become SQL quiet afterward with unchanged assertions/time limits. Controlled removal of only ordinary scope guards reproduces two coarse-hint SQL failures; exact guard restoration passes. Real producer, outer transaction, claim, authority, 103-item backlog, retry and drain cases pass. Photon transport is mocked; callbacks, locks and observed SQL are real. - Normal merges preserve 12661 parent/unrelated entries, 35 owned entries and 21 automatic shared results, with five original conflicts reviewed explicitly. The parent's actual squash reconciliation preserves the entire held child tree. The final quality fix changes only its owner and tests. Fourteen added comments are removed with identical nontrivia tokens; no directives are removed and the final comment check is empty. - Database build, server types/build, boundaries and exact-head migration order pass. The database tree is identical to merged #17702: no new SQL, queue table or snapshot is generated. Earlier benchmarks, host limitations, failed assertions and their repairs remain in `doc/plans/2026-10-26-native-status-reassessment-sleep-audit.md` and `doc/idle-native-status-reassessment.md`. - This qualifies targeted external PostgreSQL behavior, not embedded bootstrap on the semaphore-exhausted host, a full local repository suite, deployed sleep or measured fleet savings. Fresh exact-head CI and review remain required. ## Risks - Notifications retain the process-local supported-writer contract. Independent SQL writers and uncoordinated replicas are not covered by a new transport. - Reassessment competes with current authority changes. Existing row/source locks and retries remain required; arbitrary missing identities have no row to lock, so this is not a general predicate-lock guarantee. - Discovery pages 100 rows but retains outstanding candidates in memory. It remains proportional to backlog size, and cancellation occurs between queries. - Other orphan/workspace/session duties and Cloud sleep eligibility remain unchanged. Missing supported producer coverage could strand dormant work, so the producer audit and real callback/transaction tests remain part of acceptance. ## Model Used OpenAI Codex, GPT-6 family, with reasoning, repository tools, shell execution and PostgreSQL tests. The runtime does not expose a more specific serving snapshot or context-window size. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass (targeted scope is stated above) - [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> Co-authored-by: Codex <noreply@openai.com>
1157 lines
41 KiB
TypeScript
1157 lines
41 KiB
TypeScript
import { notifyNativeStatusReassessment } from "../native-status-reassessment-notifications.js";
|
|
import { notifyUnsafeWorkspaceExportRunChange } from "../unsafe-workspace-export-notifications.js";
|
|
import { notifyCancelledWorkspacePreservation } from "../cancelled-workspace-preservation-notifications.js";
|
|
import { notifyInstructionCollection } from "../instruction-collection-notifications.js";
|
|
import { notifyExecutionRunWork } from "../execution-control-notifications.js";
|
|
import { hasNativeRunnerCheckpoint } from "./native-runner-checkpoint.js";
|
|
import { readNativeWorkspaceSyncReference } from "./native-workspace-sync.js";
|
|
import { activeNativeExecutionRunIds, NATIVE_PREPARATION_FENCING_VERSION } from "./native-active-runs.js";
|
|
import {
|
|
PROCESS_IDENTITY_RECORDED,
|
|
PROCESS_START_REQUESTED,
|
|
recordNativeLocalProcessStop,
|
|
} from "../native-local-process-stop.js";
|
|
import { randomUUID } from "node:crypto";
|
|
import { and, desc, eq, inArray, isNotNull, isNull, lte, or, sql } from "drizzle-orm";
|
|
import type { Db } from "@paperclipai/db";
|
|
import {
|
|
agents,
|
|
environmentLeases,
|
|
heartbeatRunEvents,
|
|
heartbeatRuns,
|
|
issues,
|
|
nativeRunFinalizations,
|
|
} from "@paperclipai/db";
|
|
import { REMOTE_CONTROLLER_LEASE_MS } from "./native-runner-recovery-contract.js";
|
|
import { readProcessStartedAt } from "../hot-restart.js";
|
|
import { getServerInfoSnapshot } from "../../server-info.js";
|
|
import { redactSensitiveText } from "../../redaction.js";
|
|
import { issueRecoveryActionService } from "../issue-recovery-actions.js";
|
|
import { isNewTerminalRunFailure, reportRunFailure } from "../run-failure-report.js";
|
|
import { isNativeRunnerOwnershipHeld } from "./native-runner-ownership.js";
|
|
import { nativeRestartInterruptedTurnId, type PersistedNativeSession } from "../../vendor/paperclip-runner/index.js";
|
|
import { retireSupersededNativeRetry } from "./native-superseded-retry.js";
|
|
|
|
export type NativeControllerIdentity = {
|
|
bootId: string;
|
|
pid: number;
|
|
processStartedAt: Date;
|
|
};
|
|
|
|
export type NativeRestartKind = "hot" | "hard" | "graceful";
|
|
|
|
export type NativeRestartRecoveryClaim =
|
|
| {
|
|
kind: "reattach_existing_runner";
|
|
runId: string;
|
|
leaseOwner: string;
|
|
controllerGeneration: number;
|
|
providerAttempt: number;
|
|
restartKind: NativeRestartKind;
|
|
recoveryRequestId: string | null;
|
|
process: {
|
|
pid: number;
|
|
processGroupId: number | null;
|
|
startedAt: string;
|
|
};
|
|
}
|
|
| {
|
|
kind: "reattach_remote_runner";
|
|
runId: string;
|
|
leaseOwner: string;
|
|
controllerGeneration: number;
|
|
providerAttempt: number;
|
|
restartKind: NativeRestartKind;
|
|
recoveryRequestId: string | null;
|
|
remote: { kind?: "sandbox"; providerLeaseId: string; remoteCwd: string }
|
|
| { kind: "plugin_task"; leaseId: string };
|
|
}
|
|
| {
|
|
kind: "resume_dead_runner";
|
|
runId: string;
|
|
leaseOwner: string;
|
|
controllerGeneration: number;
|
|
providerAttempt: number;
|
|
restartKind: NativeRestartKind;
|
|
recoveryRequestId: string | null;
|
|
}
|
|
| {
|
|
kind: "bootstrap_incomplete";
|
|
runId: string;
|
|
leaseOwner: string;
|
|
controllerGeneration: number;
|
|
providerAttempt: number;
|
|
restartKind: NativeRestartKind;
|
|
recoveryRequestId: string | null;
|
|
};
|
|
|
|
export type NativeRestartRecoveryDisposition =
|
|
| NativeRestartRecoveryClaim
|
|
| {
|
|
kind: "awaiting_evidence" | "blocked" | "already_finalized";
|
|
runId: string;
|
|
reason: string;
|
|
};
|
|
|
|
export function nextNativeProviderAttempt(
|
|
currentAttempt: number,
|
|
recoveryKind?: NativeRestartRecoveryClaim["kind"],
|
|
): number {
|
|
return recoveryKind === "reattach_existing_runner" ||
|
|
recoveryKind === "reattach_remote_runner"
|
|
? currentAttempt
|
|
: currentAttempt + 1;
|
|
}
|
|
|
|
const controllerBootId = randomUUID();
|
|
|
|
function processIsAlive(pid: number | null | undefined): boolean {
|
|
if (!pid || !Number.isInteger(pid) || pid <= 0) return false;
|
|
try {
|
|
process.kill(pid, 0);
|
|
return true;
|
|
} catch (error) {
|
|
return (error as NodeJS.ErrnoException | undefined)?.code === "EPERM";
|
|
}
|
|
}
|
|
|
|
function processGroupIsAlive(
|
|
processGroupId: number | null | undefined,
|
|
): boolean {
|
|
if (
|
|
process.platform === "win32" ||
|
|
!processGroupId ||
|
|
!Number.isInteger(processGroupId) ||
|
|
processGroupId <= 0
|
|
) {
|
|
return false;
|
|
}
|
|
try {
|
|
process.kill(-processGroupId, 0);
|
|
return true;
|
|
} catch (error) {
|
|
return (error as NodeJS.ErrnoException | undefined)?.code === "EPERM";
|
|
}
|
|
}
|
|
|
|
async function observedProcessStart(pid: number): Promise<Date | null> {
|
|
try {
|
|
const startedAt = await readProcessStartedAt(pid);
|
|
if (!startedAt) return null;
|
|
const parsed = new Date(startedAt);
|
|
return Number.isNaN(parsed.getTime()) ? null : parsed;
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
export async function currentNativeControllerIdentity(): Promise<NativeControllerIdentity> {
|
|
const observed = await observedProcessStart(process.pid);
|
|
const fallback = new Date(getServerInfoSnapshot().processStartedAt);
|
|
return {
|
|
bootId: controllerBootId,
|
|
pid: process.pid,
|
|
processStartedAt:
|
|
observed ?? (Number.isNaN(fallback.getTime()) ? new Date() : fallback),
|
|
};
|
|
}
|
|
|
|
function sameProcessStart(left: Date | null, right: Date | null): boolean {
|
|
return left !== null && right !== null && left.getTime() === right.getTime();
|
|
}
|
|
|
|
function definitivelyDifferentProcessStart(
|
|
left: Date | null,
|
|
right: Date | null,
|
|
): boolean {
|
|
if (left === null || right === null) return false;
|
|
// `ps -o lstart` has only whole-second precision on macOS and BSD. A
|
|
// sub-second disagreement can therefore be the same process when one probe
|
|
// fell back to a higher-precision spawn timestamp. Treat it as ambiguous and
|
|
// fail closed instead of declaring the live PID recycled.
|
|
return Math.abs(left.getTime() - right.getTime()) >= 1_000;
|
|
}
|
|
|
|
export async function evaluateNativeControllerTakeover(input: {
|
|
owner: Pick<
|
|
typeof nativeRunFinalizations.$inferSelect,
|
|
| "leaseOwner"
|
|
| "leaseExpiresAt"
|
|
| "controllerPid"
|
|
| "controllerProcessStartedAt"
|
|
>;
|
|
now: Date;
|
|
coordinatedPreviousController?: {
|
|
pid: number;
|
|
processStartedAt: Date | null;
|
|
} | null;
|
|
isProcessAlive?: (pid: number) => boolean;
|
|
readProcessStartedAt?: (pid: number) => Promise<Date | null>;
|
|
requireStoppedController?: boolean;
|
|
remoteLeaseFenced?: boolean;
|
|
}): Promise<{ allowed: boolean; reason: string }> {
|
|
const { owner, now } = input;
|
|
if (input.remoteLeaseFenced) {
|
|
return owner.leaseExpiresAt && owner.leaseExpiresAt > now
|
|
? { allowed: false, reason: "remote_controller_lease_live" }
|
|
: { allowed: true, reason: "remote_controller_lease_released_or_expired" };
|
|
}
|
|
const isAlive = input.isProcessAlive ?? processIsAlive;
|
|
const readStartedAt = input.readProcessStartedAt ?? observedProcessStart;
|
|
if ((!owner.leaseOwner || !owner.leaseExpiresAt) && !input.requireStoppedController) {
|
|
return { allowed: true, reason: "unowned" };
|
|
}
|
|
|
|
const priorPid = owner.controllerPid;
|
|
if (!priorPid) {
|
|
return {
|
|
allowed: false,
|
|
reason:
|
|
owner.leaseExpiresAt !== null && owner.leaseExpiresAt <= now
|
|
? "expired_lease_without_controller_identity"
|
|
: "live_legacy_lease_without_controller_identity",
|
|
};
|
|
}
|
|
if (!isAlive(priorPid)) {
|
|
return {
|
|
allowed: true,
|
|
reason:
|
|
owner.leaseExpiresAt !== null && owner.leaseExpiresAt <= now
|
|
? "expired_lease_controller_process_dead"
|
|
: "controller_process_dead",
|
|
};
|
|
}
|
|
|
|
const observedStartedAt = await readStartedAt(priorPid);
|
|
if (
|
|
owner.controllerProcessStartedAt &&
|
|
observedStartedAt &&
|
|
definitivelyDifferentProcessStart(
|
|
owner.controllerProcessStartedAt,
|
|
observedStartedAt,
|
|
)
|
|
) {
|
|
return { allowed: true, reason: "controller_pid_recycled" };
|
|
}
|
|
|
|
const coordinated = input.coordinatedPreviousController;
|
|
if (
|
|
coordinated &&
|
|
coordinated.pid === priorPid &&
|
|
coordinated.processStartedAt &&
|
|
owner.controllerProcessStartedAt &&
|
|
sameProcessStart(
|
|
coordinated.processStartedAt,
|
|
owner.controllerProcessStartedAt,
|
|
)
|
|
) {
|
|
return { allowed: false, reason: "coordinated_controller_still_alive" };
|
|
}
|
|
|
|
return { allowed: false, reason: "controller_still_alive" };
|
|
}
|
|
|
|
export type NativeProviderProcessIdentity = {
|
|
pid: number;
|
|
processStartedAt: Date | null;
|
|
};
|
|
|
|
export async function evaluateNativeProviderProcesses(input: {
|
|
identities: NativeProviderProcessIdentity[];
|
|
isProcessAlive?: (pid: number) => boolean;
|
|
readProcessStartedAt?: (pid: number) => Promise<Date | null>;
|
|
}): Promise<{
|
|
knownPids: number[];
|
|
livePids: number[];
|
|
ambiguousLivePids: number[];
|
|
recycledPids: number[];
|
|
}> {
|
|
const isAlive = input.isProcessAlive ?? processIsAlive;
|
|
const readStartedAt = input.readProcessStartedAt ?? observedProcessStart;
|
|
const expectedStarts = new Map<number, Date | null>();
|
|
for (const identity of input.identities) {
|
|
const current = expectedStarts.get(identity.pid);
|
|
if (
|
|
current === undefined ||
|
|
(current === null && identity.processStartedAt)
|
|
) {
|
|
expectedStarts.set(identity.pid, identity.processStartedAt);
|
|
}
|
|
}
|
|
|
|
const livePids: number[] = [];
|
|
const ambiguousLivePids: number[] = [];
|
|
const recycledPids: number[] = [];
|
|
for (const [pid, expectedStartedAt] of expectedStarts) {
|
|
if (!isAlive(pid)) continue;
|
|
const observedStartedAt = await readStartedAt(pid);
|
|
if (!expectedStartedAt || !observedStartedAt) {
|
|
ambiguousLivePids.push(pid);
|
|
} else if (sameProcessStart(expectedStartedAt, observedStartedAt)) {
|
|
livePids.push(pid);
|
|
} else if (
|
|
definitivelyDifferentProcessStart(expectedStartedAt, observedStartedAt)
|
|
) {
|
|
recycledPids.push(pid);
|
|
} else {
|
|
ambiguousLivePids.push(pid);
|
|
}
|
|
}
|
|
return {
|
|
knownPids: [...expectedStarts.keys()],
|
|
livePids,
|
|
ambiguousLivePids,
|
|
recycledPids,
|
|
};
|
|
}
|
|
|
|
export function classifyNativeRunnerRecoveryEvidence(input: {
|
|
runnerPidAlive: boolean;
|
|
runnerGroupAlive: boolean;
|
|
remoteSandbox?: boolean;
|
|
unclaimedBootstrap?: boolean;
|
|
processStartMatches: boolean;
|
|
knownProviderProcessAlive?: boolean;
|
|
knownProviderProcessIdentityAmbiguous?: boolean;
|
|
hasCheckpoint: boolean;
|
|
checkpointIdentityMatches?: boolean;
|
|
hasProviderEvidence: boolean;
|
|
checkpointFailed?: boolean;
|
|
providerAttempt?: number;
|
|
}): {
|
|
claimKind: NativeRestartRecoveryClaim["kind"] | null;
|
|
reason: string;
|
|
} {
|
|
if (input.checkpointFailed)
|
|
return {
|
|
claimKind: null,
|
|
reason: "provider_checkpoint_permanently_failed",
|
|
};
|
|
// Sandbox PIDs belong to another host. This claim only authorizes remote
|
|
// inspection; the executor must prove the original lease and authenticate
|
|
// the surviving runner before it can resume delivery.
|
|
if (input.remoteSandbox) {
|
|
if (input.unclaimedBootstrap === true && !input.hasCheckpoint && !input.hasProviderEvidence) {
|
|
return { claimKind: "bootstrap_incomplete", reason: "remote_execution_never_claimed" };
|
|
}
|
|
return input.hasCheckpoint &&
|
|
input.checkpointIdentityMatches === true &&
|
|
input.hasProviderEvidence
|
|
? {
|
|
claimKind: "reattach_remote_runner",
|
|
reason: "remote_runner_requires_sandbox_verification",
|
|
}
|
|
: { claimKind: null, reason: "ambiguous_remote_recovery_evidence" };
|
|
}
|
|
if (input.runnerPidAlive && input.processStartMatches) {
|
|
return {
|
|
claimKind: "reattach_existing_runner",
|
|
reason: "runner_process_identity_verified",
|
|
};
|
|
}
|
|
if (input.runnerPidAlive || input.runnerGroupAlive) {
|
|
return {
|
|
claimKind: null,
|
|
reason: input.runnerPidAlive
|
|
? "live_runner_identity_mismatch"
|
|
: "live_runner_process_group_without_exact_pid",
|
|
};
|
|
}
|
|
if (input.knownProviderProcessAlive) {
|
|
return {
|
|
claimKind: null,
|
|
reason: "live_provider_process_without_runner_authority",
|
|
};
|
|
}
|
|
if (input.knownProviderProcessIdentityAmbiguous) {
|
|
return {
|
|
claimKind: null,
|
|
reason: "live_provider_process_identity_unverifiable",
|
|
};
|
|
}
|
|
if ((input.providerAttempt ?? 0) >= 3)
|
|
return { claimKind: null, reason: "execution_recovery_budget_exhausted" };
|
|
const checkpointIdentityMatches =
|
|
input.checkpointIdentityMatches ?? input.hasCheckpoint;
|
|
if (
|
|
input.hasCheckpoint &&
|
|
checkpointIdentityMatches &&
|
|
input.hasProviderEvidence
|
|
) {
|
|
return {
|
|
claimKind: "resume_dead_runner",
|
|
reason: "dead_runner_with_exact_provider_checkpoint",
|
|
};
|
|
}
|
|
if (!input.hasCheckpoint && !input.hasProviderEvidence) {
|
|
return {
|
|
claimKind: "bootstrap_incomplete",
|
|
reason: "dead_runner_before_provider_identity",
|
|
};
|
|
}
|
|
return { claimKind: null, reason: "ambiguous_provider_recovery_evidence" };
|
|
}
|
|
|
|
function historyEntry(input: {
|
|
now: Date;
|
|
restartKind: NativeRestartKind;
|
|
controller: NativeControllerIdentity;
|
|
generation: number;
|
|
disposition: string;
|
|
reason: string;
|
|
requestId: string | null;
|
|
providerAttempt: number;
|
|
processPid: number | null;
|
|
processStartedAt: Date | null;
|
|
hasCheckpoint: boolean;
|
|
checkpointIdentityMatches?: boolean;
|
|
hasProviderEvidence: boolean;
|
|
knownProviderPids?: number[];
|
|
liveProviderPids?: number[];
|
|
ambiguousProviderPids?: number[];
|
|
recycledProviderPids?: number[];
|
|
stderrTail?: string | null;
|
|
}) {
|
|
return {
|
|
at: input.now.toISOString(),
|
|
restartKind: input.restartKind,
|
|
controllerBootId: input.controller.bootId,
|
|
controllerPid: input.controller.pid,
|
|
controllerProcessStartedAt: input.controller.processStartedAt.toISOString(),
|
|
controllerGeneration: input.generation,
|
|
disposition: input.disposition,
|
|
reason: input.reason,
|
|
stateRootAction:
|
|
input.disposition === "reattach_existing_runner" ||
|
|
input.disposition === "reattach_remote_runner"
|
|
? "reopen_exact_root"
|
|
: input.disposition === "resume_dead_runner"
|
|
? "reuse_exact_root"
|
|
: input.disposition === "bootstrap_incomplete"
|
|
? "quarantine_incomplete_root_then_bootstrap"
|
|
: input.disposition === "awaiting_evidence"
|
|
? "preserve_awaiting_evidence"
|
|
: "preserve_fail_closed",
|
|
recoveryRequestId: input.requestId,
|
|
providerAttempt: input.providerAttempt,
|
|
processPid: input.processPid,
|
|
processStartedAt: input.processStartedAt?.toISOString() ?? null,
|
|
hasCheckpoint: input.hasCheckpoint,
|
|
checkpointIdentityMatches: input.checkpointIdentityMatches ?? false,
|
|
hasProviderEvidence: input.hasProviderEvidence,
|
|
knownProviderPids: input.knownProviderPids ?? [],
|
|
liveProviderPids: input.liveProviderPids ?? [],
|
|
ambiguousProviderPids: input.ambiguousProviderPids ?? [],
|
|
recycledProviderPids: input.recycledProviderPids ?? [],
|
|
stderrTail:
|
|
input.stderrTail && input.stderrTail.trim()
|
|
? redactSensitiveText(input.stderrTail).slice(-4_096)
|
|
: null,
|
|
} satisfies Record<string, unknown>;
|
|
}
|
|
|
|
function appendBoundedRecoveryHistory(entry: Record<string, unknown>) {
|
|
const encoded = JSON.stringify(entry);
|
|
return sql`(
|
|
select coalesce(jsonb_agg(item order by ordinal), '[]'::jsonb)
|
|
from jsonb_array_elements(
|
|
coalesce(${nativeRunFinalizations.recoveryHistory}, '[]'::jsonb)
|
|
|| jsonb_build_array(${encoded}::jsonb)
|
|
) with ordinality as history(item, ordinal)
|
|
where ordinal > greatest(
|
|
jsonb_array_length(
|
|
coalesce(${nativeRunFinalizations.recoveryHistory}, '[]'::jsonb)
|
|
|| jsonb_build_array(${encoded}::jsonb)
|
|
) - 20,
|
|
0
|
|
)
|
|
)`;
|
|
}
|
|
|
|
/**
|
|
* Claims abandoned local runner executions without changing the provider retry
|
|
* attempt. The transaction locks the run, coordinator, and issue execution
|
|
* owner so two successor servers cannot both reconstruct the same authority.
|
|
*/
|
|
export async function claimNativeRestartRecoveries(input: {
|
|
db: Db;
|
|
controller?: NativeControllerIdentity;
|
|
restartKind: NativeRestartKind;
|
|
recoveryRequestId?: string | null;
|
|
runIds?: string[];
|
|
liveRunExecutions?: Pick<ReadonlySet<string>, "has">;
|
|
now?: Date;
|
|
limit?: number;
|
|
/** Called after each committed claim, before scanning the next candidate. */
|
|
onClaim?: (claim: NativeRestartRecoveryClaim, scope: {
|
|
companyId: string; issueId: string; controller: NativeControllerIdentity; remote: boolean;
|
|
}) => void;
|
|
coordinatedPreviousController?: {
|
|
pid: number;
|
|
processStartedAt: Date | null;
|
|
} | null;
|
|
}): Promise<NativeRestartRecoveryDisposition[]> {
|
|
const now = input.now ?? new Date();
|
|
const controller =
|
|
input.controller ?? (await currentNativeControllerIdentity());
|
|
const candidateQuery = input.db
|
|
.select({
|
|
runId: heartbeatRuns.id,
|
|
issueId: nativeRunFinalizations.issueId,
|
|
})
|
|
.from(heartbeatRuns)
|
|
.innerJoin(agents, eq(agents.id, heartbeatRuns.agentId))
|
|
.innerJoin(
|
|
nativeRunFinalizations,
|
|
eq(nativeRunFinalizations.runId, heartbeatRuns.id),
|
|
)
|
|
.where(
|
|
and(
|
|
eq(heartbeatRuns.runtimeMode, "native"),
|
|
eq(agents.adapterType, "paperclip_runner"),
|
|
inArray(heartbeatRuns.status, ["running", "failed"]),
|
|
isNull(nativeRunFinalizations.resultId),
|
|
or(
|
|
eq(nativeRunFinalizations.phase, "observed"),
|
|
and(
|
|
eq(nativeRunFinalizations.phase, "retryable_failure"),
|
|
or(
|
|
isNull(nativeRunFinalizations.nextAttemptAt),
|
|
lte(nativeRunFinalizations.nextAttemptAt, now),
|
|
),
|
|
),
|
|
),
|
|
...(input.runIds?.length
|
|
? [inArray(heartbeatRuns.id, input.runIds)]
|
|
: []),
|
|
),
|
|
)
|
|
.orderBy(heartbeatRuns.id);
|
|
const candidates = await (input.limit === undefined
|
|
? candidateQuery
|
|
: candidateQuery.limit(input.limit));
|
|
|
|
const dispositions: NativeRestartRecoveryDisposition[] = [];
|
|
for (const candidate of candidates) {
|
|
const now = input.now ?? new Date();
|
|
let claimScope: { companyId: string; issueId: string; controller: NativeControllerIdentity; remote: boolean } | undefined;
|
|
// Set inside the transaction only when the write below genuinely
|
|
// transitions the run into "failed". Read after the transaction
|
|
// commits, so a rolled-back write never reports a false failure.
|
|
let terminalRunToReport: typeof heartbeatRuns.$inferSelect | null = null;
|
|
const disposition = await input.db.transaction(async (tx) => {
|
|
await tx.execute(
|
|
sql`select set_config('statement_timeout', '15000', true), set_config('lock_timeout', '1000', true)`,
|
|
);
|
|
await tx
|
|
.select({ id: issues.id })
|
|
.from(issues)
|
|
.where(eq(issues.id, candidate.issueId))
|
|
.for("update");
|
|
const row = await tx
|
|
.select({
|
|
run: heartbeatRuns,
|
|
coordinator: nativeRunFinalizations,
|
|
issueExecutionRunId: issues.executionRunId,
|
|
issueAssigneeAgentId: issues.assigneeAgentId,
|
|
issueStatus: issues.status,
|
|
})
|
|
.from(heartbeatRuns)
|
|
.innerJoin(
|
|
nativeRunFinalizations,
|
|
eq(nativeRunFinalizations.runId, heartbeatRuns.id),
|
|
)
|
|
.innerJoin(
|
|
issues,
|
|
and(
|
|
eq(issues.id, nativeRunFinalizations.issueId),
|
|
eq(issues.companyId, nativeRunFinalizations.companyId),
|
|
),
|
|
)
|
|
.where(eq(heartbeatRuns.id, candidate.runId))
|
|
.for("update")
|
|
.limit(1)
|
|
.then((rows) => rows[0] ?? null);
|
|
if (!row) {
|
|
return {
|
|
kind: "blocked",
|
|
runId: candidate.runId,
|
|
reason: "recovery_rows_missing",
|
|
} as const;
|
|
}
|
|
if (isNativeRunnerOwnershipHeld(row.run)) {
|
|
return {
|
|
kind: "blocked",
|
|
runId: row.run.id,
|
|
reason: "native_execution_ownership_unverified",
|
|
} as const;
|
|
}
|
|
if (row.coordinator.resultId) {
|
|
return {
|
|
kind: "already_finalized",
|
|
runId: row.run.id,
|
|
reason: "result_already_persisted",
|
|
} as const;
|
|
}
|
|
if (!input.liveRunExecutions?.has(row.run.id) && await retireSupersededNativeRetry(tx as unknown as Db, {
|
|
run: row.run, coordinator: row.coordinator, issueExecutionRunId: row.issueExecutionRunId, now,
|
|
})) return { kind: "blocked", runId: row.run.id, reason: "native_retry_superseded" } as const;
|
|
if (row.issueExecutionRunId !== row.run.id) {
|
|
return {
|
|
kind: "blocked",
|
|
runId: row.run.id,
|
|
reason: "issue_execution_lock_changed",
|
|
} as const;
|
|
}
|
|
|
|
if (input.liveRunExecutions?.has(row.run.id)) {
|
|
return {
|
|
kind: "awaiting_evidence",
|
|
runId: row.run.id,
|
|
reason: "current_controller_preparing",
|
|
} as const;
|
|
}
|
|
|
|
const profile = row.run.runnerProfileJson ?? {};
|
|
const remoteWorkspace = readNativeWorkspaceSyncReference(profile.nativeWorkspaceSync);
|
|
const [pluginTask] = await tx.select({ id: environmentLeases.id }).from(environmentLeases).where(and(
|
|
eq(environmentLeases.companyId, row.run.companyId), eq(environmentLeases.heartbeatRunId, row.run.id),
|
|
sql`${environmentLeases.metadata}->>'runnerTaskLease' = 'true'`,
|
|
)).orderBy(desc(environmentLeases.createdAt)).limit(1);
|
|
const remoteSandbox = profile.nativeWorkspaceSync != null;
|
|
const remoteProcess = remoteSandbox || !!pluginTask;
|
|
const durableAuthority = (remoteWorkspace || pluginTask) && await hasNativeRunnerCheckpoint(tx, {
|
|
companyId: row.run.companyId, issueId: row.coordinator.issueId, runId: row.run.id,
|
|
});
|
|
const takeover = await evaluateNativeControllerTakeover({
|
|
owner: row.coordinator,
|
|
now,
|
|
remoteLeaseFenced: Boolean(durableAuthority),
|
|
coordinatedPreviousController:
|
|
input.coordinatedPreviousController ?? null,
|
|
});
|
|
if (!takeover.allowed) {
|
|
const event = historyEntry({
|
|
now,
|
|
restartKind: input.restartKind,
|
|
controller,
|
|
generation: row.coordinator.controllerGeneration,
|
|
disposition: "awaiting_evidence",
|
|
reason: takeover.reason,
|
|
requestId: input.recoveryRequestId ?? null,
|
|
providerAttempt: row.coordinator.attempt,
|
|
processPid: row.run.processPid,
|
|
processStartedAt: row.run.processStartedAt,
|
|
hasCheckpoint: false,
|
|
hasProviderEvidence: false,
|
|
stderrTail: row.run.stderrExcerpt,
|
|
});
|
|
await tx
|
|
.update(nativeRunFinalizations)
|
|
.set({
|
|
recoveryState: "awaiting_evidence",
|
|
recoveryRequestId: input.recoveryRequestId ?? null,
|
|
recoveryHistory: appendBoundedRecoveryHistory(event),
|
|
updatedAt: now,
|
|
})
|
|
.where(
|
|
and(
|
|
eq(nativeRunFinalizations.runId, row.run.id),
|
|
eq(nativeRunFinalizations.attempt, row.coordinator.attempt),
|
|
eq(nativeRunFinalizations.phase, row.coordinator.phase),
|
|
),
|
|
);
|
|
return {
|
|
kind: "awaiting_evidence",
|
|
runId: row.run.id,
|
|
reason: takeover.reason,
|
|
} as const;
|
|
}
|
|
|
|
const runnerPidAlive =
|
|
!remoteProcess && processIsAlive(row.run.processPid);
|
|
const runnerGroupAlive =
|
|
!remoteProcess && processGroupIsAlive(row.run.processGroupId);
|
|
const observedRunnerStart =
|
|
row.run.processPid && runnerPidAlive
|
|
? await observedProcessStart(row.run.processPid)
|
|
: null;
|
|
const exactRunnerIdentity =
|
|
runnerPidAlive &&
|
|
row.run.processPid !== null &&
|
|
sameProcessStart(row.run.processStartedAt, observedRunnerStart);
|
|
|
|
const checkpoint = profile.sessionCheckpoint;
|
|
const checkpointRecord =
|
|
checkpoint &&
|
|
typeof checkpoint === "object" &&
|
|
!Array.isArray(checkpoint)
|
|
? (checkpoint as Record<string, unknown>)
|
|
: {};
|
|
const hasCheckpoint = checkpoint !== undefined && checkpoint !== null;
|
|
const checkpointIdentity =
|
|
checkpointRecord.identity &&
|
|
typeof checkpointRecord.identity === "object" &&
|
|
!Array.isArray(checkpointRecord.identity)
|
|
? (checkpointRecord.identity as Record<string, unknown>)
|
|
: {};
|
|
const checkpointIdentityMatches =
|
|
hasCheckpoint &&
|
|
typeof row.run.nativeSessionId === "string" &&
|
|
row.run.nativeSessionId.length > 0 &&
|
|
checkpointIdentity.runId === row.run.id &&
|
|
checkpointIdentity.companyId === row.run.companyId &&
|
|
checkpointIdentity.issueId === row.coordinator.issueId &&
|
|
checkpointIdentity.agentId === row.run.agentId &&
|
|
checkpointIdentity.sessionId === row.run.nativeSessionId;
|
|
const hasCheckpointProviderIdentity =
|
|
(typeof checkpointRecord.providerSessionId === "string" &&
|
|
checkpointRecord.providerSessionId.length > 0) ||
|
|
(checkpointRecord.providerIdentity !== null &&
|
|
typeof checkpointRecord.providerIdentity === "object" &&
|
|
!Array.isArray(checkpointRecord.providerIdentity) &&
|
|
Object.keys(checkpointRecord.providerIdentity).length > 0);
|
|
const providerEvents = await tx
|
|
.select({
|
|
id: heartbeatRunEvents.id,
|
|
payload: heartbeatRunEvents.payload,
|
|
})
|
|
.from(heartbeatRunEvents)
|
|
.where(
|
|
and(
|
|
eq(heartbeatRunEvents.runId, row.run.id),
|
|
inArray(heartbeatRunEvents.eventType, [
|
|
"harness.ready",
|
|
"session.started",
|
|
"session.resumed",
|
|
"session.updated",
|
|
"turn.started",
|
|
"provider.event",
|
|
"provider.rpc_result",
|
|
]),
|
|
),
|
|
)
|
|
.orderBy(desc(heartbeatRunEvents.id))
|
|
.limit(100);
|
|
const checkpointProcess =
|
|
checkpointRecord.process &&
|
|
typeof checkpointRecord.process === "object" &&
|
|
!Array.isArray(checkpointRecord.process)
|
|
? (checkpointRecord.process as Record<string, unknown>)
|
|
: {};
|
|
const providerProcessIdentities: NativeProviderProcessIdentity[] = [];
|
|
const checkpointProcessFields = [
|
|
["providerPid", "providerProcessStartedAt"],
|
|
["codexPid", "codexProcessStartedAt"],
|
|
["sidecarPid", "sidecarProcessStartedAt"],
|
|
["agentPid", "agentProcessStartedAt"],
|
|
] as const;
|
|
for (const [field, startedAtField] of checkpointProcessFields) {
|
|
const value = checkpointProcess[field];
|
|
if (typeof value === "number" && Number.isInteger(value) && value > 0) {
|
|
const rawStartedAt = checkpointProcess[startedAtField];
|
|
const parsedStartedAt =
|
|
typeof rawStartedAt === "string" ? new Date(rawStartedAt) : null;
|
|
providerProcessIdentities.push({
|
|
pid: value,
|
|
processStartedAt:
|
|
parsedStartedAt && !Number.isNaN(parsedStartedAt.getTime())
|
|
? parsedStartedAt
|
|
: null,
|
|
});
|
|
}
|
|
}
|
|
for (const providerEvent of providerEvents) {
|
|
const prpEvent = providerEvent.payload?.prpEvent;
|
|
const event =
|
|
prpEvent && typeof prpEvent === "object" && !Array.isArray(prpEvent)
|
|
? (prpEvent as Record<string, unknown>)
|
|
: {};
|
|
const eventPayload =
|
|
event.payload &&
|
|
typeof event.payload === "object" &&
|
|
!Array.isArray(event.payload)
|
|
? (event.payload as Record<string, unknown>)
|
|
: {};
|
|
const processId = eventPayload.processId;
|
|
if (
|
|
typeof processId === "number" &&
|
|
Number.isInteger(processId) &&
|
|
processId > 0
|
|
) {
|
|
const rawStartedAt =
|
|
eventPayload.processStartedAt ??
|
|
eventPayload.providerProcessStartedAt;
|
|
const parsedStartedAt =
|
|
typeof rawStartedAt === "string" ? new Date(rawStartedAt) : null;
|
|
providerProcessIdentities.push({
|
|
pid: processId,
|
|
processStartedAt:
|
|
parsedStartedAt && !Number.isNaN(parsedStartedAt.getTime())
|
|
? parsedStartedAt
|
|
: null,
|
|
});
|
|
}
|
|
}
|
|
const providerProcesses = await evaluateNativeProviderProcesses({
|
|
identities: (remoteProcess ? [] : providerProcessIdentities).filter(
|
|
(identity) => identity.pid !== row.run.processPid,
|
|
),
|
|
});
|
|
const hasProviderEvidence =
|
|
hasCheckpointProviderIdentity || providerEvents.length > 0;
|
|
|
|
let unclaimedBootstrap =
|
|
remoteWorkspace?.state === "prepared" &&
|
|
row.run.runnerProfileJson?.nativePreparationFencingVersion === NATIVE_PREPARATION_FENCING_VERSION &&
|
|
row.coordinator.phase === "observed" &&
|
|
row.coordinator.attempt === 0 &&
|
|
row.coordinator.controllerGeneration === 0 &&
|
|
!row.coordinator.controllerBootId &&
|
|
!row.coordinator.controllerPid &&
|
|
!row.coordinator.controllerProcessStartedAt &&
|
|
!row.coordinator.leaseOwner &&
|
|
!row.coordinator.leaseExpiresAt &&
|
|
!row.coordinator.failureDetail?.successorRunId &&
|
|
!row.run.processPid &&
|
|
!row.run.processGroupId &&
|
|
!row.run.processStartedAt &&
|
|
!row.run.sessionIdBefore &&
|
|
!row.run.sessionIdAfter &&
|
|
Boolean(row.run.nativeSessionId && row.run.runnerInstanceId) &&
|
|
!hasCheckpoint &&
|
|
!hasProviderEvidence;
|
|
if (unclaimedBootstrap) {
|
|
if (activeNativeExecutionRunIds.has(row.run.id) &&
|
|
controller.bootId === (await currentNativeControllerIdentity()).bootId) {
|
|
return { kind: "awaiting_evidence", runId: row.run.id, reason: "current_controller_preparing" } as const;
|
|
}
|
|
const [executionEvent] = await tx
|
|
.select({ id: heartbeatRunEvents.id })
|
|
.from(heartbeatRunEvents)
|
|
.where(and(
|
|
eq(heartbeatRunEvents.companyId, row.run.companyId),
|
|
eq(heartbeatRunEvents.runId, row.run.id),
|
|
or(
|
|
isNotNull(heartbeatRunEvents.sourceEventId),
|
|
inArray(heartbeatRunEvents.eventType, [
|
|
"adapter.invoke",
|
|
PROCESS_START_REQUESTED,
|
|
PROCESS_IDENTITY_RECORDED,
|
|
"tool.execution.started",
|
|
]),
|
|
),
|
|
))
|
|
.limit(1);
|
|
unclaimedBootstrap = !executionEvent;
|
|
}
|
|
|
|
const classification = classifyNativeRunnerRecoveryEvidence({
|
|
remoteSandbox: remoteSandbox || Boolean(pluginTask && durableAuthority),
|
|
unclaimedBootstrap,
|
|
runnerPidAlive,
|
|
runnerGroupAlive,
|
|
processStartMatches: exactRunnerIdentity,
|
|
knownProviderProcessAlive: providerProcesses.livePids.length > 0,
|
|
knownProviderProcessIdentityAmbiguous:
|
|
providerProcesses.ambiguousLivePids.length > 0,
|
|
hasCheckpoint,
|
|
checkpointIdentityMatches:
|
|
checkpointIdentityMatches &&
|
|
(!remoteSandbox || remoteWorkspace !== null),
|
|
hasProviderEvidence,
|
|
checkpointFailed:
|
|
(checkpointRecord.terminal as Record<string, unknown> | undefined)
|
|
?.runTerminalState === "failed" &&
|
|
nativeRestartInterruptedTurnId(checkpointRecord as unknown as PersistedNativeSession) === null,
|
|
providerAttempt: row.coordinator.attempt,
|
|
});
|
|
const ownershipChanged =
|
|
row.issueAssigneeAgentId !== row.run.agentId ||
|
|
["done", "cancelled"].includes(row.issueStatus);
|
|
const claimKind = ownershipChanged ? null : classification.claimKind;
|
|
const reason = ownershipChanged
|
|
? "task_ownership_or_status_changed"
|
|
: classification.reason;
|
|
|
|
if (!claimKind) {
|
|
const generation = row.coordinator.controllerGeneration;
|
|
const event = historyEntry({
|
|
now,
|
|
restartKind: input.restartKind,
|
|
controller,
|
|
generation,
|
|
disposition: "blocked",
|
|
reason,
|
|
requestId: input.recoveryRequestId ?? null,
|
|
providerAttempt: row.coordinator.attempt,
|
|
processPid: row.run.processPid,
|
|
processStartedAt: row.run.processStartedAt,
|
|
hasCheckpoint,
|
|
checkpointIdentityMatches,
|
|
hasProviderEvidence,
|
|
knownProviderPids: providerProcesses.knownPids,
|
|
liveProviderPids: providerProcesses.livePids,
|
|
ambiguousProviderPids: providerProcesses.ambiguousLivePids,
|
|
recycledProviderPids: providerProcesses.recycledPids,
|
|
stderrTail: row.run.stderrExcerpt,
|
|
});
|
|
await notifyExecutionRunWork(tx);
|
|
await tx
|
|
.update(nativeRunFinalizations)
|
|
.set({
|
|
phase: "terminal_failure",
|
|
leaseOwner: null,
|
|
leaseExpiresAt: null,
|
|
nextAttemptAt: null,
|
|
failureCode: "native_restart_recovery_blocked",
|
|
failureDetail: {
|
|
...row.coordinator.failureDetail,
|
|
reason,
|
|
nextAction:
|
|
"Inspect the preserved checkpoint and reconcile the previous execution before starting a fresh session.",
|
|
},
|
|
recoveryState: "blocked",
|
|
recoveryRequestId: input.recoveryRequestId ?? null,
|
|
recoveryHistory: appendBoundedRecoveryHistory(event),
|
|
updatedAt: now,
|
|
})
|
|
.where(
|
|
and(
|
|
eq(nativeRunFinalizations.runId, row.run.id),
|
|
eq(nativeRunFinalizations.attempt, row.coordinator.attempt),
|
|
eq(nativeRunFinalizations.phase, row.coordinator.phase),
|
|
),
|
|
);
|
|
await notifyInstructionCollection(tx, { companyId: row.run.companyId, runId: row.run.id });
|
|
await notifyCancelledWorkspacePreservation(tx, { companyId: row.run.companyId, runId: row.run.id });
|
|
await notifyUnsafeWorkspaceExportRunChange(tx, row.run);
|
|
const [updatedRun] = await tx
|
|
.update(heartbeatRuns)
|
|
.set({
|
|
status: "failed",
|
|
nativePhase: "terminal_failure",
|
|
nativePhaseUpdatedAt: now,
|
|
executionStatusDeliveryId: randomUUID(),
|
|
finishedAt: now,
|
|
errorCode: "native_restart_recovery_blocked",
|
|
error: reason,
|
|
updatedAt: now,
|
|
})
|
|
.where(eq(heartbeatRuns.id, row.run.id))
|
|
.returning();
|
|
if (updatedRun && isNewTerminalRunFailure(row.run, updatedRun)) {
|
|
terminalRunToReport = updatedRun;
|
|
}
|
|
await notifyNativeStatusReassessment(tx, { companyId: row.run.companyId, issueId: row.coordinator.issueId });
|
|
await tx
|
|
.update(issues)
|
|
.set({ executionRunId: null, updatedAt: now })
|
|
.where(
|
|
and(
|
|
eq(issues.id, row.coordinator.issueId),
|
|
eq(issues.companyId, row.run.companyId),
|
|
eq(issues.executionRunId, row.run.id),
|
|
),
|
|
);
|
|
await tx
|
|
.update(issues)
|
|
.set({ checkoutRunId: null, updatedAt: now })
|
|
.where(
|
|
and(
|
|
eq(issues.id, row.coordinator.issueId),
|
|
eq(issues.companyId, row.run.companyId),
|
|
eq(issues.checkoutRunId, row.run.id),
|
|
),
|
|
);
|
|
if (
|
|
row.issueAssigneeAgentId === row.run.agentId &&
|
|
!["done", "cancelled"].includes(row.issueStatus)
|
|
)
|
|
await issueRecoveryActionService(
|
|
tx as unknown as Db,
|
|
).upsertSourceScoped({
|
|
companyId: row.run.companyId,
|
|
sourceIssueId: row.coordinator.issueId,
|
|
kind: "active_run_watchdog",
|
|
ownerType: "board",
|
|
returnOwnerAgentId: row.run.agentId,
|
|
cause: "native_restart_recovery_blocked",
|
|
fingerprint: `native-restart:${row.run.id}`,
|
|
evidence: {
|
|
runId: row.run.id,
|
|
reason,
|
|
providerAttempt: row.coordinator.attempt,
|
|
},
|
|
nextAction:
|
|
"Inspect the preserved checkpoint and reconcile the previous execution before starting a fresh session.",
|
|
maxAttempts: 3,
|
|
wakePolicy: null,
|
|
supersedeOnIdentityChange: true,
|
|
});
|
|
return { kind: "blocked", runId: row.run.id, reason } as const;
|
|
}
|
|
|
|
const generation = row.coordinator.controllerGeneration + 1;
|
|
const leaseOwner = `${controller.bootId}:${generation}:${randomUUID()}`;
|
|
const event = historyEntry({
|
|
now,
|
|
restartKind: input.restartKind,
|
|
controller,
|
|
generation,
|
|
disposition: claimKind,
|
|
reason,
|
|
requestId: input.recoveryRequestId ?? null,
|
|
providerAttempt: row.coordinator.attempt,
|
|
processPid: row.run.processPid,
|
|
processStartedAt: row.run.processStartedAt,
|
|
hasCheckpoint,
|
|
checkpointIdentityMatches,
|
|
hasProviderEvidence,
|
|
knownProviderPids: providerProcesses.knownPids,
|
|
liveProviderPids: providerProcesses.livePids,
|
|
ambiguousProviderPids: providerProcesses.ambiguousLivePids,
|
|
recycledProviderPids: providerProcesses.recycledPids,
|
|
stderrTail: row.run.stderrExcerpt,
|
|
});
|
|
const claimed = await tx
|
|
.update(nativeRunFinalizations)
|
|
.set({
|
|
phase: "observed",
|
|
leaseOwner,
|
|
// Cleanup and earlier candidates can outlive the batch observation.
|
|
// The owner row is locked: grant the full lease at this write.
|
|
leaseExpiresAt: sql`clock_timestamp() + ${durableAuthority ? REMOTE_CONTROLLER_LEASE_MS : 20 * 60_000} * interval '1 millisecond'`,
|
|
controllerBootId: controller.bootId,
|
|
controllerPid: controller.pid,
|
|
controllerProcessStartedAt: controller.processStartedAt,
|
|
controllerGeneration: generation,
|
|
recoveryState:
|
|
claimKind === "reattach_existing_runner" ||
|
|
claimKind === "reattach_remote_runner"
|
|
? "awaiting_runner_reattach"
|
|
: claimKind === "resume_dead_runner"
|
|
? "resuming_session"
|
|
: "bootstrap_incomplete",
|
|
recoveryRequestId: input.recoveryRequestId ?? null,
|
|
recoveryHistory: appendBoundedRecoveryHistory(event),
|
|
failureCode: null,
|
|
nextAttemptAt: null,
|
|
updatedAt: now,
|
|
})
|
|
.where(
|
|
and(
|
|
eq(nativeRunFinalizations.runId, row.run.id),
|
|
eq(nativeRunFinalizations.attempt, row.coordinator.attempt),
|
|
eq(nativeRunFinalizations.phase, row.coordinator.phase),
|
|
row.coordinator.leaseOwner === null
|
|
? isNull(nativeRunFinalizations.leaseOwner)
|
|
: eq(
|
|
nativeRunFinalizations.leaseOwner,
|
|
row.coordinator.leaseOwner,
|
|
),
|
|
),
|
|
)
|
|
.returning({ runId: nativeRunFinalizations.runId })
|
|
.then((rows) => rows[0] ?? null);
|
|
if (!claimed) {
|
|
return {
|
|
kind: "awaiting_evidence",
|
|
runId: row.run.id,
|
|
reason: "concurrent_recovery_claim",
|
|
} as const;
|
|
}
|
|
|
|
if (
|
|
claimKind !== "reattach_existing_runner" &&
|
|
claimKind !== "reattach_remote_runner"
|
|
) {
|
|
await recordNativeLocalProcessStop(tx as unknown as Db, row.run);
|
|
}
|
|
|
|
await tx
|
|
.update(heartbeatRuns)
|
|
.set({
|
|
status: "running",
|
|
finishedAt: null,
|
|
error: null,
|
|
errorCode: null,
|
|
nativePhase: "observed",
|
|
nativePhaseUpdatedAt: now,
|
|
...(claimKind === "reattach_existing_runner" ||
|
|
claimKind === "reattach_remote_runner"
|
|
? {}
|
|
: {
|
|
processPid: null,
|
|
processGroupId: null,
|
|
processStartedAt: null,
|
|
}),
|
|
updatedAt: now,
|
|
})
|
|
.where(eq(heartbeatRuns.id, row.run.id));
|
|
|
|
claimScope = { companyId: row.run.companyId, issueId: row.coordinator.issueId, controller, remote: Boolean(durableAuthority) };
|
|
const common = {
|
|
runId: row.run.id,
|
|
leaseOwner,
|
|
controllerGeneration: generation,
|
|
providerAttempt: row.coordinator.attempt,
|
|
restartKind: input.restartKind,
|
|
recoveryRequestId: input.recoveryRequestId ?? null,
|
|
};
|
|
if (claimKind === "reattach_remote_runner") {
|
|
return {
|
|
kind: claimKind,
|
|
...common,
|
|
remote: pluginTask ? { kind: "plugin_task", leaseId: pluginTask.id } : {
|
|
providerLeaseId: remoteWorkspace!.providerLeaseId,
|
|
remoteCwd: remoteWorkspace!.remoteCwd,
|
|
},
|
|
} satisfies NativeRestartRecoveryClaim;
|
|
}
|
|
if (claimKind === "reattach_existing_runner") {
|
|
return {
|
|
kind: claimKind,
|
|
...common,
|
|
process: {
|
|
pid: row.run.processPid!,
|
|
processGroupId: row.run.processGroupId,
|
|
startedAt: row.run.processStartedAt!.toISOString(),
|
|
},
|
|
} satisfies NativeRestartRecoveryClaim;
|
|
}
|
|
return {
|
|
kind: claimKind,
|
|
...common,
|
|
} satisfies NativeRestartRecoveryClaim;
|
|
});
|
|
if (terminalRunToReport)
|
|
void reportRunFailure(input.db, terminalRunToReport);
|
|
if (claimScope && "leaseOwner" in disposition) input.onClaim?.(disposition, claimScope);
|
|
dispositions.push(disposition);
|
|
}
|
|
return dispositions;
|
|
}
|
|
|
|
export async function nativeRestartRecoverySummary(db: Db) {
|
|
const rows = await db
|
|
.select({
|
|
state: nativeRunFinalizations.recoveryState,
|
|
count: sql<number>`count(*)::int`,
|
|
})
|
|
.from(nativeRunFinalizations)
|
|
.where(
|
|
inArray(nativeRunFinalizations.recoveryState, [
|
|
"awaiting_evidence",
|
|
"awaiting_runner_reattach",
|
|
"resuming_session",
|
|
"bootstrap_incomplete",
|
|
"blocked",
|
|
]),
|
|
)
|
|
.groupBy(nativeRunFinalizations.recoveryState);
|
|
return Object.fromEntries(
|
|
rows.map((row) => [row.state ?? "unknown", row.count]),
|
|
);
|
|
}
|