Files
PaperClipAI/server/src/services/native-runtime/provider-limit-resume.ts
T
DottaandClaude Opus 5.5 c36e791bd9 fix(native): back off and retry a provider rate limit that reports no reset (#22216)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for work
> - Native runs drive ACP agents, such as Claude, through the runner. The runner types each provider failure for the server.
> - When a provider limit stops a turn, the server holds the task. It retries the task automatically at the reset that the provider reports (#20692).
> - Claude can reject a request at the account rate limit with "This request would exceed your account's rate limit. Please try again later." This text has no reset time and no window.
> - The server then plans no automatic Retry. The task stays blocked until a person retries it, and the case work stops before a final reply.
> - This pull request gives a `rate_limit` failure without a reported reset the default provider-limit cooldown, and then requests the task's Retry.
> - The benefit is that a short account rate limit no longer strands a task. The existing Retry admission keeps the saved work and all gates.

## Linked Issues or Issue Description

Refs #20692, #19246, #21100

**What happened?**

A native task ran on a Claude agent. In the middle of the turn, Claude returned HTTP 429 with "This request would exceed your account's rate limit. Please try again later." The runner typed the failure as `rate_limit`, with no `retryAt`. The server put the task on hold with "Restore model provider usage capacity, then retry the task. The provider did not report when its usage limit resets." It did not plan an automatic Retry. The task stayed blocked until a person retried it.

**Expected behavior**

A rate limit passes by itself. Paperclip should wait a bounded time, and then retry the task. It should keep the saved work and should not start another request before the wait ends.

**Steps to reproduce**

1. Run a native task on a Claude agent whose account is at its rate limit.
2. Let Claude reject a request in the turn with the 429 account rate-limit text above.
3. See that the task hold has no reset time and that no automatic Retry is planned.

**Paperclip version or commit**

`master` at 8282d386da.

## What Changed

- `readNativeUsageLimitReset` (server, native runtime) now gives a `rate_limit` turn failure without a reported reset an estimated reset. The estimated reset is the failure time plus `PROVIDER_LIMIT_DEFAULT_COOLDOWN_MS` (one hour). This is the same wait that already holds the agent's new work after the same failure, so both holds end at about the same time.
- The reset carries an `estimated` flag. The hold text says that the provider did not report the reset, and it gives the time when Paperclip will retry.
- A `quota_exhausted` failure without a reported reset does not change. It still waits for a person, because an exhausted allowance does not pass by itself.
- The existing bounds still apply: a maximum of three automatic Retries in a row without a successful run, Retry admission gates, and the accountable-user check.
- This change is a fallback. When the runner sets `retryAt` (for example, #21100 for a named rate-limit window) or the text contains a reset, Paperclip uses that time.

## Verification

- New test in `server/src/services/native-runtime/native-provider-capacity.integration.test.ts`: "backs off and retries a Claude account rate limit that reports no reset".
- Before the fix, the test failed: `AssertionError: expected NaN to be greater than or equal to 1795028502736`. The hold had no `providerLimitResetAt`, because no reset was planned.
- After the fix: `cd server && pnpm vitest run src/services/native-runtime/native-provider-capacity.integration.test.ts` passes (11 tests).
- Related files pass: `native-provider-limit-cooldown.integration.test.ts`, `src/__tests__/heartbeat-provider-limit-wait.test.ts`, `task-interruption-presentation.test.ts`, and the capacity file (4 files, 90 tests).
- `cd server && pnpm typecheck` passes.
- `pnpm verify` selected 2,925 of 3,792 Vitest files, because the changed module is deep in the server import graph. Its first selected group passed (2 files, 12 tests). I stopped the broad local run and rely on the required CI test checks for that coverage.

## Risks

- Low risk. The change applies only to a native turn failure that is typed `rate_limit` and has no reported reset.
- If the account stays at its limit for more than one hour, the automatic Retry can fail again. After three automatic Retries in a row, the task waits for a person, as before.
- The task stays in the blocked state during the wait, as it does for a reported reset. A person can select Retry to start it sooner.

## 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 (no doc change is necessary: no subsystem doc describes this hold, and the hold text and tests describe the behavior)
- [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-18 15:24:52 -06:00

303 lines
18 KiB
TypeScript

import { and, asc, desc, eq, gt, inArray, isNull, like, sql } from "drizzle-orm";
import {
agentWakeupRequests,
heartbeatRunEvents,
heartbeatRuns,
issueRecoveryActions,
issues,
type Db,
} from "@paperclipai/db";
import { readProviderFailure } from "@paperclipai/shared";
import { HttpError } from "../../errors.js";
import { logger } from "../../middleware/logger.js";
import type { createDeliveryWorkCoordinator } from "../delivery-work-coordinator.js";
import { DELIVERY_QUEUES } from "../delivery-work-notifications.js";
import { isProvenTurnSettlement, TURN_SETTLED_EVENTS, TURN_STARTED_EVENTS } from "../heartbeat/restart-interrupted-turn.js";
import { parseProviderQuotaClockReset } from "../provider-quota-reset.js";
import { registerScopedDeadlineWork } from "../scoped-deadline-work.js";
import { PROVIDER_LIMIT_DEFAULT_COOLDOWN_MS } from "../system-recovery-state.js";
import { requestTaskRetry } from "../task-retry.js";
/** The chat service's Retry callback, which a connected conversation's Retry needs. */
export type PrepareChatRetry = NonNullable<Parameters<typeof requestTaskRetry>[0]["prepareChatRetry"]>;
/**
* A native run whose provider ended its turn because the account's usage limit
* ran out. When the provider reported when the limit resets, Paperclip asks for
* the task's Retry itself at that time, as the accountable user would. Retry
* admission keeps every gate (stop proof, saved work, action reconciliation),
* so this never starts work a user's own Retry could not.
*/
export const NATIVE_PROVIDER_USAGE_LIMIT = "native_provider_usage_limit";
/** Longer than a weekly limit's reset, so the reset is the only wait. */
export const PROVIDER_LIMIT_RESUME_MAX_WAIT_MS = 8 * 24 * 60 * 60_000;
/** A reset older than this belongs to an incident nobody is waiting on. */
const STALE_RESET_MS = 24 * 60 * 60_000;
/** Automatic Retries in a row without a successful run between them. */
const MAX_AUTOMATIC_RESUMES = 3;
export const PROVIDER_LIMIT_RESUME_KEY_PREFIX = "provider-limit-reset:";
const LIMIT_CATEGORIES = ["rate_limit", "quota_exhausted"];
const asRecord = (value: unknown): Record<string, unknown> =>
value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {};
/** The provider-reported failure on a settled turn event, raw or PRP-wrapped. */
function providerFailureOf(payload: unknown) {
const direct = asRecord(asRecord(payload).error).providerFailure;
const wrapped = asRecord(asRecord(asRecord(asRecord(payload).prpEvent).payload).error).providerFailure;
return readProviderFailure(direct) ?? readProviderFailure(wrapped);
}
export type ProviderLimitReset = {
resetAt: Date; observedAt: Date;
/** False for a reset further out than Paperclip waits by itself (a monthly limit). */
withinAutomaticWait: boolean;
/** True when the provider reported no reset and Paperclip waits its default cooldown. */
estimated?: true;
};
/**
* When the provider said the usage limit resets, from the run's own durable
* events. Null unless the last turn event is a provider-observed settlement
* reporting an exhausted allowance with a reset after it. A rate limit that
* names no reset (Claude's "try again later") waits the default cooldown, the
* same wait that holds the agent's new work, so the task is not stranded.
*/
export async function readNativeUsageLimitReset(
db: Pick<Db, "select">,
run: { id: string; companyId: string },
): Promise<ProviderLimitReset | null> {
const [lastTurn] = await db.select({ eventType: heartbeatRunEvents.eventType, payload: heartbeatRunEvents.payload,
createdAt: heartbeatRunEvents.createdAt })
.from(heartbeatRunEvents).where(and(
eq(heartbeatRunEvents.companyId, run.companyId), eq(heartbeatRunEvents.runId, run.id),
inArray(heartbeatRunEvents.eventType, [...TURN_STARTED_EVENTS, ...TURN_SETTLED_EVENTS]),
)).orderBy(desc(heartbeatRunEvents.seq)).limit(1);
// An unsettled or unobserved turn may still be working: its outcome is unknown.
if (!lastTurn || lastTurn.eventType !== "turn.failed" || !isProvenTurnSettlement(lastTurn)) return null;
const failure = providerFailureOf(lastTurn.payload);
if (!failure || !LIMIT_CATEGORIES.includes(failure.category)) return null;
const observedAt = lastTurn.createdAt;
const typed = failure.retryAt ? new Date(failure.retryAt) : null;
const reported = typed && Number.isFinite(typed.getTime()) ? typed : parseProviderQuotaClockReset(failure.message, observedAt);
// An exhausted allowance without a reset still needs a person; a rate limit passes by itself.
const estimated = !reported && failure.category === "rate_limit";
const resetAt = estimated ? new Date(observedAt.getTime() + PROVIDER_LIMIT_DEFAULT_COOLDOWN_MS) : reported;
if (!resetAt || resetAt.getTime() <= observedAt.getTime()) return null;
return { resetAt, observedAt,
withinAutomaticWait: resetAt.getTime() - observedAt.getTime() <= PROVIDER_LIMIT_RESUME_MAX_WAIT_MS,
...(estimated ? { estimated: true as const } : {}) };
}
/** The user whose authority Retry uses: the requester, else the run's accountable user. */
async function accountableUser(db: Pick<Db, "select">, run: typeof heartbeatRuns.$inferSelect) {
const [wake] = run.wakeupRequestId ? await db.select({ type: agentWakeupRequests.requestedByActorType,
id: agentWakeupRequests.requestedByActorId }).from(agentWakeupRequests).where(and(
eq(agentWakeupRequests.companyId, run.companyId), eq(agentWakeupRequests.id, run.wakeupRequestId))) : [];
if (wake?.type === "user" && wake.id) return wake.id;
return run.responsibleUserId ?? null;
}
export type ProviderLimitResumePlan =
| { automatic: true; resetAt: Date; actorId: string; estimated?: true }
| { automatic: false; resetAt: Date | null; estimated?: true };
/** Whether this failed run's task continues by itself once the limit resets. */
export async function planProviderLimitResume(db: Pick<Db, "select">, runId: string): Promise<ProviderLimitResumePlan> {
const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId));
if (!run) return { automatic: false, resetAt: null };
const reset = await readNativeUsageLimitReset(db, run);
if (!reset) return { automatic: false, resetAt: null };
// A reset beyond the bounded wait is still reported; only the automatic Retry is bounded.
const actorId = reset.withinAutomaticWait ? await accountableUser(db, run) : null;
const estimated = reset.estimated ? { estimated: true as const } : {};
return actorId ? { automatic: true, resetAt: reset.resetAt, actorId, ...estimated }
: { automatic: false, resetAt: reset.resetAt, ...estimated };
}
export function providerLimitNextAction(plan: ProviderLimitResumePlan) {
if (plan.estimated && plan.resetAt) {
const unreported = "The provider did not report when its rate limit resets.";
return plan.automatic
? `${unreported} Paperclip will retry this task at ${plan.resetAt.toISOString()}; Retry starts it sooner if usage capacity is already restored.`
: `${unreported} Retry the task after ${plan.resetAt.toISOString()}, or sooner if usage capacity is restored.`;
}
if (plan.automatic) {
return `The provider usage limit resets at ${plan.resetAt.toISOString()}. Paperclip will retry this task then; Retry starts it sooner if usage capacity is already restored.`;
}
return plan.resetAt
? `The provider usage limit resets at ${plan.resetAt.toISOString()}. Retry the task after that time, or sooner if usage capacity is restored.`
: "Restore model provider usage capacity, then retry the task. The provider did not report when its usage limit resets.";
}
type Outcome =
| { requested: true; requestId: string }
| { requested: false; waitUntil: Date }
| { requested: false; reason: string };
async function settle(db: Db, actionId: string, state: Record<string, unknown>, nextAction?: string) {
await db.update(issueRecoveryActions).set({
evidence: sql`coalesce(${issueRecoveryActions.evidence}, '{}'::jsonb) || jsonb_build_object('providerLimitResume', ${JSON.stringify(state)}::jsonb)`,
...(nextAction ? { nextAction } : {}),
updatedAt: new Date(),
}).where(and(eq(issueRecoveryActions.id, actionId), sql`${issueRecoveryActions.evidence}->'providerLimitResume' is null`));
}
/** Why Paperclip did not retry after a reset it announced; the Retry stays.
* Every give-up reason is listed, so no give-up leaves the promise standing. */
const NOT_RETRIED = {
source_run_mismatch: "the failed run no longer matches this hold",
reset_unknown: "the provider's reset could no longer be read",
task_changed: "the task changed",
no_accountable_user: "no user is accountable for the run",
automatic_retry_budget_used: "three automatic Retries in a row did not restore usage",
retry_stale: "a newer run exists",
retry_refused: "Retry was not allowed for the accountable user",
reset_stale: "the reset passed more than a day ago",
} as const;
type NotRetriedReason = keyof typeof NOT_RETRIED;
/**
* Requests the task's Retry for one usage-limit hold once its reset has
* passed. Idempotent per run: the Retry key and the recorded outcome both
* prevent a second request.
*/
export async function requestProviderLimitResumeRetry(db: Db, input: {
companyId: string; actionId: string; prepareChatRetry?: PrepareChatRetry;
}, now = new Date()): Promise<Outcome> {
const [action] = await db.select().from(issueRecoveryActions).where(and(
eq(issueRecoveryActions.companyId, input.companyId), eq(issueRecoveryActions.id, input.actionId)));
if (!action || action.status !== "active" || action.kind !== "active_run_watchdog" || action.cause !== NATIVE_PROVIDER_USAGE_LIMIT
|| action.evidence?.providerLimitResume) return { requested: false, reason: "not_waiting" };
const runId = typeof action.evidence?.runId === "string" ? action.evidence.runId : null;
const [run] = runId ? await db.select().from(heartbeatRuns).where(and(
eq(heartbeatRuns.companyId, action.companyId), sql`${heartbeatRuns.id}::text = ${runId}`)) : [];
const done = async (reason: NotRetriedReason, extra: Record<string, unknown> = {}) => {
// Replace a promise to retry with what the user can do now.
const nextAction = action.evidence?.providerLimitResetAt
? `Paperclip did not retry this task after the provider usage limit reset because ${NOT_RETRIED[reason]}. Retry the task when usage capacity is available.`
: undefined;
await settle(db, action.id, { state: "not_requested", reason, decidedAt: now.toISOString(), ...extra }, nextAction);
return { requested: false as const, reason };
};
// The failure that created the hold may still be settling its run.
if (run && ["queued", "running"].includes(run.status)) return { requested: false, waitUntil: new Date(now.getTime() + 60_000) };
if (!run || run.runtimeMode !== "native" || run.status !== "failed" || run.errorCode !== NATIVE_PROVIDER_USAGE_LIMIT)
return done("source_run_mismatch");
const reset = await readNativeUsageLimitReset(db, run);
if (!reset) return done("reset_unknown");
if (!reset.withinAutomaticWait) {
// Too far out to wait by itself: the hold names the reset and leaves the
// Retry to the user; it never promised an automatic one.
await db.update(issueRecoveryActions).set({
nextAction: providerLimitNextAction({ automatic: false, resetAt: reset.resetAt }),
evidence: sql`coalesce(${issueRecoveryActions.evidence}, '{}'::jsonb) || jsonb_build_object('providerLimitResetAt', ${reset.resetAt.toISOString()}::text)`,
updatedAt: now,
}).where(and(eq(issueRecoveryActions.id, action.id), eq(issueRecoveryActions.status, "active")));
await settle(db, action.id, { state: "not_requested", reason: "reset_beyond_wait", resetAt: reset.resetAt.toISOString(),
decidedAt: now.toISOString() });
return { requested: false, reason: "reset_beyond_wait" };
}
if (reset.resetAt.getTime() > now.getTime()) {
// A hold saved by an earlier release names no reset; tell its reader when work resumes.
if (!action.evidence?.providerLimitResetAt) {
const actorId = await accountableUser(db, run);
await db.update(issueRecoveryActions).set({
nextAction: providerLimitNextAction(actorId
? { automatic: true, resetAt: reset.resetAt, actorId, estimated: reset.estimated }
: { automatic: false, resetAt: reset.resetAt, estimated: reset.estimated }),
evidence: sql`coalesce(${issueRecoveryActions.evidence}, '{}'::jsonb) || jsonb_build_object('providerLimitResetAt', ${reset.resetAt.toISOString()}::text)`,
updatedAt: now,
}).where(and(eq(issueRecoveryActions.id, action.id), eq(issueRecoveryActions.status, "active")));
}
return { requested: false, waitUntil: reset.resetAt };
}
if (now.getTime() - reset.resetAt.getTime() > STALE_RESET_MS) return done("reset_stale", { resetAt: reset.resetAt.toISOString() });
const issueId = action.sourceIssueId;
const [issue] = await db.select({ status: issues.status, assigneeAgentId: issues.assigneeAgentId }).from(issues)
.where(and(eq(issues.companyId, run.companyId), eq(issues.id, issueId)));
if (!issue || issue.assigneeAgentId !== run.agentId || ["done", "cancelled"].includes(issue.status)) return done("task_changed");
const actorId = await accountableUser(db, run);
if (!actorId) return done("no_accountable_user");
// Bound a provider that keeps reporting resets that do not restore capacity.
const [lastSuccess] = await db.select({ finishedAt: heartbeatRuns.finishedAt }).from(heartbeatRuns).where(and(
eq(heartbeatRuns.companyId, run.companyId), eq(heartbeatRuns.agentId, run.agentId), eq(heartbeatRuns.status, "succeeded"),
sql`coalesce(${heartbeatRuns.nativeIssueId}::text, ${heartbeatRuns.issueId}::text, ${heartbeatRuns.contextSnapshot}->>'issueId') = ${issueId}`,
)).orderBy(desc(heartbeatRuns.finishedAt)).limit(1);
const earlier = await db.select({ id: agentWakeupRequests.id }).from(agentWakeupRequests).where(and(
eq(agentWakeupRequests.companyId, run.companyId), eq(agentWakeupRequests.agentId, run.agentId),
like(agentWakeupRequests.idempotencyKey, `task-retry:${PROVIDER_LIMIT_RESUME_KEY_PREFIX}%`),
sql`${agentWakeupRequests.payload}->>'issueId' = ${issueId}`,
lastSuccess?.finishedAt ? gt(agentWakeupRequests.requestedAt, lastSuccess.finishedAt) : undefined,
)).limit(MAX_AUTOMATIC_RESUMES);
if (earlier.length >= MAX_AUTOMATIC_RESUMES) return done("automatic_retry_budget_used");
try {
const receipt = await requestTaskRetry({ db, companyId: run.companyId, issueId, actorId,
actorSource: actorId === "local-board" ? "local_implicit" : "session",
idempotencyKey: `${PROVIDER_LIMIT_RESUME_KEY_PREFIX}${run.id}`, observedRunId: run.id,
initiatedBy: "provider_limit_reset", prepareChatRetry: input.prepareChatRetry });
if (!receipt.accepted || !receipt.requestId) return done("retry_stale");
await settle(db, action.id, { state: "requested", requestId: receipt.requestId, resetAt: reset.resetAt.toISOString(),
requestedAt: now.toISOString() });
return { requested: true, requestId: receipt.requestId };
} catch (error) {
// Authority or conversation checks refused it; the visible Retry remains.
if (!(error instanceof HttpError)) throw error;
logger.info({ runId: run.id, status: error.status }, "provider limit reset left for an explicit Retry");
return done("retry_refused", { status: error.status });
}
}
type Scope = { companyId: string };
const LOAD_PAGE_SIZE = 500;
type Entry = { id: string; companyId: string; dueAt: number };
/**
* Deadline owner for usage-limit holds: one entry per hold, due at its
* provider-reported reset. Holds are the durable truth; a new hold notifies
* this queue, and startup reconstructs every waiting hold.
*/
export function registerProviderLimitResumeWork(
db: Db,
coordinator: ReturnType<typeof createDeliveryWorkCoordinator>,
owner: { resume(companyId: string, requestId: string): Promise<unknown>; schedulingSuppressed(): Promise<boolean>;
/** Read when a Retry is requested: the chat service registers it after startup. */
prepareChatRetry?: () => PrepareChatRetry | undefined },
canRun: () => boolean,
) {
const cursors = new Map<string, string>();
return registerScopedDeadlineWork<Entry, Scope>(coordinator, {
queue: DELIVERY_QUEUES.providerLimitResume,
decodeScope: hint => hint === "*" ? undefined : JSON.parse(hint) as Scope,
matches: (entry, scope) => !scope || entry.companyId === scope.companyId,
load: async scope => {
// One bounded page per pass, resumed from a stable cursor until every
// waiting hold is loaded: a hold left out would never retry.
const key = scope ? JSON.stringify(scope) : "*";
const cursor = cursors.get(key);
const rows = await db.select({ id: issueRecoveryActions.id, companyId: issueRecoveryActions.companyId })
.from(issueRecoveryActions).where(and(
scope ? eq(issueRecoveryActions.companyId, scope.companyId) : undefined,
eq(issueRecoveryActions.status, "active"), eq(issueRecoveryActions.kind, "active_run_watchdog"),
eq(issueRecoveryActions.cause, NATIVE_PROVIDER_USAGE_LIMIT),
sql`${issueRecoveryActions.evidence}->'providerLimitResume' is null`,
isNull(issueRecoveryActions.resolvedAt),
cursor ? gt(issueRecoveryActions.id, cursor) : undefined,
)).orderBy(asc(issueRecoveryActions.id)).limit(LOAD_PAGE_SIZE);
const complete = rows.length < LOAD_PAGE_SIZE;
if (complete) cursors.delete(key); else cursors.set(key, rows.at(-1)!.id);
// check() reads each hold's reset and returns its real deadline.
return { rows: rows.map(row => ({ ...row, dueAt: 0 })), complete };
},
check: async entry => {
if (await owner.schedulingSuppressed()) return { ...entry, dueAt: Date.now() + 5 * 60_000 };
const outcome = await requestProviderLimitResumeRetry(db, { companyId: entry.companyId, actionId: entry.id,
prepareChatRetry: owner.prepareChatRetry?.() });
if ("waitUntil" in outcome) return { ...entry, dueAt: outcome.waitUntil.getTime() };
if (outcome.requested) await owner.resume(entry.companyId, outcome.requestId).catch((error: unknown) =>
logger.warn({ err: error, actionId: entry.id }, "provider limit Retry remains queued"));
return null;
},
}, canRun);
}