perf(budgets): read only the needed run columns under the run lock (#20130)

## 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>
This commit is contained in:
HisarWebandClaude Opus 5.5 authored and GitHub committed 2026-11-23 19:41:25 -06:00
1 parent 724693f635
commit 2b8ae371d3
2 files changed
+30 -1

No files matched your search

@@ -1,5 +1,6 @@
import { randomUUID } from "node:crypto";
import { and, eq, sql } from "drizzle-orm";
import { drizzle } from "drizzle-orm/postgres-js";
import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";
import { agents, budgetPolicies, budgetReservations, companies, costEvents, createDb, heartbeatRuns, projects, type Db } from "@paperclipai/db";
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
@@ -123,6 +124,21 @@ const support = await getEmbeddedPostgresTestSupport();
expect((await f.exposure()).effectiveHeldCents).toBe(`${admitted * 60}.0000000`);
});
it("locks the run row without reading its large snapshot or log columns", async () => {
const f = await fixture({ reservationCents: "10" });
const runId = await f.queuedRun();
await db.update(heartbeatRuns).set({ contextSnapshot: { issueId: randomUUID(), payload: "x".repeat(65536) } })
.where(eq(heartbeatRuns.id, runId));
const queries: string[] = [];
const recorded = drizzle(db.$client, { schema: db._.fullSchema, logger: { logQuery: query => queries.push(query) } }) as unknown as Db;
await expect(reserveRunBudget(recorded, f.companyId, runId, f.projectId)).resolves.toMatchObject({ reused: false });
const runLock = queries.filter(query => /from "heartbeat_runs"/.test(query) && /for update/.test(query));
expect(runLock).toHaveLength(1);
const selected = runLock[0].slice(0, runLock[0].indexOf(' from "heartbeat_runs"')).replaceAll('"heartbeat_runs".', "");
expect([...selected.matchAll(/"(\w+)"/g)].map(match => match[1]).sort())
.toEqual(["agent_id", "company_id", "cost_accounted_at", "id", "native_issue_id", "result_json", "runtime_mode", "status", "usage_json"]);
});
it("commits a budget release while dispatch waits for asynchronous lifecycle readiness", async () => {
const f = await fixture();
const worker = configureAgentLifecycle(db, {
+14 -1
View File
@@ -77,6 +77,18 @@ export async function recheckRunBudgetReservationInTransaction(
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.
@@ -96,7 +108,8 @@ export async function reserveRunBudget(db: Db, companyId: string, runId: string,
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().from(heartbeatRuns).where(and(eq(heartbeatRuns.id, runId), eq(heartbeatRuns.companyId, companyId))).for("update");
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) {