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 > - Budget policies and usage records are written in serialized accounting transactions for each company > - When several writes for one company run at the same time, PostgreSQL rejects all but one and Paperclip retries the others > - The retries were few and short (4 attempts, 10 to 30 ms, the same delay for every writer), so concurrent writers collided again and the request failed with 503 > - The 503 message also said "this run's budget" for a policy write that has no run > - This pull request retries contended accounting writes with jittered exponential backoff and gives the error a correct message > - The benefit is that normal concurrent budget changes succeed, and a real failure tells the user what happened ## Linked Issues or Issue Description **What happened?** Several budget policy writes for one company at the same time returned 503 after 4 serialization retries. The same retry exhaustion appeared often in server logs of the chat feature evals. The message said "Paperclip could not save this run's budget or usage records … Retry the run" for a policy write. **Expected behavior** Concurrent budget policy writes succeed. If contention continues, the error describes budget or usage changes, not a run. **Steps to reproduce** Send 9 budget policy upserts for one company at the same time. Before this change, about half of them fail with 503. **Paperclip version or commit** master ## What Changed - `withOperationAccountingTransaction` retries up to `ACCOUNTING_TRANSACTION_ATTEMPTS` (8) times. The delay before each retry is jittered exponential backoff (`accountingRetryDelayMs`): 10 ms × 2^(attempt+1), capped at 400 ms, randomized between half and the full value. The worst case total wait is about 1.4 s. - `AccountingContentionError` uses a new generic message: "Paperclip could not save these budget or usage changes because other updates to the same company kept conflicting with them. Try again." - A failed run keeps its run-specific `ACCOUNTING_CONTENTION_MESSAGE` (run completion still uses it). - The existing exhausted-retry test uses the new attempt constant. ## Verification - `cd server && npx vitest run src/__tests__/budget-policy-write-contention.test.ts` - Red before the change: 5 of 9 concurrent policy writes failed with `AccountingContentionError`, and the message mentioned a run. - Green after: all writes succeed (5 of 5 repeated runs; also 3 of 3 runs with 17 concurrent writers). - `run-accounting-contention`, `run-completion`, `budget-control-publication`, `budget-evaluation-work` and `heartbeat-native-predispatch-retry` tests. - Paid runner E2E evidence for `goals.align-existing-work` is linked in a comment. ## Risks - Low. A write that keeps losing now waits up to about 1.4 s before it fails, instead of about 60 ms. Only transactions that PostgreSQL rolled back (40001 or 40P01) are retried, as before. - Moving policy writes out of the accounting transaction was considered. It is not done here, because the policy fence keeps budget evaluation consistent with policy changes. > 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 - Anthropic Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use and code 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 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
127 lines
6.2 KiB
TypeScript
127 lines
6.2 KiB
TypeScript
import { eq } from "drizzle-orm";
|
|
import { companies, type Db } from "@paperclipai/db";
|
|
import { publishActivity, type ActivityPublication } from "./activity-log.js";
|
|
import { HttpError, notFound } from "../errors.js";
|
|
import { logger } from "../middleware/logger.js";
|
|
import { withBudgetSpan } from "./budget-tracing.js";
|
|
|
|
/** Serialize ledger and budget mutations in one company. Always acquire this
|
|
* before locking a run or a policy, so concurrent writers use one lock order.
|
|
* NO KEY UPDATE permits FK KEY SHARE locks held by recovery callers. */
|
|
export async function withAccountingTransaction<T>(db: Db, companyId: string, work: (tx: Db, publications: ActivityPublication[]) => Promise<T>): Promise<T> {
|
|
const publications: ActivityPublication[] = [];
|
|
const result = await withBudgetSpan("budget.accounting.transaction", () => db.transaction(async (transaction) => {
|
|
const tx = transaction as unknown as Db;
|
|
const [company] = await withBudgetSpan("budget.accounting.lock_wait", () => tx.select({ id: companies.id }).from(companies)
|
|
.where(eq(companies.id, companyId)).for("no key update"));
|
|
if (!company) throw notFound("Company not found");
|
|
return work(tx, publications);
|
|
}));
|
|
publishAccountingActivities(companyId, publications);
|
|
return result;
|
|
}
|
|
|
|
/** Independent paid operations share a consistent snapshot, never a company
|
|
* writer mutex. Only retry transactions PostgreSQL proves were rolled back;
|
|
* an uncertain commit must be replayed by its durable operation identity.
|
|
* A writer whose mutable reads are protected by an aggregate row lock can use
|
|
* READ COMMITTED, so unrelated updates before that lock do not invalidate its
|
|
* snapshot. Multi-aggregate readers keep the default consistent snapshot. */
|
|
export async function withOperationAccountingTransaction<T>(db: Db, companyId: string,
|
|
work: (tx: Db, publications: ActivityPublication[]) => Promise<T>,
|
|
options: { isolationLevel?: "read committed" } = {}): Promise<T> {
|
|
for (let attempt = 0; ; attempt++) {
|
|
const publications: ActivityPublication[] = [];
|
|
try {
|
|
const result = await withBudgetSpan("budget.accounting.transaction", () => db.transaction(async transaction => {
|
|
const tx = transaction as unknown as Db;
|
|
const [company] = await tx.select({ id: companies.id }).from(companies).where(eq(companies.id, companyId));
|
|
if (!company) throw notFound("Company not found");
|
|
return work(tx, publications);
|
|
}, { isolationLevel: options.isolationLevel ?? "repeatable read" }));
|
|
publishAccountingActivities(companyId, publications);
|
|
return result;
|
|
} catch (error) {
|
|
if (!isAccountingRetryable(error)) throw error;
|
|
if (attempt + 1 >= ACCOUNTING_TRANSACTION_ATTEMPTS) {
|
|
const contention = new AccountingContentionError(error, attempt + 1);
|
|
logger.warn({ companyId, sqlState: contention.code, attempts: contention.attempts, err: error },
|
|
"Accounting transaction exhausted its serialization retries");
|
|
throw contention;
|
|
}
|
|
await new Promise(resolve => setTimeout(resolve, accountingRetryDelayMs(attempt)));
|
|
}
|
|
}
|
|
}
|
|
|
|
export const ACCOUNTING_TRANSACTION_ATTEMPTS = 8;
|
|
|
|
const ACCOUNTING_RETRY_BASE_DELAY_MS = 10;
|
|
const ACCOUNTING_RETRY_MAX_DELAY_MS = 400;
|
|
|
|
export function accountingRetryDelayMs(attempt: number, random: () => number = Math.random): number {
|
|
const ceiling = Math.min(ACCOUNTING_RETRY_MAX_DELAY_MS, ACCOUNTING_RETRY_BASE_DELAY_MS * 2 ** (attempt + 1));
|
|
return Math.round(ceiling / 2 + random() * (ceiling / 2));
|
|
}
|
|
|
|
export const ACCOUNTING_CONTENTION_MESSAGE = "Paperclip could not save this run's budget or usage records because other "
|
|
+ "updates to the same run kept conflicting with them. Retry the run.";
|
|
|
|
export const ACCOUNTING_WRITE_CONTENTION_MESSAGE = "Paperclip could not save these budget or usage changes because other "
|
|
+ "updates to the same company kept conflicting with them. Try again.";
|
|
|
|
/** Bounded, SQL-free failure for exhausted serialization retries. `code`
|
|
* keeps the SQLSTATE (40001 or 40P01) for retry classifiers and diagnostics;
|
|
* the database error, with its statement text, stays only in `cause`. */
|
|
export class AccountingContentionError extends HttpError {
|
|
readonly code: string;
|
|
constructor(cause: unknown, readonly attempts: number) {
|
|
super(503, ACCOUNTING_WRITE_CONTENTION_MESSAGE);
|
|
this.name = "AccountingContentionError";
|
|
this.code = accountingRetryCode(cause) ?? "40001";
|
|
this.cause = cause;
|
|
}
|
|
}
|
|
|
|
export function isAccountingContentionError(error: unknown): error is AccountingContentionError {
|
|
let current = error;
|
|
for (let depth = 0; current && typeof current === "object" && depth < 4; depth++) {
|
|
if (current instanceof AccountingContentionError) return true;
|
|
current = (current as { cause?: unknown }).cause;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
function accountingRetryCode(error: unknown): string | null {
|
|
let current = error;
|
|
for (let depth = 0; current && typeof current === "object" && depth < 4; depth++) {
|
|
const row = current as { code?: string; cause?: unknown };
|
|
if (row.code === "40001" || row.code === "40P01") return row.code;
|
|
current = row.cause;
|
|
}
|
|
return null;
|
|
}
|
|
|
|
export function isAccountingRetryable(error: unknown): boolean {
|
|
return accountingRetryCode(error) !== null;
|
|
}
|
|
|
|
/** Consistent operator reports must not wait for or delay accounting writers.
|
|
* Reads see one committed snapshot; repairs still revalidate under the lock. */
|
|
export function withAccountingReadSnapshot<T>(db: Db, companyId: string, work: (tx: Db) => Promise<T>): Promise<T> {
|
|
return db.transaction(async transaction => {
|
|
const tx = transaction as unknown as Db;
|
|
const [company] = await tx.select({ id: companies.id }).from(companies).where(eq(companies.id, companyId));
|
|
if (!company) throw notFound("Company not found");
|
|
return work(tx);
|
|
}, { isolationLevel: "repeatable read", accessMode: "read only" });
|
|
}
|
|
|
|
/** Database history is durable even when the live subscriber channel fails. */
|
|
export function publishAccountingActivities(companyId: string, publications: ActivityPublication[]) {
|
|
for (const publication of publications) {
|
|
try { publishActivity(publication); }
|
|
catch (error) { logger.warn({ err: error, companyId }, "Accounting committed; live activity publication failed"); }
|
|
}
|
|
}
|