mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-01 15:35:12 +01:00
## Thinking Path > - Paperclip manages AI agents and preserves their results through failures. > - Native completion must save workspace output before it commits the accepted result. > - The orphan recovery pass repeatedly revisits this work even when the subsystem is idle. > - Accepted results, workspace receipts, retry dates and leases already provide durable truth. > - This PR wakes a scoped worker from those writes and schedules only real unfinished work. > - It preserves existing finalization authority and keeps later projection and resource recovery separate. ## Linked Issues or Issue Description Refs #17734 and #17717. This is slice 53 of the existing sleep stack, targeting master after parent #17734 merged at `a019d00a393b57f531afe8dd8ab0b8a1820d1c4c`. A current search found no duplicate accepted-result commit PR. **What problem does this solve?** Native accepted-result recovery currently depends on periodic orphan scanning. Quiet instances keep doing work to discover that no result needs a commit. **What improvement do you propose?** Use the shared delivery coordinator with transaction-bound producer signals. Reconstruct unfinished results at startup. Preserve saved retry and lease deadlines. Remove only uncommitted-result execution from the periodic pass. **Why is this useful?** The accepted-result worker becomes quiet with no work or retained completed history. Real results and completed workspace operations reactivate it without a polling delay. This does not claim that the whole server or database can sleep yet. ## What Changed - Track the initial result-commit sweep through shutdown without blocking HTTP readiness on recovery locks. - Keep ordinary company-only finalization hints from reconstructing dormant result work. Existing company settings and dedicated owner signals remain supported. - Add a native result-commit worker. Bind candidates by company, issue, run, accepted result and a successful workspace receipt. Exclude committed, terminal, held and pending-effect work. - Signal both accepted-result writers and workspace receipt writes before their transaction changes. Extend the existing finalization fanout for retry, lease, effect and completion transitions. - Add an optional atomic due-date check to the existing finalizer claim. A lease collision or later retry does not consume a failed attempt. - Signal native retry cancellation so it removes the saved wake after commit. - Register through the existing heartbeat suppression and shared delivery lifecycle. Preserve outer commit/rollback, drain/resume, settings activation and shutdown behavior. - Delegate only uncommitted-result execution from the periodic orphan pass. Keep committed projection and resource settlement recovery enabled. - Add real producer/lifecycle tests and a detailed audit. No new tables, provider branches or per-feature timers. ## Verification - Current local source `2af88fa55f961a74340880240019f6cd31e21bf1` incorporates the parent with a normal merge. All 1,203 parent-only, nine owned-only and 12 automatic shared paths are preserved. The only manual conflict keeps the new result fanout inside the existing ordinary issue/run scope guard. The complete package tree matches parent profile 80 byte-for-byte. - Controlled real-database regression: the original result-only unscoped fanout produces three candidate SELECTs for routine company hints. The same zero-query assertion passes after restoring the scoped fanout. A real workspace receipt and accepted result then commit exactly one decision and return to quiet. Red and green restore production bytes exactly. Twenty cases outside the focused pattern are not counted as passing there. - The complete main selection passes **1,746 cases in 16 files**, without skips, in 277.97 seconds. This includes all 21 result-worker lifecycle cases and 82 startup cases, including held result recovery, HTTP readiness and shutdown joining. Separate process recovery passes 410 cases in 162.42 seconds and external-chat response passes 273 in 53.41 seconds. Total: **2,429 distinct passes in 18 complete files**, with no skips. Normal merge `998239b019defe52e7b5d64f884de4e871ccd736` adopts the actual parent squash and preserves this complete tested child tree. - Production server typecheck, build, module boundaries, migration order and source identity checks pass. Fifteen dedicated PostgreSQL 17 databases use the unchanged migration 413 schema. Embedded-only calls use the existing fresh-per-call recovery helper. All temporary imports restore byte-exact, and every selected test hash matches after completion. No assertion or timeout is relaxed. - Runner validation belongs to the unchanged parent package tree: 130 passing installation/compatibility/transport cases, 22 installed ACPX/Grok contract cases and 26 native-provider Rust cases. One existing opt-in closed Pi snapshot case is skipped because its distribution root is not configured. This does not claim live provider qualification. - Earlier Greptile 4/5 on `656f6722be1aedf3d52b7f853956e15838204278` correctly identified startup blocking on result recovery. The prior branch `108cf0dc8296bf451b721ddac55ecbcd035d00f0` already tracks its ready promise through the existing lifecycle owner. Current full startup acceptance verifies the fix in the merged context. The later Greptile service error is not a pass; current-head acceptance now passes: all 57 checks are clean, including protected CI and security. Greptile gives 5/5 on `b2efdb2dbbbef5b2227ffa2bd2a9a6cfe3867fe2`, with no actionable findings. No Ponytail verdict is present under the authorized missing-review policy. - The owner audit at `doc/plans/2026-10-26-native-result-commit-sleep-audit.md` retains earlier failures and their disposition. These checks do not claim a full local repository suite, deployed app/database suspension, expanded Cloud wake coverage or measured cost savings. ## Risks - Process-local signals cover instrumented application writes in the owning server process. They do not cover independent SQL writers or another replica without supported ingress. Durable startup reconstruction remains enabled. - The initial native decision and its run projection are separate transactions. The periodic reconciler still repairs already-committed results and releases resources. This PR must not be used to infer that committed means fully settled. - Candidate discovery adds bounded, narrow reads at startup and after signals. No large-fleet query benchmark is claimed. - Existing Cloud alarm coverage, host sleep safety and resource blockers are unchanged. No deployed sleep or savings claim is made. - Parent #17734 has merged. This PR targets master at `a019d00a393b57f531afe8dd8ab0b8a1820d1c4c`. Fresh current-head CI and review remain required before merge. ## Model Used OpenAI Codex, GPT-6 family, with repository tools and code execution. The exact serving model ID and context-window size are not exposed in this session. No subagent was used for this slice. ## 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> Co-authored-by: Codex <noreply@openai.com>
319 lines
19 KiB
TypeScript
319 lines
19 KiB
TypeScript
import { notifyNativeResultCommit } from "../native-result-commit-notifications.js";
|
|
import { notifyNativeWorkspaceFinalization, releaseNativeWorkspaceFinalization } from "../native-workspace-finalization-notifications.js";
|
|
import { notifyNativeStatusReassessment } from "../native-status-reassessment-notifications.js";
|
|
import { beginRunPhase } from "../execution-preparation-timing.js";
|
|
import { logActivity } from "../activity-log.js";
|
|
import { issueRecoveryActionService } from "../issue-recovery-actions.js";
|
|
import { nativeSha256 } from "./canonical.js";
|
|
import { NATIVE_WORKSPACE_OWNER_UNVERIFIED } from "./native-workspace-finalization-recovery-state.js";
|
|
import { randomUUID } from "node:crypto";
|
|
import os from "node:os";
|
|
import { and, eq, inArray, sql } from "drizzle-orm";
|
|
import { heartbeatRuns, issues, issueRecoveryActions, nativeRunFinalizations, workspaceOperations, withDedicatedDbConnection, type Db } from "@paperclipai/db";
|
|
import { currentNativeWorkspaceRecoveryResult } from "./native-workspace-recovery-binding.js";
|
|
import { withWorkspaceLockKeepalive } from "./native-workspace-lock-keepalive.js";
|
|
import {
|
|
currentNativeControllerIdentity,
|
|
evaluateNativeControllerTakeover,
|
|
} from "./native-restart-recovery.js";
|
|
|
|
import { currentWorkspaceWorker, requestWorkspaceWorkerStopProof, type WorkspaceWorker, type WorkspaceWorkerStopProof } from "./native-workspace-platform-proof.js";
|
|
|
|
const OWNER_KEY = "nativeWorkspaceFinalizationOwner";
|
|
|
|
export function nativeWorkspaceFinalizationLockKey(companyId: string, runId: string): string {
|
|
return `native-workspace-finalization:${companyId}:${runId}`;
|
|
}
|
|
export async function tryLockNativeWorkspaceFinalization(tx: Db, input: { companyId: string; runId: string }): Promise<boolean> {
|
|
const [lock] = await tx.execute(sql`select pg_try_advisory_xact_lock(hashtextextended(
|
|
${nativeWorkspaceFinalizationLockKey(input.companyId, input.runId)}, 0)) as acquired`) as unknown as Array<{ acquired: boolean }>;
|
|
return lock.acquired;
|
|
}
|
|
|
|
const activeOwnerTokens = new Set<string>();
|
|
const activeRunOwners = new Map<string, { token: string; db: Db }>();
|
|
// Positive same-boot evidence, retained only when durable cleanup could not be
|
|
// confirmed. Absence from the active set alone never proves another token joined.
|
|
const joinedOwnerTokens = new Set<string>();
|
|
type Owner = {
|
|
token: string;
|
|
controllerBootId?: string;
|
|
hostname: string;
|
|
pid: number;
|
|
processStartedAt: string;
|
|
worker?: WorkspaceWorker;
|
|
};
|
|
export type NativeWorkspaceFinalizationWaitReason =
|
|
| "busy"
|
|
| "owner_active"
|
|
| "platform_stop_pending"
|
|
| "owner_unverified"
|
|
| "binding_changed";
|
|
|
|
export type NativeWorkspaceFinalizationOwnership = {
|
|
token: string;
|
|
/** Recheck both the physical lock connection and the durable owner before publishing. */
|
|
assertHeld(): Promise<void>;
|
|
};
|
|
export class NativeWorkspaceFinalizationBusyError extends Error {
|
|
constructor() { super("native_workspace_finalization_busy"); }
|
|
}
|
|
export class NativeWorkspaceFinalizationOwnershipLostError extends Error {
|
|
constructor(options?: ErrorOptions) {
|
|
super("native_workspace_finalization_ownership_lost", options);
|
|
}
|
|
}
|
|
|
|
function readOwner(value: unknown): Owner | null {
|
|
if (!value || typeof value !== "object") return null;
|
|
const owner = value as Partial<Owner>;
|
|
return typeof owner.token === "string" && typeof owner.hostname === "string"
|
|
&& Number.isInteger(owner.pid) && Number(owner.pid) > 0
|
|
&& typeof owner.processStartedAt === "string" && Number.isFinite(Date.parse(owner.processStartedAt))
|
|
? owner as Owner : null;
|
|
}
|
|
|
|
/**
|
|
* The advisory lock serializes controllers without holding row locks across I/O.
|
|
* The durable receipt additionally prevents a disconnected lock session from
|
|
* authorizing takeover while its controller is still doing physical copyback.
|
|
* There is deliberately no wall-clock timeout that can steal a slow export.
|
|
*/
|
|
export async function withNativeWorkspaceFinalizationOwnership<T>(
|
|
input: { db: Db; companyId: string; runId: string; retainedRepairActionId?: string },
|
|
action: (ownership: NativeWorkspaceFinalizationOwnership) => Promise<T>,
|
|
): Promise<{ acquired: false; reason: NativeWorkspaceFinalizationWaitReason } | { acquired: true; value: T }> {
|
|
const identity = await currentNativeControllerIdentity();
|
|
const owner: Owner = {
|
|
token: randomUUID(), controllerBootId: identity.bootId, hostname: os.hostname(), pid: identity.pid,
|
|
processStartedAt: identity.processStartedAt.toISOString(), worker: currentWorkspaceWorker(),
|
|
};
|
|
const scope = and(eq(heartbeatRuns.id, input.runId), eq(heartbeatRuns.companyId, input.companyId),
|
|
input.retainedRepairActionId ? inArray(heartbeatRuns.runtimeMode, ["native", "legacy"]) : eq(heartbeatRuns.runtimeMode, "native"));
|
|
const owned = and(scope, sql`${heartbeatRuns.runnerProfileJson}->${OWNER_KEY}->>'token' = ${owner.token}`);
|
|
const runKey = nativeWorkspaceFinalizationLockKey(input.companyId, input.runId);
|
|
let claimed = false;
|
|
let actionPromise: Promise<T> | undefined;
|
|
const finishAcquisition = beginRunPhase("execution.workspace_ownership_wait");
|
|
try {
|
|
return await withDedicatedDbConnection(input.db, (dedicated) => dedicated.transaction(async (lock) => {
|
|
const rows = await lock.execute(sql`select pg_try_advisory_xact_lock(hashtextextended(${nativeWorkspaceFinalizationLockKey(input.companyId, input.runId)}, 0)) as acquired,
|
|
(select setting::bigint from pg_settings where name = 'idle_in_transaction_session_timeout') as idle_timeout_ms`);
|
|
if (rows[0]?.acquired !== true) return {
|
|
acquired: false,
|
|
reason: !input.retainedRepairActionId && activeRunOwners.get(runKey)?.db === input.db ? "owner_active" : "busy",
|
|
} as const;
|
|
return withWorkspaceLockKeepalive(lock as unknown as Db, Number(rows[0].idle_timeout_ms), async () => {
|
|
// Reads and durable progress use the ordinary pool, not the lock transaction.
|
|
const [run] = await input.db.select({ profile: heartbeatRuns.runnerProfileJson,
|
|
issueId: sql<string | null>`coalesce(${heartbeatRuns.nativeIssueId}::text, ${heartbeatRuns.issueId}::text, ${heartbeatRuns.contextSnapshot}->>'issueId')`,
|
|
agentId: heartbeatRuns.agentId }).from(heartbeatRuns).where(scope).limit(1);
|
|
if (!run) throw new Error("native_workspace_finalization_binding_missing");
|
|
const rawPrior = run.profile?.[OWNER_KEY];
|
|
const prior = readOwner(rawPrior);
|
|
let automaticResultId: string | undefined;
|
|
const currentRecoveryResult = async (db: Db) => {
|
|
if (!run.issueId) return null;
|
|
// Use the arbiter's lock order and release row locks before copyback I/O.
|
|
const [coordinator] = await db.select().from(nativeRunFinalizations).where(and(
|
|
eq(nativeRunFinalizations.companyId, input.companyId), eq(nativeRunFinalizations.runId, input.runId),
|
|
eq(nativeRunFinalizations.issueId, run.issueId),
|
|
)).for("update");
|
|
const [issue] = await db.select().from(issues).where(and(
|
|
eq(issues.companyId, input.companyId), eq(issues.id, run.issueId),
|
|
)).for("update");
|
|
const [currentRun] = await db.select().from(heartbeatRuns).where(scope).for("update");
|
|
if (input.retainedRepairActionId) {
|
|
const [repair] = await db.select().from(issueRecoveryActions).where(and(
|
|
eq(issueRecoveryActions.companyId, input.companyId), eq(issueRecoveryActions.sourceIssueId, run.issueId),
|
|
eq(issueRecoveryActions.id, input.retainedRepairActionId),
|
|
)).for("update");
|
|
const continuation = repair?.evidence.explicitUserContinuation as {
|
|
runId?: string; readiness?: { mode?: string; sourceRunId?: string };
|
|
} | undefined;
|
|
const independentRun = continuation?.readiness?.mode === "fresh_isolated_workspace"
|
|
&& continuation.readiness.sourceRunId === input.runId ? continuation.runId : undefined;
|
|
return currentRun && issue && repair && repair.evidence.runId === currentRun.id
|
|
&& repair.evidence.workspaceRecovery && !coordinator?.leaseOwner
|
|
&& ["failed", "interrupted", "timed_out", "cancelled", "succeeded"].includes(currentRun.status)
|
|
&& (!issue.executionRunId || issue.executionRunId === independentRun)
|
|
&& (!issue.checkoutRunId || issue.checkoutRunId === independentRun) ? repair : null;
|
|
}
|
|
return coordinator && issue && currentRun ? currentNativeWorkspaceRecoveryResult(db, {
|
|
companyId: input.companyId, coordinator, issue, run: currentRun,
|
|
}) : null;
|
|
};
|
|
let platformProof: WorkspaceWorkerStopProof | null = null;
|
|
let platformStopPending = false;
|
|
if (rawPrior != null) {
|
|
const requireStopVerification = async () => {
|
|
if (input.retainedRepairActionId) return { acquired: false, reason: "owner_unverified" } as const;
|
|
const fingerprint = nativeSha256({ runId: input.runId, owner: rawPrior });
|
|
const nextAction = "Verify the previous controller and its workspace-copyback processes have stopped, then release only this exact workspace owner receipt using doc/native-workspace-finalization-recovery.md. Resume workspace finalization without another provider turn.";
|
|
const recovery = issueRecoveryActionService(input.db);
|
|
const existing = run.issueId ? await recovery.getActiveForIssue(input.companyId, run.issueId) : null;
|
|
// Rechecking the same physical owner is not a new recovery attempt.
|
|
if (existing?.cause === NATIVE_WORKSPACE_OWNER_UNVERIFIED && existing.fingerprint === fingerprint) {
|
|
if (!existing.evidence?.workspaceOwnerStop) {
|
|
await input.db.update(issueRecoveryActions).set({ nextAction, updatedAt: new Date(),
|
|
evidence: sql`jsonb_set(coalesce(${issueRecoveryActions.evidence}, '{}'::jsonb), '{workspaceOwnerRecovery}', '{"state":"operator_required"}'::jsonb)`,
|
|
}).where(and(
|
|
eq(issueRecoveryActions.companyId, input.companyId), eq(issueRecoveryActions.id, existing.id),
|
|
eq(issueRecoveryActions.fingerprint, fingerprint), eq(issueRecoveryActions.cause, NATIVE_WORKSPACE_OWNER_UNVERIFIED),
|
|
inArray(issueRecoveryActions.status, ["active", "escalated"]),
|
|
sql`${issueRecoveryActions.evidence}->'workspaceOwnerStop' is null`,
|
|
sql`(${issueRecoveryActions.nextAction} is distinct from ${nextAction} or ${issueRecoveryActions.evidence}#>>'{workspaceOwnerRecovery,state}' is distinct from 'operator_required')`,
|
|
));
|
|
}
|
|
return { acquired: false, reason: platformStopPending ? "platform_stop_pending" : "owner_unverified" } as const;
|
|
}
|
|
if (run.issueId) await recovery.upsertSourceScoped({
|
|
companyId: input.companyId, sourceIssueId: run.issueId,
|
|
kind: "active_run_watchdog", ownerType: "board", returnOwnerAgentId: run.agentId,
|
|
cause: NATIVE_WORKSPACE_OWNER_UNVERIFIED,
|
|
fingerprint,
|
|
evidence: { runId: input.runId, owner: rawPrior, workspaceOwnerRecovery: { state: "operator_required" } },
|
|
nextAction,
|
|
wakePolicy: null, maxAttempts: 1, supersedeOnIdentityChange: true,
|
|
});
|
|
return { acquired: false, reason: platformStopPending ? "platform_stop_pending" : "owner_unverified" } as const;
|
|
};
|
|
// The harness checks the exact owned deployment, including orphaned children.
|
|
// A live deployment, unsigned answer or older receipt stays fenced.
|
|
if (prior?.controllerBootId === identity.bootId && prior.pid === identity.pid
|
|
&& activeOwnerTokens.has(prior.token)) {
|
|
return { acquired: false, reason: input.retainedRepairActionId ? "owner_unverified"
|
|
: activeRunOwners.get(runKey)?.db === input.db ? "owner_active" : "busy" } as const;
|
|
}
|
|
if (prior?.worker) {
|
|
const check = await requestWorkspaceWorkerStopProof({ runId: input.runId, ownerToken: prior.token, worker: prior.worker });
|
|
platformProof = check.status === "verified" ? check.proof : null;
|
|
platformStopPending = check.status === "pending";
|
|
}
|
|
if (!prior) return requireStopVerification();
|
|
if (!platformProof && prior.hostname !== owner.hostname) return requireStopVerification();
|
|
const knownJoinedHere = prior.controllerBootId === identity.bootId
|
|
&& prior.pid === identity.pid && joinedOwnerTokens.has(prior.token)
|
|
&& !activeOwnerTokens.has(prior.token);
|
|
if (!platformProof && !knownJoinedHere) {
|
|
const takeover = await evaluateNativeControllerTakeover({
|
|
owner: { leaseOwner: prior.token, leaseExpiresAt: new Date(0), controllerPid: prior.pid,
|
|
controllerProcessStartedAt: new Date(prior.processStartedAt) }, now: new Date(),
|
|
});
|
|
if (!takeover.allowed) return requireStopVerification();
|
|
// A dead parent may have orphaned tar/Git children. Only a durable
|
|
// completed-copyback barrier proves they joined; otherwise board proof
|
|
// is required even on the same host. Both callers reuse this barrier.
|
|
const [completedCopyback] = await input.db.select({ id: workspaceOperations.id }).from(workspaceOperations).where(and(
|
|
eq(workspaceOperations.companyId, input.companyId),
|
|
eq(workspaceOperations.heartbeatRunId, input.runId),
|
|
eq(workspaceOperations.issueId, run.issueId!),
|
|
eq(workspaceOperations.phase, "workspace_finalize"),
|
|
eq(workspaceOperations.status, "succeeded"),
|
|
)).limit(1);
|
|
if (!completedCopyback) return requireStopVerification();
|
|
}
|
|
}
|
|
// Claim before the potentially ambiguous write so finally can remove
|
|
// only our token even if the server committed but its response was lost.
|
|
const claimOwner = async (db: Db) => {
|
|
activeOwnerTokens.add(owner.token);
|
|
activeRunOwners.set(runKey, { token: owner.token, db: input.db });
|
|
claimed = true;
|
|
const [claimedRun] = await db.update(heartbeatRuns).set({
|
|
runnerProfileJson: sql`jsonb_set(coalesce(${heartbeatRuns.runnerProfileJson}, '{}'::jsonb), array[${OWNER_KEY}], ${JSON.stringify(owner)}::jsonb) || ${JSON.stringify(platformProof ? { nativeWorkspaceOwnerStopProof: platformProof } : {})}::jsonb`,
|
|
}).where(and(scope, prior
|
|
? sql`${heartbeatRuns.runnerProfileJson}->${OWNER_KEY} = ${JSON.stringify(rawPrior)}::jsonb`
|
|
: sql`${heartbeatRuns.runnerProfileJson}->>${OWNER_KEY} is null`
|
|
)).returning({ id: heartbeatRuns.id });
|
|
return claimedRun;
|
|
};
|
|
// A stop receipt proves the old worker exited, not that its task is still
|
|
// current. Revalidate after the provider read and atomically with the CAS.
|
|
const claimedRun = platformProof ? await input.db.transaction(async tx => {
|
|
const result = await currentRecoveryResult(tx as unknown as Db);
|
|
if (!result) return null;
|
|
const claimedRun = await claimOwner(tx as unknown as Db);
|
|
if (claimedRun) automaticResultId = result.id;
|
|
return claimedRun;
|
|
}) : await claimOwner(input.db);
|
|
if (!claimedRun) {
|
|
|
|
|
|
activeOwnerTokens.delete(owner.token);
|
|
if (activeRunOwners.get(runKey)?.token === owner.token) activeRunOwners.delete(runKey);
|
|
claimed = false;
|
|
return { acquired: false, reason: "binding_changed" } as const;
|
|
}
|
|
if (platformProof && run.issueId) await logActivity(input.db, {
|
|
companyId: input.companyId, actorType: "system", actorId: "workspace-recovery",
|
|
action: "issue.workspace_owner_stop_verified", entityType: "issue", entityId: run.issueId,
|
|
runId: input.runId, details: { proof: platformProof },
|
|
});
|
|
if (prior) joinedOwnerTokens.delete(prior.token);
|
|
const ownership: NativeWorkspaceFinalizationOwnership = {
|
|
token: owner.token,
|
|
assertHeld: async () => {
|
|
try {
|
|
// A failed transaction is never transparently reconnected by the DB client.
|
|
await lock.execute(sql`select 1`);
|
|
const [current] = await input.db.select({ id: heartbeatRuns.id }).from(heartbeatRuns).where(owned).limit(1);
|
|
if (!current) throw new Error("owner_replaced");
|
|
if (automaticResultId) {
|
|
const result = await input.db.transaction(tx => currentRecoveryResult(tx as unknown as Db));
|
|
if (result?.id !== automaticResultId) throw new Error("task_replaced");
|
|
}
|
|
} catch (cause) {
|
|
throw new NativeWorkspaceFinalizationOwnershipLostError({ cause });
|
|
}
|
|
},
|
|
};
|
|
await ownership.assertHeld();
|
|
if (platformProof && run.issueId) await input.db.update(issueRecoveryActions).set({
|
|
evidence: sql`jsonb_set(coalesce(${issueRecoveryActions.evidence}, '{}'::jsonb), '{workspaceOwnerRecovery}', '{"state":"resuming"}'::jsonb)`,
|
|
updatedAt: new Date(),
|
|
}).where(and(
|
|
eq(issueRecoveryActions.companyId, input.companyId), eq(issueRecoveryActions.sourceIssueId, run.issueId),
|
|
eq(issueRecoveryActions.cause, NATIVE_WORKSPACE_OWNER_UNVERIFIED),
|
|
eq(issueRecoveryActions.fingerprint, nativeSha256({ runId: input.runId, owner: rawPrior })),
|
|
inArray(issueRecoveryActions.status, ["active", "escalated"]),
|
|
));
|
|
finishAcquisition();
|
|
actionPromise = action(ownership);
|
|
const value = await actionPromise;
|
|
await ownership.assertHeld();
|
|
return { acquired: true, value } as const;
|
|
});
|
|
}));
|
|
} catch (error) {
|
|
finishAcquisition(true);
|
|
throw error;
|
|
} finally {
|
|
finishAcquisition();
|
|
// postgres.js may reject the transaction when the socket dies before the
|
|
// callback settles. Join that callback before releasing its durable fence.
|
|
await actionPromise?.catch(() => undefined);
|
|
if (claimed) {
|
|
activeOwnerTokens.delete(owner.token);
|
|
if (activeRunOwners.get(runKey)?.token === owner.token) activeRunOwners.delete(runKey);
|
|
joinedOwnerTokens.add(owner.token);
|
|
try {
|
|
await input.db.transaction(async tx => {
|
|
await notifyNativeResultCommit(tx, { companyId: input.companyId, runId: input.runId });
|
|
await notifyNativeWorkspaceFinalization(tx, { companyId: input.companyId, runId: input.runId });
|
|
await notifyNativeStatusReassessment(tx, { companyId: input.companyId, runId: input.runId });
|
|
await tx.update(heartbeatRuns).set({
|
|
runnerProfileJson: sql`coalesce(${heartbeatRuns.runnerProfileJson}, '{}'::jsonb) - ${OWNER_KEY}`,
|
|
}).where(owned);
|
|
});
|
|
joinedOwnerTokens.delete(owner.token);
|
|
} catch {
|
|
// A reconnect in this exact controller boot can use the positive join
|
|
// receipt. A new boot still needs durable barrier or operator proof.
|
|
} finally {
|
|
releaseNativeWorkspaceFinalization(input.db, { companyId: input.companyId, runId: input.runId });
|
|
}
|
|
}
|
|
}
|
|
}
|