Files
PaperClipAI/server/src/__tests__/heartbeat-refused-assignment-wake.test.ts
T
DottaandClaude Opus 5.5 f6cb3e43f4 fix(admission): admit new work independent of other runs' cleanup and accounting (#19944)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Budget admission decides if new agent work can start in a company
> - Five admission gates waited on the cleanup or accounting of other
runs
> - The restart-chaos campaign found that these gates froze companies
for up to 10 minutes, caused false budget pauses, denied in-run writes,
and dropped wakes, comments and Retries
> - The durable ownership plan (Decision 1) removes the company-wide
accounting gate. It does not narrow it again
> - This pull request removes the five gates. Unfinished accounting now
adds its bounded estimate to exposure
> - The benefit is that one run's unsettled accounting never stops the
other work in its company

## Linked Issues or Issue Description

Refs #19831 (plan, section D), #19838 (inventory, finding 3), #19927
(Phase 2 reconciler data), #19497, #19724, #19826.

**What happened?**
Admission refused new work in these cases, with no reached hard stop and
no pause:
- a terminal run awaited accounting (`waitingRunCount`);
- a native run recovered its accounting (`recoveringRunCount`);
- a budget-owned scope hold awaited reconciliation, after the hard stop
no longer applied;
- a budget input was older than 15 s (`budget_evaluation_work`);
- the predecessor run row of a task was missing (`hasPendingRunCleanup`
failed closed).

**Expected behavior**
Admission never waits on the cleanup or accounting of another run. Only
a reached hard stop, an explicit pause or an inactive company refuses
new work (invariant 3).

**Steps to reproduce**
Make a company with an active budget policy. Leave one failed run with
`cost_accounting_pending = true`. Request work for another agent. On
`master` admission refuses with "Company cannot start work while
completed runs await accounting."

## What Changed

- `budgets.ts`: admission refuses only for a reached hard stop or an
explicit pause. The code removes `observedBlocks`, the
`recoveringRunCount` check, the stale `budgetHeld` refusal and the 15 s
input-age gate. It also removes the unused
`inspectInvocationEligibility`. `reconcileScope` no longer returns
accounting holds.
- `budget-exposure.ts`: removes the `waiting` and `recovering`
aggregates and the own-task subquery. The admission query is smaller.
Unfinished accounting stays exposure: the larger of the held reservation
and the observed cost.
- `budget-evaluation-work.ts`: removes `oldestBudgetInputAt`, which
nothing reads now.
- `execution-blocker.ts`: `hasPendingRunCleanup` returns false for a
missing run row. A run row that is deleted removes its finalization
coordinator and nulls its lease references, so the row owns nothing. A
predecessor that owns a lease or a coordinator still holds the successor
of its own task.
- `recovery/ownership-invariant-report.ts`: the I3 check no longer
mirrors the removed gate. It reports a wake request or a run that was
refused with an accounting-hold reason. Any such report is a regression.
- `doc/SPEC-implementation.md`: adds the product rule "Admission is
independent of cleanup and accounting". `doc/execution-semantics.md` is
aligned.

## Verification

- New `server/src/__tests__/admission-independent-of-cleanup.test.ts`,
on embedded Postgres. It has one case per gate. All six cases fail on
`master` and pass here. A seventh case (an explicit pause still refuses)
passes on both. One case also asserts invariant 3 together with
exposure: two failed runs that each hold a 400-cent reservation fill a
1000-cent budget, and a hard stop still refuses.
- Existing tests that asserted the old gates now assert admission
(invariants 3 and 4): `closed-native-receipt-accounting`,
`budgets-service`, `budget-evaluation-work`,
`heartbeat-held-comment-wake`, `ownership-reconciliation-report`. In
`heartbeat-held-comment-wake`, each saved comment, Retry, assignment and
continuation is delivered exactly once while another run's accounting is
pending. Settling accounting later does not deliver it again.
- All six files pass locally, one file per process. The server package
typecheck passes.
- Speed: admission is on the turn path. This change only removes work
from it: two correlated aggregates, one own-task subquery and one
`budget_evaluation_work` read per policy. No wait or I/O is added before
`turn.start`.
- Not run here: the chaos waves (K13 storm, K6 crash loop, K4 long
holds). The coordinating session schedules them on the shared harness.

## Risks

- Behavior change: work starts while accounting for other runs settles.
Spend stays bounded by the reservation capacity check and the hard stop,
which read the ledger plus observed cost. A run that has no reservation
and no observed cost adds zero exposure until its charge commits. This
is the gap that Decision 1 accepts. Budget enforcement was already best
effort (SPEC 11.6).
- A budget-owned pause with no reached hard stop no longer refuses work
in budget admission. The paused company or agent is still refused by the
existing pause checks until the budget worker lifts the pause.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, with tool use and code
execution in Claude Code.

## 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

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-07 21:46:39 -06:00

162 lines
9.4 KiB
TypeScript

import { randomUUID } from "node:crypto";
import { mkdtemp, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { and, eq } from "drizzle-orm";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { agents, agentWakeupRequests, authUsers, budgetPolicies, companies, companyMemberships, createDb, heartbeatRuns,
issues, projects } from "@paperclipai/db";
import { registerServerAdapter, unregisterServerAdapter } from "../adapters/index.js";
import { heartbeatService } from "../services/heartbeat.js";
import { queueIssueAssignmentWakeup } from "../services/issue-assignment-wakeup.js";
import { taskInterruptionPresentation } from "../services/task-interruption-presentation.js";
import { recoveryPostgresSupport, startRecoveryPostgres } from "./helpers/recovery-postgres.js";
const describePostgres = recoveryPostgresSupport.supported ? describe : describe.skip;
if (!recoveryPostgresSupport.supported) console.warn(`Skipping refused assignment wake tests: ${recoveryPostgresSupport.reason}`);
/**
* A temporary budget hold can refuse a new task's assignment wake. Since Phase
* 3 another run's accounting never holds admission (invariant 3); the hold
* left is a budget-owned pause that is not a reached hard stop. The task must wait
* honestly and start once the hold clears, instead of resting `blocked` with no run.
*/
describePostgres("refused assignment wake during a temporary admission hold", () => {
let temporary: Awaited<ReturnType<typeof startRecoveryPostgres>>;
let db: ReturnType<typeof createDb>;
let heartbeat: ReturnType<typeof heartbeatService>;
const adapterType = "codex_local";
const dispatched: string[] = [];
const oldHome = process.env.PAPERCLIP_HOME;
let home: string;
beforeAll(async () => {
temporary = await startRecoveryPostgres("heartbeat-refused-assignment-");
db = createDb(temporary.connectionString);
home = await mkdtemp(path.join(tmpdir(), "paperclip-refused-assignment-"));
process.env.PAPERCLIP_HOME = home;
heartbeat = heartbeatService(db);
registerServerAdapter({
type: adapterType, supportsLocalAgentJwt: false,
execute: async input => {
dispatched.push(input.runId);
await db.update(issues).set({ status: "done" }).where(eq(issues.id, String(input.context.issueId)));
return { exitCode: 0, signal: null, timedOut: false, resultJson: {} };
},
testEnvironment: async () => ({ adapterType, status: "pass", checks: [], testedAt: new Date().toISOString() }),
});
}, 240_000);
afterAll(async () => {
await heartbeat?.drainActiveRunExecutions();
unregisterServerAdapter(adapterType);
await db?.$client.end({ timeout: 0 });
await temporary?.cleanup();
if (oldHome === undefined) delete process.env.PAPERCLIP_HOME; else process.env.PAPERCLIP_HOME = oldHome;
if (home) await rm(home, { recursive: true, force: true });
});
/** A company with a hard-stop budget whose task's project carries a
* budget-owned pause that no project policy justifies: admission refuses the
* task's work until the pause lifts. A completed run with pending
* accounting is present too; it must not hold anything (invariant 3). */
async function seedHeldCompany() {
const companyId = randomUUID(), agentId = randomUUID(), otherAgentId = randomUUID(), issueId = randomUUID();
const userId = `hold-user-${companyId}`;
await db.insert(authUsers).values({ id: userId, name: "Hold user", email: `${userId}@example.test`, createdAt: new Date(), updatedAt: new Date() });
await db.insert(companies).values({ id: companyId, name: "Accounting hold fixture", issuePrefix: `H${companyId.slice(0, 6)}` });
await db.insert(companyMemberships).values({ companyId, principalId: userId, principalType: "user", status: "active", membershipRole: "member" });
await db.insert(agents).values([
{ id: agentId, companyId, name: "Assignee", adapterType, status: "idle", adapterConfig: {} },
{ id: otherAgentId, companyId, name: "Earlier worker", adapterType, status: "idle", adapterConfig: {} },
]);
await db.insert(budgetPolicies).values({ companyId, scopeType: "company", scopeId: companyId, windowKind: "calendar_month_utc",
amount: 2_000, hardStopEnabled: true, unpricedUsagePolicy: "allow" });
const [pending] = await db.insert(heartbeatRuns).values({ companyId, agentId: otherAgentId, invocationSource: "automation",
triggerDetail: "system", status: "succeeded", startedAt: new Date(Date.now() - 60_000), finishedAt: new Date(),
costAccountingPending: true, contextSnapshot: {} }).returning();
const [project] = await db.insert(projects).values({ companyId, name: "Budget-paused project", status: "in_progress",
pauseReason: "budget", pausedAt: new Date() }).returning();
await db.insert(issues).values({ id: issueId, companyId, projectId: project.id, title: "New task created during the hold", status: "todo",
assigneeAgentId: agentId, responsibleUserId: userId, issueNumber: 1 });
return { companyId, agentId, issueId, userId, projectId: project.id, pendingRunId: pending.id };
}
async function liftHold(f: { projectId: string }) {
await db.update(projects).set({ pauseReason: null, pausedAt: null }).where(eq(projects.id, f.projectId));
}
async function assign(f: Awaited<ReturnType<typeof seedHeldCompany>>) {
return queueIssueAssignmentWakeup({ heartbeat, issue: { id: f.issueId, assigneeAgentId: f.agentId, status: "todo" },
reason: "issue_assigned", mutation: "create", contextSource: "issue.create",
requestedByActorType: "user", requestedByActorId: f.userId, rethrowOnError: true });
}
const issueRuns = (f: { companyId: string; agentId: string }) => db.select().from(heartbeatRuns).where(and(
eq(heartbeatRuns.companyId, f.companyId), eq(heartbeatRuns.agentId, f.agentId)));
it("keeps the task waiting during the hold and starts exactly one run once it clears", async () => {
const f = await seedHeldCompany();
await expect(assign(f)).rejects.toMatchObject({ status: 409 });
const [refused] = await db.select().from(agentWakeupRequests).where(and(
eq(agentWakeupRequests.companyId, f.companyId), eq(agentWakeupRequests.agentId, f.agentId)));
expect(refused).toMatchObject({ status: "skipped", reason: "budget.blocked" });
// Recovery sweeps while the hold lasts must not turn the wait into a dead `blocked` task.
await heartbeat.reconcileStrandedAssignedIssues({ companyId: f.companyId });
await heartbeat.reconcileStrandedAssignedIssues({ companyId: f.companyId });
const [waiting] = await db.select().from(issues).where(eq(issues.id, f.issueId));
expect(waiting.status).toBe("todo");
expect(await issueRuns(f)).toHaveLength(0);
// This pause needs an operator resume, so the task asks the user; it does
// not offer a Retry that cannot start either.
expect(await taskInterruptionPresentation(db, waiting)).toMatchObject({ responsibility: "user", state: "waiting_for_user",
canRetry: false });
// The budget pause lifts: the hold clears.
await liftHold(f);
await heartbeat.reconcileStrandedAssignedIssues({ companyId: f.companyId });
await heartbeat.reconcileStrandedAssignedIssues({ companyId: f.companyId });
await heartbeat.drainActiveRunExecutions();
// Exactly one provider turn starts the task. (A post-run continuation the
// adapter fixture leaves behind is cancelled unstarted once the task is done.)
const providerTurns = async () => {
const ids = new Set((await issueRuns(f)).map(run => run.id));
return dispatched.filter(id => ids.has(id));
};
expect(await providerTurns()).toHaveLength(1);
const [started] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, (await providerTurns())[0]));
expect(started).toMatchObject({ status: "succeeded", contextSnapshot: expect.objectContaining({
source: "issue.assigned_todo_liveness_dispatch" }) });
const [finished] = await db.select().from(issues).where(eq(issues.id, f.issueId));
expect(finished.status).toBe("done");
// A later sweep does not start a duplicate.
await heartbeat.reconcileStrandedAssignedIssues({ companyId: f.companyId });
await heartbeat.drainActiveRunExecutions();
expect(await providerTurns()).toHaveLength(1);
}, 180_000);
it("does not wake a task whose assignee was removed while the hold lasted", async () => {
const f = await seedHeldCompany();
await expect(assign(f)).rejects.toMatchObject({ status: 409 });
await db.update(agents).set({ status: "terminated" }).where(eq(agents.id, f.agentId));
await liftHold(f);
await heartbeat.reconcileStrandedAssignedIssues({ companyId: f.companyId });
await heartbeat.drainActiveRunExecutions();
expect(await issueRuns(f)).toHaveLength(0);
}, 180_000);
it("does not wake a task cancelled while the hold lasted", async () => {
const f = await seedHeldCompany();
await expect(assign(f)).rejects.toMatchObject({ status: 409 });
await db.update(issues).set({ status: "cancelled" }).where(eq(issues.id, f.issueId));
await liftHold(f);
await heartbeat.reconcileStrandedAssignedIssues({ companyId: f.companyId });
await heartbeat.drainActiveRunExecutions();
expect(await issueRuns(f)).toHaveLength(0);
const [cancelled] = await db.select().from(issues).where(eq(issues.id, f.issueId));
expect(await taskInterruptionPresentation(db, cancelled)).toBeNull();
}, 180_000);
});