fix(heartbeat): a provider usage-limit hold applies only to the account that reported it (#22800)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Agents run on an AI connection: a connected provider account (a
connection grant), or the host's own account
> - When a provider reports an exhausted allowance, Paperclip holds new
work for that agent until the reported reset (`provider_limit_wait`),
and schedules one recheck at the reset
> - The hold was keyed by agent only. After a user connected a
different, working account and the agent moved to it, every new run was
still cancelled with the old account's reset time. A reply on the task
did not recheck the wait. Only a manual "Check now" got work moving
> - A usage limit belongs to the account that reported it. When that
account is gone or replaced, the hold must be gone too, and waiting work
must start without manual repair
> - The banner's "Check now" button also failed here. It answered 409
"Issue has no scheduled monitor", because the button calls the
issue-monitor route and this task has a scheduled retry, not a monitor
> - This pull request scopes the hold to the credential, releases
waiting work when the account changes or is revoked, makes a reply
recheck the wait, and makes "Check now" recheck a waiting retry
> - The benefit is that fixing the account fixes the task. The same
account stays held, so an exhausted account is not called again

## Linked Issues or Issue Description

No public issue exists. Bug report:

**What happened?**
An agent's connected provider account ran out of quota, with a reset
about six days away. Paperclip held the agent's work ("Pool exhausted",
runs cancelled with `provider_limit_wait`, one recheck scheduled 24
hours later). The user then connected a different, paid account. The old
account became revoked, and the agent was moved to the new account. The
agent's connection test passed. But every new run was still cancelled at
once with the old account's reset time. A new comment on the task did
not start a run, although the composer said "Sending a reply wakes the
agent now". The task stayed in `todo`. Pressing "Check now" on the "Pool
exhausted" banner did nothing: `POST /issues/:id/monitor/check-now`
answered 409, because the task has no issue monitor
(`triggerIssueMonitor` throws "Issue has no scheduled monitor").

**Expected behavior**
A limit reported on account A must not hold a run that uses account B.
When account A is revoked, removed or replaced on the agent, the hold
stops. Work that waited on it starts promptly. While the agent still
uses account A, the hold stays, with the plain message. A reply does
what the composer says.

**Steps to reproduce**
1. Bind an agent to connected account A.
2. Let a run fail with `quota_exhausted` and a reported reset days away.
The next wake is cancelled with `provider_limit_wait`, and a recheck is
scheduled about 24 hours later.
3. Connect account B and move the agent to it, or revoke account A.
4. Wake the agent on the task, or reply on the task. Before this change,
the run is cancelled with `provider_limit_wait` again, and the reply
does not recheck.

## What Changed

- `server/src/services/native-runtime/native-startup-retry.ts`: limit
evidence now comes only from runs on the checked credential. A run
records its grant in `contextSnapshot.aiConnection.grantId`. A run with
no recorded grant used the host's own account. Evidence from a revoked,
expired or removed grant never applies. A later success on another
account no longer clears this account's limit. New helpers resolve the
credential of an agent's next run from its saved binding
(`shared`/`delegated`: the bound grant; `responsible_user`: that user's
default grants for the provider).
- `server/src/services/heartbeat/provider-limit-wait.ts`: the
pre-dispatch hold checks the agent's current credential, and records the
limited grant on `providerLimitWait.grantId`. New
`releaseProviderLimitWaits` makes waiting usage-limit retries due now,
notifies retry dispatch in the same transaction, and logs
`issue.scheduled_retry_retry_now` activity with `source:
provider_limit_recheck`. The recheck goes through normal dispatch. It
reads saved evidence only, so a still-limited account is held again with
no provider work.
- `server/src/services/agent-configuration.ts`: a change to an agent's
`runtimeConfig.aiConnection` releases that agent's waits, in the same
transaction as the change.
- `server/src/services/tool-access/connections/grants.ts` and
`removal.ts`: revoking or removing an account releases the waits whose
limit was reported on it (after commit, best effort; the evidence rule
alone already stops the hold).
- `server/src/services/heartbeat/queue.ts`: a user's wake that is folded
into a usage wait (comment or other user wake) rechecks it at once.
Agent and system wakes keep the scheduled time, so they cannot loop.
- `server/src/routes/issues.ts`: `POST /issues/:id/monitor/check-now` on
a task with no monitor and a waiting scheduled retry now starts that
retry (the same path as "retry now"). The retry rechecks availability
before any work. It logs `issue.scheduled_retry_retry_now` with `source:
monitor_check_now`. If the check cannot start, the 409 has a plain
reason. Tasks with a monitor keep the old behavior.
- `ui/src/components/IssueMonitorBanner.tsx`: for a usage wait, the
composer now says "Sending a reply checks usage again now. The agent
starts as soon as usage is available." The banner says work also resumes
when the agent uses a different account.
- Upgrade safety: holds are derived from saved run evidence, so old
holds resolve by the new rule after deploy. A wait saved before this
change has no `grantId`; the release finds its account from the run that
reported the limit (`providerLimitWait.sourceRunId`).
- `queue.ts` was already far above 1,000 lines. This change adds one
small helper beside the two coalescing paths that need it, rather than a
new module for one call.

## Verification

- Red first: the new tests ran against the `origin/master` sources and 6
of them failed (hold on account A blocked a run on account B; revoked
account still held; rebind and reply did not release the 24-hour retry;
old-shape release missing). The shared-account test passed on master
too, as intended: it guards that the hold stays.
- Check now: a route test covers a `todo` task with no monitor and a
waiting retry (200, the retry starts, the monitor path is not called,
activity is logged) and a refused check (409 with a plain reason). An
integration test covers the exact saved state: `todo` task, cancelled
`provider_limit_wait` run, `scheduled_retry` successor, agent already
moved to another account. "Check now" starts the retry, and it is not
held again.
- Green: `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/heartbeat-provider-limit-wait.test.ts
src/services/native-runtime/native-provider-limit-cooldown.integration.test.ts
src/services/native-runtime/native-startup-retry.integration.test.ts`
passes (58 tests), and
`src/__tests__/issue-execution-policy-routes.test.ts`.
- UI: `ui/src/components/IssueMonitorBanner.test.tsx` passes (2 tests).
- `npx tsc --noEmit -p server` passes.
- `pnpm verify` exited 2 ("broader verification required"; its graph
worker was killed under machine load). I ran the focused checks above
and rely on required CI for broad coverage.
- New tests cover: same account still held with the plain message; agent
moved to another connected account starts; revoked account stops
holding; rebind releases the pending retry and logs activity; a wait
saved in the old shape is released when its account is revoked, and not
when another account is revoked; two agents on one account both stay
held when one agent moves away; a user reply rechecks at once and holds
again (keeping the reply) while the account is still limited, and an
agent's comment does not.
- Not run live: I did not reproduce this on a running instance. I read
the evidence from a local instance where the bug happened, and I did not
change that instance. Live confirmation of the release after deploy is
still to do.

## Risks

- Behavior change: a limit no longer carries over to a different
account. If two accounts share one provider-side quota, the agent can
make one call on the new account before that account gets its own hold.
- A `responsible_user` agent whose user has no saved default cannot
resolve its account before the run. In that case only the revoked-grant
rule applies, as before.
- A user reply on a still-limited account makes one cancelled recheck
run and a new scheduled wait. This is cheap (no workspace or provider
work) and is bounded by the number of user replies.
- No schema change and no new background worker.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, agentic coding with
tool use and code execution in Claude Code.

## 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
- [ ] 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:
DottaandClaude Opus 5.5 authored and GitHub committed 2026-11-24 15:01:19 -06:00
1 parent 4401962e69
commit 137bd29531
18 files changed
+911 -30

No files matched your search

@@ -4,18 +4,32 @@ import { tmpdir } from "node:os";
import path from "node:path";
import { eq } from "drizzle-orm";
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
import { agents, authUsers, companies, companyMemberships, createDb, heartbeatRunEvents, heartbeatRuns, issues } from "@paperclipai/db";
import {
activityLog, agents, authUsers, companies, companyMemberships, connectionGrants, createDb, heartbeatRunEvents, heartbeatRuns, issues,
aiProviderDefaults, toolApplications, toolConnectionInstalls, toolConnections,
} from "@paperclipai/db";
import { registerServerAdapter, unregisterServerAdapter } from "../adapters/index.js";
import { heartbeatService } from "../services/heartbeat.js";
import { createProviderLimitWait } from "../services/heartbeat/provider-limit-wait.js";
import { createProviderLimitWait, releaseProviderLimitWaits } from "../services/heartbeat/provider-limit-wait.js";
import { agentService } from "../services/agents.js";
import { aiConnectionService } from "../services/ai-connections.js";
import { toolAccessService } from "../services/tool-access.js";
import { executionProjectionsForRuns } from "../services/execution-projection.js";
import { recoveryPostgresSupport, startRecoveryPostgres } from "./helpers/recovery-postgres.js";
const providerLimitCancellation = vi.hoisted(() => ({ after: null as null | (() => Promise<unknown>) }));
const releaseFailure = vi.hoisted(() => ({ next: false }));
vi.mock("../services/heartbeat/provider-limit-wait.js", async importOriginal => {
const actual = await importOriginal<typeof import("../services/heartbeat/provider-limit-wait.js")>();
return {
...actual,
releaseProviderLimitWaits: async (...args: Parameters<typeof actual.releaseProviderLimitWaits>) => {
if (releaseFailure.next) {
releaseFailure.next = false;
throw new Error("release step failed");
}
return actual.releaseProviderLimitWaits(...args);
},
createProviderLimitWait: (...[database, deps]: Parameters<typeof actual.createProviderLimitWait>) =>
actual.createProviderLimitWait(database, {
...deps,
@@ -28,6 +42,18 @@ vi.mock("../services/heartbeat/provider-limit-wait.js", async importOriginal =>
};
});
const retryDispatchNotice = vi.hoisted(() => ({ before: null as null | ((transaction: object) => Promise<unknown>) }));
vi.mock("../services/run-dispatch-notifications.js", async importOriginal => {
const actual = await importOriginal<typeof import("../services/run-dispatch-notifications.js")>();
return {
...actual,
notifyScheduledRetryDispatch: async (...args: Parameters<typeof actual.notifyScheduledRetryDispatch>) => {
await retryDispatchNotice.before?.(args[0]);
return actual.notifyScheduledRetryDispatch(...args);
},
};
});
const describePostgres = recoveryPostgresSupport.supported ? describe : describe.skip;
if (!recoveryPostgresSupport.supported) console.warn(`Skipping provider limit wait tests: ${recoveryPostgresSupport.reason}`);
@@ -232,4 +258,370 @@ describePostgres("heartbeat provider usage limit wait", () => {
retryability: "unknown", message: "ACP agent reported a terminal limit failure." } } }]);
expect(dispatched.has((await wake(unrelated)).id)).toBe(true);
}, 60_000);
/**
* A usage limit belongs to the account it was reported on. Connecting a
* different account, or revoking the limited one, ends the hold; the same
* account stays held.
*/
describe("account-scoped holds", () => {
type Account = { connectionId: string; grantId: string };
async function accounts(companyId: string, count: number): Promise<Account[]> {
const [application] = await db.insert(toolApplications)
.values({ companyId, name: `AI accounts ${randomUUID()}`, type: "mcp_http" }).returning();
const created: Account[] = [];
for (let index = 0; index < count; index += 1) {
const [connection] = await db.insert(toolConnections).values({ companyId, applicationId: application.id, uid: randomUUID(),
name: `AI account ${index}`, connectionPurpose: "ai", transport: "runtime_auth", authKind: "none" }).returning();
const [grant] = await db.insert(connectionGrants).values({ companyId, connectionId: connection.id, kind: "organization" }).returning();
created.push({ connectionId: connection.id, grantId: grant.id });
}
return created;
}
const binding = (account: Account) => ({ mode: "shared", provider: "google", method: "subscription", ...account });
/** A turn on `account` that the provider refused with a quota reset days away. */
const quotaOn = (account: Account) => ({
status: "failed",
startedAt: new Date(Date.now() - 7 * 60_000),
finishedAt: new Date(Date.now() - 5 * 60_000),
errorCode: "native_provider_usage_limit",
contextSnapshot: { aiConnection: { mode: "shared", provider: "google", method: "subscription", ...account } },
resultJson: { providerFailure: { schema: "paperclip.provider-failure.v1", provider: "antigravity", phase: "turn",
category: "quota_exhausted", httpStatus: 429, providerCode: "RESOURCE_EXHAUSTED", retryability: "requires_action",
retryAt: new Date(Date.now() + 6 * 24 * 60 * 60_000).toISOString(), message: "Usage limit reached for this account." } },
});
/** An agent bound to `bound`, whose earlier turn hit the quota on `limited`. */
async function heldFixture(options: { count?: number } = {}) {
const f = await seed([]);
const list = await accounts(f.companyId, options.count ?? 2);
await db.update(agents).set({ runtimeConfig: { aiConnection: binding(list[0]) } }).where(eq(agents.id, f.agentId));
await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.agentId, invocationSource: "automation",
triggerDetail: "system", ...quotaOn(list[0]) });
return { ...f, accounts: list };
}
async function deferDirect(f: { companyId: string; agentId: string; issueId: string }, environment: {
early?: () => Promise<"host" | "managed" | null | "undecided">; dispatch?: "host" | "managed" | null;
} = {}) {
const [agent] = await db.select().from(agents).where(eq(agents.id, f.agentId));
const [run] = await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.agentId, status: "running",
invocationSource: "automation", triggerDetail: "system", contextSnapshot: { issueId: f.issueId } }).returning();
const deps = {
setRunStatusIfRunning: vi.fn(async () => ({ updated: true, run: { ...run, status: "cancelled" } })),
setWakeupStatus: vi.fn(async () => undefined),
appendRunEvent: vi.fn(async () => undefined),
scheduleBoundedRetryForRun: vi.fn(async () => ({ outcome: "scheduled" })),
releaseIssueExecutionAndPromote: vi.fn(async () => undefined),
finalizeAgentStatus: vi.fn(async () => undefined),
...(environment.early ? { sshAuthentication: environment.early } : {}),
};
const deferred = await createProviderLimitWait(db, deps as never)
.deferRunForProviderLimit(run, agent, { resumingAdmittedRun: false, conversation: false,
...(environment.dispatch !== undefined ? { sshAuthentication: environment.dispatch } : {}) });
return { deferred, deps };
}
async function scheduledRetry(agentId: string) {
const rows = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.agentId, agentId));
return rows.find(row => row.status === "scheduled_retry") ?? null;
}
it("keeps holding the account that reported the limit, with the plain message", async () => {
const f = await heldFixture();
const finished = await wake(f);
expect(dispatched.has(finished.id)).toBe(false);
expect(finished).toMatchObject({ status: "cancelled", errorCode: "provider_limit_wait",
resultJson: { providerLimitWait: { resetReported: true, category: "quota_exhausted", grantId: f.accounts[0].grantId } } });
expect(finished.error).toMatch(/^This agent's provider usage limit has a reported reset at .+ Work is held/);
}, 60_000);
it("starts a run whose agent now uses a different connected account", async () => {
const f = await heldFixture();
await db.update(agents).set({ runtimeConfig: { aiConnection: binding(f.accounts[1]) } }).where(eq(agents.id, f.agentId));
const { deferred, deps } = await deferDirect(f);
expect(deferred).toBe(false);
expect(deps.setRunStatusIfRunning).not.toHaveBeenCalled();
});
it("follows the user's default account when the agent uses its responsible user's default", async () => {
const f = await seed([]);
const userId = `limit-user-${f.companyId}`;
const [application] = await db.insert(toolApplications)
.values({ companyId: f.companyId, name: `Personal AI ${randomUUID()}`, type: "mcp_http" }).returning();
const personal: Account[] = [];
for (const name of ["Personal A", "Personal B"]) {
const [connection] = await db.insert(toolConnections).values({ companyId: f.companyId, applicationId: application.id,
uid: randomUUID(), name, connectionPurpose: "ai", transport: "runtime_auth", authKind: "none", enabled: true,
status: "active", healthStatus: "ok", config: { ai: { provider: "google", method: "subscription" }, aiIsolatedSubscription: true } }).returning();
const [grant] = await db.insert(connectionGrants).values({ companyId: f.companyId, connectionId: connection.id,
kind: "user", subjectUserId: userId }).returning();
await db.insert(toolConnectionInstalls).values({ companyId: f.companyId, connectionId: connection.id,
targetType: "company", targetId: f.companyId });
personal.push({ connectionId: connection.id, grantId: grant.id });
}
// The agent names no account; each run uses its responsible user's default.
await db.update(agents).set({ adapterType: "paperclip_runner", adapterConfig: { provider: "acpx", acpxAgent: "antigravity" },
runtimeConfig: { aiConnection: { mode: "responsible_user", provider: "google", method: "subscription" } } })
.where(eq(agents.id, f.agentId));
await db.insert(aiProviderDefaults).values({ companyId: f.companyId, userId, provider: "google", grantId: personal[0].grantId });
await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.agentId, invocationSource: "automation",
triggerDetail: "system", ...quotaOn(personal[0]) });
const deferAs = async () => {
const [agent] = await db.select().from(agents).where(eq(agents.id, f.agentId));
const [run] = await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.agentId, status: "running",
invocationSource: "automation", triggerDetail: "system", responsibleUserId: userId,
contextSnapshot: { issueId: f.issueId } }).returning();
return createProviderLimitWait(db, {
setRunStatusIfRunning: async () => ({ updated: true, run: { ...run, status: "cancelled" } }),
setWakeupStatus: async () => undefined, appendRunEvent: async () => undefined,
scheduleBoundedRetryForRun: async () => ({ outcome: "scheduled" }),
releaseIssueExecutionAndPromote: async () => undefined, finalizeAgentStatus: async () => undefined,
} as never).deferRunForProviderLimit(run, agent, { resumingAdmittedRun: false, conversation: false });
};
expect(await deferAs()).toBe(true);
// A task already waiting on account A, saved by an earlier hold.
const [wait] = await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.agentId, status: "cancelled",
invocationSource: "automation", triggerDetail: "system", errorCode: "provider_limit_wait",
startedAt: new Date(Date.now() - 60_000), finishedAt: new Date(Date.now() - 60_000),
resultJson: { providerLimitWait: { grantId: personal[0].grantId } }, contextSnapshot: { issueId: f.issueId } }).returning();
const [waiting] = await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.agentId, status: "scheduled_retry",
invocationSource: "automation", triggerDetail: "system", retryOfRunId: wait.id, scheduledRetryAttempt: 1,
scheduledRetryReason: "ai_connection_pool_wait", scheduledRetryAt: new Date(Date.now() + 24 * 60 * 60_000),
contextSnapshot: { issueId: f.issueId } }).returning();
// The user picks account B as their default; the route then releases
// waits whose limit was on the previous default.
const { previousGrantId } = await aiConnectionService(db).setDefault(f.companyId, userId, personal[1].grantId);
expect(previousGrantId).toBe(personal[0].grantId);
expect(await deferAs()).toBe(false);
expect(await releaseProviderLimitWaits(db, { companyId: f.companyId, reason: "ai_connection_changed",
grantIds: [previousGrantId!] })).toEqual([waiting.id]);
const [released] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, waiting.id));
expect(released.scheduledRetryAt!.getTime()).toBeLessThanOrEqual(Date.now());
});
it("ignores a limit on an account that expired or needs a new sign-in", async () => {
for (const status of ["expired", "needs_reauthorization"] as const) {
const f = await heldFixture();
await db.update(connectionGrants).set({ status }).where(eq(connectionGrants.id, f.accounts[0].grantId));
expect((await deferDirect(f)).deferred).toBe(false);
}
});
it("keeps holding the bound account when another account later reports a billing refusal", async () => {
const f = await heldFixture();
// Account B's newer refusal needs billing action and names no reset.
await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.agentId, invocationSource: "automation",
triggerDetail: "system", ...quotaOn(f.accounts[1]), startedAt: new Date(Date.now() - 2 * 60_000), finishedAt: new Date(Date.now() - 60_000),
resultJson: { providerFailure: { schema: "paperclip.provider-failure.v1", provider: "antigravity", phase: "turn",
category: "quota_exhausted", retryability: "requires_action", message: "Check your plan and billing details." } } });
expect((await deferDirect(f)).deferred).toBe(true);
});
it("checks the host's own account when the harness signs in with a preconfigured home", async () => {
const f = await heldFixture();
await db.update(agents).set({ adapterType: "paperclip_runner", adapterConfig: { provider: "acpx", acpxAgent: "antigravity", homeMode: "preconfigured" } })
.where(eq(agents.id, f.agentId));
// The saved account's limit does not hold a run that will use the host sign-in.
expect((await deferDirect(f)).deferred).toBe(false);
await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.agentId, invocationSource: "automation",
triggerDetail: "system", ...quotaOn(f.accounts[0]), contextSnapshot: {} });
// A limit reported on the host sign-in does.
expect((await deferDirect(f)).deferred).toBe(true);
});
it("checks a task's own environment only once dispatch knows which account it signs in with", async () => {
// Account A (the agent's binding) is limited; the host sign-in is not.
const f = await heldFixture();
// Before preparation the task's environment is undecided, so nothing is held yet.
expect((await deferDirect(f, { early: async () => "undecided" })).deferred).toBe(false);
// A low-trust environment with managed credentials uses account A: held.
expect((await deferDirect(f, { dispatch: "managed" })).deferred).toBe(true);
// One that keeps the host's login does not use account A: not held.
expect((await deferDirect(f, { dispatch: "host" })).deferred).toBe(false);
});
it("holds a host limit when the task's environment keeps the host login, and not when it uses managed credentials", async () => {
const f = await heldFixture();
await db.delete(heartbeatRuns).where(eq(heartbeatRuns.agentId, f.agentId));
// Only the host sign-in is limited.
await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.agentId, invocationSource: "automation",
triggerDetail: "system", ...quotaOn(f.accounts[0]), contextSnapshot: {} });
expect((await deferDirect(f, { dispatch: "host" })).deferred).toBe(true);
expect((await deferDirect(f, { dispatch: "managed" })).deferred).toBe(false);
});
it("clears a limit only after a success on the same account", async () => {
const f = await heldFixture();
const succeededOn = (account: Account) => ({ status: "succeeded", startedAt: new Date(Date.now() - 2 * 60_000),
finishedAt: new Date(Date.now() - 60_000), contextSnapshot: { aiConnection: { grantId: account.grantId } } });
await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.agentId, invocationSource: "automation",
triggerDetail: "system", ...succeededOn(f.accounts[1]) });
expect((await deferDirect(f)).deferred).toBe(true);
await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.agentId, invocationSource: "automation",
triggerDetail: "system", ...succeededOn(f.accounts[0]) });
expect((await deferDirect(f)).deferred).toBe(false);
});
it("stops holding work once the limited account is revoked", async () => {
const f = await heldFixture();
expect((await deferDirect(f)).deferred).toBe(true);
await db.update(connectionGrants).set({ status: "revoked", revokedAt: new Date() })
.where(eq(connectionGrants.id, f.accounts[0].grantId));
expect((await deferDirect(f)).deferred).toBe(false);
});
it("releases the waiting retry when the agent is moved to another account", async () => {
const f = await heldFixture();
const held = await wake(f);
expect(held.errorCode).toBe("provider_limit_wait");
const retry = await scheduledRetry(f.agentId);
expect(retry!.scheduledRetryAt!.getTime()).toBeGreaterThan(Date.now() + 60 * 60_000);
// Dispatch hears of the due retry before the write that makes it due.
const seenAtNotice: number[] = [];
retryDispatchNotice.before = async transaction => {
const [row] = await (transaction as typeof db).select({ at: heartbeatRuns.scheduledRetryAt }).from(heartbeatRuns)
.where(eq(heartbeatRuns.id, retry!.id));
seenAtNotice.push(row!.at!.getTime());
};
try {
await agentService(db).update(f.agentId, { runtimeConfig: { aiConnection: binding(f.accounts[1]) } });
} finally {
retryDispatchNotice.before = null;
}
expect(seenAtNotice).toEqual([retry!.scheduledRetryAt!.getTime()]);
const [released] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, retry!.id));
expect(released.status).toBe("scheduled_retry");
expect(released.scheduledRetryAt!.getTime()).toBeLessThanOrEqual(Date.now());
expect((await heartbeat.promoteDueScheduledRetries(new Date())).runIds).toContain(retry!.id);
const activity = await db.select().from(activityLog).where(eq(activityLog.runId, retry!.id));
expect(activity).toContainEqual(expect.objectContaining({ action: "issue.scheduled_retry_retry_now", entityId: f.issueId,
details: expect.objectContaining({ reason: "ai_connection_changed" }) }));
}, 60_000);
it("releases a wait saved before the account was recorded on it when that account is revoked", async () => {
const f = await heldFixture();
const held = await wake(f);
// Waits saved by the previous release name only the run that reported the limit.
const { grantId: _recorded, ...previousShape } = (held.resultJson as { providerLimitWait: Record<string, unknown> }).providerLimitWait;
await db.update(heartbeatRuns).set({ resultJson: { ...held.resultJson, providerLimitWait: previousShape } })
.where(eq(heartbeatRuns.id, held.id));
const retry = await scheduledRetry(f.agentId);
// Another account's revocation leaves the wait alone.
expect(await releaseProviderLimitWaits(db, { companyId: f.companyId, reason: "ai_connection_revoked",
grantIds: [f.accounts[1].grantId] })).toEqual([]);
await db.update(connectionGrants).set({ status: "revoked", revokedAt: new Date() })
.where(eq(connectionGrants.id, f.accounts[0].grantId));
expect(await releaseProviderLimitWaits(db, { companyId: f.companyId, reason: "ai_connection_revoked",
grantIds: [f.accounts[0].grantId] })).toEqual([retry!.id]);
expect((await heartbeat.promoteDueScheduledRetries(new Date())).runIds).toContain(retry!.id);
}, 60_000);
it("commits a revocation and its release together, so a revoked account never leaves work waiting", async () => {
const f = await heldFixture();
await wake(f);
const retry = await scheduledRetry(f.agentId);
const actor = { actorType: "user" as const, actorId: `limit-user-${f.companyId}` };
const retryAt = async () => (await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, retry!.id)))[0].scheduledRetryAt!.getTime();
const grantStatus = async () => (await db.select().from(connectionGrants).where(eq(connectionGrants.id, f.accounts[0].grantId)))[0].status;
// If the release fails, the revocation fails with it: never revoked with work still waiting.
releaseFailure.next = true;
await expect(toolAccessService(db).revokeConnectionGrant(f.accounts[0].connectionId, f.accounts[0].grantId, actor))
.rejects.toThrow("release step failed");
expect(await grantStatus()).toBe("active");
expect(await retryAt()).toBe(retry!.scheduledRetryAt!.getTime());
// A committed revocation has already made the waiting work due.
await toolAccessService(db).revokeConnectionGrant(f.accounts[0].connectionId, f.accounts[0].grantId, actor);
expect(await grantStatus()).toBe("revoked");
expect(await retryAt()).toBeLessThanOrEqual(Date.now());
expect((await heartbeat.promoteDueScheduledRetries(new Date())).runIds).toContain(retry!.id);
}, 60_000);
it("keeps holding every agent that still shares the limited account", async () => {
const first = await heldFixture();
// Two agents in one company share account A; both reported its limit.
const sharedCompany = first.companyId;
const [secondAgent] = await db.insert(agents).values({ id: randomUUID(), companyId: sharedCompany, name: "Second shared agent",
adapterType, status: "idle", adapterConfig: {}, runtimeConfig: { aiConnection: binding(first.accounts[0]) } }).returning();
const [secondIssue] = await db.insert(issues).values({ id: randomUUID(), companyId: sharedCompany, title: "Second task",
status: "todo", assigneeAgentId: secondAgent.id, issueNumber: 2 }).returning();
await db.insert(heartbeatRuns).values({ companyId: sharedCompany, agentId: secondAgent.id, invocationSource: "automation",
triggerDetail: "system", ...quotaOn(first.accounts[0]) });
const shared = { companyId: sharedCompany, agentId: secondAgent.id as typeof first.agentId, issueId: secondIssue.id as typeof first.issueId };
expect((await wake(first)).errorCode).toBe("provider_limit_wait");
expect((await wake(shared)).errorCode).toBe("provider_limit_wait");
const sharedRetry = await scheduledRetry(secondAgent.id);
// Moving one agent to account B leaves the other's account A hold intact.
await agentService(db).update(first.agentId, { runtimeConfig: { aiConnection: binding(first.accounts[1]) } });
const [stillWaiting] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, sharedRetry!.id));
expect(stillWaiting.scheduledRetryAt!.getTime()).toBe(sharedRetry!.scheduledRetryAt!.getTime());
expect((await deferDirect(shared)).deferred).toBe(true);
}, 60_000);
it("starts the waiting work on Check now once the agent already uses another account", async () => {
// The state saved before this fix: the task is todo, its run was held
// for account A, its recheck is a day away, and the agent was moved to
// account B without releasing the wait.
const f = await heldFixture();
const held = await wake(f);
expect(held.errorCode).toBe("provider_limit_wait");
const retry = await scheduledRetry(f.agentId);
await db.update(agents).set({ runtimeConfig: { aiConnection: binding(f.accounts[1]) } }).where(eq(agents.id, f.agentId));
const [task] = await db.select().from(issues).where(eq(issues.id, f.issueId));
expect(task).toMatchObject({ status: "todo", monitorNextCheckAt: null, executionRunId: retry!.id });
// "Check now" on this task starts its waiting retry.
const checked = await heartbeat.retryScheduledRetryNow({ issueId: f.issueId, actor: { actorType: "user", actorId: `limit-user-${f.companyId}` } });
expect(checked.outcome).toBe("promoted");
await heartbeat.resumeQueuedRuns();
await heartbeat.drainActiveRunExecutions();
const [started] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, retry!.id));
// Account A's limit no longer holds the run. This fixture has no stored
// credential for account B, so the run goes on to that setup check.
expect(started.status).not.toBe("scheduled_retry");
expect(started.errorCode).not.toBe("provider_limit_wait");
const waits = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.retryOfRunId, retry!.id));
expect(waits.filter(run => run.scheduledRetryReason === "ai_connection_pool_wait")).toEqual([]);
}, 60_000);
it("rechecks the wait at once when the user replies, and holds again while the account is still limited", async () => {
const f = await heldFixture();
await wake(f);
const retry = await scheduledRetry(f.agentId);
const userId = `limit-user-${f.companyId}`;
const commentId = randomUUID();
// Another agent's comment keeps the scheduled recheck.
await heartbeat.wakeup(f.agentId, { source: "automation", triggerDetail: "system", reason: "issue_commented",
payload: { issueId: f.issueId, commentId: randomUUID() }, requestedByActorType: "agent", requestedByActorId: randomUUID(),
contextSnapshot: { issueId: f.issueId, wakeReason: "issue_commented" } });
expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, retry!.id)))[0].scheduledRetryAt!.getTime())
.toBe(retry!.scheduledRetryAt!.getTime());
await heartbeat.wakeup(f.agentId, { source: "automation", triggerDetail: "system", reason: "issue_commented",
payload: { issueId: f.issueId, commentId }, requestedByActorType: "user", requestedByActorId: userId,
contextSnapshot: { issueId: f.issueId, commentId, wakeCommentId: commentId, wakeReason: "issue_commented" } });
const [rechecking] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, retry!.id));
expect(rechecking.scheduledRetryAt!.getTime()).toBeLessThanOrEqual(Date.now());
expect((await heartbeat.promoteDueScheduledRetries(new Date())).runIds).toContain(retry!.id);
await heartbeat.resumeQueuedRuns();
await heartbeat.drainActiveRunExecutions();
const [rechecked] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, retry!.id));
expect(dispatched.has(retry!.id)).toBe(false);
expect(rechecked).toMatchObject({ status: "cancelled", errorCode: "provider_limit_wait" });
const [successor] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.retryOfRunId, retry!.id));
expect(successor).toMatchObject({ status: "scheduled_retry", scheduledRetryReason: "ai_connection_pool_wait" });
expect(successor.contextSnapshot).toMatchObject({ wakeCommentId: commentId });
}, 60_000);
});
});
@@ -17,6 +17,7 @@ const mockIssueService = vi.hoisted(() => ({
getRelationSummaries: vi.fn(),
listWakeableBlockedDependents: vi.fn(),
getWakeableParentAfterChildCompletion: vi.fn(),
getCurrentScheduledRetry: vi.fn(async (): Promise<{ status: string } | null> => null),
}));
const mockHeartbeatService = vi.hoisted(() => ({
@@ -27,6 +28,8 @@ const mockHeartbeatService = vi.hoisted(() => ({
getActiveRunForAgent: vi.fn(async () => null),
getQueuedAssignmentRunForIssue: vi.fn(async () => null),
cancelRun: vi.fn(async () => null),
retryScheduledRetryNow: vi.fn(async (): Promise<{ outcome: string; message: string; scheduledRetry: null }> =>
({ outcome: "promoted", message: "Scheduled retry was promoted to the queued run pool", scheduledRetry: null })),
}));
const mockAccessService = vi.hoisted(() => ({
@@ -1214,6 +1217,34 @@ describe("issue execution policy routes", () => {
);
});
it("checks a waiting usage retry now when the task has no monitor", async () => {
// A todo task whose run waits for provider usage: no issue monitor, one scheduled retry.
mockIssueService.getById.mockResolvedValue({
id: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", companyId: "company-1", status: "todo", monitorNextCheckAt: null,
assigneeAgentId: "33333333-3333-4333-8333-333333333333", assigneeUserId: null, executionPolicy: null, executionState: null,
});
mockIssueService.getCurrentScheduledRetry.mockResolvedValueOnce({ status: "scheduled_retry" });
mockHeartbeatService.triggerIssueMonitor.mockClear();
const res = await request(await createApp())
.post("/api/issues/aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa/monitor/check-now").send({});
expect(res.status).toBe(200);
expect(res.body).toMatchObject({ ok: true, outcome: "promoted" });
expect(mockHeartbeatService.retryScheduledRetryNow).toHaveBeenCalledWith(expect.objectContaining({
issueId: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa" }));
expect(mockHeartbeatService.triggerIssueMonitor).not.toHaveBeenCalled();
expect(mockLogActivity).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({
action: "issue.scheduled_retry_retry_now", details: expect.objectContaining({ source: "monitor_check_now" }) }));
// A check that cannot start says why, in plain words.
mockIssueService.getCurrentScheduledRetry.mockResolvedValueOnce({ status: "scheduled_retry" });
mockHeartbeatService.retryScheduledRetryNow.mockResolvedValueOnce({ outcome: "gate_suppressed",
message: "Scheduled retry suppressed because the agent no longer exists", scheduledRetry: null });
const refused = await request(await createApp())
.post("/api/issues/aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa/monitor/check-now").send({});
expect(refused.status).toBe(409);
expect(refused.body.error).toBe("The check could not start because the task changed. Refresh the task to see its current state.");
});
it.each(["execution_reconciliation_required", "monitor_dispatch_deferred", "monitor_replaced"])("does not claim success for a skipped monitor check: %s", async (reason) => {
mockIssueService.getById.mockResolvedValue({
id: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", companyId: "company-1", status: "blocked",
@@ -826,13 +826,26 @@ describeEmbeddedPostgres("issue scheduled retry routes", () => {
const retry = await request(app).post(`/api/issues/${f.issueId}/retry`)
.send({ idempotencyKey: randomUUID(), observedRunId: f.retryRunId });
const retryNow = await request(app).post(`/api/issues/${f.issueId}/scheduled-retry/retry-now`).send({});
// The banner's Check now starts the same retry, so it needs the same access.
const checkNow = await request(app).post(`/api/issues/${f.issueId}/monitor/check-now`).send({});
expect(retry.status, JSON.stringify(retry.body)).toBe(404);
expect(retryNow.status, JSON.stringify(retryNow.body)).toBe(404);
expect(checkNow.status, JSON.stringify(checkNow.body)).toBe(404);
const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.retryRunId));
expect(run!.status).toBe("scheduled_retry");
});
it("starts the waiting retry from Check now for a member who can see the task", async () => {
const f = await seedIssueWithRetry();
const app = createApp(boardActor(f.companyId));
const checkNow = await request(app).post(`/api/issues/${f.issueId}/monitor/check-now`).send({});
expect(checkNow.status, JSON.stringify(checkNow.body)).toBe(200);
expect(checkNow.body).toMatchObject({ ok: true, outcome: "promoted" });
const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.retryRunId));
expect(run!.status).toBe("queued");
});
it("promotes the existing scheduled retry and treats duplicate clicks as idempotent", async () => {
const { companyId, issueId, retryRunId } = await seedIssueWithRetry();
const app = createApp(boardActor(companyId));