diff --git a/server/src/__tests__/budget-enforcement-scoping.test.ts b/server/src/__tests__/budget-enforcement-scoping.test.ts index bfe44479e7f..592d835d067 100644 --- a/server/src/__tests__/budget-enforcement-scoping.test.ts +++ b/server/src/__tests__/budget-enforcement-scoping.test.ts @@ -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, { diff --git a/server/src/services/budget-reservations.ts b/server/src/services/budget-reservations.ts index 7e5bcbe6d47..2805930ccc6 100644 --- a/server/src/services/budget-reservations.ts +++ b/server/src/services/budget-reservations.ts @@ -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) {