mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-25 16:14:26 +01:00
## Thinking Path > - Paperclip lets people start and stop work by AI agents. > - Stop must end the current turn and preserve the task for a later message. > - A person can press Stop while the server still prepares the turn. > - The preparation owner can prove that no model work started. > - That path saved the proof but left the Stop receipt at `requested`. > - The page then reported an unverified Stop and a failed attempt. > - This PR completes the receipt after proof and shows the confirmed Stop without a failure notice. ## Linked Issues or Issue Description **What happened?** A person submits a task by mistake and presses Stop during preparation. The run ends before the adapter starts. The server records that no provider work started, but the Stop receipt stays at `requested`. The page waits for a receipt that will never change. It then reports that it cannot verify Stop. The task also shows a failed-attempt notice. **Expected behavior** Stop ends the current turn without a failure notice. A later message starts one new turn through normal admission. Stop does not restart the task by itself. **Steps to reproduce** Hold session preparation before adapter dispatch. Press Stop through the run API. Release preparation and wait for the owner to finish. Read the run and the task's interruption state. Send a new task comment. Related: #20644 covers saved Retry after a committed native cancellation. #21382 covers a provider failure after native Stop. This PR covers Stop before adapter dispatch and its page presentation. ## What Changed - Complete the Stop receipt in `settleCancelledLegacyPreparation`. Keep its existing checks for process, session, events, leases and saved files. - Require no saved `budgetDispatch.handedOffAt` marker under the run lock. This marker can exist before an adapter records its start. A stale controller must keep the recovery hold after this handoff. - Write and require the `preparation_settled` proof before clearing the failed-attempt notice. Both page queries use one bounded SQL projection. Unknown and foreign proof labels keep the notice. - Clear an obsolete automatic-recovery marker only for a user's operator Stop. Keep system cancellation delivery metadata so saved comments still reach admission. Cover both cases with persisted recovery records and the stale-comment journey. - Give the bounded SQL result an explicit column name. Keep its real-query tests for typed and bounded Stop evidence. - Give the Retry test an active company membership and remove it during cleanup. The test uses normal authorization. - Record an expected cancellation as information in the run log. - Add a regression through the real Stop, run-read and comment routes with a real test database. Only the adapter boundary is simulated. Check that preparation cannot confirm Stop early, Stop does not restart work, and one later message starts one turn. - Document preparation Stop settlement in the heartbeat module notes. ## Verification - Head: `372ad381f4b60258e17b6b05eda133ed875e7de3`. This revision includes master `20b0d4e5a5`. [Full CI attempt 2](https://github.com/paperclipai/paperclip/actions/runs/43910771322/attempts/2) completed successfully: all 52 executed jobs passed, including Build, Typecheck, all Runner lanes, all nine serialized suites, all twelve server shards and all eight browser shards. Greptile and Paperclip Review are both 5/5, and Superagent passed on this exact head. All three inline threads are resolved. The final commit inventory has 57 successful checks, one neutral review and three expected skips, with no pending or failing checks; Snyk also passed. - All 339 focused tests pass at this head across 11 suites. The Stop, saved-comment and fresh-continuation suites pass 132 tests. Eight other Stop contract suites pass 207 tests. - Red: the preparation regression receives `executionCancellation.state = requested` after the owner finishes. The presentation regressions report a failed attempt after a confirmed Stop. - Red: automatic recovery resolves the hold first, then preparation confirms Stop, but the run still shows a recovery notice. Green: the confirmed operator Stop clears the obsolete marker and projects `completed` / `Stopped`. - Red: the previous repair also changed system cancellations. Both stale-comment and Retry cases pass on the base and fail on the previous PR head. A direct regression also catches a preparation Stop receipt written for a system cancellation. Green: only a user's operator Stop gets this receipt; system cancellations keep their recovery delivery metadata. - Red: the real-query tests read PostgreSQL's implicit expression-column name after the expression changed. Green: the query has the explicit `result_json` alias, and all typed and bounded evidence assertions pass. - Red: a saved dispatch handoff marker was present before any adapter event. Both new cases returned an acknowledged Stop instead of keeping the hold. Green: the current locked row must have no marker, including a marker with JSON null. The receipt stays requested and the hold stays active. The tests use a stale owner snapshot. - The HTTP Stop/read/comment test uses real routes and PostgreSQL. It proves that pending preparation cannot confirm Stop, the owner confirms it after cleanup, Stop does not restart work, and a later message starts exactly one turn. Only the adapter boundary is simulated. - All source typecheck layers and the changed `test-tree-0` layer pass in low-memory mode. The first full typecheck attempt lost the compiler to the workspace memory limit while tests ran in parallel. The affected layers then passed alone. Other test layers passed on the previous head. The full current-head CI Typecheck + Release Registry job passed. `git diff --check` passes. - `pnpm verify` returned exit 2 and requested broader CI. No full local suite was started. - Environment: Linux x64, Node 25.9.0, fresh embedded PostgreSQL. This does not execute a live model or change staging. CI supplies Rust and full-suite coverage. - Previous-head CI found the SQL assertion and continuation regressions above. Its cancelled workspace lane lost its runner before a test result and was retried once. Previous-head results do not count as final-head passes. ## Risks - Only a requested, expected operator Stop with an acknowledged receipt gets neutral presentation. Unknown termination and file recovery remain visible. - The preparation owner writes acknowledgement only after all existing evidence checks pass. Terminal status alone is insufficient. A retained local lease test checks both refusal before release and confirmation after release. - The receipt does not grant replay authority. Budget, approval, dependency and cleanup gates still control later messages. - No schema or migration changes are required. ## Model Used OpenAI Codex, GPT-6, with reasoning and code tools. The exact served model build and context size are not exposed in this session. ## 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>
192 lines
11 KiB
TypeScript
192 lines
11 KiB
TypeScript
import type { heartbeatRuns } from "@paperclipai/db";
|
|
import { sql, type SQLWrapper } from "drizzle-orm";
|
|
|
|
type Run = Pick<typeof heartbeatRuns.$inferSelect, "status" | "startedAt" | "finishedAt" | "runtimeMode" | "errorCode" | "error" | "resultJson">;
|
|
const SOURCES = ["operator", "queued_message", "shutdown", "provider", "transport", "control_plane", "controller_lease", "unknown"] as const;
|
|
export type CancellationSource = typeof SOURCES[number];
|
|
export interface RunCancellation {
|
|
source: CancellationSource;
|
|
expected: boolean;
|
|
initiator: { type: "user" | "agent" | "system" | "provider"; id?: string };
|
|
reason: string;
|
|
recordedAt: string;
|
|
}
|
|
|
|
/** Server-owned local evidence. Sentry receives only the closed labels below. */
|
|
export function readRunCancellation(result: Run["resultJson"] | undefined): RunCancellation | null {
|
|
const value = result?.cancellation;
|
|
if (!value || typeof value !== "object" || Array.isArray(value)) return null;
|
|
const entry = value as Record<string, unknown>;
|
|
const initiator = entry.initiator as Record<string, unknown> | undefined;
|
|
if (!SOURCES.includes(entry.source as CancellationSource) || typeof entry.expected !== "boolean" ||
|
|
!initiator || !["user", "agent", "system", "provider"].includes(initiator.type as string) ||
|
|
typeof entry.reason !== "string" || typeof entry.recordedAt !== "string") return null;
|
|
return { source: entry.source as CancellationSource, expected: entry.expected,
|
|
initiator: { type: initiator.type as RunCancellation["initiator"]["type"],
|
|
...(typeof initiator.id === "string" ? { id: initiator.id } : {}) },
|
|
reason: entry.reason.slice(0, 512), recordedAt: entry.recordedAt };
|
|
}
|
|
|
|
export function requestedRunCancellation(result: Run["resultJson"], reason: string): RunCancellation {
|
|
const queued = typeof result?.queuedCommentInterruptQueueId === "string";
|
|
const actorType = result?.cancelledByActorType ?? result?.interruptedByActorType;
|
|
const user = actorType === "user" || actorType === "board" || typeof result?.cancelledByUserId === "string";
|
|
const agent = actorType === "agent";
|
|
const actorId = result?.cancelledByUserId ?? result?.cancelledByAgentId ?? result?.interruptedByActorId;
|
|
const source: CancellationSource = queued ? "queued_message" : user ? "operator" : "control_plane";
|
|
return { source, expected: true, initiator: {
|
|
type: user ? "user" : agent ? "agent" : "system",
|
|
...(typeof actorId === "string" ? { id: actorId } : {}),
|
|
}, reason: reason.slice(0, 512), recordedAt: new Date().toISOString() };
|
|
}
|
|
|
|
const LEGACY_CONTROLLER_LEASE_LOSS_CAUSES = ["renewal_rejected", "renewal_deadline", "renewal_error"] as const;
|
|
export type LegacyControllerLeaseLossCause = typeof LEGACY_CONTROLLER_LEASE_LOSS_CAUSES[number];
|
|
const controllerLeaseLossReason = (cause: LegacyControllerLeaseLossCause) => `Legacy controller lease lost (${cause})`;
|
|
|
|
/** The host aborted its own adapter after losing durable run ownership. */
|
|
export function controllerLeaseLossCancellation(cause: LegacyControllerLeaseLossCause): RunCancellation {
|
|
return { source: "controller_lease", expected: false, initiator: { type: "system" },
|
|
reason: controllerLeaseLossReason(cause), recordedAt: new Date().toISOString() };
|
|
}
|
|
|
|
/** Closed cause label for diagnostics; only the server-written reason matches. */
|
|
export function readControllerLeaseLossCause(cancellation: RunCancellation): LegacyControllerLeaseLossCause | null {
|
|
if (cancellation.source !== "controller_lease") return null;
|
|
return LEGACY_CONTROLLER_LEASE_LOSS_CAUSES.find(cause => cancellation.reason === controllerLeaseLossReason(cause)) ?? null;
|
|
}
|
|
|
|
/** Watchdog timings at the moment the lease was lost, in milliseconds. */
|
|
export interface LegacyControllerLeaseLossTiming {
|
|
sinceRenewalMs: number;
|
|
renewalPendingMs: number | null;
|
|
deadlineLateMs: number | null;
|
|
renewalCount: number;
|
|
}
|
|
/** Read-side record: a `null` timing is dropped, so every present timing is a number. */
|
|
export type LegacyControllerLeaseLoss = { cause: LegacyControllerLeaseLossCause }
|
|
& Partial<Record<keyof LegacyControllerLeaseLossTiming, number>>;
|
|
|
|
const MAX_LEASE_LOSS_TIMING = 86_400_000;
|
|
const leaseLossTimingValue = (value: unknown) =>
|
|
typeof value === "number" && Number.isFinite(value) && value >= 0
|
|
? Math.min(Math.round(value), MAX_LEASE_LOSS_TIMING) : undefined;
|
|
|
|
/** Closed cause and bounded counters only; unknown keys and values are dropped. */
|
|
export function readControllerLeaseLoss(value: unknown): LegacyControllerLeaseLoss | null {
|
|
if (!value || typeof value !== "object") return null;
|
|
const record = value as Record<string, unknown>;
|
|
const cause = LEGACY_CONTROLLER_LEASE_LOSS_CAUSES.find(label => label === record.cause);
|
|
if (!cause) return null;
|
|
const loss: LegacyControllerLeaseLoss = { cause };
|
|
for (const field of ["sinceRenewalMs", "renewalPendingMs", "deadlineLateMs", "renewalCount"] as const) {
|
|
const timing = leaseLossTimingValue(record[field]);
|
|
if (timing !== undefined) loss[field] = timing;
|
|
}
|
|
return loss;
|
|
}
|
|
|
|
/** A queue admission wait has no provider attempt to retry. Historical rows can
|
|
* carry unknown cancellation provenance, so use the queue's original receipt. */
|
|
export function isQueuedDependencyWait(run: Pick<Run, "status" | "errorCode" | "resultJson"> & Partial<Pick<Run, "runtimeMode" | "startedAt">>): boolean {
|
|
const source = run.resultJson?.timeoutSource;
|
|
const queueReceipt = (source === "dependency_gate" && run.runtimeMode === "legacy") ||
|
|
(source === "stale_queued_run_gate" && (run.runtimeMode === "legacy" || run.runtimeMode === "native"));
|
|
return run.status === "cancelled" && queueReceipt && run.startedAt === null &&
|
|
run.errorCode === "issue_dependencies_blocked" && run.resultJson?.stopReason === run.errorCode &&
|
|
run.resultJson?.timeoutFired !== true;
|
|
}
|
|
|
|
/** Preserve recorded stop intent when adapter completion replaces resultJson. */
|
|
export function cancellationResultJson(run: Run, status: string, patch?: Run["resultJson"], errorCode?: string | null, error?: string | null): Run["resultJson"] {
|
|
if (status !== "cancelled" && status !== "interrupted") return patch ?? run.resultJson;
|
|
const result = { ...run.resultJson, ...patch };
|
|
const previous = readRunCancellation(run.resultJson);
|
|
let cancellation = previous?.expected ? previous : readRunCancellation(patch) ?? previous;
|
|
const code = errorCode ?? run.errorCode;
|
|
if (!cancellation) {
|
|
if (isQueuedDependencyWait({ ...run, status, errorCode: code, resultJson: result })) {
|
|
cancellation = requestedRunCancellation(result, "Waiting for task dependencies to resolve");
|
|
} else if (code === "server_shutdown_interrupted") {
|
|
cancellation = { source: "shutdown", expected: true, initiator: { type: "system" },
|
|
reason: "Server shutdown interrupted execution", recordedAt: new Date().toISOString() };
|
|
} else if (result.cancelledByActorType || result.cancelledByUserId || result.interruptedByActorType || result.queuedCommentInterruptQueueId) {
|
|
cancellation = requestedRunCancellation(result, error ?? run.error ?? "Execution stopped");
|
|
} else {
|
|
const source = code === "duplex_channel_lost" ? "transport" : result.status === "cancelled" ? "provider" : "unknown";
|
|
const description = source === "provider" ? "Provider cancelled execution"
|
|
: source === "transport" ? "Connection to the execution provider was lost"
|
|
: "Execution stopped without a recorded cancellation request";
|
|
const detail = error ?? run.error;
|
|
cancellation = { source, expected: false, initiator: { type: source === "provider" ? "provider" : "system" },
|
|
reason: (!detail || /^cancelled\.?$/i.test(detail) ? description : `${description}: ${detail}`).slice(0, 512),
|
|
recordedAt: new Date().toISOString() };
|
|
}
|
|
}
|
|
return { ...result, cancellation };
|
|
}
|
|
|
|
/** Eligibility only; admission still verifies process/lease shutdown and gates.
|
|
* Historical ambiguous cancellations and outstanding tools stay held.
|
|
*/
|
|
export function canContinueCancelledRun(run: Run): boolean {
|
|
const cancellation = readRunCancellation(run.resultJson);
|
|
return run.status === "cancelled" && run.runtimeMode === "legacy" && Boolean(run.startedAt && run.finishedAt) &&
|
|
cancellation?.expected === false && ["provider", "transport"].includes(cancellation.source) &&
|
|
run.resultJson?.acpToolInventoryComplete === true && run.resultJson?.acpPendingToolCount === 0;
|
|
}
|
|
|
|
/** The user's recorded Stop or interrupt on a settled run. A stopped native
|
|
* run whose runner was unreachable can settle as `failed` once its transport
|
|
* fails closed; the user's Stop request still bounds which messages are new. */
|
|
export function recordedUserStop(run: Pick<Run, "status" | "resultJson">) {
|
|
if (run.status !== "cancelled" && run.status !== "failed") return null;
|
|
const cancellation = readRunCancellation(run.resultJson);
|
|
return cancellation && cancellation.initiator.type === "user" &&
|
|
["operator", "queued_message"].includes(cancellation.source) ? cancellation : null;
|
|
}
|
|
|
|
/** Presentation of a settled operator Stop; this does not grant replay authority. */
|
|
export function isAcknowledgedLegacyUserStop(run: Pick<Run, "status" | "resultJson"> & Partial<Pick<Run, "runtimeMode" | "finishedAt">>): boolean {
|
|
const cancellation = recordedUserStop(run);
|
|
const receipt = run.resultJson?.executionCancellation as Record<string, unknown> | undefined;
|
|
return run.status === "cancelled" && run.runtimeMode === "legacy" && Boolean(run.finishedAt)
|
|
&& cancellation?.source === "operator" && cancellation.expected
|
|
&& receipt?.state === "acknowledged" && receipt.proof === "preparation_settled";
|
|
}
|
|
|
|
/** The same bounded Stop evidence for both task-page projections. */
|
|
export function runStopPresentationJson(result: SQLWrapper) {
|
|
return sql<Record<string, unknown>>`jsonb_build_object(
|
|
'cancellation', jsonb_build_object(
|
|
'source', left(${result}->'cancellation'->>'source', 32),
|
|
'expected', ${result}->'cancellation'->'expected',
|
|
'initiator', jsonb_build_object('type', left(${result}->'cancellation'->'initiator'->>'type', 32)),
|
|
'reason', left(${result}->'cancellation'->>'reason', 512),
|
|
'recordedAt', left(${result}->'cancellation'->>'recordedAt', 64)),
|
|
'executionCancellation', jsonb_build_object(
|
|
'state', left(${result}->'executionCancellation'->>'state', 32),
|
|
'proof', left(${result}->'executionCancellation'->>'proof', 64)))`;
|
|
}
|
|
|
|
/** When a user's Stop or interrupt took effect for message ordering. A native
|
|
* run finishes only after its provider stop and workspace save settle, which
|
|
* can take many seconds. A message written after the Stop request is a new
|
|
* direction even when that settlement finished later, so compare against the
|
|
* recorded request rather than `finishedAt`. Other cancellations keep
|
|
* `finishedAt`. */
|
|
export function userStopBoundaryAt(run: Pick<Run, "status" | "finishedAt" | "resultJson">): Date | null {
|
|
if (!run.finishedAt) return null;
|
|
const cancellation = recordedUserStop(run);
|
|
if (!cancellation) return run.finishedAt;
|
|
const requestedAt = new Date(cancellation.recordedAt);
|
|
return Number.isFinite(requestedAt.getTime()) && requestedAt < run.finishedAt ? requestedAt : run.finishedAt;
|
|
}
|
|
|
|
export function isUnexpectedRunCancellation(run: Run): boolean {
|
|
const bootstrap = run.resultJson?.executionRecovery as Record<string, unknown> | undefined;
|
|
return run.status === "cancelled" && Boolean(run.startedAt) &&
|
|
!(bootstrap?.kind === "bootstrap" && bootstrap.providerWorkStarted === false) &&
|
|
readRunCancellation(run.resultJson)?.expected !== true;
|
|
}
|