mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-25 16:14:26 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Before a run is dispatched, `reserveRunBudget` reserves budget under the company accounting lock, the same lock that charges and policy changes use > - Inside that transaction it read the full `heartbeat_runs` row `FOR UPDATE`, including `context_snapshot` and the log columns > - Admission and native Stop recovery read only a few of those columns > - On one instance 5 to 8 waiters queued on the company lock while this query took up to 1.3 s; `context_snapshot` was 28 kB on average and up to 2.8 MB > - This pull request selects only the columns that the reservation path reads, with the same row lock > - The benefit is that the large columns are not detoasted or sent while the company lock is held, so the lock is held for a shorter time ## Linked Issues or Issue Description No issue exists. Related, but a different part of budget admission: #17966 (skip the accounting lock for admission that cannot block) and #18928 (queue accounting transactions). **What happened?** Run dispatch waited on the company accounting lock. The lock holder was the `SELECT * ... FOR UPDATE` on `heartbeat_runs` in `reserveRunBudget`, which read large `context_snapshot` values. **What did you expect?** The reservation reads only the columns it needs while it holds the company lock. **Steps to reproduce** 1. Create a company with a budget policy and runs with large context snapshots. 2. Start many runs at the same time. 3. Look at `pg_stat_activity` or the query log. The `heartbeat_runs` row read in `reserveRunBudget` returns all columns while other transactions wait on the company lock. **Paperclip version** `master` at the time of this PR. ## What Changed - `server/src/services/budget-reservations.ts`: a new `RESERVATION_RUN_COLUMNS` with `id`, `companyId`, `agentId`, `nativeIssueId`, `status`, `costAccountedAt`, `resultJson`, `runtimeMode` and `usageJson`. `reserveRunBudget` selects these columns `FOR UPDATE` instead of the full row. These are the fields that admission and `readClaimedNativeStopRecovery` read. - `server/src/__tests__/budget-enforcement-scoping.test.ts`: a new test checks that the locked query selects only these columns. ## Verification - `cd server && npx vitest run src/__tests__/budget-enforcement-scoping.test.ts`: passes, including the new test. - `pnpm --filter @paperclipai/server typecheck`: passes. The type of `run` is now the narrow select, so a later use of a column that is not selected fails the typecheck. ## Risks - Low risk. The row lock, the filter and the logic do not change. If a future change in this function needs another column, it has to be added to `RESERVATION_RUN_COLUMNS`; the typecheck shows this. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use (shell, git, test runs). Extended reasoning on. ## 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>
185 lines
13 KiB
TypeScript
185 lines
13 KiB
TypeScript
import { and, eq, sql } from "drizzle-orm";
|
|
import { agents, budgetReservations, heartbeatRuns, nativeRunFinalizations, type Db } from "@paperclipai/db";
|
|
import { centsToUnits, unitsToCents } from "@paperclipai/shared";
|
|
import { conflict, notFound } from "../errors.js";
|
|
import { withOperationAccountingTransaction } from "./accounting-transaction.js";
|
|
import { queueBudgetEvaluation } from "./budget-evaluation-work.js";
|
|
import { lockBudgetAdmissionControls } from "./budget-admission-controls.js";
|
|
import { budgetServiceInTransaction } from "./budgets.js";
|
|
import { withBudgetSpan } from "./budget-tracing.js";
|
|
import type { ActivityPublication } from "./activity-log.js";
|
|
import { readClaimedNativeStopRecovery } from "./native-runtime/native-cancellation-request.js";
|
|
import { extendOwnNativeRecoveryClaimInTransaction, readOwnNativeRecoveryClaimLease } from "./native-runtime/native-execution-lease.js";
|
|
|
|
/** Native finalization takes its coordinator before issue/run locks. Recovery
|
|
* admission uses the same order after the company accounting lock, so its
|
|
* later ownership checks never wait for a coordinator while holding a run. */
|
|
export async function lockRunBudgetRecoveryOwnerInTransaction(
|
|
tx: Db, companyId: string, runId: string, recoveryLeaseOwner?: string,
|
|
) {
|
|
if (!recoveryLeaseOwner) return;
|
|
const [coordinator] = await tx.select({ leaseOwner: nativeRunFinalizations.leaseOwner }).from(nativeRunFinalizations)
|
|
.where(and(eq(nativeRunFinalizations.companyId, companyId), eq(nativeRunFinalizations.runId, runId))).for("update");
|
|
if (!coordinator || coordinator.leaseOwner !== recoveryLeaseOwner
|
|
|| await readOwnNativeRecoveryClaimLease(tx, { companyId, runId, leaseOwner: recoveryLeaseOwner }) === "lost")
|
|
throw conflict("Native recovery no longer owns provider dispatch");
|
|
}
|
|
|
|
/** Called by the final dispatch gate with the company and run already locked.
|
|
* Admission may have waited through preparation; that earlier reservation is
|
|
* evidence of ownership, not permission to bypass a newer charge or pause.
|
|
* Recovery callers prelock their coordinator before taking issue/run locks. */
|
|
export async function recheckRunBudgetReservationInTransaction(
|
|
tx: Db,
|
|
publications: ActivityPublication[],
|
|
run: typeof heartbeatRuns.$inferSelect,
|
|
reservationId: string,
|
|
recoveryLeaseOwner?: string,
|
|
): Promise<string | null> {
|
|
const stopRecovery = await readClaimedNativeStopRecovery(tx, run, recoveryLeaseOwner);
|
|
if ((run.resultJson?.cancellation || run.resultJson?.startupCancellation) && !stopRecovery)
|
|
return "Run cancellation already requested";
|
|
if (run.costAccountedAt || !["queued", "running"].includes(run.status))
|
|
return "Run can no longer start provider work";
|
|
const [reservation] = await tx.select().from(budgetReservations).where(and(
|
|
eq(budgetReservations.id, reservationId), eq(budgetReservations.companyId, run.companyId),
|
|
eq(budgetReservations.runId, run.id), eq(budgetReservations.agentId, run.agentId),
|
|
eq(budgetReservations.state, "held"),
|
|
)).for("update");
|
|
if (!reservation) return "Provider dispatch no longer owns a held budget reservation";
|
|
if (recoveryLeaseOwner && (run.runtimeMode !== "native" || await readOwnNativeRecoveryClaimLease(tx,
|
|
{ companyId: run.companyId, runId: run.id, leaseOwner: recoveryLeaseOwner }) === "lost"))
|
|
return "Native recovery no longer owns provider dispatch";
|
|
const keepRecoveryClaim = async () => !recoveryLeaseOwner || await extendOwnNativeRecoveryClaimInTransaction(tx,
|
|
{ companyId: run.companyId, runId: run.id, leaseOwner: recoveryLeaseOwner })
|
|
? null : "Native recovery no longer owns provider dispatch";
|
|
if (stopRecovery) return keepRecoveryClaim();
|
|
const { block, policies, observations } = await budgetServiceInTransaction(tx, publications)
|
|
.evaluateAdmission(run.companyId, run.agentId, { projectId: reservation.projectId, runId: run.id,
|
|
admittedRecovery: Boolean(recoveryLeaseOwner) });
|
|
if (block) return block.reason;
|
|
const [agent] = await tx.select({ status: agents.status, lifecycleState: agents.lifecycleState }).from(agents)
|
|
.where(and(eq(agents.companyId, run.companyId), eq(agents.id, run.agentId)));
|
|
if (!agent || agent.lifecycleState !== "ready" || ["paused", "terminated", "pending_approval"].includes(agent.status))
|
|
return "Agent is paused or its lifecycle is not ready for new work";
|
|
// An owned recovery reuses the hold reserveRunBudget already admitted;
|
|
// other runs' holds filling the budget must not refuse it.
|
|
if (recoveryLeaseOwner) return keepRecoveryClaim();
|
|
for (const [index, policy] of policies.entries()) {
|
|
const observed = observations[index];
|
|
// This operation's hold is already included in exposure. Do not propose it
|
|
// twice, or reject a nonzero reservation that exactly fills the budget.
|
|
const committed = centsToUnits(observed.ledgerCents) + centsToUnits(observed.effectiveHeldCents);
|
|
const limit = centsToUnits(policy.amount);
|
|
if (committed > limit || (centsToUnits(reservation.amountCents) === 0n && committed >= limit))
|
|
return "Available budget is reserved by unfinished runs";
|
|
}
|
|
return null;
|
|
}
|
|
|
|
const RESERVATION_RUN_COLUMNS = {
|
|
id: heartbeatRuns.id,
|
|
companyId: heartbeatRuns.companyId,
|
|
agentId: heartbeatRuns.agentId,
|
|
nativeIssueId: heartbeatRuns.nativeIssueId,
|
|
status: heartbeatRuns.status,
|
|
costAccountedAt: heartbeatRuns.costAccountedAt,
|
|
resultJson: heartbeatRuns.resultJson,
|
|
runtimeMode: heartbeatRuns.runtimeMode,
|
|
usageJson: heartbeatRuns.usageJson,
|
|
};
|
|
|
|
/** Reserve before dispatch, under the same company lock as charges and policy
|
|
* changes. Estimates constrain admission; they cannot cap a provider's bill.
|
|
* A reservation survives timeouts and restarts until accounting proves closure.
|
|
*
|
|
* READ COMMITTED: every mutable read follows the shared admission fences, the
|
|
* agent share lock and the run-row lock, so it sees each commit that preceded
|
|
* those locks. Run-log appends and output progress update the run row while a
|
|
* run prepares; a repeatable-read snapshot taken before the run lock went stale
|
|
* on each such commit and could exhaust every retry. Exposure is one statement
|
|
* (hold-to-ledger atomic), and the per-run unique index plus the run lock
|
|
* fence a duplicate reservation. */
|
|
export async function reserveRunBudget(db: Db, companyId: string, runId: string, projectId: string | null, ledgerScope: Record<string, unknown> = {}, recoveryLeaseOwner?: string) {
|
|
const result = await withBudgetSpan("budget.admission.reserve", () => withOperationAccountingTransaction(db, companyId, async (tx, publications) => {
|
|
await lockBudgetAdmissionControls(tx, companyId, projectId);
|
|
const [hint] = await tx.select({ agentId: heartbeatRuns.agentId }).from(heartbeatRuns)
|
|
.where(and(eq(heartbeatRuns.id, runId), eq(heartbeatRuns.companyId, companyId)));
|
|
if (!hint) throw notFound("Run not found");
|
|
await tx.select({ id: agents.id }).from(agents).where(and(eq(agents.companyId, companyId), eq(agents.id, hint.agentId))).for("share");
|
|
await lockRunBudgetRecoveryOwnerInTransaction(tx, companyId, runId, recoveryLeaseOwner);
|
|
const [run] = await tx.select(RESERVATION_RUN_COLUMNS).from(heartbeatRuns)
|
|
.where(and(eq(heartbeatRuns.id, runId), eq(heartbeatRuns.companyId, companyId))).for("update");
|
|
if (!run) throw notFound("Run not found");
|
|
const stopRecovery = await readClaimedNativeStopRecovery(tx, run, recoveryLeaseOwner);
|
|
if ((run.resultJson?.cancellation || run.resultJson?.startupCancellation) && !stopRecovery) {
|
|
if (run.runtimeMode !== "native") throw conflict("Run cancellation already requested");
|
|
const { NativeCancellationPendingRecoveryError } = await import("./native-runtime/native-session-executor.js");
|
|
throw new NativeCancellationPendingRecoveryError();
|
|
}
|
|
if (run.costAccountedAt || !["queued", "running"].includes(run.status)) throw conflict("Run can no longer start provider work");
|
|
const [existing] = await tx.select().from(budgetReservations).where(and(eq(budgetReservations.companyId, companyId), eq(budgetReservations.runId, runId)));
|
|
if (existing) {
|
|
// The native coordinator fences recovery ownership. Reuse the original
|
|
// hold only for that live owner, never for an ordinary duplicate dispatch.
|
|
const owner = recoveryLeaseOwner && run.runtimeMode === "native" && existing.state === "held"
|
|
&& existing.projectId === projectId
|
|
&& await readOwnNativeRecoveryClaimLease(tx, { companyId, runId, leaseOwner: recoveryLeaseOwner }) !== "lost";
|
|
const keepRecoveryClaim = async () => {
|
|
if (!await extendOwnNativeRecoveryClaimInTransaction(tx, { companyId, runId, leaseOwner: recoveryLeaseOwner! }))
|
|
throw conflict("Native recovery no longer owns provider dispatch");
|
|
};
|
|
if (owner) {
|
|
if (stopRecovery) {
|
|
await keepRecoveryClaim();
|
|
return { ...existing, reused: true };
|
|
}
|
|
// Recovery has already made this run queued/running, so its own pending
|
|
// accounting is excluded. Current overruns, other unfinished runs and
|
|
// scope pauses still apply before any more paid work starts.
|
|
const block = await budgetServiceInTransaction(tx, publications).getInvocationBlock(companyId, run.agentId, { projectId, runId, admittedRecovery: true });
|
|
if (block) return { admissionBlockReason: block.reason };
|
|
const [agent] = await tx.select({ status: agents.status, lifecycleState: agents.lifecycleState }).from(agents)
|
|
.where(and(eq(agents.companyId, companyId), eq(agents.id, run.agentId)));
|
|
if (!agent || agent.lifecycleState !== "ready" || ["paused", "terminated", "pending_approval"].includes(agent.status))
|
|
return { admissionBlockReason: "Agent is paused and cannot start new work" };
|
|
await keepRecoveryClaim();
|
|
return { ...existing, reused: true };
|
|
}
|
|
throw conflict("Provider dispatch has already reserved this run");
|
|
}
|
|
if (stopRecovery) throw conflict("Native Stop recovery requires the original held reservation");
|
|
const { block, policies, observations } = await budgetServiceInTransaction(tx, publications).evaluateAdmission(companyId, run.agentId, { projectId, runId });
|
|
if (block) return { admissionBlockReason: block.reason };
|
|
// A budget release can start asynchronous resume hooks. Capacity alone
|
|
// does not authorize dispatch before that lifecycle operation is ready.
|
|
const [agent] = await tx.select({ status: agents.status, lifecycleState: agents.lifecycleState }).from(agents)
|
|
.where(and(eq(agents.companyId, companyId), eq(agents.id, run.agentId)));
|
|
if (!agent || agent.lifecycleState !== "ready" || ["paused", "terminated", "pending_approval"].includes(agent.status))
|
|
return { admissionBlockReason: "Agent is paused or its lifecycle is not ready for new work" };
|
|
const amount = policies.reduce((max, policy) => { const next = centsToUnits(policy.reservationCents); return next > max ? next : max; }, 0n);
|
|
for (const [index, policy] of policies.entries()) {
|
|
const observed = observations[index];
|
|
// Even zero-estimate runs cannot enter a scope whose available capacity
|
|
// is completely reserved. Outstanding reservations carry across months.
|
|
const committed = centsToUnits(observed.ledgerCents) + centsToUnits(observed.effectiveHeldCents);
|
|
const limit = centsToUnits(policy.amount);
|
|
if (committed >= limit || committed + amount > limit) return { admissionBlockReason: "Available budget is reserved by unfinished runs" };
|
|
}
|
|
// A zero-valued row also fences duplicate dispatch when estimates are off.
|
|
const [reservation] = await tx.insert(budgetReservations).values({ companyId, runId, agentId: run.agentId, projectId,
|
|
amountCents: unitsToCents(amount), providerStartedAt: new Date() }).returning();
|
|
await tx.update(heartbeatRuns).set({ costAccountingPending: true,
|
|
usageJson: sql`coalesce(${heartbeatRuns.usageJson}, '{}'::jsonb) || ${JSON.stringify({ accountingReceiptReady: false, ledgerScope: { ...(run.usageJson?.ledgerScope as object ?? {}), ...ledgerScope, projectId } })}::jsonb`,
|
|
}).where(eq(heartbeatRuns.id, runId));
|
|
await queueBudgetEvaluation(tx, { companyId, agentId: run.agentId, projectId });
|
|
if (recoveryLeaseOwner && !await extendOwnNativeRecoveryClaimInTransaction(tx, { companyId, runId, leaseOwner: recoveryLeaseOwner }))
|
|
throw conflict("Native recovery no longer owns provider dispatch");
|
|
return { ...reservation, reused: false };
|
|
}, { isolationLevel: "read committed" }));
|
|
// Commit required block/resume transitions even when dispatch is denied.
|
|
// Throwing inside the transaction would discard those durable obligations.
|
|
if ("admissionBlockReason" in result) throw conflict(result.admissionBlockReason ?? "Budget admission blocked");
|
|
return result;
|
|
}
|