mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-16 20:12:20 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The native runtime releases owners of failed runs. When the owner's controller is in a process space that Paperclip cannot verify, it shows controller namespace attention on the task instead. > - On a hosted instance with zero active runs, this writer made about 21% of all work signals. It inserted a new active attention row for the same task about every 26 seconds. > - The tasks were already done or cancelled. Recovery resolved each row as `source_terminal`. The active slot was then free, so the next owner-release pass inserted a new row and published a graph recovery signal again. The loop did not stop. > - A live task had the same defect: after the fresh-continuation fallback resolved its attention, the next pass made the same incident again. > - This pull request stops the writer from surfacing attention for finished tasks. It also stops the writer from making an incident again when that run authority was resolved after its lease expired. Those owners are no longer release candidates and do not set the release deadline. > - The benefit is that an idle instance does not write or publish anything for these runs. Attention still shows once for a live task. ## Linked Issues or Issue Description **What happened?** The failed-run owner release (`settleFailedRunOwner`, expired-owner path) called `surfaceNativeControllerNamespaceAttention` for every expired foreign owner that had no active attention. It did this even when the source task was `done` or `cancelled`. Recovery resolved that attention as `source_terminal`. The next pass found no active attention and inserted a new board row. Each insert published `notifyIssueGraphRecovery` and the other execution-control signals. The stranded-task check then ran again for the task graph. A hosted instance collected about 45,000 rows on 13 finished tasks in this way. **Expected behavior** A pass that changes nothing writes nothing and publishes nothing. A finished task never gets controller namespace attention. A live task gets one incident for each exact run authority. A resolved incident stays resolved until the authority changes. **Steps to reproduce** 1. Make a native run that failed, with an `observed` coordinator whose foreign lease has expired and whose controller host is not recorded. 2. Mark the task done or cancelled, or let the fresh-continuation fallback resolve the attention of a live task. 3. Run the execution-finalization worker with the issue recovery workers for 30 minutes. 4. On master, each task gets about 40 to 60 new attention rows. The writer publishes thousands of signals. ## What Changed - `surfaceNativeControllerNamespaceAttention` (shared helper): before it creates attention, it checks for a resolved incident for this run that was resolved at or after the owner's current lease expiry. If one exists, it writes nothing. - New `settledNativeControllerNamespaceAttention` SQL predicate. It is shared by the helper, the release candidate page, and the release deadline query, so all three use the same rule. - `settleFailedRunOwner` (expired-owner path) does not surface attention when the task is `done` or `cancelled`. The restart-recovery claim path has the same guard. - `releaseAbandonedNativeOwners` and `nextAbandonedNativeOwnerReleaseAt` skip foreign owners whose task is finished or whose incident is settled. A pass that has nothing to do selects nothing, and no immediate deadline is set again. Local owners keep the normal proof-based release. - The owner release proofs did not change. A foreign owner is still never released without proof. - Tests: `server/src/__tests__/native-failed-run-owner-release-idle.test.ts` (real PostgreSQL, real coordinator and workers, fake clock, statement and signal counters) and three new cases in `native-failed-run-owner-release.test.ts`. ## Verification - `pnpm --filter @paperclipai/server exec vitest run src/__tests__/native-failed-run-owner-release-idle.test.ts src/services/native-runtime/native-failed-run-owner-release.test.ts src/services/native-runtime/native-restart-recovery.test.ts src/services/native-runtime/native-restart-recovery-isolation.test.ts`: 80 tests pass. - Red on master, green with this change. The test seeds one done task and one cancelled task (each with an earlier resolved `source_terminal` incident) and one live task, then runs 30 idle minutes: - master: 126 attention inserts, 249 attention writes, 7,024 signals, 8,025 statements. - this branch: 1 attention insert (the live task, surfaced once), 2 attention writes (that insert and the fallback's resolution), 36 signals, 350 statements. All of this is startup work. Nothing repeats. - After the fresh continuation settles a live task's attention, six unrelated finalization wakes over 30 minutes: - master: 3 attention inserts, 90 signals, 551 statements, and the release deadline stays due. - this branch: 0 attention writes, 0 run writes, 6 signals (the test's own wakes), 153 statements, and the release deadline is null. - New unit cases: a done or cancelled task never surfaces, and surfaces once when it is reopened. A settled incident stays settled over repeated passes. A renewed authority (a new lease expiry) surfaces one new incident. - The three new unit cases fail on master and pass on this branch. - `tsc --noEmit` for `server` passes. ## Risks - Low risk. The change only removes writes. It does not weaken a release proof, an authorization, a budget, a pause, or an approval check. - An incident that a person resolved or dismissed after the lease expired is not made again for the same authority. A renewed authority (a later lease expiry) still makes a new incident. - A superseded incident (status `cancelled`) still shows again when the superseding action clears. This keeps the current behavior. - The historical rows that the loop made are not removed. This change only stops new rows. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude Code with tool use (shell, file edits, test execution). ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge Refs #21621, #21616, #21617 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
122 lines
7.9 KiB
TypeScript
122 lines
7.9 KiB
TypeScript
import { and, asc, eq, exists, gt, not, notInArray, sql, type SQL } from "drizzle-orm";
|
|
import { heartbeatRuns, issues, nativeRunFinalizations, nativeRunResults, statusDecisions, workAssessments, workspaceOperations,
|
|
type Db } from "@paperclipai/db";
|
|
import type { createDeliveryWorkCoordinator } from "../delivery-work-coordinator.js";
|
|
import { DELIVERY_QUEUES } from "../delivery-work-notifications.js";
|
|
import type { NativeResultCommitScope } from "../native-result-commit-notifications.js";
|
|
import { registerScopedDeadlineWork } from "../scoped-deadline-work.js";
|
|
import { pendingNativeStatusEffectsCondition } from "./native-pending-effect-work.js";
|
|
import { nativeRunnerOwnershipNotHeldCondition } from "./native-runner-ownership.js";
|
|
import { finalizeNativeRun, NativeFinalizationDeferredError, recordNativeFinalizationFailure } from "./native-run-finalizer.js";
|
|
import { readNativeWorkspaceSyncReference } from "./native-workspace-sync.js";
|
|
|
|
type Entry = { id: string; companyId: string; issueId: string; dueAt: number };
|
|
|
|
function recordedFinalizationErrorCondition(db: Db): SQL {
|
|
return and(eq(nativeRunFinalizations.phase, "retryable_failure"),
|
|
sql`${nativeRunFinalizations.failureCode} is distinct from 'workspace_finalization_failed'`,
|
|
exists(db.select({ id: statusDecisions.id }).from(statusDecisions)
|
|
.innerJoin(workAssessments, and(eq(workAssessments.id, statusDecisions.assessmentId),
|
|
eq(workAssessments.companyId, statusDecisions.companyId), eq(workAssessments.issueId, statusDecisions.issueId)))
|
|
.where(and(eq(statusDecisions.id, nativeRunFinalizations.decisionId),
|
|
eq(statusDecisions.companyId, nativeRunFinalizations.companyId), eq(statusDecisions.issueId, nativeRunFinalizations.issueId),
|
|
eq(statusDecisions.assessmentId, nativeRunFinalizations.assessmentId),
|
|
eq(workAssessments.runId, nativeRunFinalizations.runId), eq(workAssessments.resultId, nativeRunFinalizations.resultId),
|
|
sql`${statusDecisions.decisionJson}->'effects' @> jsonb_build_array(jsonb_build_object(
|
|
'kind', 'record_finalization_error', 'cause', ${nativeRunFinalizations.failureCode}::text))`))),
|
|
sql`${issues.updatedAt} <= ${nativeRunFinalizations.updatedAt}`,
|
|
sql`not exists (select 1 from heartbeat_runs successor
|
|
where successor.company_id = ${nativeRunFinalizations.companyId} and successor.id <> ${nativeRunFinalizations.runId}
|
|
and (successor.context_snapshot->>'issueId' = ${nativeRunFinalizations.issueId}::text
|
|
or successor.issue_id = ${nativeRunFinalizations.issueId})
|
|
and successor.created_at > ${nativeRunFinalizations.updatedAt})`)!;
|
|
}
|
|
|
|
export function nativeResultCommitWork(db: Db, finalize = finalizeNativeRun) {
|
|
function candidates(scope?: NativeResultCommitScope, after?: string) {
|
|
return db.select({ id: nativeRunFinalizations.runId, companyId: nativeRunFinalizations.companyId,
|
|
issueId: nativeRunFinalizations.issueId, nextAttemptAt: nativeRunFinalizations.nextAttemptAt,
|
|
leaseOwner: nativeRunFinalizations.leaseOwner, leaseExpiresAt: nativeRunFinalizations.leaseExpiresAt,
|
|
}).from(nativeRunFinalizations)
|
|
.innerJoin(heartbeatRuns, and(eq(heartbeatRuns.id, nativeRunFinalizations.runId),
|
|
eq(heartbeatRuns.companyId, nativeRunFinalizations.companyId), eq(heartbeatRuns.nativeIssueId, nativeRunFinalizations.issueId)))
|
|
.innerJoin(issues, and(eq(issues.id, nativeRunFinalizations.issueId), eq(issues.companyId, nativeRunFinalizations.companyId)))
|
|
.innerJoin(nativeRunResults, and(eq(nativeRunResults.id, nativeRunFinalizations.resultId),
|
|
eq(nativeRunResults.runId, nativeRunFinalizations.runId), eq(nativeRunResults.companyId, nativeRunFinalizations.companyId),
|
|
eq(nativeRunResults.issueId, nativeRunFinalizations.issueId), eq(nativeRunResults.schemaStatus, "accepted")))
|
|
.where(and(eq(heartbeatRuns.runtimeMode, "native"), nativeRunnerOwnershipNotHeldCondition(),
|
|
notInArray(nativeRunFinalizations.phase, ["committed", "terminal_failure"]),
|
|
not(pendingNativeStatusEffectsCondition(db)),
|
|
not(recordedFinalizationErrorCondition(db)),
|
|
exists(db.select({ id: workspaceOperations.id }).from(workspaceOperations).where(and(
|
|
eq(workspaceOperations.companyId, nativeRunFinalizations.companyId),
|
|
eq(workspaceOperations.issueId, nativeRunFinalizations.issueId), eq(workspaceOperations.heartbeatRunId, nativeRunFinalizations.runId),
|
|
eq(workspaceOperations.phase, "workspace_finalize"), eq(workspaceOperations.status, "succeeded"),
|
|
))),
|
|
scope ? eq(nativeRunFinalizations.companyId, scope.companyId) : undefined,
|
|
scope?.issueId ? eq(nativeRunFinalizations.issueId, scope.issueId) : undefined,
|
|
scope?.runId ? eq(nativeRunFinalizations.runId, scope.runId) : undefined,
|
|
after ? gt(nativeRunFinalizations.runId, after) : undefined,
|
|
)).orderBy(asc(nativeRunFinalizations.runId)).limit(100);
|
|
}
|
|
function entry(row: Awaited<ReturnType<typeof candidates>>[number]): Entry {
|
|
return { id: row.id, companyId: row.companyId, issueId: row.issueId,
|
|
dueAt: Math.max(row.nextAttemptAt?.getTime() ?? 0, row.leaseOwner ? row.leaseExpiresAt?.getTime() ?? 0 : 0) };
|
|
}
|
|
async function load(scope?: NativeResultCommitScope, signal?: AbortSignal, canRun = () => true): Promise<Entry[]> {
|
|
const entries: Entry[] = [];
|
|
let after: string | undefined;
|
|
while (canRun() && !signal?.aborted) {
|
|
const rows = await candidates(scope, after);
|
|
entries.push(...rows.map(entry));
|
|
if (rows.length < 100) return entries;
|
|
after = rows[rows.length - 1].id;
|
|
}
|
|
throw new Error("Native result commit discovery stopped");
|
|
}
|
|
async function check(current: Entry, signal?: AbortSignal): Promise<Entry | null> {
|
|
if (signal?.aborted) throw new Error("Native result commit stopped");
|
|
const scope = { companyId: current.companyId, issueId: current.issueId, runId: current.id };
|
|
const [row] = await candidates(scope);
|
|
if (!row) return null;
|
|
const due = entry(row);
|
|
if (due.dueAt > Date.now()) return due;
|
|
const [run] = await db.select({ profile: heartbeatRuns.runnerProfileJson }).from(heartbeatRuns)
|
|
.where(and(eq(heartbeatRuns.companyId, current.companyId), eq(heartbeatRuns.id, current.id)));
|
|
if (!run) return null;
|
|
if (signal?.aborted) throw new Error("Native result commit stopped");
|
|
try {
|
|
await finalize({ db, runId: current.id, workspaceFinalizeStatus: "succeeded", projectRunStatus: true,
|
|
onlyWhenDue: true, skipNativeResponsePresentation: true, skipNativeReviewResponse: true,
|
|
preserveProviderAttempt: Boolean(readNativeWorkspaceSyncReference(run.profile?.nativeWorkspaceSync)),
|
|
});
|
|
} catch (error) {
|
|
|
|
if (!(error instanceof NativeFinalizationDeferredError)) {
|
|
await recordNativeFinalizationFailure({ db, runId: current.id, error, projectRunStatus: true });
|
|
}
|
|
}
|
|
const [remaining] = await candidates(scope);
|
|
if (!remaining) return null;
|
|
const next = entry(remaining);
|
|
|
|
|
|
return next.dueAt > Date.now() ? next : { ...next, dueAt: Date.now() + 30_000 };
|
|
}
|
|
function register(coordinator: ReturnType<typeof createDeliveryWorkCoordinator>, canRun: () => boolean,
|
|
canRecover: () => Promise<boolean> = async () => true) {
|
|
return registerScopedDeadlineWork(coordinator, {
|
|
queue: DELIVERY_QUEUES.nativeResultCommit, batchSize: 1,
|
|
decodeScope: (hint: string): NativeResultCommitScope | undefined => hint === "*" ? undefined : JSON.parse(hint),
|
|
matches: (item: Entry, scope?: NativeResultCommitScope) => !scope || item.companyId === scope.companyId
|
|
&& (!scope.issueId || item.issueId === scope.issueId) && (!scope.runId || item.id === scope.runId),
|
|
load: async (scope, signal) => await canRecover() ? load(scope, signal, canRun) : [],
|
|
check: async (item, signal) => {
|
|
if (!canRun()) throw new Error("Native result commit paused");
|
|
return await canRecover() ? check(item, signal) : null;
|
|
},
|
|
}, canRun);
|
|
}
|
|
return { load, check, register };
|
|
}
|